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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRBasket.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasket.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.basket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.stream.Collectors;
import org.jdom2.Element;
/**
* Implements a basket of entries.
* The basket has a type attribute that allows to
* distinguish multiple baskets within the same session.
* The basket implements the List and Set interfaces,
* it behaves like an ordered Set of entries.
* Entries already contained in the basket can not be
* re-added, each entry can be contained only once in the basket.
*
* @author Frank Lützenkirchen
*/
public class MCRBasket implements List<MCRBasketEntry>, Set<MCRBasketEntry> {
/** The internal list of basket entries */
private List<MCRBasketEntry> list = new ArrayList<>();
/** The type of basket */
private String type;
/** The ID of the derivate that holds the persistent data of this basket */
private String derivateID;
/**
* Creates a new basket of the given type.
*
* @param type the type of basket, an attribute that can be used by the application to distinguish
* multiple basket within the same session.
*/
public MCRBasket(String type) {
this.type = type;
}
/**
* Returns the type of basket.
*/
public String getType() {
return type;
}
/**
* Returns the ID of the derivate that holds the persistent data of this basket, or null
*/
public String getDerivateID() {
return derivateID;
}
/**
* Sets the ID of the derivate that holds the persistent data of this basket
*/
public void setDerivateID(String derivateID) {
this.derivateID = derivateID;
}
@Override
public void add(int index, MCRBasketEntry entry) {
if (!contains(entry)) {
list.add(index, entry);
}
}
@Override
public boolean add(MCRBasketEntry entry) {
return !contains(entry) && list.add(entry);
}
@Override
public boolean addAll(Collection<? extends MCRBasketEntry> collection) {
boolean changed = false;
for (MCRBasketEntry entry : collection) {
if (!contains(entry)) {
changed = true;
add(entry);
}
}
return changed;
}
@Override
public boolean addAll(int index, Collection<? extends MCRBasketEntry> collection) {
return list.addAll(index, collection.stream().filter(entry -> !contains(entry)).collect(Collectors.toList()));
}
@Override
public void clear() {
list.clear();
}
@Override
public boolean contains(Object o) {
return list.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.containsAll(c);
}
@Override
public MCRBasketEntry get(int index) {
return list.get(index);
}
/**
* Returns the basket entry with the given ID, or null.
*
* @param id the ID of the basket entry.
*/
public MCRBasketEntry get(String id) {
return this.stream().filter(entry -> id.equals(entry.getID())).findFirst().orElse(null);
}
@Override
public int indexOf(Object o) {
return list.indexOf(o);
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public Iterator<MCRBasketEntry> iterator() {
return list.iterator();
}
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
@Override
public ListIterator<MCRBasketEntry> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<MCRBasketEntry> listIterator(int index) {
return list.listIterator(index);
}
@Override
public MCRBasketEntry remove(int index) {
return list.remove(index);
}
@Override
public boolean remove(Object o) {
return list.remove(o);
}
/**
* Removes the entry with the given ID from the basket.
*
* @return true, if the basket entry was removed successfully.
*/
public boolean removeEntry(String id) {
MCRBasketEntry entry = get(id);
if (entry == null) {
return false;
}
return remove(entry);
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public MCRBasketEntry set(int index, MCRBasketEntry entry) {
return (contains(entry) ? null : list.set(index, entry));
}
@Override
public int size() {
return list.size();
}
@Override
public List<MCRBasketEntry> subList(int fromIndex, int toIndex) {
return list.subList(fromIndex, toIndex);
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
/**
* Moves the basket entry one position up in the
* list of basket entries.
*/
public void up(MCRBasketEntry entry) {
move(entry, -1);
}
/**
* Moves the basket entry one position down in the
* list of basket entries.
*/
public void down(MCRBasketEntry entry) {
move(entry, 1);
}
/**
* Moves a basket entry up or down in the
* list of basket entries.
*
* @param change the number of index positions to move the entry.
*/
public void move(MCRBasketEntry entry, int change) {
int posOld = indexOf(entry);
int posNew = posOld + change;
if ((posNew < 0) || (posNew > list.size() - 1)) {
return;
}
remove(posOld);
add(posNew, entry);
}
/**
* For all basket entries, if their XML content is not resolved yet,
* resolves the XML from the given URI in the entry.
*/
public void resolveContent() {
for (MCRBasketEntry entry : list) {
Element content = entry.getContent();
if (content == null) {
entry.resolveContent();
}
}
}
@Override
public Spliterator<MCRBasketEntry> spliterator() {
return list.spliterator();
}
}
| 7,215 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBasketEntry.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketEntry.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.basket;
import org.jdom2.Element;
import org.mycore.common.xml.MCRURIResolver;
/**
* Represents an entry in a basket. Each entry has at least
* a unique ID, for example the MCRObjectID, and an URI that
* can be used to read the object's XML representation to
* render the object in the basket UI. Each basket entry
* may have an optional comment. The basket entry provides
* methods to resolve the object's XML and to set in in the
* basket entry. This can be used by applications that wish
* to edit XML in the basket itself.
*
* @author Frank Lützenkirchen
*/
public class MCRBasketEntry {
/** The ID of the object contained in this basket entry */
private String id;
/** The URI where to read the object's XML data from */
private String uri;
/** Optional comment for this basket entry */
private String comment;
/** The XML data of the object in the basket, read from the URI */
private Element content;
/**
* Creates a new basket entry. The XML that represents the object
* is not immediately read from the given URI. Call resolveContent() to
* read the content.
*
* @param id the ID of the object to add to the basket.
* @param uri the URI where to read the object's xml data from
*/
public MCRBasketEntry(String id, String uri) {
this.id = id;
this.uri = uri;
}
/** Returns the ID of the object contained in this basket entry */
public String getID() {
return id;
}
/** Returns the URI where to read the object's XML data from */
public String getURI() {
return uri;
}
/**
* Reads the XML data of the object in the basket entry, using the given URI,
* and stores it in the basket entry.
*/
public void resolveContent() {
if ((uri != null) && !uri.isEmpty()) {
setContent(MCRURIResolver.instance().resolve(uri));
}
}
/**
* Returns the XML data of the object in the basket entry, or null if
* setContent() or resolveContent() was not called yet.
*/
public Element getContent() {
return content;
}
/**
* Sets the XML data of the object in the basket entry.
*/
public void setContent(Element content) {
this.content = content.clone();
}
/**
* Returns the optional comment set for this basket entry.
*/
public String getComment() {
return comment;
}
/**
* Sets the optional comment for this basket entry.
*/
public void setComment(String comment) {
this.comment = comment;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MCRBasketEntry basketEntry) {
return basketEntry.id.equals(id);
} else {
return false;
}
}
@Override
public int hashCode() {
return id.hashCode();
}
}
| 3,678 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBasketXMLBuilder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketXMLBuilder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.basket;
import org.jdom2.Document;
import org.jdom2.Element;
/**
* Builds xml representations of a basket and its entries.
*
* @author Frank Lützenkirchen
*/
public class MCRBasketXMLBuilder {
/** If true, the XML data representing the objects in basket entries is included too. */
private boolean addContent;
/**
* Creates a new XML builder.
*
* @param addContent if true, the XML data representing the objects in basket entries is included too.
*/
public MCRBasketXMLBuilder(boolean addContent) {
this.addContent = addContent;
}
/**
* Builds an XML representation of a basket entry.
* Note that setContent() or resolveContent() must have been called before
* if XML content of the basket entry's object should be included.
*/
public Element buildXML(MCRBasketEntry entry) {
Element xml = new Element("entry");
xml.setAttribute("id", entry.getID());
xml.setAttribute("uri", entry.getURI());
if (addContent) {
Element content = entry.getContent();
if (content != null) {
xml.addContent(content.clone());
}
}
String comment = entry.getComment();
if (comment != null) {
xml.addContent(new Element("comment").setText(comment));
}
return xml;
}
/**
* Builds an XML representation of a basket and its entries.
*/
public Document buildXML(MCRBasket basket) {
Element xml = new Element("basket");
xml.setAttribute("type", basket.getType());
String derivateID = basket.getDerivateID();
if (derivateID != null) {
xml.setAttribute("id", derivateID);
}
for (MCRBasketEntry entry : basket) {
xml.addContent(buildXML(entry));
}
return new Document(xml);
}
}
| 2,645 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBasketResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.basket;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
/**
* Resolves entries from a basket, for example to edit the data
* in an editor form. Syntax: basket:{typeID}:{entryID}
*
* @author Frank Lützenkirchen
*/
public class MCRBasketResolver implements URIResolver {
public Source resolve(String href, String base) throws TransformerException {
try {
String[] tokens = href.split(":");
String type = tokens[1];
MCRBasket basket = MCRBasketManager.getOrCreateBasketInSession(type);
if (tokens.length > 2) {
String id = tokens[2];
MCRBasketEntry entry = basket.get(id);
entry.resolveContent();
Element xml = new MCRBasketXMLBuilder(true).buildXML(entry);
Document doc = new Document(xml);
return new JDOMSource(doc);
} else {
//resolve entire basket
MCRBasketXMLBuilder basketXMLBuilder = new MCRBasketXMLBuilder(false);
Document doc = basketXMLBuilder.buildXML(basket);
return new JDOMSource(doc);
}
} catch (Exception ex) {
throw new TransformerException(ex);
}
}
}
| 2,178 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBasketXMLParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketXMLParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.basket;
import org.jdom2.Document;
import org.jdom2.Element;
/**
* Parses XML representations of baskets and their entries.
*
* @author Frank Lützenkirchen
*/
public class MCRBasketXMLParser {
/**
* Parses an XML document representing a basket.
*/
public MCRBasket parseXML(Document doc) {
Element xml = doc.getRootElement();
String type = xml.getAttributeValue("type");
MCRBasket basket = new MCRBasket(type);
String derivateID = xml.getAttributeValue("id");
if (derivateID != null) {
basket.setDerivateID(derivateID);
}
for (Element child : xml.getChildren()) {
MCRBasketEntry entry = parseXML(child);
basket.add(entry);
}
return basket;
}
/**
* Parses an XML element that represents a basket entry.
*/
public MCRBasketEntry parseXML(Element xml) {
String id = xml.getAttributeValue("id");
String uri = xml.getAttributeValue("uri");
MCRBasketEntry entry = new MCRBasketEntry(id, uri);
String comment = xml.getChildTextTrim("comment");
if (comment != null) {
entry.setComment(comment);
}
return entry;
}
}
| 1,999 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBasketServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/basket/MCRBasketServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.basket;
import java.net.URI;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Provides the web front end to manage baskets and their contents.
* Required parameter is the type of basket and the action to perform.
* For a basket of objects, possible requests would be:
*
* BasketServlet?type=objects&action=show
* to output the contents of the objects basket using basket-{type}.xsl
* BasketServlet?type=objects&action=clear
* to remove all entries in the objects basket.
* BasketServlet?type=objects&action=add&id=DocPortal_document_00774301&uri=mcrobject:DocPortal_document_00774301
* to add a new entry with ID DocPortal_document_00774301 to the basket,
* reading its contents from URI mcrobject:DocPortal_document_00774301
* BasketServlet?type=objects&action=add&id=DocPortal_document_00774301&uri=mcrobject:DocPortal_document_00774301&resolve=true
* to add a new entry with ID DocPortal_document_00774301 to the basket,
* immediately resolving content from the given URI.
* BasketServlet?type=objects&action=remove&id=DocPortal_document_00774301
* to remove the entry with ID DocPortal_document_00774301 from the basket
* BasketServlet?type=objects&action=up&id=DocPortal_document_00774301
* to move the entry with ID DocPortal_document_00774301 one position up in the basket
* BasketServlet?type=objects&action=down&id=DocPortal_document_00774301
* to move the entry with ID DocPortal_document_00774301 one position down in the basket
* BasketServlet?type=objects&action=comment&id=DocPortal_document_00774301
* to change the comment stored in the basket. This is called
* using EditorServlet submission, see basket-edit.xml for an example.
* BasketServlet?type=objects&action=create&ownerID=DocPortal_basket_01234567
* to store a basket in a new file "basket" in a new derivate that is owned by the metadata object
* with the given ownerID.
* BasketServlet?type=objects&action=update
* to update a persistent basket in its derivate - that is the derivate the basket was loaded from.
* BasketServlet?action=retrieve&derivateID=DocPortal_derivate_12345678
* to retrieve a basket's data from a file "basket.xml" in the given derivate into the current user's session.
*
* @author Frank L\u00fctzenkirchen
**/
public class MCRBasketServlet extends MCRServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(MCRBasketServlet.class);
public static final String ALLOW_LIST_PROPERTY_NAME = "MCR.Basket.Resolver.AllowList";
private static final List<String> URI_ALLOW_LIST = MCRConfiguration2
.getOrThrow(ALLOW_LIST_PROPERTY_NAME, MCRConfiguration2::splitValue)
.collect(Collectors.toList());
public void doGetPost(MCRServletJob job) throws Exception {
HttpServletRequest req = job.getRequest();
HttpServletResponse res = job.getResponse();
String type = req.getParameter("type");
String action = req.getParameter("action");
String[] uris = req.getParameterValues("uri");
String[] ids = req.getParameterValues("id");
String redirect = getProperty(req, "redirect");
URI referer = getReferer(req);
boolean resolveContent = "true".equals(req.getParameter("resolve"));
LOGGER.info("{} {} {}", action, type, ids == null ? "" : ids);
MCRBasket basket = MCRBasketManager.getOrCreateBasketInSession(type);
if (Objects.equals(action, "add")) {
if (uris.length != ids.length) {
throw new MCRException("Amount of URIs must match amount of IDs");
}
for (int i = 0; i < uris.length; i++) {
String uri = uris[i];
if (URI_ALLOW_LIST.stream().noneMatch(uri::startsWith)) {
throw new MCRException("The URI \"" + uri + "\" is forbidden ");
}
MCRBasketEntry entry = new MCRBasketEntry(ids[i], uri);
basket.add(entry);
if (resolveContent) {
entry.resolveContent();
}
}
} else if (Objects.equals(action, "remove")) {
for (String id : ids) {
basket.removeEntry(id);
}
} else if (Objects.equals(action, "up")) {
for (String id : ids) {
basket.up(basket.get(id));
}
} else if (Objects.equals(action, "down")) {
for (String id : ids) {
basket.down(basket.get(id));
}
} else if (Objects.equals(action, "clear")) {
basket.clear();
} else if (Objects.equals(action, "create")) {
String ownerID = req.getParameter("ownerID");
MCRObjectID ownerOID = MCRObjectID.getInstance(ownerID);
MCRBasketPersistence.createDerivateWithBasket(basket, ownerOID);
} else if (Objects.equals(action, "update")) {
MCRBasketPersistence.updateBasket(basket);
} else if (Objects.equals(action, "retrieve")) {
String derivateID = req.getParameter("derivateID");
basket = MCRBasketPersistence.retrieveBasket(derivateID);
type = basket.getType();
MCRBasketManager.setBasketInSession(basket);
} else if (Objects.equals(action, "comment")) {
Document sub = (Document) (job.getRequest().getAttribute("MCRXEditorSubmission"));
String comment = sub.getRootElement().getChildTextTrim("comment");
for (String id : ids) {
basket.get(id).setComment(comment);
}
} else if (Objects.equals(action, "show")) {
req.setAttribute("XSL.Style", type);
Document xml = new MCRBasketXMLBuilder(true).buildXML(basket);
getLayoutService().doLayout(req, res, new MCRJDOMContent(xml));
return;
}
if (referer != null && Objects.equals(redirect, "referer")) {
res.sendRedirect(res.encodeRedirectURL(referer.toString()));
} else if (redirect != null) {
res.sendRedirect(res.encodeRedirectURL(redirect));
} else {
res.sendRedirect(res.encodeRedirectURL(getServletBaseURL() + "MCRBasketServlet?action=show&type=" + type));
}
}
}
| 7,706 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWebsocketDefaultConfigurator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/ws/common/MCRWebsocketDefaultConfigurator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.ws.common;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
/**
* Default mycore configuration for websocket endpoints.
*
* @author Michel Buechner (mcrmibue)
* @author Matthias Eichner
*/
public class MCRWebsocketDefaultConfigurator extends ServerEndpointConfig.Configurator {
public static final String HTTP_SESSION = "http.session";
@Override
public <T> T getEndpointInstance(Class<T> endpointClass) {
return MCRConfiguration2.instantiateClass(endpointClass.getName());
}
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
config.getUserProperties().put(MCRServlet.ATTR_MYCORE_SESSION,
httpSession.getAttribute(MCRServlet.ATTR_MYCORE_SESSION));
config.getUserProperties().put(HTTP_SESSION, httpSession);
}
}
| 1,928 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWebsocketJSONDecoder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/ws/common/MCRWebsocketJSONDecoder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.ws.common;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.websocket.Decoder;
import jakarta.websocket.EndpointConfig;
/**
* Decodes a json string to a gson object.
*
* @author Matthias Eichner
*/
public class MCRWebsocketJSONDecoder implements Decoder.Text<JsonObject> {
@Override
public JsonObject decode(String request) {
return JsonParser.parseString(request).getAsJsonObject();
}
@Override
public void init(EndpointConfig config) {
// nothing to initialize
}
@Override
public void destroy() {
// nothing to destroy
}
@Override
public boolean willDecode(String s) {
return s != null;
}
}
| 1,477 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractEndpoint.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/frontend/ws/endoint/MCRAbstractEndpoint.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.frontend.ws.endoint;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Supplier;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSessionResolver;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.websocket.Session;
/**
* Starting class for all mycore websocket endpoints.
*
* @author Michel Buechner (mcrmibue)
* @author Matthias Eichner
*/
public abstract class MCRAbstractEndpoint {
/**
* Encapsulates a supplier with a mycore session.
*
* @param session the websocket session
* @param supplier the supplier
* @return the result of the supplier
*/
protected <T> T sessionized(Session session, Supplier<T> supplier) {
activate(session);
try {
return supplier.get();
} finally {
passivate(session);
}
}
/**
* Encapsulates a function with a mycore session.
*
* @param session the websocket session
* @param runnable the runnable
*/
protected void sessionized(Session session, Runnable runnable) {
try {
activate(session);
runnable.run();
} finally {
passivate(session);
}
}
/**
* Retrieves the mycore session id from the websocket session and binds
* the current thread with this mycore session.
*
* @param session the websocket session
*/
protected void activate(Session session) {
MCRSessionMgr.unlock();
String mcrSessionKey = MCRServlet.ATTR_MYCORE_SESSION;
Optional<MCRSession> optionalSession = ((MCRSessionResolver) session.getUserProperties()
.get(mcrSessionKey))
.resolveSession();
if (optionalSession.isPresent()) {
MCRSession mcrSession = optionalSession.get();
MCRSessionMgr.setCurrentSession(mcrSession);
} else {
throw new MCRException(
String.format(Locale.ROOT,
"Unable to retrieve the mycore session of websocket %s. The mycore session should be bound to the"
+ " property key %s.",
session.getId(), mcrSessionKey));
}
}
/**
* Releases the mycore session from this thread.
*
* @param session the websocket session
*/
protected void passivate(Session session) {
MCRSessionMgr.releaseCurrentSession();
}
}
| 3,282 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIPCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRIPCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import org.mycore.access.mcrimpl.MCRAccessData;
public interface MCRIPCondition extends MCRCondition<MCRAccessData> {
void set(String ip);
}
| 907 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFalseCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRFalseCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import org.jdom2.Element;
/**
* Implementation of the boolean "false" primitive
*
* @author Matthias Kramm
*/
public class MCRFalseCondition<T> implements MCRCondition<T> {
public MCRFalseCondition() {
}
public boolean evaluate(T o) {
return false;
}
@Override
public String toString() {
return "false";
}
public Element toXML() {
Element cond = new Element("boolean");
cond.setAttribute("operator", "false");
return cond;
}
}
| 1,273 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import org.jdom2.Element;
/**
* @author Frank Lützenkirchen
*/
public interface MCRCondition<T> {
/**
* Returns this condition as a String.
*
* @return a condition string that can be parsed
*/
String toString();
/**
* Returns this condition as an Element.
*
* @return this condition in XML format
*/
Element toXML();
/**
* Evalutates this condition.
* @param o a parameter object
* @return true if this condition is met
*/
boolean evaluate(T o);
}
| 1,302 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNotCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRNotCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import org.jdom2.Element;
/**
* @author Frank Lützenkirchen
*/
public class MCRNotCondition<T> implements MCRCondition<T> {
private MCRCondition<T> child;
public MCRNotCondition(MCRCondition<T> child) {
this.child = child;
}
public MCRCondition<T> getChild() {
return child;
}
@Override
public String toString() {
return "not (" + child + ")";
}
public boolean evaluate(T o) {
return !child.evaluate(o);
}
public Element toXML() {
Element not = new Element("boolean");
not.setAttribute("operator", "not");
not.addContent(child.toXML());
return not;
}
}
| 1,435 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRParseException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRParseException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
public class MCRParseException extends org.mycore.common.MCRException {
private static final long serialVersionUID = 1L;
public MCRParseException(String text) {
super(text);
}
}
| 961 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRBooleanClauseParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRBooleanClauseParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jdom2.Element;
/**
* Class for parsing Boolean clauses
*
* @author Matthias Kramm
* @author Christoph Neidahl (OPNA2608)
*/
public class MCRBooleanClauseParser<T> {
private static Pattern bracket = Pattern.compile("\\([^)(]*\\)");
private static Pattern apostrophe = Pattern.compile("\"[^\"]*?\"");
private static Pattern and = Pattern.compile("[)\\s]+[aA][nN][dD][\\s(]+");
private static Pattern or = Pattern.compile("[)\\s]+[oO][rR][\\s(]+");
private static Pattern bracket_marker = Pattern.compile("@<([0-9]*)>@");
/**
* This both strings are for temporary bracket substitution in case of brackets
* in a text string in a condition like 'title contains "foo (and bar)".
*/
private static String opening_bracket = "%%%%%%%%%%";
private static String closing_bracket = "##########";
private static String extendClauses(final String s, final List<String> l) {
String sintern = s;
while (true) {
Matcher m = bracket_marker.matcher(sintern);
if (m.find()) {
String c = m.group();
String clause = l.get(Integer.parseInt(m.group(1)));
sintern = sintern.replaceAll(c, clause);
} else {
break;
}
}
return sintern;
}
/**
* Parse a complex or simple condition in XML format and put it in an condition object.
*
* @param condition a MyCoRe condition object in XML format
* @return a MyCoRe condition object in the MCRCondition format
*/
public MCRCondition<T> parse(Element condition) {
if (condition == null) {
return defaultRule();
}
if (condition.getName().equalsIgnoreCase("boolean")) {
String operator = condition.getAttributeValue("operator");
if (operator == null) {
throw new MCRParseException("Syntax error: attribute operator not found");
}
if (operator.equalsIgnoreCase("not")) {
Element child = condition.getChildren().get(0);
return new MCRNotCondition<>(parse(child));
} else if (operator.equalsIgnoreCase("and") || operator.equalsIgnoreCase("or")) {
List<Element> children = condition.getChildren();
MCRCondition<T> cond;
if (operator.equalsIgnoreCase("and")) {
MCRAndCondition<T> acond = new MCRAndCondition<>();
for (Object aChildren : children) {
Element child = (Element) aChildren;
acond.addChild(parse(child));
}
cond = acond;
} else {
MCROrCondition<T> ocond = new MCROrCondition<>();
for (Object aChildren : children) {
Element child = (Element) aChildren;
ocond.addChild(parse(child));
}
cond = ocond;
}
return cond;
} else {
return parseSimpleCondition(condition);
}
}
return parseSimpleCondition(condition);
}
/**
* Parse a complex or simple condition in String format and put it in an condition object.
*
* @param s a MyCoRe condition object in String format
* @return a MyCoRe condition object in the MCRCondition format
*/
public MCRCondition<T> parse(String s) throws MCRParseException {
s = s.replaceAll("\t", " ").replaceAll("\n", " ").replaceAll("\r", " ");
if (s.trim().length() == 0 || s.equals("()")) {
return defaultRule();
}
return parse(s, null);
}
private MCRCondition<T> parse(String s, List<String> l) throws MCRParseException {
// initialize if start parsing
if (l == null) {
l = new ArrayList<>();
}
// a empty condition
s = s.trim();
if (s.equals("()")) {
s = "(true)";
}
while (true) {
// replace all bracket expressions with $n
while (s.charAt(0) == '(' && s.charAt(s.length() - 1) == ')'
&& s.substring(1, s.length() - 1).indexOf('(') < 0 && s.substring(1, s.length() - 1).indexOf(')') < 0) {
s = s.trim().substring(1, s.length() - 1).trim();
}
// replace brackets in texts inside "..." with temporary strings
Matcher a = apostrophe.matcher(s); // find bracket pairs
if (a.find()) {
String clause = a.group();
clause = clause.replaceAll("\\(", opening_bracket);
clause = clause.replaceAll("\\)", closing_bracket);
s = s.substring(0, a.start()) + clause + s.substring(a.end());
}
// find bracket pairs and replace text inside brackets with @<number>@
Matcher m = bracket.matcher(s);
if (m.find()) {
String clause = m.group();
s = s.substring(0, m.start()) + "@<" + l.size() + ">@" + s.substring(m.end());
l.add(extendClauses(clause, l));
} else {
break;
}
}
// after replacing bracket pairs check for unmatched parenthis
if ((s.indexOf('(') >= 0) ^ (s.indexOf(')') >= 0)) { // missing opening or closing bracket?
throw new MCRParseException("Syntax error: missing bracket in \"" + s + "\"");
}
/* handle OR */
Matcher m = or.matcher(s);
int last = 0;
MCROrCondition<T> orclause = new MCROrCondition<>();
while (m.find()) {
int l1 = m.start();
if (last >= l1) {
throw new MCRParseException("subclause of OR missing while parsing \"" + s + "\"");
}
MCRCondition<T> c = parse(extendClauses(s.substring(last, l1), l), l);
last = m.end();
orclause.addChild(c);
}
if (last != 0) {
MCRCondition<T> c = parse(extendClauses(s.substring(last), l), l);
orclause.addChild(c);
return orclause;
}
/* handle AND */
m = and.matcher(s);
last = 0;
MCRAndCondition<T> andclause = new MCRAndCondition<>();
while (m.find()) {
int l1 = m.start();
if (last >= l1) {
throw new MCRParseException("subclause of AND missing while parsing \"" + s + "\"");
}
MCRCondition<T> c = parse(extendClauses(s.substring(last, l1), l), l);
last = m.end();
andclause.addChild(c);
}
if (last != 0) {
MCRCondition<T> c = parse(extendClauses(s.substring(last), l), l);
andclause.addChild(c);
return andclause;
}
/* handle NOT */
s = s.trim();
if (s.toLowerCase(Locale.ROOT).startsWith("not ")) {
MCRCondition<T> inverse = parse(extendClauses(s.substring(4), l), l);
return new MCRNotCondition<>(inverse);
}
// expands tokens with previously analysed expressions
s = extendClauses(s, l);
// recusion ONLY if parenthis (can) match
if ((s.indexOf('(') >= 0) && (s.indexOf(')') >= 0)) {
return parse(s, l);
} else {
// replace back brackets in apostrophe
s = s.replaceAll(opening_bracket, "(");
s = s.replaceAll(closing_bracket, ")");
return parseSimpleCondition(s);
}
}
protected MCRCondition<T> parseSimpleCondition(String s) throws MCRParseException {
/* handle specific rules */
if (s.equalsIgnoreCase("true")) {
return new MCRTrueCondition<>();
}
if (s.equalsIgnoreCase("false")) {
return new MCRFalseCondition<>();
}
throw new MCRParseException("Syntax error: " + s); // extendClauses(s,
// l));
}
protected MCRCondition<T> parseSimpleCondition(Element element) throws MCRParseException {
// <boolean operator="true|false" />
String name;
try {
name = element.getAttributeValue("operator").toLowerCase(Locale.ROOT);
} catch (Exception e) {
throw new MCRParseException("Syntax error: attribute operator not found");
}
if (name.equals("true")) {
return new MCRTrueCondition<>();
}
if (name.equals("false")) {
return new MCRFalseCondition<>();
}
throw new MCRParseException("Syntax error: <" + name + ">");
}
protected MCRCondition<T> defaultRule() {
return new MCRTrueCondition<>();
}
}
| 9,742 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROrCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCROrCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
/**
* @author Frank Lützenkirchen
*/
public class MCROrCondition<T> extends MCRSetCondition<T> {
public MCROrCondition() {
super("or");
}
@SafeVarargs
public MCROrCondition(MCRCondition<T>... conditions) {
this();
for (MCRCondition<T> mcrCondition : conditions) {
addChild(mcrCondition);
}
}
@Override
public boolean evaluate(T o) {
return children.stream().anyMatch(child -> child.evaluate(o));
}
}
| 1,251 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSetCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRSetCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.jdom2.Element;
/**
* @author Frank Lützenkirchen
*/
public abstract class MCRSetCondition<T> implements MCRCondition<T> {
public static final String AND = "and";
public static final String OR = "or";
protected String operator;
protected List<MCRCondition<T>> children = new ArrayList<>();
protected MCRSetCondition(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public MCRSetCondition<T> addChild(MCRCondition<T> condition) {
children.add(condition);
return this;
}
public MCRSetCondition<T> addAll(Collection<MCRCondition<T>> conditions) {
children.addAll(conditions);
return this;
}
public List<MCRCondition<T>> getChildren() {
return children;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < children.size(); i++) {
sb.append('(').append(children.get(i)).append(')');
if (i < children.size() - 1) {
sb.append(' ').append(operator.toUpperCase(Locale.ROOT)).append(' ');
}
}
return sb.toString();
}
public Element toXML() {
Element cond = new Element("boolean").setAttribute("operator", operator);
for (MCRCondition<T> child : children) {
cond.addContent(child.toXML());
}
return cond;
}
public abstract boolean evaluate(T o);
}
| 2,388 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAndCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRAndCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
/**
* @author Frank Lützenkirchen
*/
public class MCRAndCondition<T> extends MCRSetCondition<T> {
public MCRAndCondition() {
super("and");
}
@SafeVarargs
public MCRAndCondition(MCRCondition<T>... children) {
this();
for (MCRCondition<T> mcrCondition : children) {
addChild(mcrCondition);
}
}
@Override
public boolean evaluate(T o) {
return children.stream().allMatch(child -> child.evaluate(o));
}
}
| 1,251 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTrueCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/parsers/bool/MCRTrueCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.parsers.bool;
import org.jdom2.Element;
/**
* Implementation of the boolean "true" primitive
*
* @author Matthias Kramm
*/
public class MCRTrueCondition<T> implements MCRCondition<T> {
public MCRTrueCondition() {
}
public boolean evaluate(T o) {
return true;
}
@Override
public String toString() {
return "true";
}
public Element toXML() {
Element cond = new Element("boolean");
cond.setAttribute("operator", "true");
return cond;
}
}
| 1,267 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJMXBridge.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/mbeans/MCRJMXBridge.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.mbeans;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.events.MCRShutdownHandler.Closeable;
public class MCRJMXBridge implements Closeable {
static final WeakReference<MCRJMXBridge> SINGLETON = new WeakReference<>(new MCRJMXBridge());
private static final Logger LOGGER = LogManager.getLogger(MCRJMXBridge.class);
private static java.util.List<WeakReference<ObjectName>> ONAME_LIST = Collections
.synchronizedList(new ArrayList<>());
private static boolean shutdown;
private MCRJMXBridge() {
MCRShutdownHandler.getInstance().addCloseable(this);
}
public static void register(Object mbean, String type, String component) {
if (shutdown) {
return;
}
ObjectName name;
try {
name = getObjectName(type, component);
} catch (MalformedObjectNameException e) {
e.printStackTrace();
return;
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
if (mbs.isRegistered(name)) {
unregister(type, component);
}
mbs.registerMBean(mbean, name);
ONAME_LIST.add(new WeakReference<>(name));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unregister(String type, String component) {
if (shutdown) {
return;
}
ObjectName name;
try {
name = getObjectName(type, component);
} catch (MalformedObjectNameException e) {
e.printStackTrace();
return;
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
if (mbs.isRegistered(name)) {
mbs.unregisterMBean(name);
}
// As WeakReference does not overwrite Object.equals():
ONAME_LIST.removeIf(wr -> name.equals(wr.get()));
} catch (Exception e) {
e.printStackTrace();
}
}
private static ObjectName getObjectName(String type, String component) throws MalformedObjectNameException {
return new ObjectName(
MCRConfiguration2.getString("MCR.NameOfProject").orElse("MyCoRe-Application").replace(':', ' ')
+ ":type="
+ type + ",component=" + component);
}
@Override
public void prepareClose() {
shutdown = true;
}
@Override
public void close() {
LOGGER.debug("Shutting down {}", MCRJMXBridge.class.getSimpleName());
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Iterator<WeakReference<ObjectName>> wrIterator = ONAME_LIST.iterator();
while (wrIterator.hasNext()) {
try {
ObjectName objectName = wrIterator.next().get();
LOGGER.debug("Unregister {}", objectName.getCanonicalName());
mbs.unregisterMBean(objectName);
wrIterator.remove();
} catch (Exception e) {
e.printStackTrace();
}
}
SINGLETON.clear();
}
public static ObjectInstance getMBean(String type, String component)
throws MalformedObjectNameException, InstanceNotFoundException {
ObjectName name = getObjectName(type, component);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
if (mbs.isRegistered(name)) {
return mbs.getObjectInstance(name);
}
return null;
}
}
| 4,832 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCompressServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/zipper/MCRCompressServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.zipper;
import static org.mycore.access.MCRAccessManager.PERMISSION_READ;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRParameterizedTransformer;
import org.mycore.common.xml.MCRLayoutService;
import org.mycore.common.xml.MCRXMLFunctions;
import org.mycore.common.xsl.MCRParameterCollector;
import org.mycore.datamodel.common.MCRISO8601Date;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* This servlet delivers the contents of MCROjects to the client in
* container files (see classes extending this servlet). Read permission is required.
* There are three modes
* <ol>
* <li>if id=mycoreobjectID (delivers the metadata, including all derivates)</li>
* <li>if id=derivateID (delivers all files of the derivate)</li>
* <li>if id=derivateID/directoryPath (delivers all files in the given directory of the derivate)</li>
* </ol>
*
* "id" maybe specified as {@link HttpServletRequest#getPathInfo()} or as
* {@link MCRServlet#getProperty(HttpServletRequest, String)}.
* @author Thomas Scheffler (yagee)
*
*/
public abstract class MCRCompressServlet<T extends AutoCloseable> extends MCRServlet {
private static final long serialVersionUID = 1L;
protected static String KEY_OBJECT_ID = MCRCompressServlet.class.getCanonicalName() + ".object";
protected static String KEY_PATH = MCRCompressServlet.class.getCanonicalName() + ".path";
private static Pattern PATH_INFO_PATTERN = Pattern.compile("\\A([\\w]+)/([\\w/]+)\\z");
private static Logger LOGGER = LogManager.getLogger(MCRCompressServlet.class);
@Override
protected void think(MCRServletJob job) throws Exception {
HttpServletRequest req = job.getRequest();
//id parameter for backward compatibility
String paramid = getProperty(req, "id");
if (paramid == null) {
String pathInfo = req.getPathInfo();
if (pathInfo != null) {
paramid = pathInfo.substring(1);
}
}
if (paramid == null) {
job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "What should I do?");
return;
}
Matcher ma = PATH_INFO_PATTERN.matcher(paramid);
//path & directory
MCRObjectID id;
String path;
try {
if (ma.find()) {
id = MCRObjectID.getInstance(ma.group(1));
path = ma.group(2);
} else {
id = MCRObjectID.getInstance(paramid);
path = null;
}
} catch (MCRException e) {
String objId = ma.find() ? ma.group(1) : paramid;
job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "ID is not valid: " + objId);
return;
}
boolean readPermission = id.getTypeId().equals("derivate") ? MCRAccessManager
.checkDerivateContentPermission(id, PERMISSION_READ)
: MCRAccessManager.checkPermission(id, PERMISSION_READ);
if (!readPermission) {
job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, "You may not read " + id);
return;
}
req.setAttribute(KEY_OBJECT_ID, id);
req.setAttribute(KEY_PATH, path);
}
@Override
protected void render(MCRServletJob job, Exception ex) throws Exception {
if (ex != null) {
//we cannot handle it ourself
throw ex;
}
if (job.getResponse().isCommitted()) {
return;
}
MCRObjectID id = (MCRObjectID) job.getRequest().getAttribute(KEY_OBJECT_ID);
String path = (String) job.getRequest().getAttribute(KEY_PATH);
try (ServletOutputStream sout = job.getResponse().getOutputStream()) {
StringBuffer requestURL = job.getRequest().getRequestURL();
if (job.getRequest().getQueryString() != null) {
requestURL.append('?').append(job.getRequest().getQueryString());
}
MCRISO8601Date mcriso8601Date = new MCRISO8601Date();
mcriso8601Date.setDate(new Date());
String comment = "Created by " + requestURL + " at " + mcriso8601Date.getISOString();
try (T container = createContainer(sout, comment)) {
job.getResponse().setContentType(getMimeType());
String filename = getFileName(id, path);
job.getResponse().addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
if (id.getTypeId().equals("derivate")) {
sendDerivate(id, path, container);
} else {
sendObject(id, job, container);
}
disposeContainer(container);
}
}
}
private void sendObject(MCRObjectID id, MCRServletJob job, T container) throws Exception {
MCRContent content = MCRXMLMetadataManager.instance().retrieveContent(id);
if (content == null) {
throw new FileNotFoundException("Could not find object: " + id);
}
long lastModified = MCRXMLMetadataManager.instance().getLastModified(id);
HttpServletRequest req = job.getRequest();
byte[] metaDataContent = getMetaDataContent(content, req);
sendMetadataCompressed("metadata.xml", metaDataContent, lastModified, container);
// zip all derivates
List<Element> li = content.asXML().getRootElement().getChild("structure").getChild("derobjects")
.getChildren("derobject");
for (Element el : li) {
if (el.getAttributeValue("inherited").equals("0")) {
String ownerID = el.getAttributeValue("href", XLINK_NAMESPACE);
MCRObjectID derId = MCRObjectID.getInstance(ownerID);
// here the access check is tested only against the derivate
if (MCRAccessManager.checkDerivateContentPermission(derId, PERMISSION_READ)
&& MCRXMLFunctions.isDisplayedEnabledDerivate(ownerID)) {
sendDerivate(derId, null, container);
}
}
}
}
private byte[] getMetaDataContent(MCRContent content, HttpServletRequest req) throws Exception {
// zip the object's Metadata
MCRParameterCollector parameters = new MCRParameterCollector(req);
if (parameters.getParameter("Style", null) == null) {
parameters.setParameter("Style", "compress");
}
MCRContentTransformer contentTransformer = MCRLayoutService.getContentTransformer(content.getDocType(),
parameters);
ByteArrayOutputStream out = new ByteArrayOutputStream(32 * 1024);
if (contentTransformer instanceof MCRParameterizedTransformer parameterizedTransformer) {
parameterizedTransformer.transform(content, out, parameters);
} else {
contentTransformer.transform(content, out);
}
return out.toByteArray();
}
private void sendDerivate(MCRObjectID id, String path, T container) throws IOException {
MCRPath resolvedPath = MCRPath.getPath(id.toString(), path == null ? "/" : path);
if (!Files.exists(resolvedPath)) {
throw new NoSuchFileException(id.toString(), path, "Could not find path " + resolvedPath);
}
if (Files.isRegularFile(resolvedPath)) {
BasicFileAttributes attrs = Files.readAttributes(resolvedPath, BasicFileAttributes.class);
sendCompressedFile(resolvedPath, attrs, container);
LOGGER.debug("file {} zipped", resolvedPath);
return;
}
// root is a directory
Files.walkFileTree(resolvedPath, new CompressVisitor<>(this, container));
}
private String getFileName(MCRObjectID id, String path) {
if (path == null || path.equals("")) {
return new MessageFormat("{0}.{1}", Locale.ROOT).format(new Object[] { id, getFileExtension() });
} else {
return new MessageFormat("{0}-{1}.{2}", Locale.ROOT).format(
new Object[] { id, path.replaceAll("/", "-"), getFileExtension() });
}
}
/**
* Constructs a path name in form of {ownerID}+'/'+{path} or {ownerID} if path is root component.
* @param path absolute path
*/
protected String getFilename(MCRPath path) {
return path.getNameCount() == 0 ? path.getOwner()
: path.getOwner() + '/'
+ path.getRoot().relativize(path);
}
protected abstract void sendCompressedDirectory(MCRPath file, BasicFileAttributes attrs, T container)
throws IOException;
protected abstract void sendCompressedFile(MCRPath file, BasicFileAttributes attrs, T container) throws IOException;
protected abstract void sendMetadataCompressed(String fileName, byte[] content, long modified, T container)
throws IOException;
protected abstract String getMimeType();
protected abstract String getFileExtension();
protected abstract T createContainer(ServletOutputStream sout, String comment);
protected abstract void disposeContainer(T container) throws IOException;
private static class CompressVisitor<T extends AutoCloseable> extends SimpleFileVisitor<Path> {
private MCRCompressServlet<T> impl;
private T container;
CompressVisitor(MCRCompressServlet<T> impl, T container) {
this.impl = impl;
this.container = container;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
impl.sendCompressedDirectory(MCRPath.toMCRPath(dir), attrs, container);
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
impl.sendCompressedFile(MCRPath.toMCRPath(file), attrs, container);
LOGGER.debug("file {} zipped", file);
return super.visitFile(file, attrs);
}
}
}
| 12,029 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTarServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/zipper/MCRTarServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.zipper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.niofs.MCRPath;
import jakarta.servlet.ServletOutputStream;
/**
* Uses TAR format to deliver requested content.
*
* This servlet produces TAR files as defined in POSIX.1-2001 standard and UTF-8 encoding for file names.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRTarServlet extends MCRCompressServlet<TarArchiveOutputStream> {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger(MCRTarServlet.class);
@Override
protected void sendCompressedDirectory(MCRPath file, BasicFileAttributes attrs,
TarArchiveOutputStream container) throws IOException {
TarArchiveEntry entry = new TarArchiveEntry(getFilename(file) + '/');
entry.setModTime(attrs.lastModifiedTime().toMillis());
container.putArchiveEntry(entry);
container.closeArchiveEntry();
}
@Override
protected void sendCompressedFile(MCRPath file, BasicFileAttributes attrs,
TarArchiveOutputStream container) throws IOException {
TarArchiveEntry entry = new TarArchiveEntry(getFilename(file));
entry.setModTime(attrs.lastModifiedTime().toMillis());
entry.setSize(attrs.size());
container.putArchiveEntry(entry);
try {
Files.copy(file, container);
} finally {
container.closeArchiveEntry();
}
}
@Override
protected void sendMetadataCompressed(String fileName, byte[] content, long lastModified,
TarArchiveOutputStream container) throws IOException {
TarArchiveEntry entry = new TarArchiveEntry(fileName);
entry.setModTime(lastModified);
entry.setSize(content.length);
container.putArchiveEntry(entry);
container.write(content);
container.closeArchiveEntry();
}
@Override
protected String getMimeType() {
return "application/x-tar";
}
@Override
protected String getFileExtension() {
return "tar";
}
@Override
protected TarArchiveOutputStream createContainer(ServletOutputStream sout, String comment) {
LOGGER.info("Constructing tar archive: {}", comment);
TarArchiveOutputStream tout = new TarArchiveOutputStream(sout, "UTF8");
tout.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
tout.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
return tout;
}
@Override
protected void disposeContainer(TarArchiveOutputStream container) throws IOException {
container.finish();
}
}
| 3,682 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRZipServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/zipper/MCRZipServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.zipper;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.Deflater;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.mycore.datamodel.niofs.MCRPath;
import jakarta.servlet.ServletOutputStream;
/**
* Uses ZIP format to deliver requested content.
* {@link Deflater#BEST_COMPRESSION} is used for compression.
* @author Thomas Scheffler
*/
public class MCRZipServlet extends MCRCompressServlet<ZipArchiveOutputStream> {
private static final long serialVersionUID = 1L;
@Override
protected void sendCompressedDirectory(MCRPath file, BasicFileAttributes attrs, ZipArchiveOutputStream container)
throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(getFilename(file) + "/");
entry.setTime(attrs.lastModifiedTime().toMillis());
container.putArchiveEntry(entry);
container.closeArchiveEntry();
}
@Override
protected void sendCompressedFile(MCRPath file, BasicFileAttributes attrs, ZipArchiveOutputStream container)
throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(getFilename(file));
entry.setTime(attrs.lastModifiedTime().toMillis());
entry.setSize(attrs.size());
container.putArchiveEntry(entry);
try {
Files.copy(file, container);
} finally {
container.closeArchiveEntry();
}
}
@Override
protected void sendMetadataCompressed(String fileName, byte[] content, long lastModified,
ZipArchiveOutputStream container) throws IOException {
ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
entry.setSize(content.length);
entry.setTime(lastModified);
container.putArchiveEntry(entry);
container.write(content);
container.closeArchiveEntry();
}
@Override
protected String getMimeType() {
return "application/zip";
}
@Override
protected String getFileExtension() {
return "zip";
}
@Override
protected ZipArchiveOutputStream createContainer(ServletOutputStream sout, String comment) {
ZipArchiveOutputStream zout = new ZipArchiveOutputStream(new BufferedOutputStream(sout));
zout.setComment(comment);
zout.setLevel(Deflater.BEST_COMPRESSION);
return zout;
}
@Override
protected void disposeContainer(ZipArchiveOutputStream container) throws IOException {
container.finish();
}
}
| 3,410 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRetryHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/http/MCRRetryHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.http;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.protocol.HttpContext;
/**
* Handles request retries.
* @author Thomas Scheffler (yagee)
*/
class MCRRetryHandler implements HttpRequestRetryHandler {
int maxExecutionCount;
MCRRetryHandler(int maxExecutionCount) {
super();
this.maxExecutionCount = maxExecutionCount;
}
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= maxExecutionCount) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return true;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return true;
}
return !(exception instanceof SSLException);
}
}
| 1,993 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIdleConnectionMonitorThread.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/http/MCRIdleConnectionMonitorThread.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.http;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.HttpClientConnectionManager;
/**
* Monitors a {@link HttpClientConnectionManager} for expired or idle connections.
*
* These connections will be closed every 5 seconds.
* @author Thomas Scheffler (yagee)
*/
public class MCRIdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public MCRIdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Close inactive connection
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
| 1,962 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHttpUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/http/MCRHttpUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.http;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.mycore.common.MCRCoreVersion;
import org.mycore.common.config.MCRConfiguration2;
public class MCRHttpUtils {
public static CloseableHttpClient getHttpClient(HttpClientConnectionManager connectionManager, int maxConnections) {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(StandardCharsets.UTF_8).build();
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true)
.setSoReuseAddress(true).build();
//setup http client
return HttpClients.custom().setConnectionManager(connectionManager)
.setUserAgent(getHttpUserAgent()).setRetryHandler(new MCRRetryHandler(maxConnections))
.setDefaultRequestConfig(requestConfig).setDefaultConnectionConfig(connectionConfig)
.setDefaultSocketConfig(socketConfig).build();
}
public static String getHttpUserAgent() {
return String.format(Locale.ROOT, "MyCoRe/%s (%s; java %s)", MCRCoreVersion.getCompleteVersion(),
MCRConfiguration2.getString("MCR.NameOfProject").orElse("undefined"),
System.getProperty("java.version"));
}
public static PoolingHttpClientConnectionManager getConnectionManager(int maxConnections) {
//configure connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(maxConnections);
connectionManager.setMaxTotal(maxConnections);
connectionManager.setValidateAfterInactivity(30000);
return connectionManager;
}
public static HttpHost getHttpHost(String serverUrl) {
HttpHost host = null;
//determine host name
HttpGet serverGet = new HttpGet(serverUrl);
final URI requestURI = serverGet.getURI();
if (requestURI.isAbsolute()) {
host = URIUtils.extractHost(requestURI);
}
return host;
}
}
| 3,446 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRQueryParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/fieldquery/MCRQueryParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRAndCondition;
import org.mycore.parsers.bool.MCRBooleanClauseParser;
import org.mycore.parsers.bool.MCRCondition;
import org.mycore.parsers.bool.MCRNotCondition;
import org.mycore.parsers.bool.MCROrCondition;
import org.mycore.parsers.bool.MCRParseException;
import org.mycore.parsers.bool.MCRSetCondition;
/**
* Parses query conditions for use in MCRSearcher.
*
* @author Frank Lützenkirchen
*/
public class MCRQueryParser extends MCRBooleanClauseParser<Void> {
/**
* Parses XML element containing a simple query condition
*
* @param e
* the 'condition' element
* @return the parsed MCRQueryCondition object
*/
@Override
protected MCRCondition<Void> parseSimpleCondition(Element e) throws MCRParseException {
String name = e.getName();
if (!name.equals("condition")) {
throw new MCRParseException("Not a valid <" + name + ">");
}
String field = e.getAttributeValue("field");
String opera = e.getAttributeValue("operator");
String value = e.getAttributeValue("value");
return buildConditions(field, opera, value);
}
/**
* Builds a new MCRCondition from parsed elements
*
* @param field
* one or more field names, separated by comma
* @param oper
* the condition operator
* @param value
* the condition value
*/
private MCRCondition<Void> buildConditions(String field, String oper, String value) {
if (field.contains(",")) { // Multiple fields in one condition, combine with OR
StringTokenizer st = new StringTokenizer(field, ", ");
MCROrCondition<Void> oc = new MCROrCondition<>();
while (st.hasMoreTokens()) {
oc.addChild(buildConditions(st.nextToken(), oper, value));
}
return oc;
} else if (field.contains("-")) { // date condition von-bis
StringTokenizer st = new StringTokenizer(field, "- ");
String fieldFrom = st.nextToken();
String fieldTo = st.nextToken();
if (oper.equals("=")) {
// von-bis = x --> (von <= x) AND (bis >= x)
MCRAndCondition<Void> ac = new MCRAndCondition<>();
ac.addChild(buildCondition(fieldFrom, "<=", value));
ac.addChild(buildCondition(fieldTo, ">=", value));
return ac;
} else if (oper.contains("<")) {
return buildCondition(fieldFrom, oper, value);
} else {
// oper.contains( ">" )
return buildCondition(fieldTo, oper, value);
}
} else {
return buildCondition(field, oper, value);
}
}
/**
* Builds a new MCRQueryCondition
*
* @param field
* the name of the search field
* @param oper
* the condition operator
* @param value
* the condition value
*/
private MCRQueryCondition buildCondition(String field, String oper, String value) {
if (Objects.equals(value, "TODAY")) {
value = getToday();
}
return new MCRQueryCondition(field, oper, value);
}
private String getToday() {
return LocalDate.now(ZoneOffset.systemDefault())
.format(DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY));
}
/** Pattern for MCRQueryConditions expressed as String */
private static Pattern pattern = Pattern.compile("([^ \t\r\n]+)\\s+([^ \t\r\n]+)\\s+([^ \"\t\r\n]+|\"[^\"]*\")");
/**
* Parses a String containing a simple query condition, for example: (title
* contains "Java") and (creatorID = "122132131")
*
* @param s
* the condition as a String
* @return the parsed MCRQueryCondition object
*/
@Override
protected MCRCondition<Void> parseSimpleCondition(String s) throws MCRParseException {
Matcher m = pattern.matcher(s);
if (!m.find()) {
return super.parseSimpleCondition(s);
}
String field = m.group(1);
String operator = m.group(2);
String value = m.group(3);
if (value.startsWith("\"") && value.endsWith("\"")) {
value = value.substring(1, value.length() - 1);
}
return buildConditions(field, operator, value);
}
@Override
public MCRCondition<Void> parse(Element condition) throws MCRParseException {
MCRCondition<Void> cond = super.parse(condition);
return normalizeCondition(cond);
}
@Override
public MCRCondition<Void> parse(String s) throws MCRParseException {
MCRCondition<Void> cond = super.parse(s);
return normalizeCondition(cond);
}
/**
* Normalizes a parsed query condition. AND/OR conditions that just have one
* child will be replaced with that child. NOT(NOT(X)) will be normalized to X.
* (A AND (b AND c)) will be normalized to (A AND B AND C), same for nested ORs.
* AND/OR/NOT conditions with no child conditions will be removed.
* Conditions that use the operator "contains" will be splitted into multiple
* simpler conditions if the condition value contains phrases surrounded
* by '...' or wildcard search with * or ?.
*/
public static MCRCondition<Void> normalizeCondition(MCRCondition<Void> cond) {
if (cond == null) {
return null;
} else if (cond instanceof MCRSetCondition<Void> sc) {
List<MCRCondition<Void>> children = sc.getChildren();
sc = sc instanceof MCRAndCondition ? new MCRAndCondition<>() : new MCROrCondition<>();
for (MCRCondition<Void> child : children) {
MCRCondition<Void> normalizedChild = normalizeCondition(child);
if (normalizedChild != null) {
if (normalizedChild instanceof MCRSetCondition
&& sc.getOperator().equals(((MCRSetCondition) normalizedChild).getOperator())) {
// Replace (a AND (b AND c)) with (a AND b AND c), same for OR
sc.addAll(((MCRSetCondition<Void>) normalizedChild).getChildren());
} else {
sc.addChild(normalizedChild);
}
}
}
children = sc.getChildren();
if (children.size() == 0) {
return null; // Completely remove empty AND condition
} else if (children.size() == 1) {
return children.get(0); // Replace AND with just one child
} else {
return sc;
}
} else if (cond instanceof MCRNotCondition<Void> nc) {
MCRCondition<Void> child = normalizeCondition(nc.getChild());
if (child == null) {
return null; // Remove empty NOT
} else if (child instanceof MCRNotCondition) {
return normalizeCondition(((MCRNotCondition<Void>) child).getChild());
} else {
return new MCRNotCondition<>(child);
}
} else if (cond instanceof MCRQueryCondition qc) {
if (!qc.getOperator().equals("contains")) {
return qc;
}
// Normalize value when contains operator is used
List<String> values = new ArrayList<>();
StringBuilder phrase = null;
StringTokenizer st = new StringTokenizer(qc.getValue(), " ");
while (st.hasMoreTokens()) {
String value = st.nextToken();
if (phrase != null) {
// we are within phrase
if (value.endsWith("'")) {
// end of phrase
value = phrase + " " + value;
values.add(value);
phrase = null;
} else {
// in middle of phrase
phrase.append(' ').append(value);
}
} else if (value.startsWith("'")) {
// begin of phrase
if (value.endsWith("'")) {
// one-word phrase
values.add(value.substring(1, value.length() - 1));
} else {
phrase = new StringBuilder(value);
}
} else if (value.startsWith("-'")) {
// begin of NOT phrase
if (value.endsWith("'")) {
// one-word phrase
values.add("-" + value.substring(2, value.length() - 1));
} else {
phrase = new StringBuilder(value);
}
} else {
values.add(value);
}
}
MCRAndCondition<Void> ac = new MCRAndCondition<>();
for (String value : values) {
if (value.startsWith("'")) {
ac.addChild(new MCRQueryCondition(qc.getFieldName(), "phrase", value.substring(1,
value.length() - 1)));
} else if (value.startsWith("-'")) {
ac.addChild(new MCRNotCondition<>(
new MCRQueryCondition(qc.getFieldName(), "phrase", value.substring(2, value.length() - 1))));
} else if (value.contains("*") || value.contains("?")) {
ac.addChild(new MCRQueryCondition(qc.getFieldName(), "like", value));
} else if (value.startsWith("-")) {
// -word means "NOT word"
MCRCondition<Void> subCond = new MCRQueryCondition(qc.getFieldName(), "contains",
value.substring(1));
ac.addChild(new MCRNotCondition<>(subCond));
} else {
ac.addChild(new MCRQueryCondition(qc.getFieldName(), "contains", value));
}
}
if (values.size() == 1) {
return ac.getChildren().get(0);
} else {
return ac;
}
} else {
return cond;
}
}
/** Used for input validation in editor search form */
public static boolean validateQueryExpression(String query) {
try {
MCRCondition<Void> cond = new MCRQueryParser().parse(query);
return cond != null;
} catch (Throwable t) {
return false;
}
}
}
| 11,769 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRQuery.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/fieldquery/MCRQuery.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRCondition;
/** Represents a query with its condition and optional parameters */
public class MCRQuery {
private static final Logger LOGGER = LogManager.getLogger(MCRQuery.class);
/** The query condition */
private MCRCondition<Void> cond;
/** The maximum number of results, default is 0 = unlimited */
private int maxResults = 0;
/** The number of results per page, default is 10 */
private int numPerPage = 10;
/** A list of MCRSortBy criteria, may be empty */
private List<MCRSortBy> sortBy = new ArrayList<>();
/** A List of SOLR fields they should be return in the response */
private List<String> returnFields = new ArrayList<>();
/** A cached xml representation of the query */
private Document doc = null;
/**
* Builds a new MCRQuery object without sort criteria and unlimited results.
*
* @param cond
* the query conditions
*/
public MCRQuery(MCRCondition<Void> cond) {
this.cond = MCRQueryParser.normalizeCondition(cond);
}
/**
* Builds a new MCRQuery object with sort criteria and limited number of
* results.
*
* @param cond
* the query conditions
* @param sortBy
* a list of MCRSortBy criteria for sorting the results
* @param maxResults
* the maximum number of results to return
* @param returnFields
* the return fields for the SOLR parameter fl
*/
public MCRQuery(MCRCondition<Void> cond, List<MCRSortBy> sortBy, int maxResults, List<String> returnFields) {
this.cond = MCRQueryParser.normalizeCondition(cond);
this.setSortBy(sortBy);
setMaxResults(maxResults);
this.setReturnFields(returnFields);
}
/**
* Returns the query condition
*
* @return the query condition
*/
public MCRCondition<Void> getCondition() {
return cond;
}
/**
* Returns the maximum number of results the query should return
*
* @return the maximum number of results, or 0
*/
public int getMaxResults() {
return maxResults;
}
/**
* Sets the maximum number of results the query should return. Default is 0
* which means "return all results".
*
* @param maxResults
* the maximum number of results
*/
public void setMaxResults(int maxResults) {
if (maxResults < 0) {
this.maxResults = 0;
} else {
this.maxResults = maxResults;
}
doc = null;
}
/**
* Sets the maximum number of results the query should return. Default is 0
* which means "return all results".
*
* @param maxResultsString
* the maximum number of results as String
*/
public void setMaxResults(String maxResultsString) {
doc = null;
if (maxResultsString == null || maxResultsString.length() == 0) {
this.maxResults = 0;
return;
}
try {
this.maxResults = Integer.parseInt(maxResultsString);
} catch (NumberFormatException e) {
LOGGER.warn("The Results maxstring " + maxResultsString + " contains not an integer, 0 as default is set");
this.maxResults = 0;
}
}
/**
* Returns the number of results per page that the query should return
*
* @return the number of results per page
*/
public int getNumPerPage() {
return numPerPage;
}
/**
* Sets the number of results per page that the query should return. Default is 10.
*
* @param numPerPage
* the number of results per page
*/
public void setNumPerPage(int numPerPage) {
if (numPerPage < 0) {
this.numPerPage = 10;
} else {
this.numPerPage = numPerPage;
}
doc = null;
}
/**
* Sets the number of results per page that the query should return. Default is 10.
*
* @param numPerPageString
* the number of results per page as String
*/
public void setNumPerPage(String numPerPageString) {
doc = null;
if (numPerPageString == null || numPerPageString.length() == 0) {
this.numPerPage = 10;
return;
}
try {
this.numPerPage = Integer.parseInt(numPerPageString);
} catch (NumberFormatException e) {
LOGGER.warn("The numPerPage string " + numPerPageString + " contains not an integer, 10 as default is set");
this.numPerPage = 10;
}
}
/**
* Returns the list of MCRSortBy criteria for sorting query results
*
* @return a list of MCRSortBy objects, may be empty
*/
public List<MCRSortBy> getSortBy() {
return sortBy;
}
/**
* Sets the sort criteria for the query results
*
* @param sortBy
* a list of MCRSortBy objects, may be empty
*/
public void setSortBy(List<MCRSortBy> sortBy) {
if (sortBy == null) {
sortBy = new ArrayList<>();
}
this.sortBy = sortBy;
doc = null;
}
/**
* Sets the sort criteria for the query results
*
* @param sortBy
* a MCRSortBy object
*/
public void setSortBy(MCRSortBy sortBy) {
this.sortBy = new ArrayList<>();
if (sortBy != null) {
this.sortBy.add(sortBy);
}
doc = null;
}
/**
* Returns the list of SOLR-fields they should return for a query
* results
*
* @return a list of field names, may be empty
*/
public List<String> getReturnFields() {
return returnFields;
}
/**
* Returns the CSV-list of SOLR-fields they should return for a query
* results
*
* @return a list of field names, may be empty
*/
public String getReturnFieldsAsString() {
return returnFields.stream().collect(Collectors.joining(","));
}
/**
* Sets the return fields list for the query results
*
* @param returnFields
* a list of SOLR return fields, may be empty
*/
public void setReturnFields(List<String> returnFields) {
this.returnFields = returnFields == null ? new ArrayList<>() : returnFields;
}
/**
* Sets the return fields as String for the query results
*
* @param returnFields
* a CSV-list of SOLR return fields, may be empty
*/
public void setReturnFields(String returnFields) {
if (returnFields == null || returnFields.length() == 0) {
this.returnFields = new ArrayList<>();
return;
}
this.returnFields = Arrays.asList(returnFields.split(","));
}
/**
* Builds a XML representation of the query
*
* @return a XML document containing all query parameters
*/
public synchronized Document buildXML() {
if (doc == null) {
Element query = new Element("query");
query.setAttribute("maxResults", String.valueOf(maxResults));
query.setAttribute("numPerPage", String.valueOf(numPerPage));
if (sortBy != null && sortBy.size() > 0) {
Element sortByElem = new Element("sortBy");
query.addContent(sortByElem);
for (MCRSortBy sb : sortBy) {
Element ref = new Element("field");
ref.setAttribute("name", sb.getFieldName());
ref.setAttribute("order", sb.getSortOrder() ? "ascending" : "descending");
sortByElem.addContent(ref);
}
}
if (returnFields != null && returnFields.size() > 0) {
Element returns = new Element("returnFields");
returns.setText(returnFields.stream().collect(Collectors.joining(",")));
query.addContent(returns);
}
Element conditions = new Element("conditions");
query.addContent(conditions);
conditions.setAttribute("format", "xml");
conditions.addContent(cond.toXML());
doc = new Document(query);
}
return doc;
}
/**
* Parses a XML representation of a query.
*
* @param doc
* the XML document
* @return the parsed MCRQuery
*/
public static MCRQuery parseXML(Document doc) {
Element xml = doc.getRootElement();
Element conditions = xml.getChild("conditions");
MCRQuery query = null;
if (conditions.getAttributeValue("format", "xml").equals("xml")) {
Element condElem = conditions.getChildren().get(0);
query = new MCRQuery(new MCRQueryParser().parse(condElem));
} else {
String queryString = conditions.getTextTrim();
query = new MCRQuery(new MCRQueryParser().parse(queryString));
}
String max = xml.getAttributeValue("maxResults", "");
query.setMaxResults(max);
String num = xml.getAttributeValue("numPerPage", "");
query.setNumPerPage(num);
List<MCRSortBy> sortBy = null;
Element sortByElem = xml.getChild("sortBy");
if (sortByElem != null) {
List<Element> children = sortByElem.getChildren();
sortBy = new ArrayList<>(children.size());
for (Element sortByChild : children) {
String name = sortByChild.getAttributeValue("name");
String ad = sortByChild.getAttributeValue("order");
boolean direction = Objects.equals(ad, "ascending") ? MCRSortBy.ASCENDING : MCRSortBy.DESCENDING;
sortBy.add(new MCRSortBy(name, direction));
}
}
if (sortBy != null) {
query.setSortBy(sortBy);
}
Element returns = xml.getChild("returnFields");
if (returns != null) {
query.setReturnFields(returns.getText());
}
return query;
}
}
| 11,199 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRQueryCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/fieldquery/MCRQueryCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRCondition;
/**
* Represents a simple query condition, which consists of a search field,
* a value and a comparison operator.
*
* @author Frank Lützenkirchen
*/
public class MCRQueryCondition extends MCRFieldBaseValue implements MCRCondition<Void> {
/** The comparison operator used in this condition */
private String operator;
public MCRQueryCondition(String fieldName, String operator, String value) {
super(fieldName, value);
this.operator = operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
/** Returns the comparison operator used in this condition */
public String getOperator() {
return this.operator;
}
@Override
public String toString() {
return getFieldName() + " " + getOperator() + " \"" + getValue() + "\"";
}
public Element toXML() {
Element condition = new Element("condition");
condition.setAttribute("field", getFieldName());
condition.setAttribute("operator", operator);
condition.setAttribute("value", getValue());
return condition;
}
public boolean evaluate(Void o) {
//there is no 'void' instance
throw new UnsupportedOperationException();
}
}
| 2,102 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSortBy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/fieldquery/MCRSortBy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
/**
* Represents a single sort criteria for sorting query results.
* Each MCRSortBy defines one field to sort by, and the order
* (ascending or descending).
*
* @author Frank Lützenkirchen
*/
public class MCRSortBy {
/** Sort this field in ascending order */
public static final boolean ASCENDING = true;
/** Sort this field in descending order */
public static final boolean DESCENDING = false;
/** The field to sort by */
private String fieldName;
/** Sort order of this field */
private boolean order = ASCENDING;
/**
* Creates a new sort criteria
*
* @param fieldName the field to sort by
* @param order the sort order (ascending or descending)
*
* @see #ASCENDING
* @see #DESCENDING
*/
public MCRSortBy(String fieldName, boolean order) {
this.fieldName = fieldName;
this.order = order;
}
public String getFieldName() {
return fieldName;
}
/**
* Returns the sort order for this field.
*
* @see #ASCENDING
* @see #DESCENDING
*
* @return true when order is {@link MCRSortBy#ASCENDING} or false whenorder is {@link MCRSortBy#DESCENDING}
*/
public boolean getSortOrder() {
return order;
}
}
| 2,051 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFieldBaseValue.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/fieldquery/MCRFieldBaseValue.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.fieldquery;
import org.jdom2.Element;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
public class MCRFieldBaseValue {
/**
* The field this value belongs to
*/
protected String fieldName;
/**
* The fields's value, as a String
*/
protected String value;
public MCRFieldBaseValue() {
super();
}
public MCRFieldBaseValue(String name, String value) {
this.fieldName = name;
this.value = value;
}
public void setFieldName(String fieldName) {
if (fieldName == null) {
throw new NullPointerException("field name cannot be null.");
}
this.fieldName = fieldName;
}
/**
* Returns the field this value belongs to
*/
public String getFieldName() {
return fieldName;
}
/**
* Sets or updates the field value
*
* @param value the value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Returns the value of the field as a String
*
* @return the value of the field as a String
*/
public String getValue() {
return value;
}
/**
* Builds a XML representation of this field's value
*
* @return a 'field' element with attribute 'name' and the value as element
* content
*/
public Element buildXML() {
Element eField = new Element("field", MCRConstants.MCR_NAMESPACE);
eField.setAttribute("name", getFieldName());
eField.addContent(value);
return eField;
}
/**
* Parses a XML representation of a field value
*
* @param xml
* the field value as XML element
* @return the parsed MCRFieldValue object
*/
public static MCRFieldBaseValue parseXML(Element xml) {
String name = xml.getAttributeValue("name", "");
String value = xml.getText();
if (name.length() == 0) {
throw new MCRException("Field value attribute 'name' is empty");
}
if (value.length() == 0) {
throw new MCRException("Field value is empty");
}
return new MCRFieldBaseValue(name, value);
}
@Override
public String toString() {
return getFieldName() + " = " + value;
}
}
| 3,092 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectStaticContentGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/staticcontent/MCRObjectStaticContentGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.staticcontent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
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.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRObjectStaticContentGenerator {
public static final String TRANSFORMER_SUFFIX = ".Transformer";
public static final String ROOT_PATH_SUFFIX = ".Path";
private static final Logger LOGGER = LogManager.getLogger();
protected static final String CONFIG_ID_PREFIX = "MCR.Object.Static.Content.Generator.";
private static final String DEFAULT_TRANSFORMER_PATH_PROPERTY = "MCR.Object.Static.Content.Default.Path";
private static final String CLASS_SUFFIX = ".Class";
protected final String configID;
private MCRContentTransformer transformer;
private Path staticFileRootPath;
public MCRObjectStaticContentGenerator(String configID) {
this(
MCRConfiguration2.getString(CONFIG_ID_PREFIX + configID + TRANSFORMER_SUFFIX).orElseThrow(
() -> new MCRConfigurationException(
"The suffix " + TRANSFORMER_SUFFIX + " is not set for " + CONFIG_ID_PREFIX + configID)),
MCRConfiguration2.getString(CONFIG_ID_PREFIX + configID + ROOT_PATH_SUFFIX)
.orElseGet(() -> MCRConfiguration2.getStringOrThrow(DEFAULT_TRANSFORMER_PATH_PROPERTY) + "/"
+ configID),
configID);
}
protected MCRObjectStaticContentGenerator(String transformer, String staticFileRootPath, String configID) {
this(MCRContentTransformerFactory.getTransformer(transformer),
staticFileRootPath != null ? Paths.get(staticFileRootPath) : null, configID);
}
protected MCRObjectStaticContentGenerator(MCRContentTransformer transformer, Path staticFileRootPath,
String configID) {
this.transformer = transformer;
this.staticFileRootPath = staticFileRootPath;
this.configID = configID;
}
static MCRObjectStaticContentGenerator get(String id) {
try {
return MCRConfiguration2.getString(CONFIG_ID_PREFIX + id + CLASS_SUFFIX)
.map(c -> {
try {
return (Class<MCRObjectStaticContentGenerator>) MCRClassTools.forName(c);
} catch (ClassNotFoundException e) {
throw new MCRException(e);
}
}).orElse(MCRObjectStaticContentGenerator.class).getDeclaredConstructor(String.class).newInstance(id);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e) {
throw new MCRException(e);
}
}
public static List<String> getContentGenerators() {
return MCRConfiguration2.getPropertiesMap()
.keySet()
.stream()
.filter(k -> k.startsWith(CONFIG_ID_PREFIX))
.map(wholeProperty -> {
String propertySuffix = wholeProperty.substring(CONFIG_ID_PREFIX.length());
final int i = propertySuffix.indexOf('.');
if (i > 0) {
return propertySuffix.substring(0, i);
}
return propertySuffix;
})
.distinct()
.collect(Collectors.toList());
}
public void generate(MCRObject object) throws IOException {
LOGGER.debug(() -> "Create static content with " + getTransformer() + " for " + object);
final MCRObjectID objectID = object.getId();
if (!filter(object)) {
return;
}
final Path slotDirPath = getSlotDirPath(objectID);
if (!Files.exists(slotDirPath)) {
Files.createDirectories(slotDirPath);
}
final MCRContent result = getTransformer().transform(new MCRBaseContent(object));
final Path filePath = getFilePath(objectID);
try (OutputStream os = Files
.newOutputStream(filePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
result.sendTo(os);
}
}
public InputStream get(MCRObjectID id) throws IOException {
return Files.newInputStream(getFilePath(id));
}
private Path getFilePath(MCRObjectID id) {
return getSlotDirPath(id).resolve(id.toString().concat(".xml"));
}
protected Path getSlotDirPath(MCRObjectID id) {
final String numberAsString = id.getNumberAsString();
final int folderSize = 3;
final int folders = (int) Math.ceil(numberAsString.length() / (double) folderSize);
Path result = getStaticFileRootPath();
for (int i = 0; i < folders; i++) {
result = result.resolve(
numberAsString.substring(folderSize * i, Math.min(folderSize * i + 3, numberAsString.length())));
}
final Path finalResult = result;
LOGGER.debug(() -> "Resolved slot path is" + finalResult.toString());
return result;
}
/**
* Allows to implement an own instance which filters if the object is suitable to create static content.
* The class can be defined by appending .Class after the id just like with transformer
* E.g. we do not want to run the epicur stylesheets with no urn
* @param object the object to check
* @return true if the object is suitable
*/
protected boolean filter(MCRObject object) {
return true;
}
public Path getStaticFileRootPath() {
return this.staticFileRootPath;
}
public MCRContentTransformer getTransformer() {
return transformer;
}
public String getConfigID() {
return configID;
}
}
| 7,222 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStaticContentResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/staticcontent/MCRStaticContentResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.staticcontent;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import org.mycore.common.MCRException;
import org.mycore.common.xsl.MCRLazyStreamSource;
import org.mycore.datamodel.metadata.MCRObjectID;
public class MCRStaticContentResolver implements URIResolver {
@Override
public Source resolve(String href, String base) {
final String[] parts = href.split(":", 3);
if (parts.length != 3) {
throw new MCRException("href needs to be staticContent:ContentGeneratorID:ObjectID but was " + href);
}
final String contentGeneratorID = parts[1];
final MCRObjectID objectID = MCRObjectID.getInstance(parts[2]);
final MCRObjectStaticContentGenerator generator = new MCRObjectStaticContentGenerator(contentGeneratorID);
return new MCRLazyStreamSource(() -> generator.get(objectID), href);
}
}
| 1,653 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStaticContentEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/staticcontent/MCRStaticContentEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.staticcontent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRObject;
public class MCRStaticContentEventHandler extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger();
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
handleObjectUpdated(evt, obj);
}
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
handleObjectUpdated(evt, obj);
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
MCRObjectStaticContentGenerator.getContentGenerators()
.stream()
.map(MCRObjectStaticContentGenerator::get)
.forEach(cg -> {
try {
cg.generate(obj);
} catch (Exception e) {
LOGGER.error(
"Error while creating static content " + cg.getTransformer() + " for " + obj.getId() + "!", e);
}
});
}
}
| 1,948 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCombinedResourceBundleControl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/i18n/MCRCombinedResourceBundleControl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.i18n;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRComponent;
import org.mycore.common.config.MCRConfigurationInputStream;
import org.mycore.datamodel.language.MCRLanguageFactory;
import com.google.common.collect.Lists;
/**
* A {@link Control} that stacks ResourceBundles of {@link MCRComponent}.
*
* @author Thomas Scheffler (yagee)
* @since 2014.04
*/
public class MCRCombinedResourceBundleControl extends Control {
private static Logger LOGGER = LogManager.getLogger(MCRCombinedResourceBundleControl.class);
private Locale defaultLocale = MCRLanguageFactory.instance().getDefaultLanguage().getLocale();
private static final ResourceBundle.Control CONTROL_HELPER = new ResourceBundle.Control() {
};
@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IOException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("New bundle: {}, locale {}", baseName, locale);
}
if (locale.equals(Locale.ROOT)) {
//MCR-1064 fallback should be default language, if property key does not exist
locale = defaultLocale;
}
String bundleName = baseName.substring(baseName.indexOf(':') + 1);
String filename = CONTROL_HELPER.toBundleName(bundleName, locale) + ".properties";
try (MCRConfigurationInputStream propertyStream = new MCRConfigurationInputStream(filename)) {
if (propertyStream.isEmpty()) {
String className = bundleName + "_" + locale;
throw new MissingResourceException(
"Can't find bundle for base name " + baseName + ", locale " + locale, className, "");
}
return new PropertyResourceBundle(propertyStream);
}
}
@Override
public List<String> getFormats(String baseName) {
return Lists.newArrayList("mycore");
}
@Override
public Locale getFallbackLocale(String baseName, Locale locale) {
return defaultLocale.equals(locale) ? null : defaultLocale;
}
@Override
public long getTimeToLive(String baseName, Locale locale) {
//JAR files never change in runtime
return Long.MAX_VALUE;
}
@Override
public boolean needsReload(String baseName, Locale locale, String format, ClassLoader loader,
ResourceBundle bundle, long loadTime) {
//JAR files never change in runtime
return false;
}
}
| 3,557 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTranslation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/services/i18n/MCRTranslation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.i18n;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.ResourceBundle.Control;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.config.MCRProperties;
import org.mycore.common.xml.MCRDOMUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* provides services for internationalization in mycore application. You have to provide a property file named
* messages.properties in your classpath for this class to work.
*
* @author Radi Radichev
* @author Thomas Scheffler (yagee)
*/
public class MCRTranslation {
private static final String MESSAGES_BUNDLE = "messages";
private static final String DEPRECATED_MESSAGES_PROPERTIES = "/deprecated-messages.properties";
private static final Logger LOGGER = LogManager.getLogger(MCRTranslation.class);
private static final Pattern ARRAY_DETECTOR = Pattern.compile(";");
private static final Control CONTROL = new MCRCombinedResourceBundleControl();
private static boolean DEPRECATED_MESSAGES_PRESENT = false;
private static Properties DEPRECATED_MAPPING = loadProperties();
private static Set<String> AVAILABLE_LANGUAGES = loadAvailableLanguages();
static {
debug();
}
/**
* provides translation for the given label (property key). The current locale that is needed for translation is
* gathered by the language of the current MCRSession.
*
* @param label property key
* @return translated String
*/
public static String translate(String label) {
return translateToLocale(label, getCurrentLocale());
}
/**
* Checks whether there is a value for the given label and current locale.
*
* @param label property key
* @return <code>true</code> if there is a value, <code>false</code> otherwise
*/
public static boolean exists(String label) {
try {
ResourceBundle message = getResourceBundle(MESSAGES_BUNDLE, getCurrentLocale());
message.getString(label);
} catch (MissingResourceException mre) {
LOGGER.debug(mre);
return false;
}
return true;
}
/**
* provides translation for the given label (property key). The current locale that is needed for translation is
* gathered by the language of the current MCRSession.
*
* @param label property key
* @param baseName
* a fully qualified class name
* @return translated String
*/
public static String translateWithBaseName(String label, String baseName) {
return translateToLocale(label, getCurrentLocale(), baseName);
}
/**
* provides translation for the given label (property key).
*
* @param label property key
* @param locale
* target locale of translation
* @return translated String
*/
public static String translateToLocale(String label, Locale locale) {
return translateToLocale(label, locale, MESSAGES_BUNDLE);
}
/**
* Provides translation for the given label (property key) and locale.
*
* @param label property key
* @param locale
* target locale of translation
* @return translated String
*/
public static String translateToLocale(String label, String locale) {
return translateToLocale(label, getLocale(locale), MESSAGES_BUNDLE);
}
/**
* provides translation for the given label (property key).
*
* @param label property key
* @param locale
* target locale of translation
* @param baseName
* a fully qualified class name
* @return translated String
*/
public static String translateToLocale(String label, Locale locale, String baseName) {
LOGGER.debug("Translation for current locale: {}", locale.getLanguage());
ResourceBundle message;
try {
message = getResourceBundle(baseName, locale);
} catch (MissingResourceException mre) {
//no messages.properties at all
LOGGER.debug(mre.getMessage());
return "???" + label + "???";
}
String result = null;
try {
result = message.getString(label);
LOGGER.debug("Translation for {}={}", label, result);
} catch (MissingResourceException mre) {
// try to get new key if 'label' is deprecated
if (!DEPRECATED_MESSAGES_PRESENT) {
LOGGER.warn("Could not load resource '" + DEPRECATED_MESSAGES_PROPERTIES
+ "' to check for depreacted I18N keys.");
} else if (DEPRECATED_MAPPING.containsKey(label)) {
String newLabel = DEPRECATED_MAPPING.getProperty(label);
try {
result = message.getString(newLabel);
} catch (java.util.MissingResourceException e) {
}
if (result != null) {
LOGGER.warn("Usage of deprected I18N key '{}'. Please use '{}' instead.", label, newLabel);
return result;
}
}
result = "???" + label + "???";
LOGGER.debug(mre.getMessage());
}
return result;
}
/**
* Returns a map of label/value pairs which match with the given prefix. The current locale that is needed for
* translation is gathered by the language of the current MCRSession.
*
* @param prefix
* label starts with
* @return map of labels with translated values
*/
public static Map<String, String> translatePrefix(String prefix) {
return translatePrefixToLocale(prefix, getCurrentLocale());
}
/**
* Returns a map of label/value pairs which match with the given prefix.
*
* @param prefix
* label starts with
* @param locale
* target locale of translation
* @return map of labels with translated values
*/
public static Map<String, String> translatePrefixToLocale(String prefix, Locale locale) {
LOGGER.debug("Translation for locale: {}", locale.getLanguage());
HashMap<String, String> map = new HashMap<>();
ResourceBundle message = getResourceBundle(MESSAGES_BUNDLE, locale);
Enumeration<String> keys = message.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (key.startsWith(prefix)) {
map.put(key, message.getString(key));
}
}
return map;
}
/**
* provides translation for the given label (property key). The current locale that is needed for translation is
* gathered by the language of the current MCRSession.
*
* @param label property key
* @param arguments
* Objects that are inserted instead of placeholders in the property values
* @return translated String
*/
public static String translate(String label, Object... arguments) {
if (arguments.length > 0 && arguments[0] instanceof Locale) {
LOGGER.warn("MCR-2970, MCR-2978: seems like you want to call translateToLocale() instead");
}
return translateToLocale(label, getCurrentLocale(), arguments);
}
/**
* Provides translation for the given label (property key).
*
* @param label property key
* @param locale target locale of translation
* @param arguments Objects that are inserted instead of placeholders in the property values
* @return translated String
*/
public static String translateToLocale(String label, Locale locale, Object... arguments) {
String msgFormat = translateToLocale(label, locale);
MessageFormat formatter = new MessageFormat(msgFormat, locale);
String result = formatter.format(arguments);
LOGGER.debug("Translation for {}={}", label, result);
return result;
}
/**
* provides translation for the given label (property key). The current locale that is needed for translation is
* gathered by the language of the current MCRSession. Be aware that any occurence of ';' and '\' in
* <code>argument</code> has to be masked by '\'. You can use ';' to build an array of arguments: "foo;bar" would
* result in {"foo","bar"} (the array)
*
* @param label property key
* @param argument
* String that is inserted instead of placeholders in the property values
* @return translated String
* @see #translate(String, Object[])
*/
public static String translate(String label, String argument) {
return translate(label, (Object[]) getStringArray(argument));
}
/**
* Provides translation for the given label (property key). Be aware that any occurence of ';' and '\' in
* <code>argument</code> has to be masked by '\'. You can use ';' to build an array of arguments: "foo;bar" would
* result in {"foo","bar"} (the array)
*
* @param label property key
* @param argument
* String that is inserted instead of placeholders in the property values
* @param locale target locale of translation
* @return translated String
* @see #translate(String, Object[])
*/
public static String translateToLocale(String label, String argument, Locale locale) {
return translateToLocale(label, locale, (Object[]) getStringArray(argument));
}
/**
* Provides translation for the given label (property key). Be aware that any occurence of ';' and '\' in
* <code>argument</code> has to be masked by '\'. You can use ';' to build an array of arguments: "foo;bar" would
* result in {"foo","bar"} (the array)
*
* @param label property key
* @param argument
* String that is inserted instead of placeholders in the property values
* @param locale target locale of translation
* @return translated String
* @see #translate(String, Object[])
*/
public static String translateToLocale(String label, String argument, String locale) {
return translateToLocale(label, argument, MCRTranslation.getLocale(locale));
}
public static Locale getCurrentLocale() {
String currentLanguage = MCRSessionMgr.getCurrentSession().getCurrentLanguage();
return getLocale(currentLanguage);
}
public static Locale getLocale(String language) {
if (language.equals("id")) {
// workaround for bug with indonesian
// INDONESIAN ID OCEANIC/INDONESIAN [*Changed 1989 from original ISO 639:1988, IN]
// Java doesn't work with id
language = "in";
LOGGER.debug("Translation for current locale: {}", language);
}
return Locale.forLanguageTag(language);
}
public static Set<String> getAvailableLanguages() {
return AVAILABLE_LANGUAGES;
}
public static Document getAvailableLanguagesAsXML() {
DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
try {
Document document = documentBuilder.newDocument();
Element i18nRoot = document.createElement("i18n");
document.appendChild(i18nRoot);
for (String lang : AVAILABLE_LANGUAGES) {
Element langElement = document.createElement("lang");
langElement.setTextContent(lang);
i18nRoot.appendChild(langElement);
}
return document;
} finally {
MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
}
}
static String[] getStringArray(String masked) {
List<String> a = new ArrayList<>();
boolean mask = false;
StringBuilder buf = new StringBuilder();
if (masked == null) {
return new String[0];
}
if (!isArray(masked)) {
a.add(masked);
} else {
for (int i = 0; i < masked.length(); i++) {
switch (masked.charAt(i)) {
case ';' -> {
if (mask) {
buf.append(';');
mask = false;
} else {
a.add(buf.toString());
buf.setLength(0);
}
}
case '\\' -> {
if (mask) {
buf.append('\\');
mask = false;
} else {
mask = true;
}
}
default -> buf.append(masked.charAt(i));
}
}
a.add(buf.toString());
}
return a.toArray(String[]::new);
}
static boolean isArray(String masked) {
Matcher m = ARRAY_DETECTOR.matcher(masked);
while (m.find()) {
int pos = m.start();
int count = 0;
for (int i = pos - 1; i > 0; i--) {
if (masked.charAt(i) == '\\') {
count++;
} else {
break;
}
}
if (count % 2 == 0) {
return true;
}
}
return false;
}
static Properties loadProperties() {
Properties deprecatedMapping = new Properties();
try {
final InputStream propertiesStream = MCRTranslation.class
.getResourceAsStream(DEPRECATED_MESSAGES_PROPERTIES);
if (propertiesStream == null) {
LOGGER.warn("Could not find resource '" + DEPRECATED_MESSAGES_PROPERTIES + "'.");
return deprecatedMapping;
}
deprecatedMapping.load(propertiesStream);
DEPRECATED_MESSAGES_PRESENT = true;
} catch (IOException e) {
LOGGER.warn("Could not load resource '" + DEPRECATED_MESSAGES_PROPERTIES + "'.", e);
}
return deprecatedMapping;
}
static Set<String> loadAvailableLanguages() {
// try to load application relevant languages
return MCRConfiguration2.getString("MCR.Metadata.Languages")
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toSet()))
.orElseGet(MCRTranslation::loadLanguagesByMessagesBundle);//all languages by available messages_*.properties
}
static Set<String> loadLanguagesByMessagesBundle() {
Set<String> languages = new HashSet<>();
for (Locale locale : Locale.getAvailableLocales()) {
try {
if (!locale.getLanguage().equals("")) {
ResourceBundle bundle = getResourceBundle(MESSAGES_BUNDLE, locale);
languages.add(bundle.getLocale().toString());
}
} catch (MissingResourceException e) {
LOGGER.debug("Could not load " + MESSAGES_BUNDLE + " for locale: {}", locale);
}
}
return languages;
}
public static ResourceBundle getResourceBundle(String baseName, Locale locale) {
return baseName.contains(".") ? ResourceBundle.getBundle(baseName, locale)
: ResourceBundle.getBundle("stacked:" + baseName, locale, CONTROL);
}
/**
* output the current message properties to configuration directory
*/
private static void debug() {
for (String lang : MCRTranslation.getAvailableLanguages()) {
ResourceBundle rb = MCRTranslation.getResourceBundle("messages", MCRTranslation.getLocale(lang));
Properties props = new MCRProperties();
rb.keySet().forEach(key -> props.put(key, rb.getString(key)));
File resolvedMsgFile = MCRConfigurationDir.getConfigFile("messages_" + lang + ".resolved.properties");
if (resolvedMsgFile != null) {
try (OutputStream os = new FileOutputStream(resolvedMsgFile)) {
props.store(os, "MyCoRe Messages for Locale " + lang);
} catch (IOException e) {
LOGGER.warn("Could not store resolved properties to {}", resolvedMsgFile.getAbsolutePath(), e);
}
}
}
}
}
| 17,916 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessBaseImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessBaseImpl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import jakarta.inject.Singleton;
/**
* This class is a base implementation of the <code>MCRAccessInterface</code>.
*
* It will simply allow everything and will do nothing on persistent operations.
* Feel free to extend this class if your implementation can only support parts
* of the Interface definition.
*
* @author Jens Kupferschmidt
*
*/
@Singleton
public class MCRAccessBaseImpl implements MCRRuleAccessInterface {
protected static final String ACCESS_PERMISSIONS = MCRConfiguration2.getString("MCR.Access.AccessPermissions")
.orElse("read,write,delete");
/** the logger */
private static final Logger LOGGER = LogManager.getLogger(MCRAccessBaseImpl.class);
public MCRAccessBaseImpl() {
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#addRule(java.lang.String,
* java.lang.String, org.jdom2.Element)
*/
public void addRule(String id, String permission, Element rule, String description) throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl addRule for ID {} for permission {}", id, permission);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#addRule(java.lang.String,
* org.jdom2.Element)
*/
public void addRule(String permission, Element rule, String description) throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl addRule for permission {}", permission);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#removeRule(java.lang.String,
* java.lang.String)
*/
public void removeRule(String id, String permission) throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl removeRule for ID {} for permission {}", id, permission);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#removeRule(java.lang.String)
*/
public void removeRule(String permission) throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl removeRule for permission {}", permission);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#removeAllRules(java.lang.String)
*/
public void removeAllRules(String id) throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl removeAllRules for ID {}", id);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#updateRule(java.lang.String,
* java.lang.String, org.jdom2.Element)
*/
public void updateRule(String id, String permission, Element rule, String description)
throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl updateRule for ID {} for permission {}", id, permission);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#updateRule(java.lang.String,
* org.jdom2.Element)
*/
public void updateRule(String permission, Element rule, String description) throws MCRException {
LOGGER.debug("Execute MCRAccessBaseImpl updateRule for permission {}", permission);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#checkAccess(java.lang.String,
* java.lang.String)
*/
public boolean checkPermission(String id, String permission) {
LOGGER.debug("Execute MCRAccessBaseImpl checkPermission for ID {} for permission {}", id, permission);
long start = System.currentTimeMillis();
try {
MCRAccessRule rule = getAccessRule(id, permission);
if (rule == null) {
LOGGER.debug("No rule defined. Checking if current user is super user.");
MCRSystemUserInformation superUserInstance = MCRSystemUserInformation.getSuperUserInstance();
String superUserID = superUserInstance.getUserID();
return superUserID.equals(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID());
}
boolean validate = rule.validate();
LOGGER.debug(validate ? "Current user has permission." : "Current user does not have permission.");
return validate;
} finally {
LOGGER.debug("Check {} on {} took:{}", permission, id, System.currentTimeMillis() - start);
}
}
@Override
public boolean checkPermission(String id, String permission, MCRUserInformation userInfo) {
LOGGER.debug("Execute MCRAccessBaseImpl checkPermission for ID " + id + " for permission " + permission
+ " for user" + userInfo == null ? "null" : userInfo.getUserID());
return true;
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#checkAccess(java.lang.String)
*/
public boolean checkPermission(String permission) {
LOGGER.debug("Execute MCRAccessBaseImpl checkPermission for permission {}", permission);
return true;
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#checkAccess(java.lang.String, MCRUser)
*/
@Deprecated
@Override
public boolean checkPermissionForUser(String permission, String userID) {
LOGGER.debug("Execute MCRAccessBaseImpl checkPermission for permission {} for user {}", permission, userID);
return true;
}
@Override
public boolean checkPermissionForUser(String permission, MCRUserInformation userInfo) {
LOGGER.debug(
"Execute MCRAccessBaseImpl checkPermission for permission " + permission + " for user " + userInfo == null
? "null"
: userInfo.getUserID());
return true;
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#checkPermission(java.lang.String, java.lang.String, org.jdom2.Document)
*/
public boolean checkPermission(Element rule) {
return true;
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getAccessRule(java.lang.String,
* java.lang.String)
*/
public Element getRule(String objID, String permission) {
return null;
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getAccessRule(java.lang.String)
*/
public Element getRule(String permission) {
return null;
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getRuleDescription(java.lang.String)
*/
public String getRuleDescription(String permission) {
return "";
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getRuleDescription(java.lang.String, java.lang.String)
*/
public String getRuleDescription(String id, String permission) {
return "";
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getPermissionsForID(java.lang.String)
*/
public Collection<String> getPermissionsForID(String objid) {
return Collections.emptySet();
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getPermissions()
*/
public Collection<String> getPermissions() {
return Collections.emptySet();
}
/**
* checks wether a rule with the id and permission is defined. It's the same
* as calling
*
* <pre>
* (getRule(id, permission)!=null);
* </pre>
*
* @see #getRule(String, String)
*/
public boolean hasRule(String id, String permission) {
return getRule(id, permission) != null;
}
/**
* checks wether a rule with the id is defined. It's the same as calling
*
* <pre>
* (getPermissionsForID(id).size()>0);
* </pre>
*
* @see #getRule(String, String)
*/
public boolean hasRule(String id) {
return getPermissionsForID(id).size() > 0;
}
/**
* just returns the String of Access Permissions configured in
* property "MCR.AccessPermissions"
*
* @return the permissions as List
*/
public Collection<String> getAccessPermissionsFromConfiguration() {
String[] permissions = ACCESS_PERMISSIONS.split(",");
return Arrays.asList(permissions);
}
/*
* (non-Javadoc)
*
* @see org.mycore.access.MCRAccessInterface#getAllControlledIDs()
*/
public Collection<String> getAllControlledIDs() {
return null;
}
public void createRule(String rule, String creator, String description) {
LOGGER.debug("Execute MCRAccessBaseImpl createRule with rule {} \n and description {}", rule, description);
}
public void createRule(Element rule, String creator, String description) {
// TODO Auto-generated method stub
}
public String getNormalizedRuleString(Element rule) {
// TODO Auto-generated method stub
return null;
}
@Override
public MCRAccessRule getAccessRule(String id, String permission) {
return () -> true;
}
}
| 10,290 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
// package
package org.mycore.access;
import java.util.Collection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRStringContent;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
/**
* This class holds all EventHandler methods to manage the access part of the
* simple workflow.
*
* @author Jens Kupferschmidt
*/
public class MCRAccessEventHandler extends MCREventHandlerBase {
// the logger
private static Logger LOGGER = LogManager.getLogger(MCRAccessEventHandler.class);
private static MCRRuleAccessInterface AI = MCRAccessManager.getAccessImpl();
private static String storedrules = MCRConfiguration2.getString("MCR.Access.StorePermissions")
.orElse("read,write,delete");
// get the standard read rule from config or it's the true rule
private static String strReadRule = MCRConfiguration2.getString("MCR.Access.Rule.STANDARD-READ-RULE")
.orElse("<condition format=\"xml\"><boolean operator=\"true\" /></condition>");
private static Element readrule;
// get the standard edit rule from config or it's the true rule
private static String strEditRule = MCRConfiguration2.getString("MCR.Access.Rule.STANDARD-EDIT-RULE")
.orElse("<condition format=\"xml\"><boolean operator=\"true\" /></condition>");
private static Element editrule;
static {
try {
readrule = new MCRStringContent(strReadRule).asXML().getRootElement().detach();
editrule = new MCRStringContent(strEditRule).asXML().getRootElement().detach();
} catch (RuntimeException rte) {
throw rte;
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* This method will be used to create the access rules for SWF for a
* MCRObject.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
handleBaseCreated(obj, MCRConfiguration2.getBoolean("MCR.Access.AddObjectDefaultRule").orElse(true));
}
/**
* This method will be used to update the access rules for SWF for a
* MCRObject.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
handleBaseUpdated(obj, MCRConfiguration2.getBoolean("MCR.Access.AddObjectDefaultRule").orElse(true));
}
/**
* This method will be used to delete the access rules for SWF for a
* MCRObject.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
handleBaseDeleted(obj);
}
/**
* This method will be used to repair the access rules for SWF for a
* MCRObject.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
// Do nothing
}
/**
* This method will be used to create the access rules for SWF for a
* MCRDerivate.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
handleBaseCreated(der, MCRConfiguration2.getBoolean("MCR.Access.AddDerivateDefaultRule").orElse(true));
}
/**
* This method will be used to update the access rules for SWF for a
* MCRDerivate.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
handleBaseUpdated(der, MCRConfiguration2.getBoolean("MCR.Access.AddDerivateDefaultRule").orElse(true));
}
/**
* This method will be used to delete the access rules for SWF for a
* MCRDerivate.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
handleBaseDeleted(der);
}
/**
* This method will be used to repair the access rules for SWF for a
* MCRDerivate.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
@Override
protected void handleDerivateRepaired(MCREvent evt, MCRDerivate der) {
// Do nothing
}
private void handleBaseCreated(MCRBase base, boolean addDefaultRules) {
// save the start time
long t1 = System.currentTimeMillis();
// create
Collection<String> li = AI.getPermissionsForID(base.getId().toString());
int aclsize = 0;
if (li != null) {
aclsize = li.size();
}
int rulesize = base.getService().getRulesSize();
if (rulesize == 0 && aclsize == 0 && addDefaultRules) {
setDefaultPermissions(base.getId().toString(), true);
LOGGER.warn("The ACL conditions for this object are empty!");
}
while (0 < rulesize) {
Element conditions = base.getService().getRule(0).getCondition();
String permission = base.getService().getRule(0).getPermission();
if (storedrules.contains(permission)) {
MCRAccessManager.addRule(base.getId(), permission, conditions, "");
}
base.getService().removeRule(0);
rulesize--;
}
// save the stop time
long t2 = System.currentTimeMillis();
double diff = (t2 - t1) / 1000.0;
LOGGER.debug("MCRAccessEventHandler create: done in {} sec.", diff);
}
private void handleBaseUpdated(MCRBase base, boolean addDefaultRules) {
// save the start time
long t1 = System.currentTimeMillis();
// update
Collection<String> li = AI.getPermissionsForID(base.getId().toString());
int aclsize = 0;
if (li != null) {
aclsize = li.size();
}
int rulesize = base.getService().getRulesSize();
if (rulesize == 0 && aclsize == 0 && addDefaultRules) {
setDefaultPermissions(base.getId().toString(), false);
LOGGER.warn("The ACL conditions for this object was empty!");
}
if (aclsize == 0) {
while (0 < rulesize) {
Element conditions = base.getService().getRule(0).getCondition();
String permission = base.getService().getRule(0).getPermission();
if (storedrules.contains(permission)) {
MCRAccessManager.updateRule(base.getId(), permission, conditions, "");
}
base.getService().removeRule(0);
rulesize--;
}
}
// save the stop time
long t2 = System.currentTimeMillis();
double diff = (t2 - t1) / 1000.0;
LOGGER.debug("MCRAccessEventHandler update: done in {} sec.", diff);
}
private void handleBaseDeleted(MCRBase base) {
// save the start time
long t1 = System.currentTimeMillis();
// delete
MCRAccessManager.removeAllRules(base.getId());
// save the stop time
long t2 = System.currentTimeMillis();
double diff = (t2 - t1) / 1000.0;
LOGGER.debug("MCRAccessEventHandler delete: done in {} sec.", diff);
}
/**
* This method sets Default Rules to all permissions that are configured. if
* <i>overwrite</i> = true, then the old permission entries that are in the
* database are overwritten, else not.
*/
private void setDefaultPermissions(String id, boolean overwrite) {
Collection<String> savedPermissions = MCRAccessManager.getPermissionsForID(id);
Collection<String> configuredPermissions = AI.getAccessPermissionsFromConfiguration();
for (String permission : configuredPermissions) {
if (storedrules.contains(permission)) {
if (savedPermissions != null && savedPermissions.contains(permission)) {
if (overwrite) {
MCRAccessManager.removeRule(id, permission);
if (permission.startsWith(MCRAccessManager.PERMISSION_READ)) {
MCRAccessManager.addRule(id, permission, readrule, "");
} else {
MCRAccessManager.addRule(id, permission, editrule, "");
}
}
} else {
if (permission.startsWith(MCRAccessManager.PERMISSION_READ)) {
MCRAccessManager.addRule(id, permission, readrule, "");
} else {
MCRAccessManager.addRule(id, permission, editrule, "");
}
}
}
}
}
}
| 10,482 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessRule.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessRule.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
/**
* @author Thomas Scheffler (yagee)
*
*/
public interface MCRAccessRule {
/**
* determines whether the current user has the permission to perform a
* certain action.
*
* @return true if the permission is granted, else false
*/
boolean validate();
}
| 1,045 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessCacheManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRSessionEvent;
import org.mycore.common.events.MCRSessionListener;
/**
* @author Thomas Scheffler (yagee)
*
*/
class MCRAccessCacheManager implements MCRSessionListener {
private static final int CAPACITY = MCRConfiguration2.getOrThrow("MCR.Access.Cache.Size", Integer::valueOf);
private static String key = MCRAccessCacheManager.class.getCanonicalName();
ThreadLocal<MCRCache<MCRPermissionHandle, Boolean>> accessCache = ThreadLocal.withInitial(() -> {
//this is only called for every session that was created before this class could attach to session events
MCRSession session = MCRSessionMgr.getCurrentSession();
@SuppressWarnings("unchecked")
MCRCache<MCRPermissionHandle, Boolean> cache = (MCRCache<MCRPermissionHandle, Boolean>) session.get(key);
if (cache == null) {
cache = createCache(session);
session.put(key, cache);
}
return cache;
});
@Override
@SuppressWarnings("unchecked")
public void sessionEvent(MCRSessionEvent event) {
MCRCache<MCRPermissionHandle, Boolean> cache;
MCRSession session = event.getSession();
switch (event.getType()) {
case created:
case activated:
break;
case passivated:
accessCache.remove();
break;
case destroyed:
cache = getCacheFromSession(session);
if (cache != null) {
cache.close();
}
break;
default:
break;
}
}
private MCRCache<MCRPermissionHandle, Boolean> getCacheFromSession(MCRSession session) {
return (MCRCache<MCRPermissionHandle, Boolean>) session.get(key);
}
private MCRCache<MCRPermissionHandle, Boolean> createCache(MCRSession session) {
return new MCRCache<>(CAPACITY, "Access rights in MCRSession " + session.getID());
}
MCRAccessCacheManager() {
//init for current user done
MCRSessionMgr.addSessionListener(this);
}
public Boolean isPermitted(String id, String permission) {
MCRPermissionHandle handle = new MCRPermissionHandle(id, permission);
MCRCache<MCRPermissionHandle, Boolean> permissionCache = accessCache.get();
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
return permissionCache.getIfUpToDate(handle, currentSession.getLoginTime());
}
public void cachePermission(String id, String permission, boolean permitted) {
MCRPermissionHandle handle = new MCRPermissionHandle(id, permission);
accessCache.get().put(handle, permitted);
}
public void removePermission(String id, String permission) {
MCRPermissionHandle handle = new MCRPermissionHandle(id, permission);
MCRCache<MCRPermissionHandle, Boolean> permissionCache = accessCache.get();
permissionCache.remove(handle);
}
public void removePermission(String... ids) {
MCRCache<MCRPermissionHandle, Boolean> permissionCache = accessCache.get();
removePermissionFromCache(permissionCache, Stream.of(ids).collect(Collectors.toSet()));
}
private void removePermissionFromCache(MCRCache<MCRPermissionHandle, Boolean> permissionCache, Set<String> ids) {
final List<MCRPermissionHandle> handlesToRemove = permissionCache.keys()
.stream()
.filter(hdl -> hdl.id() != null)
.filter(hdl -> ids.contains(hdl.id()))
.collect(Collectors.toList());
handlesToRemove.forEach(permissionCache::remove);
}
public void removePermissionFromAllCachesById(String... ids) {
final Set<String> idSet = Stream.of(ids).collect(Collectors.toSet());
MCRSessionMgr.getAllSessions().forEach((sessionId, mcrSession) -> {
final MCRCache<MCRPermissionHandle, Boolean> cache = getCacheFromSession(mcrSession);
if (cache != null) {
removePermissionFromCache(cache, idSet);
}
});
}
private record MCRPermissionHandle(String id, String permission) {
private MCRPermissionHandle {
permission = permission.intern();
}
}
}
| 5,320 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRemoveAclEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRRemoveAclEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
// package
package org.mycore.access;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
/**
* This class contains EventHandler methods to remove the access part of
* MCRObjects.
*
* @author Thomas Scheffler (yagee)
* @author Jens Kupferschmidt
*/
public class MCRRemoveAclEventHandler extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger(MCRRemoveAclEventHandler.class);
@Override
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
handleAddOrModify(obj);
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
handleAddOrModify(obj);
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
handleDelete(obj);
}
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
}
@Override
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
handleAddOrModify(der);
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
handleAddOrModify(der);
}
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
handleDelete(der);
}
@Override
protected void handleDerivateRepaired(MCREvent evt, MCRDerivate der) {
}
private void handleAddOrModify(MCRBase base) {
long start = System.currentTimeMillis();
int rulesize = base.getService().getRulesSize();
while (0 < rulesize) {
base.getService().removeRule(0);
rulesize--;
}
long diff = System.currentTimeMillis() - start;
LOGGER.debug("event handled in {}", diff);
}
private void handleDelete(MCRBase base) {
long start = System.currentTimeMillis();
MCRAccessManager.removeAllRules(base.getId());
long diff = System.currentTimeMillis() - start;
LOGGER.debug("event handled in {}", diff);
}
}
| 2,995 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessInterface.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessInterface.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import org.mycore.common.MCRUserInformation;
public interface MCRAccessInterface {
/**
* determines whether the current user has the permission to perform a
* certain action.
*
* All information regarding the current user is capsulated by a
* <code>MCRSession</code> instance which can be retrieved by
*
* <pre>
* MCRSession currentSession = MCRSessionMgr.getCurrentSession();
* </pre>
*
* This method is used for checking "a priori permissions" like "create-document"
* where a String ID does not exist yet
*
* @param permission
* the permission/action to be granted, e.g. "create-document"
* @return true if the permission is granted, else false
* @see org.mycore.common.MCRSessionMgr#getCurrentSession()
* @see org.mycore.common.MCRSession
*/
boolean checkPermission(String permission);
/**
* determines whether the current user has the permission to perform a
* certain action.
*/
boolean checkPermission(String id, String permission);
/**
* determines whether a given user has the permission to perform a
* certain action. no session data will be checked here.
*
* This method is used for checking "a priori permissions" like "create-document"
* where a String ID does not exist yet
*
* @param permission
* the permission/action to be granted, e.g. "create-document"
* @param userInfo
* the MCRUser, whose permissions are checked
* @return true if the permission is granted, else false
*/
// TODO: maybe rename to checkPermission or rename checkPermission to checkPermissionForUser
boolean checkPermissionForUser(String permission, MCRUserInformation userInfo);
/**
* determines whether a given user has the permission to perform a
* certain action. no session data will be checked here.
*
*
* The parameter <code>id</code> serves as an identifier for the concrete
* underlying rule, e.g. a MCRObjectID.
*
* @param id
* the ID-String of the object
* @param permission
* the permission/action to be granted, e.g. "read"
* @param userInfo
* the MCRUser, whose permissions are checked
* @return true if the permission is granted, else false
*/
boolean checkPermission(String id, String permission, MCRUserInformation userInfo);
}
| 3,247 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRuleAccessInterface.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRRuleAccessInterface.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.Collection;
import org.jdom2.Element;
import org.mycore.common.MCRException;
/**
* This serves as an interface to an underlying access controll system.
*
* @author Thomas Scheffler (yagee)
*
* @since 1.3
*/
public interface MCRRuleAccessInterface extends MCRAccessInterface {
/**
* create an access rule in the rulestore using an rule string in plain text
*
* @param rule
* the rule string in plain text
* @param description
* a String description of the rule in prosa
*/
void createRule(String rule, String creator, String description);
/**
* create an access rule in the rulestore using an rule string in plain text
*
* @param rule
* the rule string as xml
* @param description
* a String description of the rule in prosa
*/
void createRule(Element rule, String creator, String description);
/**
* generate rule string from xml
*
* @return the normalized rule string
*/
String getNormalizedRuleString(Element rule);
/**
* adds an access rule for an ID to an access system. The parameter
* <code>id</code> serves as an identifier for the concrete underlying
* rule, e.g. a MCRObjectID.
*
* @param id
* the ID-String of the object
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* a String description of the rule in prosa
* @throws MCRException
* if an error occured
*/
void addRule(String id, String permission, Element rule, String description) throws MCRException;
/**
* adds an access rule for an "a priori-permission" like "create-document"
*
* @param permission
* the access permission for the rule (e.g. "create-document")
* @param rule
* the access rule
* @param description
* a String description of the rule in prosa
* @throws MCRException
* if an error occured
*/
void addRule(String permission, Element rule, String description) throws MCRException;
/**
* removes a rule. The parameter <code>id</code> serves as an identifier
* for the concrete underlying rule, e.g. a MCRObjectID.
*
* @param id
* the ID-String of the object
* @param permission
* the access permission for the rule
* @throws MCRException
* if an error occured
*/
void removeRule(String id, String permission) throws MCRException;
/**
* removes a rule for an "a priori permission" like "create-document"
*
* @param permission
* the access permission for the rule
* @throws MCRException
* if an error occured
*/
void removeRule(String permission) throws MCRException;
/**
* removes all rules of the <code>id</code>. The parameter
* <code>id</code> serves as an identifier for the concrete underlying
* rule, e.g. a MCRObjectID.
*
* @param id
* the ID-String of the object
* @throws MCRException
* if an errow was occured
*/
void removeAllRules(String id) throws MCRException;
/**
* updates an access rule for an ID to an access system. The parameter
* <code>id</code> serves as an identifier for the concrete underlying
* rule, e.g. a MCRObjectID.
*
* @param id
* the ID-String of the object
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* a String description of the rule in prosa
* @throws MCRException
* if an errow was occured
*/
void updateRule(String id, String permission, Element rule, String description) throws MCRException;
/**
* updates an access rule for an "a priori permission"
* of an access system like "create-document".
*
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* a String description of the rule in prosa
* @throws MCRException
* if an errow was occured
*/
void updateRule(String permission, Element rule, String description) throws MCRException;
/**
* returns a MCRAccessRule which could be validated
*
* All information regarding the current user is capsulated by a
* <code>MCRSession</code> instance which can be retrieved by
*
* <pre>
* MCRSession currentSession = MCRSessionMgr.getCurrentSession();
* </pre>
*
* The parameter <code>id</code> serves as an identifier for the concrete
* underlying rule, e.g. a MCRObjectID.
*
* @param id
* the ID-String of the object
* @param permission
* the permission/action to be granted, e.g. "read"
* @return MCRAccessRule instance or null if no rule is defined;
* @see org.mycore.common.MCRSessionMgr#getCurrentSession()
* @see org.mycore.common.MCRSession
*/
MCRAccessRule getAccessRule(String id, String permission);
/**
* determines whether a given user has the permission to perform a
* certain action. no session data will be checked here.
*
* This method is used for checking "a priori permissions" like "create-document"
* where a String ID does not exist yet
*
* @param permission
* the permission/action to be granted, e.g. "create-document"
* @param userID
* the MCRUser, whose permissions are checked
* @return true if the permission is granted, else false
* @see org.mycore.common.MCRSessionMgr#getCurrentSession()
* @see org.mycore.common.MCRSession
*/
@Deprecated
boolean checkPermissionForUser(String permission, String userID);
/**
* determines whether the current user has the permission to perform a
* certain action.
*
* All information regarding the current user is capsulated by a
* <code>MCRSession</code> instance which can be retrieved by
*
* <pre>
* MCRSession currentSession = MCRSessionMgr.getCurrentSession();
* </pre>
* @param rule
* the jdom-representation of a mycore access rule
* @return true if the permission is granted, else false
* @see org.mycore.common.MCRSessionMgr#getCurrentSession()
* @see org.mycore.common.MCRSession
*/
boolean checkPermission(Element rule);
/**
* exports a access rule as JDOM element.
*
* @param id
* the ID-String of the object
* @param permission
* the access permission for the rule
* @return the rule as jdom element, or <code>null</code> if no rule is
* defined
*/
Element getRule(String id, String permission);
/**
* exports a access rule for a "a priori permission"
* as JDOM element.
*
* @param permission
* the access permission for the rule
* @return the rule as jdom element, or <code>null</code> if no rule is
* defined
*/
Element getRule(String permission);
/**
* returns the prosa description of a defined rule for a "a priori" permission like "create-document".
*
* @param permission
* the access permission for the rule
* @return the String of the description
*/
String getRuleDescription(String permission);
/**
* returns the prosa description of a defined rule.
*
* @param id
* the ID-String of the object
* @param permission
* the access permission for the rule
* @return the String of the description
*/
String getRuleDescription(String id, String permission);
/**
* lists all permissions defined for the <code>id</code>.
*
* The parameter <code>id</code> serves as an identifier for the concrete
* underlying rule, e.g. a MCRObjectID.
*
* @return a <code>List</code> of all for <code>id</code> defined
* permission
*/
Collection<String> getPermissionsForID(String id);
/**
* lists all a-priori permissions like "create-document".
*
* @return a <code>List</code> of all defined permissions
*/
Collection<String> getPermissions();
/**
* list all object-related Access Permissions that are defined
* in configuration files
*
* @return a List of permissiond from the configuration
*/
Collection<String> getAccessPermissionsFromConfiguration();
/**
* lists all String IDs, a permission is assigned to.
*
* The parameter <code>id</code> serves as an identifier for the concrete
* underlying rule, e.g. a MCRObjectID.
*
* @return a sorted and distinct <code>List</code> of all <code>String</code> IDs
*/
Collection<String> getAllControlledIDs();
/**
* checks wether a rule with the <code>id</code> and
* <code>permission</code> is defined.
*
* @param id
* the ID-String of the object
* @param permission
* the access permission for the rule
* @return false, if getRule(id, permission) would return null, else true
*/
boolean hasRule(String id, String permission);
/**
* checks wether a rule with the <code>id</code> is defined.
*
* @param id
* the ID-String of the object
* @return false, if getPermissionsForID(id) would return an empty list,
* else true
*/
boolean hasRule(String id);
}
| 10,707 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.access.strategies.MCRAccessCheckStrategy;
import org.mycore.access.strategies.MCRDerivateIDStrategy;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.util.concurrent.MCRFixedUserCallable;
/**
* @author Thomas Scheffler
*/
public class MCRAccessManager {
private static final MCRAccessCacheManager ACCESS_CACHE = new MCRAccessCacheManager();
public static final Logger LOGGER = LogManager.getLogger(MCRAccessManager.class);
public static final String PERMISSION_READ = "read";
public static final String PERMISSION_WRITE = "writedb";
public static final String PERMISSION_DELETE = "deletedb";
public static final String PERMISSION_PREVIEW = "preview";
public static final String PERMISSION_VIEW = "view";
public static final String PERMISSION_HISTORY_VIEW = "view-history";
public static final String PERMISSION_HISTORY_READ = "read-history";
public static final String PERMISSION_HISTORY_DELETE = "delete-history";
private static final ExecutorService EXECUTOR_SERVICE;
static {
EXECUTOR_SERVICE = Executors.newWorkStealingPool();
MCRShutdownHandler.getInstance().addCloseable(EXECUTOR_SERVICE::shutdownNow);
}
@SuppressWarnings("unchecked")
public static <T extends MCRAccessInterface> T getAccessImpl() {
return (T) MCRConfiguration2.<MCRAccessInterface>getInstanceOf("MCR.Access.Class")
.orElseGet(MCRAccessBaseImpl::new);
}
private static MCRAccessCheckStrategy getAccessStrategy() {
// if acccessStrategy equals accessImpl we reuse the accessImpl,
// to make sure, that only one singleton gets created
// (used to instantiate fact-based access system)
Optional<String> optStrategy = MCRConfiguration2.getString("MCR.Access.Strategy.Class");
Optional<String> optAccessImpl = MCRConfiguration2.getString("MCR.Access.Class");
if (optStrategy.isPresent() && optAccessImpl.isPresent() && optStrategy.get().equals(optAccessImpl.get())) {
return MCRConfiguration2.<MCRAccessCheckStrategy>getInstanceOf("MCR.Access.Class").orElseThrow();
} else {
return MCRConfiguration2.<MCRAccessCheckStrategy>getInstanceOf("MCR.Access.Strategy.Class")
.orElseGet(MCRDerivateIDStrategy::new);
}
}
/**
* adds an access rule for an MCRObjectID to an access system.
*
* @param id
* the MCRObjectID of the object
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* description for the given access rule, e.g. "allows public access"
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#addRule(String, String, Element, String)
*/
public static void addRule(MCRObjectID id, String permission, Element rule, String description)
throws MCRException {
requireRulesInterface().addRule(id.toString(), permission, rule, description);
}
/**
* adds an access rule for an ID to an access system.
*
* @param id
* the ID of the object as String
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* description for the given access rule, e.g. "allows public access"
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#addRule(String, String, Element, String)
*/
public static void addRule(String id, String permission, Element rule, String description)
throws MCRException {
requireRulesInterface().addRule(id, permission, rule, description);
}
/**
* removes the <code>permission</code> rule for the MCRObjectID.
*
* @param id
* the MCRObjectID of an object
* @param permission
* the access permission for the rule
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#removeRule(String, String)
*/
public static void removeRule(MCRObjectID id, String permission) throws MCRException {
requireRulesInterface().removeRule(id.toString(), permission);
}
/**
* removes the <code>permission</code> rule for the ID.
*
* @param id
* the ID of an object as String
* @param permission
* the access permission for the rule
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#removeRule(String, String)
*/
public static void removeRule(String id, String permission) throws MCRException {
requireRulesInterface().removeRule(id, permission);
}
/**
* removes all rules for the MCRObjectID.
*
* @param id
* the MCRObjectID of an object
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#removeRule(String)
*/
public static void removeAllRules(MCRObjectID id) throws MCRException {
requireRulesInterface().removeAllRules(id.toString());
}
/**
* updates an access rule for an MCRObjectID.
*
* @param id
* the MCRObjectID of the object
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* description for the given access rule, e.g. "allows public access"
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#updateRule(String, String, Element, String)
*/
public static void updateRule(MCRObjectID id, String permission, Element rule, String description)
throws MCRException {
requireRulesInterface().updateRule(id.toString(), permission, rule, description);
}
/**
* updates an access rule for an ID.
*
* @param id
* the ID of the object
* @param permission
* the access permission for the rule
* @param rule
* the access rule
* @param description
* description for the given access rule, e.g. "allows public access"
* @throws MCRException
* if an error was occurred
* @see MCRRuleAccessInterface#updateRule(String, String, Element, String)
*/
public static void updateRule(String id, String permission, Element rule, String description)
throws MCRException {
requireRulesInterface().updateRule(id, permission, rule, description);
}
/**
* determines whether the current user has the permission to perform a certain action.
*
* @param id
* the MCRObjectID of the object
* @param permission
* the access permission for the rule
* @return true if the access is allowed otherwise it return
* @see MCRRuleAccessInterface#checkPermission(String, String)
*/
public static boolean checkPermission(MCRObjectID id, String permission) {
return checkPermission(id.toString(), permission);
}
/**
* checks if the current user has the permission to perform an action on the derivate metadata.
* @param derId the MCRObjectID of the derivate
* @param permission the access permission for the rule
* @return true, if the access is allowed
*/
public static boolean checkDerivateMetadataPermission(MCRObjectID derId, String permission) {
MCRObjectID objectId = MCRMetadataManager.getObjectId(derId, 10, TimeUnit.MINUTES);
if (objectId != null) {
return checkPermission(objectId, permission);
}
return checkPermission(derId.toString(), permission);
}
/**
* checks if the current user has the permission to perform an action on the derivate content.
* @param derId the MCRObjectID of the derivate
* @param permission the access permission for the rule
* @return true, if the access is allowed
*/
public static boolean checkDerivateContentPermission(MCRObjectID derId, String permission) {
return checkPermission(derId.toString(), permission);
}
/**
* checks if the current user has the permission to view the derivate content.
* @param derId the MCRObjectID of the derivate
* @return true, if the access is allowed
*/
public static boolean checkDerivateDisplayPermission(String derId) {
return checkPermission(derId, PERMISSION_READ) || checkPermission(derId, PERMISSION_VIEW);
}
/**
* determines whether the current user has the permission to perform a certain action.
*
* @param id
* the MCRObjectID of the object
* @param permission
* the access permission for the rule
* @return true if the permission for the id is given
*/
public static boolean checkPermission(String id, String permission) {
Boolean value = ACCESS_CACHE.isPermitted(id, permission);
if (value == null) {
value = getAccessStrategy().checkPermission(id, permission);
ACCESS_CACHE.cachePermission(id, permission, value);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("checkPermission id:{} permission:{} --> {}", id, permission, value);
}
return value;
}
/**
* determines whether the current user has the permission to perform a certain action.
*
* @param permission
* the access permission for the rule
* @return true if the permission exist
*/
public static boolean checkPermission(String permission) {
Boolean value = ACCESS_CACHE.isPermitted(null, permission);
if (value == null) {
value = getAccessImpl().checkPermission(permission);
ACCESS_CACHE.cachePermission(null, permission, value);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("checkPermission permission:{} --> {}", permission, value);
}
return value;
}
/**
* Invalidates the permission for current user on cache.
*
* @param id the {@link MCRObjectID}
* @param permission the access permission
*/
public static void invalidPermissionCache(String id, String permission) {
ACCESS_CACHE.removePermission(id, permission);
}
/**
* Invalidates all permissions for a specific id for current user on cache
* @param ids id of the cache handle
*/
public static void invalidPermissionCacheByID(String... ids) {
ACCESS_CACHE.removePermission(ids);
}
/**
* Invalidates all permissions for a specific id for all access caches in every session
* @param ids id of the cache handle
*/
public static void invalidAllPermissionCachesById(String... ids) {
ACCESS_CACHE.removePermissionFromAllCachesById(ids);
}
/**
* Invalidates the permission for current user on cache.
*
* @param permission the access permission
*/
public static void invalidPermissionCache(String permission) {
invalidPermissionCache(null, permission);
}
/**
* checks whether the current user has the permission to read/see a derivate check is also against the mcrobject,
* the derivate belongs to both checks must return true <br>
* it is needed in MCRFileNodeServlet and MCRZipServlet
*
* @param derID
* String ID of a MyCoRe-Derivate
* @return true if the access is allowed otherwise it return false
* @deprecated use {@link #checkDerivateContentPermission(MCRObjectID, String)} or
* {@link #checkDerivateMetadataPermission(MCRObjectID, String)} instead with Strategy
* that also checks for the object.
*/
@Deprecated
public static boolean checkPermissionForReadingDerivate(String derID) {
// derID must be a derivate ID
boolean accessAllowed = false;
MCRObjectID objectId = MCRMetadataManager.getObjectId(MCRObjectID.getInstance(derID), 10, TimeUnit.MINUTES);
if (objectId != null) {
accessAllowed = checkPermission(objectId, PERMISSION_READ) && checkPermission(derID, PERMISSION_READ);
} else {
accessAllowed = checkPermission(derID, PERMISSION_READ);
LogManager.getLogger("MCRAccessManager.class").warn("no mcrobject could be found for derivate: {}", derID);
}
return accessAllowed;
}
/**
* lists all permissions defined for the <code>id</code>.
*
* @param id
* the ID of the object as String
* @return a <code>List</code> of all for <code>id</code> defined permissions
*/
public static Collection<String> getPermissionsForID(String id) {
return requireRulesInterface().getPermissionsForID(id);
}
/**
* lists all permissions defined for the <code>id</code>.
*
* @param id
* the MCRObjectID of the object
* @return a <code>List</code> of all for <code>id</code> defined permissions
*/
public static Collection<String> getPermissionsForID(MCRObjectID id) {
return requireRulesInterface().getPermissionsForID(id.toString());
}
/**
* return a rule, that allows something for everybody
*
* @return a rule, that allows something for everybody
*/
public static Element getTrueRule() {
Element condition = new Element("condition");
condition.setAttribute("format", "xml");
Element booleanOp = new Element("boolean");
booleanOp.setAttribute("operator", "true");
condition.addContent(booleanOp);
return condition;
}
/**
* return a rule, that forbids something for all, but superuser
*
* @return a rule, that forbids something for all, but superuser
*/
public static Element getFalseRule() {
Element condition = new Element("condition");
condition.setAttribute("format", "xml");
Element booleanOp = new Element("boolean");
booleanOp.setAttribute("operator", "false");
condition.addContent(booleanOp);
return condition;
}
/**
* return true if a rule for the id exist
*
* @param id
* the MCRObjectID of the object
* @param permission
* the access permission for the rule
*/
public static boolean hasRule(String id, String permission) {
// if impl doesnt have a hasRule method, we assume there is a rule for id, permission
if (getAccessImpl() instanceof MCRRuleAccessInterface) {
return requireRulesInterface().hasRule(id, permission);
} else {
return true;
}
}
public static CompletableFuture<Boolean> checkPermission(MCRUserInformation user, Supplier<Boolean> checkSuplier) {
return checkPermission(user, checkSuplier, EXECUTOR_SERVICE);
}
public static CompletableFuture<Boolean> checkPermission(MCRUserInformation user, Supplier<Boolean> checkSuplier,
ExecutorService es) {
return CompletableFuture.supplyAsync(getWrappedFixedUserCallable(user, checkSuplier), es);
}
private static Supplier<Boolean> getWrappedFixedUserCallable(MCRUserInformation user,
Supplier<Boolean> checkSuplier) {
Supplier<Boolean> check = () -> {
try {
return checkSuplier.get();
} finally {
MCREntityManagerProvider.getCurrentEntityManager().clear();
}
};
MCRFixedUserCallable<Boolean> mcrFixedUserCallable = new MCRFixedUserCallable<>(check::get, user);
return () -> {
try {
return mcrFixedUserCallable.call();
} catch (Exception e) {
LOGGER.error("Exception while running ACL check for user: {}", user.getUserID(), e);
return false;
}
};
}
public static MCRRuleAccessInterface requireRulesInterface() {
if (!implementsRulesInterface()) {
throw new MCRException(MCRAccessInterface.class + " is no " + MCRRuleAccessInterface.class);
}
return getAccessImpl();
}
public static boolean implementsRulesInterface() {
return getAccessImpl() instanceof MCRRuleAccessInterface;
}
}
| 18,024 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.MCRCatchException;
public class MCRAccessException extends MCRCatchException {
private static final long serialVersionUID = 6494399676882465653L;
private Optional<String> action;
private Optional<String> id;
private Optional<String> permission;
public static MCRAccessException missingPrivilege(String action, String... privilege) {
return new MCRAccessException(Optional.ofNullable(action), null, null, privilege);
}
public static MCRAccessException missingPermission(String action, String id, String permission) {
return new MCRAccessException(Optional.ofNullable(action), id, permission);
}
private MCRAccessException(Optional<String> action, String id, String permission, String... privilege) {
super(getMessage(action, id, permission, privilege));
this.action = action;
this.id = Optional.ofNullable(id);
this.permission = Optional.ofNullable(permission);
}
private static String getMessage(Optional<String> action, String oid, String permission, String... privilege) {
StringBuilder sb = new StringBuilder();
switch (privilege.length) {
case 0 ->
//no privilege but permission was missing
sb.append("You do not have the permission '").append(permission).append("' on '").append(oid)
.append('\'');
case 1 -> sb.append("You do not have the privilege '").append(privilege[0]).append('\'');
default -> sb.append(
Stream.of(privilege).collect(
Collectors.joining("', '", "You do not have any of the required privileges ('", "')")));
}
sb.append(
action.map(s -> " to perform: " + s).orElse("."));
return sb.toString();
}
public Optional<String> getAction() {
return action;
}
public Optional<String> getId() {
return id;
}
public Optional<String> getPermission() {
return permission;
}
}
| 2,899 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessCacheEventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheEventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
/**
* Clears the access cache when an object is updated or deleted.
* It invalidates all cache entries for the object, it's derivates and all it's descendants
* in all active MCRSessions.
*/
public class MCRAccessCacheEventHandler extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger();
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
MCRAccessCacheHelper.clearAllPermissionCaches(obj.getId().toString());
}
@Override
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
LOGGER.info("Invalidate permission cache for derivate {}", der.getId());
MCRAccessManager.invalidAllPermissionCachesById(der.getId().toString());
}
@Override
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
handleDerivateUpdated(evt, der);
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
MCRAccessCacheHelper.clearAllPermissionCaches(obj.getId().toString());
}
}
| 2,099 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessCacheHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/MCRAccessCacheHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.common.MCRLinkTableManager;
/**
* This class provides helper functions for access cache.
*/
public class MCRAccessCacheHelper {
private static final Logger LOGGER = LogManager.getLogger();
/**
* removes all cached permissions for the object and its derivates including descendants from local cache.
* @param id the object id
*/
public static void clearPermissionCache(String id) {
LOGGER.info("Invalidate all permissions for obj {} from local cache", id);
final ArrayList<String> idsToClear = new ArrayList<>();
idsToClear.add(id);
collectDescendants(idsToClear, id);
MCRAccessManager.invalidPermissionCacheByID(idsToClear.toArray(new String[0]));
}
/**
* removes all cached permission for the object and its derivates including descendants from all caches.
* @param id the object id
*/
public static void clearAllPermissionCaches(String id) {
LOGGER.info("Invalidate all permissions for obj {} from all caches", id);
final ArrayList<String> idsToClear = new ArrayList<>();
idsToClear.add(id);
collectDescendants(idsToClear, id);
MCRAccessManager.invalidAllPermissionCachesById(idsToClear.toArray(new String[0]));
}
private static void collectDescendants(List<String> idsToClear, String parent) {
// get derivates
final MCRLinkTableManager ltManager = MCRLinkTableManager.instance();
idsToClear.addAll(ltManager.getDestinationOf(parent, MCRLinkTableManager.ENTRY_TYPE_DERIVATE));
// get children
final Collection<String> children = ltManager.getSourceOf(parent, MCRLinkTableManager.ENTRY_TYPE_PARENT);
children.forEach(child -> {
idsToClear.add(child);
collectDescendants(idsToClear, child);
});
}
}
| 2,784 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectCacheFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/MCRObjectCacheFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.events.MCREvent;
import org.mycore.common.events.MCREventHandlerBase;
import org.mycore.common.events.MCREventManager;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* This implementation creates an object cache
* for MyCoRe objects which are retrieved during the processing of the rules.
*
* It is registered as event handler to listen for updated and deleted objects.
*
* @author Robert Stephan
*
*/
public class MCRObjectCacheFactory extends MCREventHandlerBase {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCRObjectCacheFactory SINGLETON = new MCRObjectCacheFactory();
private static final int CACHE_MAX_SIZE = 100;
private final MCRCache<MCRObjectID, MCRObject> objectCache;
private MCRObjectCacheFactory() {
objectCache = new MCRCache<>(CACHE_MAX_SIZE, this.getClass().getName());
MCREventManager.instance().addEventHandler(MCREvent.ObjectType.OBJECT, this);
}
public static MCRObjectCacheFactory instance() {
return SINGLETON;
}
public MCRObject getObject(MCRObjectID oid) {
MCRObject obj = objectCache.get(oid);
if (obj == null) {
LOGGER.debug("reading object {} from metadata manager", oid);
try {
obj = MCRMetadataManager.retrieveMCRObject(oid);
objectCache.put(oid, obj);
} catch (MCRPersistenceException e) {
LOGGER.debug("Object does not exist", e);
return null;
}
} else {
LOGGER.debug("reading object {} from cache", oid);
}
return obj;
}
@Override
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
objectCache.remove(obj.getId());
LOGGER.debug("removing object {} from cache", obj.getId());
}
@Override
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
objectCache.remove(obj.getId());
LOGGER.debug("removing object {} from cache", obj.getId());
}
@Override
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
objectCache.remove(obj.getId());
LOGGER.debug("removing object {} from cache", obj.getId());
}
}
| 3,310 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFactsAccessSystemHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/MCRFactsAccessSystemHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.access.facts.model.MCRCombinedCondition;
import org.mycore.access.facts.model.MCRCondition;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
/**
* Utility functions for parsing conditions from rules.xml
* in fact-based access system.
*
* @author Robert Stephan
*
*/
public class MCRFactsAccessSystemHelper {
public static final String CONDITION_PREFIX = "MCR.Access.Facts.Condition.";
public static MCRCondition parse(Element xml) {
String type = xml.getName();
MCRCondition cond = build(type);
cond.parse(xml);
return cond;
}
static MCRCondition build(String type) {
Optional<MCRCondition> optCondition = MCRConfiguration2.getInstanceOf(CONDITION_PREFIX + type);
if (optCondition.isEmpty()) {
throw new MCRConfigurationException("The Condition type " + type + " is not configured!");
}
MCRCondition condition = optCondition.get();
if (MCRFactsAccessSystem.LOGGER.isDebugEnabled() && condition instanceof MCRCombinedCondition combCond) {
combCond.setDebug(true);
}
return condition;
}
}
| 2,025 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFactsHolder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/MCRFactsHolder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import org.mycore.access.facts.model.MCRFact;
import org.mycore.access.facts.model.MCRFactComputable;
/**
* This class holds all facts which are validated as 'true'
* If an identical fact is request again during the rules processing
* the result is taken from here and won't be calculated again.
*
* Internally it also stores the fact computers, for easier access.
* Fact computers are usually the conditions parsed from the rules.xml.
*
* @author Robert Stephan
*
*/
public class MCRFactsHolder {
private Collection<MCRFactComputable<MCRFact<?>>> computers;
private final Set<MCRFact<?>> facts = new HashSet<>();
public MCRFactsHolder(Collection<MCRFactComputable<MCRFact<?>>> computers) {
this.computers = computers;
}
public void add(MCRFact<?> fact) {
facts.add(fact);
}
public boolean isFact(String factName, String term) {
Optional<MCRFact<?>> osc = facts.stream()
.filter(f -> factName.equals(f.getName()))
.filter(f -> term.equals(f.getTerm()))
.findFirst();
return osc.isPresent();
}
public Optional<MCRFact<?>> require(String factName, MCRFactComputable<MCRFact<?>> factComputer) {
Optional<MCRFact<?>> osc = facts.stream().filter(f -> factName.equals(f.getName())).findFirst();
if (osc.isPresent()) {
return osc;
} else {
Optional<MCRFact<?>> fact = factComputer.computeFact(this);
if (fact.isPresent()) {
facts.add(fact.get());
return fact;
}
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
public <F extends MCRFact<?>> Optional<F> require(String factName) {
Optional<F> osc = (Optional<F>) facts.stream().filter(f -> factName.equals(f.getName())).findFirst();
if (osc.isPresent()) {
return osc;
} else {
Optional<MCRFactComputable<MCRFact<?>>> theComputer = computers.stream()
.filter(c -> factName.equals(c.getFactName())).findFirst();
if (theComputer.isPresent()) {
Optional<MCRFact<?>> fact = theComputer.get().computeFact(this);
if (fact.isPresent()) {
facts.add(fact.get());
return (Optional<F>) fact;
}
}
}
return Optional.empty();
}
@Override
public String toString() {
StringJoiner sj = new StringJoiner(" & ");
facts.stream().forEach(f -> sj.add(f.toString()));
return sj.toString();
}
}
| 3,509 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFactsAccessSystem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/MCRFactsAccessSystem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.mycore.access.MCRAccessInterface;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.access.facts.model.MCRCombinedCondition;
import org.mycore.access.facts.model.MCRCondition;
import org.mycore.access.facts.model.MCRFact;
import org.mycore.access.facts.model.MCRFactComputable;
import org.mycore.access.strategies.MCRAccessCheckStrategy;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.common.config.annotation.MCRProperty;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.inject.Singleton;
/**
* base class for XML fact based access system
*
* enabled it with the 2 properties:
* MCR.Access.Class=org.mycore.access.facts.MCRFactsAccessSystem
* MCR.Access.Strategy.Class=org.mycore.access.facts.MCRFactsAccessSystem
*
*/
@Singleton
public class MCRFactsAccessSystem implements MCRAccessInterface, MCRAccessCheckStrategy {
private static String RESOLVED_RULES_FILE_NAME = "rules.resolved.xml";
protected static final Logger LOGGER = LogManager.getLogger();
private MCRCondition rules;
private Collection<MCRFactComputable<MCRFact<?>>> computers;
//RS: when introducing this feature in 2021.06.LTS it needed to be configured twice
//(as access system and as strategy). To simplify things during the transition period
//we are going to use the base property to initialize the rulesURI for both cases
//By using the property MCR.Access.Strategy.RulesURI it could be overwritten if used for strategy.
private String rulesURI = MCRConfiguration2.getString("MCR.Access.RulesURI").orElse("resource:rules.xml");
private Map<String, String> properties;
@MCRPostConstruction
public void init(String property) {
rules = buildRulesFromXML();
computers = buildComputersFromRules();
}
private Collection<MCRFactComputable<MCRFact<?>>> buildComputersFromRules() {
Map<String, MCRFactComputable<MCRFact<?>>> collectedComputers = new HashMap<>();
collectComputers(rules, collectedComputers);
return collectedComputers.values();
}
@SuppressWarnings("unchecked")
private void collectComputers(MCRCondition coll, Map<String, MCRFactComputable<MCRFact<?>>> computers) {
if (coll instanceof MCRFactComputable<?> factComp && !computers.containsKey(factComp.getFactName())) {
computers.put(factComp.getFactName(), (MCRFactComputable<MCRFact<?>>) factComp);
}
if (coll instanceof MCRCombinedCondition combCond) {
combCond.getChildConditions().forEach(c -> collectComputers(c, computers));
}
}
@MCRProperty(name = "RulesURI", required = false)
public void setRulesURI(String uri) {
rulesURI = uri;
}
public Map<String, String> getProperties() {
return properties;
}
@MCRProperty(name = "*")
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
private MCRCondition buildRulesFromXML() {
Element eRules = MCRURIResolver.instance().resolve(rulesURI);
Objects.requireNonNull(eRules, "The rulesURI " + rulesURI + " resolved to null!");
MCRJDOMContent content = new MCRJDOMContent(eRules);
try {
File configFile = MCRConfigurationDir.getConfigFile(RESOLVED_RULES_FILE_NAME);
if (configFile != null) {
content.sendTo(configFile);
} else {
throw new IOException("MCRConfigurationDir is not available!");
}
} catch (IOException e) {
LOGGER.error("Could not write file '" + RESOLVED_RULES_FILE_NAME + "' to config directory", e);
LOGGER.info("Rules file is: \n" + new XMLOutputter(Format.getPrettyFormat()).outputString(eRules));
}
return MCRFactsAccessSystemHelper.parse(eRules);
}
@Override
public boolean checkPermission(String id, String permission) {
return this.checkPermission(id, permission, MCRSessionMgr.getCurrentSession().getUserInformation());
}
@Override
public boolean checkPermissionForUser(String permission, MCRUserInformation userInfo) {
return false;
}
public boolean checkPermission(String checkID, String permission, List<MCRFact> baseFacts) {
String action = permission.replaceAll("db$", ""); // writedb -> write
String target; // metadata|files|webpage
String cacheKey;
MCRFactsHolder facts = new MCRFactsHolder(computers);
baseFacts.forEach(facts::add);
if (checkID == null) {
cacheKey = action;
} else {
if (checkID.startsWith("webpage")) {
target = "webpage";
} else if (checkID.startsWith("solr")) {
target = "solr";
} else if (isCategory(checkID)) {
target = "category";
} else if (MCRObjectID.isValid(checkID)) {
MCRObjectID mcrId = MCRObjectID.getInstance(checkID);
target = "derivate".equals(mcrId.getTypeId()) ? "files" : "metadata";
if (MCRMetadataManager.exists(mcrId)) {
if ("derivate".equals(mcrId.getTypeId())) {
facts.add(new MCRObjectIDFact("derid", checkID, mcrId));
MCRObjectID mcrobjID = MCRMetadataManager.getObjectId(mcrId, 10, TimeUnit.MINUTES);
if (mcrobjID != null) {
facts.add(new MCRObjectIDFact("objid", checkID, mcrobjID));
}
} else {
facts.add(new MCRObjectIDFact("objid", checkID, mcrId));
}
} else {
LOGGER.debug("There is no object or derivate with id " + mcrId + " in metadata store");
}
} else {
target = "unknown";
}
cacheKey = action + " " + checkID + " " + target;
facts.add(new MCRStringFact("id", checkID));
facts.add(new MCRStringFact("target", target));
}
facts.add(new MCRStringFact("action", action));
LOGGER.debug("Testing {} ", cacheKey);
boolean result;
if (LOGGER.isDebugEnabled()) {
MCRCondition rules = buildRulesFromXML();
result = rules.matches(facts);
LOGGER.debug("Facts are: {}", facts);
Element xmlTree = rules.getBoundElement();
String xmlString = new XMLOutputter(Format.getPrettyFormat()).outputString(xmlTree);
LOGGER.debug(xmlString);
} else {
result = rules.matches(facts);
}
LOGGER.info("Checked permission to {} := {}", cacheKey, result);
return result;
}
private boolean isCategory(String checkID) {
if (!MCRCategoryID.isValid(checkID)) {
return false;
}
try {
return MCRCategoryDAOFactory.getInstance().exist(MCRCategoryID.fromString(checkID));
} catch (IllegalArgumentException e) {
return false;
}
}
@Override
public boolean checkPermission(final String checkID, String permission, MCRUserInformation userInfo) {
return checkPermission(checkID, permission, Collections.emptyList());
}
@Override
public boolean checkPermission(String permission) {
return checkPermission(null, permission);
}
}
| 9,181 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/MCRAbstractCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.model.MCRCondition;
/**
* This is the base implementation for a condition.
*
* It is the super class for MCRCombinedCondition and MCRFactCondition.
*
* @author Robert Stephan
*
*/
public abstract class MCRAbstractCondition implements MCRCondition {
private Element boundElement = null;
private String type;
private boolean debug;
/**
* implementors of this method should call super.parse(xml) to bind the XML element to the condition
*/
public void parse(Element xml) {
boundElement = xml;
type = xml.getName();
}
public Element getBoundElement() {
return boundElement;
}
public String getType() {
return type;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean b) {
this.debug = b;
}
public abstract boolean matches(MCRFactsHolder facts);
}
| 1,778 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRNotCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/combined/MCRNotCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import org.mycore.access.facts.MCRFactsHolder;
/**
* This condition negates its child condition
* (boolean NOT)
*
* Only the first child condition will be evaluated.
* Further child conditions will be ignored.
*
* @author Robert Stephan
*
*/
public final class MCRNotCondition extends MCRAbstractCombinedCondition {
public boolean matches(MCRFactsHolder facts) {
return conditions.stream()
.limit(1)
.filter(c -> !addDebugInfoIfRequested(c, facts))
.count() == 1;
}
}
| 1,313 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractCombinedCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/combined/MCRAbstractCombinedCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsAccessSystemHelper;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.condition.MCRAbstractCondition;
import org.mycore.access.facts.model.MCRCombinedCondition;
import org.mycore.access.facts.model.MCRCondition;
/**
* This is the base implementation for a combined condition.
* It can be used to create conditions for a boolean algebra (and, or, not)
*
* @author Robert Stephan
*
*/
sealed public abstract class MCRAbstractCombinedCondition extends MCRAbstractCondition implements MCRCombinedCondition
permits MCRAndCondition, MCRNotCondition, MCROrCondition, MCRXorCondition {
protected Set<MCRCondition> conditions = new LinkedHashSet<>();
public void add(MCRCondition condition) {
conditions.add(condition);
}
public void parse(Element xml) {
super.parse(xml);
for (Element child : xml.getChildren()) {
conditions.add(MCRFactsAccessSystemHelper.parse(child));
}
}
/**
* @return the conditions
*/
public Set<MCRCondition> getChildConditions() {
return conditions;
}
@Deprecated
public void debugInfoForMatchingChildElement(MCRCondition c, boolean matches) {
if (isDebug()) {
Element el = c.getBoundElement();
if (el != null) {
el.setAttribute("_matches", Boolean.toString(matches));
}
}
}
boolean addDebugInfoIfRequested(MCRCondition c, MCRFactsHolder facts) {
if (!isDebug()) {
return c.matches(facts);
}
boolean matches = c.matches(facts);
Objects.requireNonNull(c.getBoundElement(), "Condition is not bound to an element.")
.setAttribute("_matches", Boolean.toString(matches));
return matches;
}
}
| 2,721 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXorCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/combined/MCRXorCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import org.mycore.access.facts.MCRFactsHolder;
public final class MCRXorCondition extends MCRAbstractCombinedCondition {
@Override
public boolean matches(MCRFactsHolder facts) {
return conditions.stream()
.filter(c -> addDebugInfoIfRequested(c, facts))
.limit(2)
.count() == 1;
}
}
| 1,119 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCROrCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/combined/MCROrCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import org.mycore.access.facts.MCRFactsHolder;
/**
* /**
* This condition combines its child conditions with a boolean OR
*
* @author Robert Stephan
*
*/
public final class MCROrCondition extends MCRAbstractCombinedCondition {
public boolean matches(MCRFactsHolder facts) {
return conditions.stream().anyMatch(c -> addDebugInfoIfRequested(c, facts));
}
}
| 1,159 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAndCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/combined/MCRAndCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.combined;
import org.mycore.access.facts.MCRFactsHolder;
/**
* This condition combines its child conditions with a boolean AND
*
* @author Robert Stephan
*
*/
public final class MCRAndCondition extends MCRAbstractCombinedCondition {
public boolean matches(MCRFactsHolder facts) {
return conditions.stream().allMatch(c -> addDebugInfoIfRequested(c, facts));
}
}
| 1,155 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIPCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRIPCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.net.UnknownHostException;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRIpAddressFact;
import org.mycore.access.mcrimpl.MCRIPAddress;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.annotation.MCRProperty;
/**
* This condition checks if the current user has an IP of the specified IP range.
*
* Example:
* <ip>192.168.0.0/255.255.0.0</ip>
*
* Please specify IP ranges with the full netmask.
*
* @author Robert Stephan
*
*/
public class MCRIPCondition extends MCRAbstractFactCondition<MCRIpAddressFact> {
private static Logger LOGGER = LogManager.getLogger();
private String defaultIP;
public void parse(Element xml) {
super.parse(xml);
if (StringUtils.isEmpty(getTerm()) && StringUtils.isNotEmpty(defaultIP)) {
setTerm(defaultIP);
}
}
@Override
public Optional<MCRIpAddressFact> computeFact(MCRFactsHolder facts) {
MCRSession session = MCRSessionMgr.getCurrentSession();
try {
MCRIPAddress checkIP = new MCRIPAddress(getTerm());
MCRIPAddress currentIP = new MCRIPAddress(session.getCurrentIP());
if (checkIP.contains(currentIP)) {
MCRIpAddressFact fact = new MCRIpAddressFact(getFactName(), getTerm());
fact.setValue(currentIP);
facts.add(fact);
return Optional.of(fact);
}
} catch (UnknownHostException e) {
LOGGER.error("Unknown IP Address", e);
}
return Optional.empty();
}
@MCRProperty(name = "IP", required = false)
public void setDefaultIP(String ip) {
defaultIP = ip;
}
}
| 2,731 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRUserCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Optional;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
/**
* This condition checks if the current user matches the query string.
*
* Example:
* <user>mcradmin</user>
*
* @author mcradmin
*
*/
public class MCRUserCondition extends MCRStringCondition {
@Override
public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) {
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUserInformation user = session.getUserInformation();
if (user != null && getTerm().equals(user.getUserID())) {
MCRStringFact fact = new MCRStringFact(getFactName(), getTerm());
fact.setValue(user.getUserID());
facts.add(fact);
return Optional.of(fact);
}
return Optional.empty();
}
}
| 1,763 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStringCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRStringCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Optional;
import org.mycore.access.facts.MCRFactsAccessSystem;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRStringFact;
/**
* This is a simple implemenation.
* It checks if the fact already exists in the fact database and returns it.
* Otherwise it returns an empty Optional
*
* This is useful for "static" facts that are created before the rule processing started
* in MCRFactsAccessSystem.
*
* @author Robert Stephan
*
*/
public class MCRStringCondition extends MCRAbstractFactCondition<MCRStringFact> {
/**
* Subclasses should override this method to retrieve the fact from MyCoReObject, MCRSession
* or from elsewhere ...
*
* @see MCRFactsAccessSystem
*/
@Override
public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) {
MCRStringFact checkFact = new MCRStringFact(getFactName(), getTerm());
if (facts.isFact(getFactName(), getTerm())) {
return Optional.of(checkFact);
} else {
//check if a simpleFact with the default name (name of Element) was stored in facts
//and save it with the new name
if (facts.isFact(getType(), getTerm())) {
facts.add(checkFact);
return Optional.of(checkFact);
}
}
return Optional.empty();
}
}
| 2,162 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStateCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRStateCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRObject;
/**
* This implementation of a condition
* checks if the given MyCoRe object or derivate
* has the given state entry in service flags.
*
* Examples:
*
* <status>review</status>
* <status idfact="derid">published</status>
*
* @author Robert Stephan
*
*/
public class MCRStateCondition extends MCRStringCondition {
/**
* id of the fact that contains the ID of the MyCoRe-Object or Derivate
* possible values are "objid" or "derivateid".
*/
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> idc = facts.require(idFact);
if (idc.isPresent()) {
Optional<MCRObject> optMcrObj = idc.get().getObject();
if (optMcrObj.isPresent()) {
MCRCategoryID state = optMcrObj.get().getService().getState();
if (getTerm().equals(state.getId())) {
MCRStringFact fact = new MCRStringFact(getFactName(), getTerm());
fact.setValue(state.getId());
facts.add(fact);
return Optional.of(fact);
}
}
}
return Optional.empty();
}
}
| 2,525 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRCategoryCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Objects;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRCategoryIDFact;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* This implementation checks if the given object belongs to a certain classification entry.
*
* As default the object is read from the fact "objid".
* Using the attribute 'idfact' another fact containing an object id can be specified
*
* Example:
* <category idfact='the_other_object' fact='published'>state:published</category>
*
* This rule will check if the object already stored as fact 'the_other_object' belongs to
* the category 'state:published'.
* If true, a fact 'published' will be stored in the facts holder.
*
*
* @author Robert Stephan
*
*/
public class MCRCategoryCondition extends MCRAbstractFactCondition<MCRCategoryIDFact> {
private static Logger LOGGER = LogManager.getLogger();
private String idFact = "objid";
@Override
public void parse(Element xml) {
super.parse(xml);
if (xml.getAttributeValue("id") != null) {
LOGGER.warn("Attribute 'id' is deprecated - use 'idfact' instead!");
}
this.idFact = Optional.ofNullable(xml.getAttributeValue("idfact")).orElse("objid");
}
@Override
public Optional<MCRCategoryIDFact> computeFact(MCRFactsHolder facts) {
Optional<MCRObjectIDFact> idc = facts.require(idFact);
if (idc.isPresent()) {
MCRObjectID objectID = idc.get().getValue();
if (objectID != null) {
MCRCategoryID categoryID = MCRCategoryID.fromString(getTerm());
MCRCategLinkService linkService = MCRCategLinkServiceFactory.getInstance();
if (linkService.isInCategory(new MCRCategLinkReference(objectID), categoryID)) {
MCRCategoryIDFact result = new MCRCategoryIDFact(getFactName(), getTerm());
result.setValue(categoryID);
facts.add(result);
return Optional.of(result);
}
}
}
return Optional.empty();
}
@Override
public String getFactName() {
return super.getFactName() + "." + idFact;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
MCRCategoryCondition that = (MCRCategoryCondition) o;
return idFact.equals(that.idFact);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), idFact);
}
}
| 3,964 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCreatedByCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRCreatedByCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRObjectIDFact;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.common.MCRSessionMgr;
import org.mycore.datamodel.metadata.MCRObject;
/**
* This condition check if the given object has the specified createdby service flag.
*
* If term in condition is empty - the check is for the current user
*
* <createdby /> checks if the object was created by currentUser
* <createdby>administrator</createdby>
*
* @author Robert Stephan
*
*/
public class MCRCreatedByCondition extends MCRStringCondition {
private String idFact = "objid";
@Override
public void parse(Element xml) {
super.parse(xml);
idFact = Optional.ofNullable(xml.getAttributeValue("idfact")).orElse("objid");
}
@Override
public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) {
Optional<MCRObjectIDFact> idc = facts.require(idFact);
if (idc.isPresent()) {
Optional<MCRObject> optMcrObj = idc.get().getObject();
if (optMcrObj.isPresent()) {
String checkUser = StringUtils.defaultIfBlank(getTerm(),
MCRSessionMgr.getCurrentSession().getUserInformation().getUserID());
List<String> flags = optMcrObj.get().getService().getFlags("createdby");
for (String flag : flags) {
if (flag.equals(checkUser)) {
MCRStringFact fact = new MCRStringFact(getFactName(), getTerm());
fact.setValue(checkUser);
facts.add(fact);
return Optional.of(fact);
}
}
}
}
return Optional.empty();
}
}
| 2,707 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRoleCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRRoleCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Optional;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
/**
* This condition checks if the user of the current session
* is member of the given role.
*
* @author Robert Stephan
*
*/
public class MCRRoleCondition extends MCRStringCondition {
@Override
public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) {
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUserInformation user = session.getUserInformation();
if (user.isUserInRole(getTerm())) {
MCRStringFact fact = new MCRStringFact(getFactName(), getTerm());
facts.add(fact);
return Optional.of(fact);
}
return Optional.empty();
}
}
| 1,672 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractFactCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRAbstractFactCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.condition.MCRAbstractCondition;
import org.mycore.access.facts.model.MCRFact;
import org.mycore.access.facts.model.MCRFactCondition;
/**
* This is the base implementation for a condition which evaluates or produces facts
*
* Subclasses should call super.parse(xml) to bind the XML element to the condition.
*
* If you specify the attribute 'fact' on the condition XML. It will be used as name for
* the newly created fact. Otherwise the name of the condition will be used as name for the fact.
*
* @author Robert Stephan
*
* @param <F> the class of the fact
*/
public abstract class MCRAbstractFactCondition<F extends MCRFact<?>> extends MCRAbstractCondition
implements MCRFactCondition<F> {
static final String UNDEFINED = "undefined";
private String factName;
private String term;
/**
* implementors of this method should call super.parse(xml) to bind the XML element to the condition
*/
public void parse(Element xml) {
super.parse(xml);
term = xml.getTextTrim();
factName = Optional.ofNullable(xml.getAttributeValue("fact")).orElse(getType());
}
@Override
public boolean matches(MCRFactsHolder facts) {
if (facts.isFact(getFactName(), getTerm())) {
return true;
}
Optional<F> computed = computeFact(facts);
return computed.isPresent();
}
public String getFactName() {
return factName;
}
public void setFactName(String factName) {
this.factName = factName;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
}
| 2,574 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRegExCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/condition/fact/MCRRegExCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.condition.fact;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
import org.mycore.access.facts.fact.MCRStringFact;
import org.mycore.access.facts.model.MCRFact;
/**
* This condition checks if the given id or another fact matches a regular expression.
*
* Examples:
* <rege>webpage:/content/search/.*_intern.xed</regex>
* <regex basefact='user'>.*admin</regex>
* <regex basefact='category'>ddc:.*</regex>
*
* @author Robert Stephan
*
*/
public class MCRRegExCondition extends MCRStringCondition {
private String baseFactName;
@Override
public void parse(Element xml) {
super.parse(xml);
baseFactName = Optional.ofNullable(xml.getAttributeValue("basefact")).orElse("id");
setFactName(Optional.ofNullable(xml.getAttributeValue("fact")).orElse(getType() + "-" + baseFactName));
}
@Override
public Optional<MCRStringFact> computeFact(MCRFactsHolder facts) {
Optional<MCRFact<?>> baseFact = facts.require(baseFactName);
if (baseFact.isPresent()) {
String v = baseFact.get().getValue().toString();
if (v.matches(getTerm())) {
MCRStringFact fact = new MCRStringFact(getFactName(), getTerm());
fact.setValue(v);
facts.add(fact);
return Optional.of(fact);
}
}
return Optional.empty();
}
}
| 2,231 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDFact.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/fact/MCRObjectIDFact.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.fact;
import java.util.Optional;
import org.mycore.access.facts.MCRObjectCacheFactory;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* This fact implementation can store a MyCoRe object id
* and allows access to the corresponding MyCoRe object.
*
* @author Robert Stephan
*
*/
public class MCRObjectIDFact extends MCRAbstractFact<MCRObjectID> {
public MCRObjectIDFact(String name, String term) {
super(name, term);
}
public MCRObjectIDFact(String name, String term, MCRObjectID value) {
super(name, term);
setValue(value);
}
/**
* @return the object for this condition or null if it is not a object
*/
public Optional<MCRObject> getObject() {
MCRObjectID objectID = getValue();
if (objectID == null) {
return Optional.empty();
}
return Optional.ofNullable(MCRObjectCacheFactory.instance().getObject(objectID));
}
}
| 1,749 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIpAddressFact.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/fact/MCRIpAddressFact.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.fact;
import org.mycore.access.mcrimpl.MCRIPAddress;
/**
* This fact implementation can store an IP address
*
* @author Robert Stephan
*
* @see MCRIPAddress
*
*/
public class MCRIpAddressFact extends MCRAbstractFact<MCRIPAddress> {
public MCRIpAddressFact(String name, String inquiry) {
super(name, inquiry);
}
}
| 1,099 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryIDFact.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/fact/MCRCategoryIDFact.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.fact;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* This fact implementation can store a MyCoRe classification as MCRCategoryID
*
* @author Robert Stephan
*
*/
public class MCRCategoryIDFact extends MCRAbstractFact<MCRCategoryID> {
public MCRCategoryIDFact(String name, String term) {
super(name, term);
}
}
| 1,111 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractFact.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/fact/MCRAbstractFact.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.fact;
import java.util.Objects;
import org.mycore.access.facts.model.MCRFact;
/**
* This is the base implementation for a fact.
* A fact consists of a name and a value.
* Additionally the query term used to retrieve the fact is stored.
*
* Two facts are equal if their names and terms are equal.
*
* @author Robert Stephan
*
* @param <T> the type of the fact
*
* @see MCRFact
*
*/
public abstract class MCRAbstractFact<T> implements MCRFact<T> {
private T value = null;
private String name;
private String term;
public MCRAbstractFact(String name, String term) {
this.name = name;
this.term = term;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void setTerm(String term) {
this.term = term;
}
@Override
public String getTerm() {
return term;
}
@Override
public void setValue(T value) {
this.value = value;
}
@Override
public T getValue() {
return value;
}
@Override
public String toString() {
return name + "=" + value.toString();
}
@Override
public int hashCode() {
return Objects.hash(name, term);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof @SuppressWarnings("rawtypes") MCRAbstractFact other)) {
return false;
}
return Objects.equals(name, other.name) && Objects.equals(term, other.term);
}
}
| 2,409 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStringFact.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/fact/MCRStringFact.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.fact;
/**
* This implementation can store a simple String as fact.
*
* In the default case the query term is stored as value.
* Subclasses may override this behaviour.
*
* @author Robert Stephan
*
*/
public class MCRStringFact extends MCRAbstractFact<String> {
public MCRStringFact(String name, String term) {
super(name, term);
setValue(term);
}
}
| 1,143 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/model/MCRCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.model;
import org.jdom2.Element;
import org.mycore.access.facts.MCRFactsHolder;
/**
* This interface represents a rule of the fact-based access system.
* It is specified in the rules.xml file.
*
* Sub interfaces are {@link MCRCombinedCondition}, which is used to build a boolean algebra (and, or, not, ...)
* and {@link MCRFactCondition}, which validates existing facts or creates new ones.
*
* New rules need to be registered in mycore.properties as follows:
*
* MCR.Access.Facts.Condition.{type}={class}
* e.g. MCR.Access.Facts.Condition.ip=org.mycore.access.facts.condition.fact.MCRIPCondition
*
* @author Robert Stephan
*
*/
public interface MCRCondition {
/**
* the type of the rule
*/
String getType();
boolean matches(MCRFactsHolder facts);
void parse(Element xml);
/**
* This is primary for rules.xml debugging purposes
* @return the part of the xml which this Condition represents
*/
Element getBoundElement();
boolean isDebug();
void setDebug(boolean b);
}
| 1,810 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCombinedCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/model/MCRCombinedCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.model;
import java.util.Set;
/**
* This interface is for conditions that combine other conditions.
* It is used to build a boolean algebra (and, or, not)
*
* @author Robert Stephan
*
* @see MCRCondition
*
*/
public interface MCRCombinedCondition extends MCRCondition {
void add(MCRCondition c);
Set<MCRCondition> getChildConditions();
}
| 1,119 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFactComputable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/model/MCRFactComputable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.model;
import java.util.Optional;
import org.mycore.access.facts.MCRFactsHolder;
/**
* This interface can be used to implement a class which can generated new
* facts based on the current fact list.
*
* Usually the fact list already contains a fact with an MyCoRe ObjectID
* which can be used to retrieve more facts from the given object.
*
* @author Robert Stephan
*
* @param <F> the class of the fact that can be created by this fact computer
*/
public interface MCRFactComputable<F extends MCRFact<?>> extends MCRCondition {
String getFactName();
/**
* Implementors are responsible to store the facts holder in the fact set
* if applicable
*
* @param facts - the facts holder containing already retrieved facts
*/
Optional<F> computeFact(MCRFactsHolder facts);
}
| 1,579 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFact.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/model/MCRFact.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.model;
/**
* A fact is simple piece of information.
* It is retrieved by an @MCRFactComputer from a certain MyCoReObject, Derivate, ...
* and other information from the application (e.g. MCRSession) or from other already retrieved facts.
*
* It consists of a name and a typed value.
*
* Additional the query string, used to retrieve the fact is, stored.
* This can be useful for facts, that are retrieved via regular expression or wildcard expressions.
*
* @author Robert Stephan
*
* @param <V> the class of the value.
*/
public interface MCRFact<V> {
void setName(String name);
String getName();
void setTerm(String term);
String getTerm();
void setValue(V value);
V getValue();
}
| 1,490 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFactCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/facts/model/MCRFactCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.facts.model;
/**
* This interface describes a rule (from rules.xml) which can evaluate existing facts
* or create new facts if applicable.
*
* By extending {@link MCRFactComputable} the rule knows how to create its facts
* from the given object or environment.
*
* New rules need to be registered in mycore.properties as follows:
*
* MCR.Access.Facts.Condition.{type}={class}
* e.g. MCR.Access.Facts.Condition.ip=org.mycore.access.facts.condition.fact.MCRIPCondition
*
* @author Robert Stephan
*
* @param <F> the fact to be generated
*/
public interface MCRFactCondition<F extends MCRFact<?>> extends MCRCondition, MCRFactComputable<F> {
}
| 1,413 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIPAddress.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRIPAddress.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.stream.IntStream;
import org.mycore.common.MCRException;
/**
* A class for representing an IP Address, or a range of IP addresses
*
* @author Matthias Kramm
*/
public class MCRIPAddress {
byte[] address;
byte[] mask;
public MCRIPAddress(String ip) throws UnknownHostException {
int i = ip.indexOf('/');
if (i >= 0) {
String ipstr = ip.substring(0, i);
String maskstr = ip.substring(i + 1);
InetAddress address = InetAddress.getByName(ipstr);
InetAddress mask = InetAddress.getByName(maskstr);
init(address, mask);
} else {
InetAddress address = InetAddress.getByName(ip);
init(address);
}
}
public MCRIPAddress(InetAddress address, InetAddress mask) {
init(address, mask);
}
public MCRIPAddress(InetAddress address) {
init(address);
}
public void init(InetAddress address, InetAddress mask) {
this.address = address.getAddress();
this.mask = mask.getAddress();
}
public void init(InetAddress address) {
this.address = address.getAddress();
mask = new byte[this.address.length];
Arrays.fill(mask, (byte) 255);
}
public boolean contains(MCRIPAddress other) {
if (address.length != other.address.length) {
return false;
}
return IntStream.range(0, address.length)
.noneMatch(t -> (address[t] & mask[t]) != (other.address[t] & mask[t]));
}
public byte[] getAddress() {
return address;
}
@Override
public String toString() {
try {
InetAddress inetAddress = InetAddress.getByAddress(address);
InetAddress maskAddress = InetAddress.getByAddress(mask);
StringBuilder sb = new StringBuilder();
sb.append(inetAddress.getHostAddress());
sb.append('/');
sb.append(maskAddress.getHostAddress());
return sb.toString();
} catch (UnknownHostException e) {
throw new MCRException(e); //should never happen
}
}
}
| 3,010 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRuleMapping.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRRuleMapping.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.Date;
public class MCRRuleMapping {
private String ruleid;
private String objid;
private String pool;
private String creator;
private Date creationdate;
public MCRRuleMapping() {
}
/**
* returns MCRObjectID as string
*
* @return MCRObjectID as string
*/
public String getObjId() {
return objid;
}
public void setObjId(String objid) {
this.objid = objid;
}
public String getPool() {
return pool;
}
public void setPool(String pool) {
this.pool = pool;
}
public String getRuleId() {
return ruleid;
}
public void setRuleId(String ruleid) {
this.ruleid = ruleid;
}
public Date getCreationdate() {
return new Date(creationdate.getTime());
}
public void setCreationdate(Date creationdate) {
this.creationdate = new Date(creationdate.getTime());
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
}
| 1,865 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessRule.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessRule.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.jdom2.Element;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRUserInformation;
import org.mycore.parsers.bool.MCRCondition;
import org.mycore.parsers.bool.MCRParseException;
public class MCRAccessRule implements org.mycore.access.MCRAccessRule {
private String id = "";
private String creator = "";
private Date creationTime = new Date();
String rule = "";
private String description = "";
private MCRCondition<MCRAccessData> parsedRule;
private static MCRRuleParser parser = new MCRRuleParser();
public MCRAccessRule(String id, String creator, Date creationTime, String rule, String description)
throws MCRParseException {
setId(id);
setCreator(creator);
setCreationTime(creationTime);
setRule(rule);
setDescription(description);
}
@Deprecated
public boolean checkAccess(String userID, Date date, MCRIPAddress ip) {
if (parsedRule == null) {
if (userID.equals(MCRSystemUserInformation.getSuperUserInstance().getUserID())) {
LogManager.getLogger(MCRAccessRule.class).debug("No rule defined, grant access to super user.");
return true;
}
return false;
}
LogManager.getLogger(this.getClass()).debug("new MCRAccessData");
MCRAccessData data = new MCRAccessData(userID, date, ip);
LogManager.getLogger(this.getClass()).debug("new MCRAccessData done.");
LogManager.getLogger(this.getClass()).debug("evaluate MCRAccessData");
boolean returns = parsedRule.evaluate(data);
LogManager.getLogger(this.getClass()).debug("evaluate MCRAccessData done.");
return returns;
}
public boolean checkAccess(MCRUserInformation userInfo, Date date, MCRIPAddress ip) {
if (parsedRule == null) {
if (userInfo.getUserID().equals(MCRSystemUserInformation.getSuperUserInstance().getUserID())) {
LogManager.getLogger(MCRAccessRule.class).debug("No rule defined, grant access to super user.");
return true;
}
return false;
}
LogManager.getLogger(this.getClass()).debug("new MCRAccessData");
MCRAccessData data = new MCRAccessData(userInfo, date, ip);
LogManager.getLogger(this.getClass()).debug("new MCRAccessData done.");
LogManager.getLogger(this.getClass()).debug("evaluate MCRAccessData");
boolean returns = parsedRule.evaluate(data);
LogManager.getLogger(this.getClass()).debug("evaluate MCRAccessData done.");
return returns;
}
public MCRCondition<MCRAccessData> getRule() {
return parsedRule;
}
public void setRule(String rule) {
this.rule = rule;
parsedRule = rule == null ? null : parser.parse(rule);
}
public String getRuleString() {
if (rule == null) {
return "";
}
return rule;
}
public Date getCreationTime() {
return new Date(creationTime.getTime());
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime == null ? null : new Date(creationTime.getTime());
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Element getRuleElement() {
Element el = new Element("mcraccessrule");
el.addContent(new Element("id").setText(id));
el.addContent(new Element("creator").setText(id));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
el.addContent(new Element("creationdate").setText(df.format(creationTime)));
el.addContent(new Element("rule").setText(rule));
el.addContent(new Element("description").setText("" + description));
return el;
}
@Override
public boolean validate() {
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUserInformation userInfo = session.getUserInformation();
MCRIPAddress mcripAddress;
try {
mcripAddress = new MCRIPAddress(session.getCurrentIP());
} catch (UnknownHostException e) {
LogManager.getLogger(MCRAccessRule.class).warn("Error while checking rule.", e);
return false;
}
return checkAccess(userInfo, new Date(), mcripAddress);
}
}
| 5,778 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIPClause.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRIPClause.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRIPCondition;
import org.mycore.parsers.bool.MCRParseException;
/**
* Implementation of a (ip xy) clause
*
* @author Matthias Kramm
*/
public class MCRIPClause implements MCRIPCondition {
private MCRIPAddress ip;
public MCRIPClause() {
}
public MCRIPClause(String ip) throws MCRParseException {
set(ip);
}
@Override
public void set(String ip) throws MCRParseException {
try {
this.ip = new MCRIPAddress(ip);
} catch (java.net.UnknownHostException e) {
throw new MCRParseException("Couldn't parse/resolve host " + ip);
}
}
@Override
public boolean evaluate(MCRAccessData data) {
return data.getIp() != null && ip.contains(data.getIp());
}
@Override
public String toString() {
return "ip " + ip + " ";
}
@Override
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", "ip");
cond.setAttribute("operator", "=");
cond.setAttribute("value", ip.toString());
return cond;
}
}
| 1,921 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserClause.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRUserClause.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.Optional;
import java.util.regex.Pattern;
import org.jdom2.Element;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
import org.mycore.parsers.bool.MCRCondition;
/**
* Implementation of a (user xy) clause
*
* @author Matthias Kramm
*/
class MCRUserClause implements MCRCondition<Object> {
private String user;
private Pattern userRegEx;
private boolean not;
MCRUserClause(String user, boolean not) {
if (user.contains("*")) {
userRegEx = toRegex(user);
}
this.user = user;
this.not = not;
}
private Pattern toRegex(String userExp) {
StringBuilder regex = new StringBuilder("^");
for (int i = 0; i < userExp.length(); i++) {
char c = userExp.charAt(i);
if (c == '*') {
regex.append(".*");
} else {
regex.append(c);
}
}
regex = regex.append('$');
return Pattern.compile(regex.toString());
}
public boolean evaluate(Object o) {
MCRUserInformation userInformation = Optional.ofNullable(o)
.filter(obj -> obj instanceof MCRAccessData)
.map(MCRAccessData.class::cast)
.map(MCRAccessData::getUserInformation)
.orElseGet(MCRSessionMgr.getCurrentSession()::getUserInformation);
if (userRegEx != null) {
return userRegEx.matcher(userInformation.getUserID()).matches() ^ not;
}
return user.equals(userInformation.getUserID()) ^ not;
}
@Override
public String toString() {
return "user" + (not ? " != " : " = ") + user + " ";
}
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", "user");
cond.setAttribute("operator", (not ? "!=" : "="));
cond.setAttribute("value", user);
return cond;
}
}
| 2,712 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDummyClause.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRDummyClause.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRCondition;
/**
* Implementation of a dummy clause (useful for debugging)
*
* @author Matthias Kramm
*/
class MCRDummyClause implements MCRCondition<Object> {
private String s;
MCRDummyClause(String s) {
this.s = s;
}
public boolean evaluate(Object o) {
return false;
}
@Override
public String toString() {
return "\"" + s + "\"";
}
public Element toXML() {
return null; /* TODO */
}
}
| 1,290 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGroupClause.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRGroupClause.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.Optional;
import org.jdom2.Element;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
import org.mycore.parsers.bool.MCRCondition;
/**
* Implementation of a (group xy) clause
*
* @author Matthias Kramm
* @author Mathias Fricke
*/
class MCRGroupClause implements MCRCondition<Object> {
private String groupname;
private boolean not;
MCRGroupClause(String group, boolean not) {
groupname = group;
this.not = not;
}
public boolean evaluate(Object o) {
MCRUserInformation userInformation = Optional.ofNullable(o)
.filter(obj -> obj instanceof MCRAccessData)
.map(MCRAccessData.class::cast)
.map(MCRAccessData::getUserInformation)
.orElseGet(MCRSessionMgr.getCurrentSession()::getUserInformation);
return userInformation.isUserInRole(groupname) ^ not;
}
@Override
public String toString() {
return "group" + (not ? " != " : " = ") + groupname + " ";
}
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", "group");
cond.setAttribute("operator", (not ? "!=" : "="));
cond.setAttribute("value", groupname);
return cond;
}
}
| 2,058 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDateAfterClause.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRDateAfterClause.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRCondition;
/**
* Implementation of a (date > xy) clause
*
* @author Matthias Kramm
*/
class MCRDateAfterClause implements MCRCondition<MCRAccessData> {
private Date date;
private DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
MCRDateAfterClause(Date date) {
this.date = date;
}
public boolean evaluate(MCRAccessData data) {
return data.getDate().after(date);
}
@Override
public String toString() {
return "date > " + dateformat.format(date) + " ";
}
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", "date");
cond.setAttribute("operator", ">");
cond.setAttribute("value", dateformat.format(date));
return cond;
}
}
| 1,743 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessData.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessData.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.Date;
import org.mycore.common.MCRUserInformation;
public class MCRAccessData {
private String userID;
private MCRUserInformation userInformation;
private Date date;
private MCRIPAddress ip;
@Deprecated
MCRAccessData(String userID, Date date, MCRIPAddress ip) {
this.userID = userID;
this.date = date;
this.ip = ip;
}
MCRAccessData(MCRUserInformation userInfo, Date date, MCRIPAddress ip) {
this.userInformation = userInfo;
this.date = date;
this.ip = ip;
}
public MCRAccessData() {
}
public Date getDate() {
return new Date(date.getTime());
}
public void setDate(Date date) {
this.date = new Date(date.getTime());
}
public MCRIPAddress getIp() {
return ip;
}
public void setIp(MCRIPAddress ip) {
this.ip = ip;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public MCRUserInformation getUserInformation() {
return userInformation;
}
public void setUserInformation(MCRUserInformation userInformation) {
this.userInformation = userInformation;
}
}
| 2,026 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.access.MCRJPAAccessStore;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
/**
* The purpose of this class is to make the choice of the persistence layer
* configurable. Any concrete database-class which stores MyCoRe Access control
* must implement this interface. Which database actually will be used can then
* be configured by reading the value <code>MCR.Persistence.Access.Store.Class</code>
* from mycore.properties.access
*
* @author Arne Seifert
*/
public abstract class MCRAccessStore {
private static final Logger LOGGER = LogManager.getLogger(MCRAccessStore.class);
protected static final String SQL_DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
protected static final String ACCESS_POOLS = MCRConfiguration2.getString("MCR.AccessPools")
.orElse("read,write,delete");
private static MCRAccessStore implementation;
public abstract String getRuleID(String objID, String acPool);
public abstract void createAccessDefinition(MCRRuleMapping accessdata);
public abstract void deleteAccessDefinition(MCRRuleMapping accessdata);
public abstract void updateAccessDefinition(MCRRuleMapping accessdata);
public abstract MCRRuleMapping getAccessDefinition(String pool, String objid);
public abstract Collection<String> getMappedObjectId(String pool); // ArrayList with ObjID's as String
public abstract Collection<String> getPoolsForObject(String objid); // ArrayList with pools as String
public abstract Collection<String> getDatabasePools();
public abstract boolean existsRule(String objid, String pool);
public abstract boolean isRuleInUse(String ruleid);
/**
*
* @return a collection of all String IDs an access rule is assigned to
*/
public abstract Collection<String> getDistinctStringIDs();
public static MCRAccessStore getInstance() {
try {
if (implementation == null) {
implementation = MCRConfiguration2
.getSingleInstanceOf("MCR.Persistence.Access.Store.Class", MCRJPAAccessStore.class).get();
}
} catch (Exception e) {
LOGGER.error(e);
}
return implementation;
}
public static Collection<String> getPools() {
String[] pool = ACCESS_POOLS.split(",");
return Arrays.asList(pool);
}
/**
* alle Elemente eines Datentypes aufbereiten
* @param type document type
*
* @return List of MCRAccessDefinition
* @see MCRAccessDefinition
*/
public Collection<MCRAccessDefinition> getDefinition(String type) {
try {
HashMap<String, Collection<String>> sqlDefinition = new HashMap<>();
Collection<String> pools = MCRAccessStore.getInstance().getDatabasePools();
//merge pools
pools.removeAll(getPools());
pools.addAll(getPools());
for (String pool : pools) {
sqlDefinition.put(pool, MCRAccessStore.getInstance().getMappedObjectId(pool));
}
Collection<MCRAccessDefinition> ret = new ArrayList<>();
Collection<String> elements;
MCRAccessDefinition def = null;
if (MCRConfiguration2.getOrThrow("MCR.Metadata.Type." + type, Boolean::parseBoolean)) {
elements = MCRXMLMetadataManager.instance().listIDsOfType(type);
} else {
return Collections.emptySet();
}
for (String element : elements) {
def = new MCRAccessDefinition();
def.setObjID(element);
for (String pool : pools) {
Collection<String> l = sqlDefinition.get(pool);
if (l.contains(element)) {
def.addPool(pool, "X");
} else {
def.addPool(pool, " ");
}
}
ret.add(def);
}
return ret;
} catch (Exception e) {
LOGGER.error("definition loading failed: ", e);
return null;
}
}
public Collection<MCRAccessDefinition> getRules(String objid) {
try {
Collection<String> pools = MCRAccessStore.getInstance().getDatabasePools();
//merge pools
pools.removeAll(getPools());
pools.addAll(getPools());
MCRAccessDefinition def = new MCRAccessDefinition();
def.setObjID(objid);
for (String pool : pools) {
String rule = getRuleID(objid, pool);
def.addPool(pool, Objects.requireNonNullElse(rule, " "));
}
return List.of(def);
} catch (Exception e) {
LOGGER.error("definition loading failed: ");
return null;
}
}
}
| 5,952 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessControlSystem.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessControlSystem.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Element;
import org.mycore.access.MCRAccessBaseImpl;
import org.mycore.access.MCRRuleAccessInterface;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
/**
* MyCoRe-Standard Implementation of the MCRAccessInterface Maps object ids to rules
*
* @author Matthias Kramm
* @author Heiko Helmbrecht
*/
public class MCRAccessControlSystem extends MCRAccessBaseImpl {
public static final String SYSTEM_RULE_PREFIX = "SYSTEMRULE";
public static final String POOL_PRIVILEGE_ID = "POOLPRIVILEGE";
public static final String LEXICOGRAPHICAL_PATTERN = "0000000000";
MCRAccessStore accessStore;
MCRRuleStore ruleStore;
MCRAccessRule dummyRule;
boolean disabled = false;
static Hashtable<String, String> ruleIDTable = new Hashtable<>();
private static final Logger LOGGER = LogManager.getLogger(MCRAccessControlSystem.class);
private MCRAccessControlSystem() {
String pools = MCRConfiguration2.getString("MCR.Access.AccessPermissions").orElse("read,write,delete");
if (pools.trim().length() == 0) {
disabled = true;
}
accessStore = MCRAccessStore.getInstance();
ruleStore = MCRRuleStore.getInstance();
nextFreeRuleID = new HashMap<>();
dummyRule = new MCRAccessRule(null, null, null, null, "dummy rule, always true");
}
private static MCRAccessControlSystem singleton;
private static HashMap<String, Integer> nextFreeRuleID;
// extended methods
public static synchronized MCRRuleAccessInterface instance() {
if (singleton == null) {
singleton = new MCRAccessControlSystem();
}
return singleton;
}
@Override
public void createRule(String ruleString, String creator, String description) {
String ruleID = getNextFreeRuleID(SYSTEM_RULE_PREFIX);
MCRAccessRule accessRule = new MCRAccessRule(ruleID, creator, new Date(), ruleString, description);
ruleStore.createRule(accessRule);
}
@Override
public void createRule(Element rule, String creator, String description) {
createRule(getNormalizedRuleString(rule), creator, description);
}
@Override
public void addRule(String id, String pool, Element rule, String description) throws MCRException {
MCRRuleMapping ruleMapping = getAutoGeneratedRuleMapping(rule, "System", pool, id, description);
String oldRuleID = accessStore.getRuleID(id, pool);
if (oldRuleID == null || oldRuleID.equals("")) {
accessStore.createAccessDefinition(ruleMapping);
} else {
accessStore.updateAccessDefinition(ruleMapping);
}
}
@Override
public void addRule(String permission, Element rule, String description) {
addRule(POOL_PRIVILEGE_ID, permission, rule, description);
}
@Override
public void removeRule(String id, String pool) throws MCRException {
MCRRuleMapping ruleMapping = accessStore.getAccessDefinition(pool, id);
accessStore.deleteAccessDefinition(ruleMapping);
}
@Override
public void removeRule(String permission) throws MCRException {
removeRule(POOL_PRIVILEGE_ID, permission);
}
@Override
public void removeAllRules(String id) throws MCRException {
for (String pool : accessStore.getPoolsForObject(id)) {
removeRule(id, pool);
}
}
@Override
public void updateRule(String id, String pool, Element rule, String description) throws MCRException {
MCRRuleMapping ruleMapping = getAutoGeneratedRuleMapping(rule, "System", pool, id, description);
String oldRuleID = accessStore.getRuleID(id, pool);
if (oldRuleID == null || oldRuleID.equals("")) {
LOGGER.debug(
"updateRule called for id <{}> and pool <{}>, but no rule is existing, so new rule was created", id,
pool);
accessStore.createAccessDefinition(ruleMapping);
} else {
accessStore.updateAccessDefinition(ruleMapping);
}
}
@Override
public void updateRule(String permission, Element rule, String description) throws MCRException {
updateRule(POOL_PRIVILEGE_ID, permission, rule, description);
}
@Override
public boolean checkPermission(String id, String permission, MCRUserInformation userInfo) {
return checkAccess(id, permission, userInfo, null);
}
@Override
public boolean checkPermission(String permission) {
LOGGER.debug("Execute MCRAccessControlSystem checkPermission for permission {}", permission);
boolean ret = checkPermission(POOL_PRIVILEGE_ID, permission);
LOGGER.debug("Execute MCRAccessControlSystem checkPermission result: {}", String.valueOf(ret));
return ret;
}
@Override
@Deprecated
public boolean checkPermissionForUser(String permission, String userID) {
return checkAccess(POOL_PRIVILEGE_ID, permission, userID, null);
}
@Override
public boolean checkPermissionForUser(String permission, MCRUserInformation userInfo) {
return checkAccess(POOL_PRIVILEGE_ID, permission, userInfo, null);
}
@Override
public boolean checkPermission(Element rule) {
MCRSession session = MCRSessionMgr.getCurrentSession();
String ruleStr = getNormalizedRuleString(rule);
MCRAccessRule accessRule = new MCRAccessRule(null, "System", new Date(), ruleStr, "");
try {
return accessRule.checkAccess(session.getUserInformation(), new Date(), new MCRIPAddress(
session.getCurrentIP()));
} catch (MCRException | UnknownHostException e) {
// only return true if access is allowed, we dont know this
LOGGER.debug("Error while checking rule.", e);
return false;
}
}
@Override
public Element getRule(String objID, String permission) {
MCRAccessRule accessRule = getAccessRule(objID, permission);
MCRRuleParser parser = new MCRRuleParser();
Element rule = parser.parse(accessRule.rule).toXML();
Element condition = new Element("condition");
condition.setAttribute("format", "xml");
if (rule != null) {
condition.addContent(rule);
}
return condition;
}
@Override
public Element getRule(String permission) {
return getRule(POOL_PRIVILEGE_ID, permission);
}
@Override
public String getRuleDescription(String permission) {
return getRuleDescription(POOL_PRIVILEGE_ID, permission);
}
@Override
public String getRuleDescription(String objID, String permission) {
MCRAccessRule accessRule = getAccessRule(objID, permission);
if (accessRule != null && accessRule.getDescription() != null) {
return accessRule.getDescription();
}
return "";
}
@Override
public Collection<String> getPermissionsForID(String objid) {
return accessStore.getPoolsForObject(objid);
}
@Override
public Collection<String> getPermissions() {
return accessStore.getPoolsForObject(POOL_PRIVILEGE_ID);
}
@Override
public boolean hasRule(String id, String permission) {
return accessStore.existsRule(id, permission);
}
@Override
public boolean hasRule(String id) {
return hasRule(id, null);
}
@Override
public Collection<String> getAllControlledIDs() {
return accessStore.getDistinctStringIDs();
}
// not extended methods
public boolean isDisabled() {
return disabled;
}
@Override
public MCRAccessRule getAccessRule(String objID, String pool) {
if (disabled) {
return dummyRule;
}
LOGGER.debug("accessStore.getRuleID()");
String ruleID = accessStore.getRuleID(objID, pool);
if (ruleID == null) {
LOGGER.debug("accessStore.getRuleID() done with null");
return null;
} else {
LOGGER.debug("accessStore.getRuleID() done with {}", ruleID);
}
return ruleStore.getRule(ruleID);
}
/**
* Validator methods to validate access definition for given object and pool
*
* @param permission
* poolname as string
* @param objID
* MCRObjectID as string
* @param userID
* MCRUser
* @param ip
* ip-Address
* @return true if access is granted according to defined access rules
*/
@Deprecated
public boolean checkAccess(String objID, String permission, String userID, MCRIPAddress ip) {
Date date = new Date();
LOGGER.debug("getAccess()");
MCRAccessRule rule = getAccessRule(objID, permission);
LOGGER.debug("getAccess() is done");
if (rule == null) {
return userID.equals(MCRSystemUserInformation.getSuperUserInstance().getUserID());
}
return rule.checkAccess(userID, date, ip);
}
/**
* Validator methods to validate access definition for given object and pool
*
* @param permission
* poolname as string
* @param objID
* MCRObjectID as string
* @param userInfo
* MCRUser
* @param ip
* ip-Address
* @return true if access is granted according to defined access rules
*/
public boolean checkAccess(String objID, String permission, MCRUserInformation userInfo, MCRIPAddress ip) {
Date date = new Date();
LOGGER.debug("getAccess()");
MCRAccessRule rule = getAccessRule(objID, permission);
LOGGER.debug("getAccess() is done");
if (rule == null) {
return userInfo.getUserID().equals(MCRSystemUserInformation.getSuperUserInstance().getUserID());
}
return rule.checkAccess(userInfo, date, ip);
}
/**
* method that delivers the next free ruleID for a given Prefix and sets the counter to counter + 1
*
* @param prefix
* String
* @return String
*/
public synchronized String getNextFreeRuleID(String prefix) {
int nextFreeID;
String sNextFreeID;
if (nextFreeRuleID.containsKey(prefix)) {
nextFreeID = nextFreeRuleID.get(prefix);
} else {
nextFreeID = ruleStore.getNextFreeRuleID(prefix);
}
sNextFreeID = LEXICOGRAPHICAL_PATTERN + nextFreeID;
sNextFreeID = sNextFreeID.substring(sNextFreeID.length() - LEXICOGRAPHICAL_PATTERN.length());
nextFreeRuleID.put(prefix, nextFreeID + 1);
return prefix + sNextFreeID;
}
/**
* delivers the rule as string, after normalizing it via sorting with MCRAccessConditionsComparator
*
* @param rule
* Jdom-Element
* @return String
*/
@Override
public String getNormalizedRuleString(Element rule) {
if (rule.getChildren() == null || rule.getChildren().size() == 0) {
return "false";
}
Element normalizedRule = normalize(rule.getChildren().get(0));
MCRRuleParser parser = new MCRRuleParser();
return parser.parse(normalizedRule).toString();
}
/**
* returns a auto-generated MCRRuleMapping, needed to create Access Definitions
*
* @param rule
* JDOM-Representation of a MCRAccess Rule
* @param creator
* String
* @param pool
* String
* @param id
* String
* @return MCRRuleMapping
*/
public MCRRuleMapping getAutoGeneratedRuleMapping(Element rule, String creator, String pool, String id,
String description) {
String ruleString = getNormalizedRuleString(rule);
String ruleID = ruleIDTable.get(ruleString);
if (ruleID == null || ruleID.length() == 0) {
Collection<String> existingIDs = ruleStore.retrieveRuleIDs(ruleString, description);
if (existingIDs != null && existingIDs.size() > 0) {
// rule yet exists
ruleID = existingIDs.iterator().next();
} else {
ruleID = getNextFreeRuleID(SYSTEM_RULE_PREFIX);
MCRAccessRule accessRule = new MCRAccessRule(ruleID, creator, new Date(), ruleString, description);
ruleStore.createRule(accessRule);
}
ruleIDTable.put(ruleString, ruleID);
}
MCRRuleMapping ruleMapping = new MCRRuleMapping();
ruleMapping.setCreator(creator);
ruleMapping.setCreationdate(new Date());
ruleMapping.setPool(pool);
ruleMapping.setRuleId(ruleID);
ruleMapping.setObjId(id);
return ruleMapping;
}
/**
* method, that normalizes the jdom-representation of a mycore access condition
*
* @param rule
* condition-JDOM of an access-rule
* @return the normalized JDOM-Rule
*/
public Element normalize(Element rule) {
Element newRule = new Element(rule.getName());
rule.getAttributes()
.stream()
.map(Attribute::clone)
.forEach(newRule::setAttribute);
rule.getChildren()
.stream()
.map(Element::clone)
.map(this::normalize)
.sorted(MCRAccessControlSystem::compareAccessConditions)
.forEachOrdered(newRule::addContent);
return newRule;
}
/**
* A Comparator for the Condition Elements for normalizing the access conditions
*/
private static int compareAccessConditions(Element el0, Element el1) {
String nameEl0 = el0.getName();
String nameEl1 = el1.getName();
int nameCompare = nameEl0.compareTo(nameEl1);
// order "boolean" before "condition"
if (nameCompare != 0) {
return nameCompare;
}
if (nameEl0.equals("boolean")) {
String opEl0 = el0.getAttributeValue("operator");
String opEl1 = el0.getAttributeValue("operator");
return opEl0.compareToIgnoreCase(opEl1);
} else if (nameEl0.equals("condition")) {
String fieldEl0 = el0.getAttributeValue("field");
String fieldEl1 = el1.getAttributeValue("field");
int fieldCompare = fieldEl0.compareToIgnoreCase(fieldEl1);
if (fieldCompare != 0) {
return fieldCompare;
}
String valueEl0 = el0.getAttributeValue("value");
String valueEl1 = el1.getAttributeValue("value");
return valueEl0.compareTo(valueEl1);
}
return 0;
}
}
| 15,932 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDateBeforeClause.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRDateBeforeClause.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.jdom2.Element;
import org.mycore.parsers.bool.MCRCondition;
/**
* Implementation of a (date < x) clause
*
* @author Matthias Kramm
*/
class MCRDateBeforeClause implements MCRCondition<MCRAccessData> {
private Date date;
private DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
MCRDateBeforeClause(Date date) {
this.date = date;
}
public boolean evaluate(MCRAccessData data) {
return data.getDate().before(date);
}
@Override
public String toString() {
return "date < " + dateformat.format(date) + " ";
}
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", "date");
cond.setAttribute("operator", "<");
cond.setAttribute("value", dateformat.format(date));
return cond;
}
}
| 1,744 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRuleParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRRuleParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import org.jdom2.Element;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.parsers.bool.MCRBooleanClauseParser;
import org.mycore.parsers.bool.MCRCondition;
import org.mycore.parsers.bool.MCRFalseCondition;
import org.mycore.parsers.bool.MCRIPCondition;
import org.mycore.parsers.bool.MCRParseException;
import org.mycore.parsers.bool.MCRTrueCondition;
public class MCRRuleParser extends MCRBooleanClauseParser {
protected MCRRuleParser() {
}
private static Date parseDate(String s, boolean dayafter) throws MCRParseException {
long time;
try {
time = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(s).getTime();
} catch (java.text.ParseException e) {
try {
time = new SimpleDateFormat("dd.MM.yyyy", Locale.ROOT).parse(s).getTime();
} catch (ParseException e1) {
throw new MCRParseException("unable to parse date " + s);
}
}
if (dayafter) {
time += 1000 * 60 * 60 * 24;
}
return new Date(time);
}
@Override
protected MCRCondition<?> parseSimpleCondition(Element e) throws MCRParseException {
String name = e.getName();
switch (name) {
case "boolean" -> {
return super.parseSimpleCondition(e);
}
case "condition" -> {
MCRCondition<?> condition = parseElement(e);
if (condition == null) {
throw new MCRParseException("Not a valid condition field <" + e.getAttributeValue("field") + ">");
}
return condition;
}
default -> throw new MCRParseException("Not a valid name <" + e.getName() + ">");
}
}
@Override
protected MCRCondition<?> parseSimpleCondition(String s) throws MCRParseException {
MCRCondition<?> condition = parseString(s);
if (condition == null) {
throw new MCRParseException("syntax error: " + s);
}
return condition;
}
protected MCRCondition<?> parseElement(Element e) {
String field = e.getAttributeValue("field").toLowerCase(Locale.ROOT).trim();
String operator = e.getAttributeValue("operator").trim();
String value = e.getAttributeValue("value").trim();
boolean not = Objects.equals(operator, "!=");
return switch (field) {
case "group" -> new MCRGroupClause(value, not);
case "user" -> new MCRUserClause(value, not);
case "ip" -> getIPClause(value);
case "date" -> switch (operator) {
case "<" -> new MCRDateBeforeClause(parseDate(value, false));
case "<=" -> new MCRDateBeforeClause(parseDate(value, true));
case ">" -> new MCRDateAfterClause(parseDate(value, true));
case ">=" -> new MCRDateAfterClause(parseDate(value, false));
default -> throw new MCRParseException("Not a valid operator <" + operator + ">");
};
default -> null;
};
}
private MCRCondition<MCRAccessData> getIPClause(String value) {
MCRIPCondition ipCond = MCRConfiguration2.<MCRIPCondition>getInstanceOf("MCR.RuleParser.ip")
.orElseGet(MCRIPClause::new);
ipCond.set(value);
return ipCond;
}
protected MCRCondition<?> parseString(String s) {
/* handle specific rules */
if (s.equalsIgnoreCase("false")) {
return new MCRFalseCondition<>();
}
if (s.equalsIgnoreCase("true")) {
return new MCRTrueCondition<>();
}
if (s.startsWith("group")) {
s = s.substring(5).trim();
if (s.startsWith("!=")) {
return new MCRGroupClause(s.substring(2).trim(), true);
} else if (s.startsWith("=")) {
return new MCRGroupClause(s.substring(1).trim(), false);
} else {
throw new MCRParseException("syntax error: " + s);
}
}
if (s.startsWith("user")) {
s = s.substring(4).trim();
if (s.startsWith("!=")) {
return new MCRUserClause(s.substring(2).trim(), true);
} else if (s.startsWith("=")) {
return new MCRUserClause(s.substring(1).trim(), false);
} else {
throw new MCRParseException("syntax error: " + s);
}
}
if (s.startsWith("ip ")) {
return getIPClause(s.substring(3).trim());
}
if (s.startsWith("date ")) {
s = s.substring(5).trim();
if (s.startsWith(">=")) {
return new MCRDateAfterClause(parseDate(s.substring(2).trim(), false));
} else if (s.startsWith("<=")) {
return new MCRDateBeforeClause(parseDate(s.substring(2).trim(), true));
} else if (s.startsWith(">")) {
return new MCRDateAfterClause(parseDate(s.substring(1).trim(), true));
} else if (s.startsWith("<")) {
return new MCRDateBeforeClause(parseDate(s.substring(1).trim(), false));
} else {
throw new MCRParseException("syntax error: " + s);
}
}
return null;
}
}
| 6,247 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessDefinition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessDefinition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.HashMap;
/**
* Maps object ids to rules
*
* @author Arne Seifert
*/
public class MCRAccessDefinition {
private String objid;
private HashMap<String, String> pools = new HashMap<>();
public MCRAccessDefinition() {
pools.clear();
}
public String getObjID() {
return objid;
}
public void setObjID(String value) {
objid = value;
}
public HashMap<String, String> getPool() {
return pools;
}
public void setPool(HashMap<String, String> pool) {
pools = pool;
}
public void addPool(String poolname, String ruleid) {
pools.put(poolname, ruleid);
}
public void clearPools() {
pools.clear();
}
}
| 1,500 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRuleStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRRuleStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import java.util.Collection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.access.MCRJPARuleStore;
import org.mycore.common.config.MCRConfiguration2;
/**
* The purpose of this interface is to make the choice of the persistence layer
* configurable. Any concrete database-class which stores MyCoRe Access control
* must implement this interface. Which database actually will be used can then
* be configured by reading the value <code>MCR.Persistence.Rule.Store_Class</code>
* from mycore.properties.access
*
* @author Arne Seifert
*/
public abstract class MCRRuleStore {
private static final Logger LOGGER = LogManager.getLogger(MCRRuleStore.class);
protected static final String SQL_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
protected static final String RULETABLENAME = "MCRACCESSRULE";
private static MCRRuleStore implementation;
public abstract void createRule(MCRAccessRule rule);
public abstract void updateRule(MCRAccessRule rule);
public abstract void deleteRule(String ruleid);
public abstract MCRAccessRule getRule(String ruleid);
public abstract boolean existsRule(String ruleid);
public abstract Collection<String> retrieveAllIDs();
public abstract Collection<String> retrieveRuleIDs(String ruleExpression, String description);
public abstract int getNextFreeRuleID(String prefix);
public static MCRRuleStore getInstance() {
try {
if (implementation == null) {
implementation = MCRConfiguration2
.getSingleInstanceOf("MCR.Persistence.Rule.Store_Class", MCRJPARuleStore.class).get();
}
} catch (Exception e) {
LOGGER.error(e);
}
return implementation;
}
}
| 2,577 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessCtrlCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/mcrimpl/MCRAccessCtrlCommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.mcrimpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessManager;
import org.mycore.frontend.cli.MCRAbstractCommands;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
/**
* This class provides a set of commands for the org.mycore.access package which
* can be used by the command line interface. (creates sql tables, run queries
*
* @author Arne Seifert
*/
@MCRCommandGroup(name = "Access Control Commands")
public class MCRAccessCtrlCommands extends MCRAbstractCommands {
public static Logger logger = LogManager.getLogger(MCRAccessCtrlCommands.class.getName());
/**
* validates access for given object and given permission
*
* @param objid
* internal database ruleid
* @param permission
* the access permission for the rule
*/
@MCRCommand(syntax = "validate objectid {0} in pool {1}",
help = "Validates access for given object and given permission",
order = 10)
public static void validate(String objid, String permission) {
System.out.println("current user has access: " + MCRAccessManager.checkPermission(objid, permission));
}
}
| 2,030 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCombineableAccessCheckStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRCombineableAccessCheckStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
/**
* @author Thomas Scheffler (yagee)
*
*/
public interface MCRCombineableAccessCheckStrategy extends MCRAccessCheckStrategy {
/**
* Checks if this strategy has a rule mapping defined.
* Can be used by other more complex strategies that require this information to decide
* if this strategy should be used.
* @param id
* a possible MCRObjectID of the object or any other "id"
* @param permission
* the access permission for the rule
* @return true if there is a mapping to a rule defined
*/
boolean hasRuleMapping(String id, String permission);
}
| 1,399 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAccessCheckStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRAccessCheckStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import org.mycore.access.MCRAccessManager;
public interface MCRAccessCheckStrategy {
/**
* determines whether the current user has the permission to perform a
* certain action.
*
* @param id
* the MCRObjectID of the object
* @param permission
* the access permission for the rule
* @return true if the access is allowed otherwise it return
* @see MCRAccessManager#checkPermission(String, String)
*/
boolean checkPermission(String id, String permission);
}
| 1,306 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivateIDStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRDerivateIDStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import java.util.Collection;
import org.mycore.datamodel.common.MCRLinkTableManager;
/**
* @author Silvio Hermann
*/
public class MCRDerivateIDStrategy implements MCRAccessCheckStrategy {
@Override
public boolean checkPermission(String id, String permission) {
if (!id.contains("_derivate_")) {
return new MCRObjectIDStrategy().checkPermission(id, permission);
}
final Collection<String> l = MCRLinkTableManager.instance().getSourceOf(id, "derivate");
if (l != null && !l.isEmpty()) {
return checkPermission(l.iterator().next(), permission);
}
return false;
}
}
| 1,418 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectIDStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRObjectIDStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import org.mycore.access.MCRAccessManager;
/**
* Use this class if you want to check against a MCRObjectID.
*
* Be aware that you must provide a access rule - for each permission - for
* every MCRObject.
*
* @author Thomas Scheffler (yagee)
*
*/
public class MCRObjectIDStrategy implements MCRCombineableAccessCheckStrategy {
/*
* (non-Javadoc)
*
* @see org.mycore.access.strategies.MCRAccessCheckStrategy#checkPermission(java.lang.String,
* java.lang.String)
*/
public boolean checkPermission(String id, String permission) {
return MCRAccessManager.getAccessImpl().checkPermission(id, permission);
}
@Override
public boolean hasRuleMapping(String id, String permission) {
return MCRAccessManager.hasRule(id, permission);
}
}
| 1,578 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRParentRuleStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRParentRuleStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import static org.mycore.common.MCRConstants.XLINK_NAMESPACE;
import java.io.IOException;
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.access.MCRAccessManager;
import org.mycore.access.MCRRuleAccessInterface;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
* Use this class if you want to have a fallback to ancestor access rules.
*
* First a check is done for the MCRObjectID. If no rule for the ID is specified
* it will be tried to check the permission agains the MCRObjectID of the parent
* object and so on.
*
* @author Thomas Scheffler (yagee)
*
*/
public class MCRParentRuleStrategy implements MCRAccessCheckStrategy {
private static final Logger LOGGER = LogManager.getLogger(MCRParentRuleStrategy.class);
/*
* (non-Javadoc)
*
* @see org.mycore.access.strategies.MCRAccessCheckStrategy#checkPermission(java.lang.String,
* java.lang.String)
*/
public boolean checkPermission(String id, String permission) {
String currentID;
MCRRuleAccessInterface mcrRuleAccessInterface = MCRAccessManager.requireRulesInterface();
for (currentID = id; currentID != null
&& !mcrRuleAccessInterface.hasRule(currentID, permission); currentID = getParentID(currentID)) {
LOGGER.debug("No access rule specified for: {}. Trying to use parent ID.", currentID);
}
LOGGER.debug("Using access rule defined for: {}", currentID);
return MCRAccessManager.getAccessImpl().checkPermission(currentID, permission);
}
private static String getParentID(String objectID) {
Document parentDoc;
try {
parentDoc = MCRXMLMetadataManager.instance().retrieveXML(MCRObjectID.getInstance(objectID));
} catch (IOException | JDOMException e) {
LOGGER.error("Could not read object: {}", objectID, e);
return null;
}
final Element parentElement = parentDoc.getRootElement().getChild("structure").getChild("parents");
if (parentElement != null) {
return parentElement.getChild("parent").getAttributeValue("href", XLINK_NAMESPACE);
}
return null;
}
}
| 3,138 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectTypeStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRObjectTypeStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessManager;
import org.mycore.access.MCRRuleAccessInterface;
import org.mycore.datamodel.classifications2.MCRCategoryDAO;
import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
/**
* Use this class if you want to have a fallback to some default access rules.
*
* First a check is done for the MCRObjectID. If no rule for the ID is specified
* it will be tried to check the permission agains the rule ID
* <code>default_<ObjectType></code> if it exists. If not the last
* fallback is done against <code>default</code>.
*
* @author Thomas Scheffler (yagee)
*
*/
public class MCRObjectTypeStrategy implements MCRCombineableAccessCheckStrategy {
private static final Pattern TYPE_PATTERN = Pattern.compile("[^_]*_([^_]*)_[0-9]*");
private static final Logger LOGGER = LogManager.getLogger(MCRObjectIDStrategy.class);
private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance();
private static MCRObjectIDStrategy idStrategy = new MCRObjectIDStrategy();
/*
* (non-Javadoc)
*
* @see org.mycore.access.strategies.MCRAccessCheckStrategy#checkPermission(java.lang.String,
* java.lang.String)
*/
public boolean checkPermission(String id, String permission) {
if (idStrategy.hasRuleMapping(id, permission)) {
LOGGER.debug("using access rule defined for object.");
return idStrategy.checkPermission(id, permission);
}
return checkObjectTypePermission(id, permission);
}
public static boolean checkObjectTypePermission(String id, String permission) {
String objectType = getObjectType(id);
if (hasTypePermission(objectType, permission)) {
LOGGER.debug("using access rule defined for object type.");
return MCRAccessManager.getAccessImpl().checkPermission("default_" + objectType, permission);
}
LOGGER.debug("using system default access rule.");
return MCRAccessManager.getAccessImpl().checkPermission("default", permission);
}
private static boolean hasTypePermission(String objectType, String permission) {
MCRRuleAccessInterface accessImpl = MCRAccessManager.getAccessImpl();
return objectType != null && accessImpl.hasRule("default_" + objectType, permission);
}
private static String getObjectType(String id) {
Matcher m = TYPE_PATTERN.matcher(id);
if (m.find() && m.groupCount() == 1) {
return m.group(1);
} else {
MCRCategoryID rootID;
try {
rootID = MCRCategoryID.rootID(id);
} catch (Exception e) {
LOGGER.debug("ID '{}' is not a valid category id.", id);
return null;
}
if (DAO.exist(rootID)) {
return "class";
}
}
return null;
}
@Override
public boolean hasRuleMapping(String id, String permission) {
return idStrategy.hasRuleMapping(id, permission) || hasTypePermission(getObjectType(id), permission)
|| MCRAccessManager.hasRule("default", permission);
}
}
| 4,153 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCreatorRuleStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRCreatorRuleStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import java.util.List;
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.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.common.MCRCreatorCache;
import org.mycore.datamodel.metadata.MCRObjectID;
/**
*
* First, a check is done if the user is in the submitter role, if the user is the creator of the object and if the
* creator is permitted to perform the requested action in the object's current state (two groups of states, submitted,
* and review, are checked). If not it will be tried to check the permission against the rule ID
* <code>default_<ObjectType></code> if it exists. If not the last
* fallback is done against <code>default</code>.
*
* Specify classification and category for submitted and review states:
* MCR.Access.Strategy.SubmittedCategories=state:submitted
* MCR.Access.Strategy.ReviewCategories=state:review
*
* Specify permissions for submitted and review states:
* MCR.Access.Strategy.CreatorSubmittedPermissions=writedb,deletedb
* MCR.Access.Strategy.CreatorReviewPermissions=read
*
* You can also specify a comma separated list of categories like: <code>state:submitted,state:new</code>
*
* @author Thomas Scheffler (yagee)
* @author Kathleen Neumann (mcrkrebs)
*
*/
public class MCRCreatorRuleStrategy implements MCRCombineableAccessCheckStrategy {
private static final Logger LOGGER = LogManager.getLogger(MCRCreatorRuleStrategy.class);
private static final List<String> SUBMITTED_CATEGORY_IDS = MCRConfiguration2
.getString("MCR.Access.Strategy.SubmittedCategories")
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toList()))
.orElse(List.of("state:submitted"));
private static final List<String> REVIEW_CATEGORY_IDS = MCRConfiguration2
.getString("MCR.Access.Strategy.ReviewCategories")
.map(MCRConfiguration2::splitValue)
.map(s -> s.collect(Collectors.toList()))
.orElse(List.of("state:review"));
private static final List<String> CREATOR_ROLES = MCRConfiguration2
.getOrThrow("MCR.Access.Strategy.CreatorRole", MCRConfiguration2::splitValue)
.collect(Collectors.toList());
private static final List<String> CREATOR_SUBMITTED_PERMISSIONS = MCRConfiguration2
.getOrThrow("MCR.Access.Strategy.CreatorSubmittedPermissions", MCRConfiguration2::splitValue)
.collect(Collectors.toList());
private static final List<String> CREATOR_REVIEW_PERMISSIONS = MCRConfiguration2
.getOrThrow("MCR.Access.Strategy.CreatorReviewPermissions", MCRConfiguration2::splitValue)
.collect(Collectors.toList());
private static List<String> CREATOR_ANY_STATE_PERMISSIONS =
MCRConfiguration2.getString("MCR.Access.Strategy.CreatorAnyStatePermissions").stream()
.flatMap(MCRConfiguration2::splitValue).toList();
private static final MCRCategLinkService LINK_SERVICE = MCRCategLinkServiceFactory.getInstance();
private static final MCRObjectTypeStrategy BASE_STRATEGY = new MCRObjectTypeStrategy();
/*
* (non-Javadoc)
*
* @see org.mycore.access.strategies.MCRAccessCheckStrategy#checkPermission(java.lang.String,
* java.lang.String)
*/
public boolean checkPermission(String id, String permission) {
LOGGER.debug("check permission {} for MCRBaseID {}", permission, id);
if (id == null || id.length() == 0 || permission == null || permission.length() == 0) {
return false;
}
//our decoration for write permission
return BASE_STRATEGY.checkPermission(id, permission) || isCreatorRuleAvailable(id, permission);
}
private static boolean objectStatusIsSubmitted(MCRObjectID mcrObjectID) {
return objectStatusIsAnyOf(mcrObjectID, SUBMITTED_CATEGORY_IDS);
}
private static boolean objectStatusIsReview(MCRObjectID mcrObjectID) {
return objectStatusIsAnyOf(mcrObjectID, REVIEW_CATEGORY_IDS);
}
private static boolean objectStatusIsAnyOf(MCRObjectID mcrObjectID, List<String> categoryIds) {
MCRCategLinkReference reference = new MCRCategLinkReference(mcrObjectID);
if (categoryIds == null) {
return false;
}
for (String categoryId : categoryIds) {
MCRCategoryID category = MCRCategoryID.fromString(categoryId);
if (LINK_SERVICE.isInCategory(reference, category)) {
return true;
}
}
return false;
}
private static boolean userHasCreatorRole(MCRUserInformation currentUser) {
return CREATOR_ROLES.stream().anyMatch(currentUser::isUserInRole);
}
private static boolean userIsCreatorOf(MCRUserInformation currentUser, MCRObjectID mcrObjectID) {
try {
String creator = MCRCreatorCache.getCreator(mcrObjectID);
return currentUser.getUserID().equals(creator);
} catch (ExecutionException e) {
LOGGER.error("Error while getting creator information.", e);
return false;
}
}
@Override
public boolean hasRuleMapping(String id, String permission) {
return BASE_STRATEGY.hasRuleMapping(id, permission) || isCreatorRuleAvailable(id, permission);
}
public boolean isCreatorRuleAvailable(String id, String permission) {
if (!MCRObjectID.isValid(id)) {
return false;
}
try {
MCRObjectID mcrObjectId = MCRObjectID.getInstance(id);
MCRUserInformation currentUser = MCRSessionMgr.getCurrentSession().getUserInformation();
if (userHasCreatorRole(currentUser) && userIsCreatorOf(currentUser, mcrObjectId)) {
if (objectStatusIsSubmitted(mcrObjectId) && CREATOR_SUBMITTED_PERMISSIONS.contains(permission)) {
return true;
}
if (objectStatusIsReview(mcrObjectId) && CREATOR_REVIEW_PERMISSIONS.contains(permission)) {
return true;
}
if (CREATOR_ANY_STATE_PERMISSIONS.contains(permission)) {
return true;
}
}
} catch (RuntimeException e) {
LOGGER.warn("Error while checking permission.", e);
}
return false;
}
}
| 7,521 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRObjectBaseStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/access/strategies/MCRObjectBaseStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.access.strategies;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessManager;
/**
* Use this class if you want to have a fallback to some default access rules.
*
* These are the rules that will be checked against if available
* <ol>
* <li><code>{id}</code>, e.g. "MyCoRe_mods_12345678"</li>
* <li><code>default_{baseId}</code>, e.g. "default_MyCoRe_mods"</li>
* <li><code>default_{objectType}</code>, e.g. "default_mods"</li>
* <li><code>default</code></li>
* </ol>
*
* This is the same behaviour as {@link MCRObjectTypeStrategy} but step 2 is inserted here.
* @author Thomas Scheffler (yagee)
* @author Jens Kupferschmidt
*
*/
public class MCRObjectBaseStrategy implements MCRCombineableAccessCheckStrategy {
private static final Logger LOGGER = LogManager.getLogger(MCRObjectBaseStrategy.class);
private static final Pattern BASE_PATTERN = Pattern.compile("([^_]*_[^_]*)_*");
private final MCRObjectTypeStrategy typeStrategy = new MCRObjectTypeStrategy();
/*
* (non-Javadoc)
*
* @see org.mycore.access.strategies.MCRAccessCheckStrategy#checkPermission(java.lang.String,
* java.lang.String)
*/
public boolean checkPermission(String id, String permission) {
LOGGER.debug("check permission {} for MCRBaseID {}", permission, id);
if (id == null || id.length() == 0 || permission == null || permission.length() == 0) {
return false;
}
if (MCRAccessManager.requireRulesInterface().hasRule(id, permission)) {
LOGGER.debug("using access rule defined for object.");
return MCRAccessManager.getAccessImpl().checkPermission(id, permission);
}
String objectBase = getObjectBase(id);
if (hasBasePermission(objectBase, permission)) {
LOGGER.debug("using access rule defined for object base.");
return MCRAccessManager.getAccessImpl().checkPermission("default_" + objectBase, permission);
}
return MCRObjectTypeStrategy.checkObjectTypePermission(id, permission);
}
private boolean hasBasePermission(String objectBase, String permission) {
return objectBase != null && MCRAccessManager.requireRulesInterface()
.hasRule("default_" + objectBase, permission);
}
private static String getObjectBase(String id) {
Matcher m = BASE_PATTERN.matcher(id);
if (m.find() && m.groupCount() == 1) {
return m.group(1);
}
return null;
}
@Override
public boolean hasRuleMapping(String id, String permission) {
return hasBasePermission(getObjectBase(id), permission) || typeStrategy.hasRuleMapping(id, permission);
}
}
| 3,584 | 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.