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
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** new MyCoRe user system */ @XmlJavaTypeAdapters({ @XmlJavaTypeAdapter(type = java.util.Date.class, value = org.mycore.user2.utils.MCRDateXMLAdapter.class) }) package org.mycore.user2; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
1,048
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPasswordHashType.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRPasswordHashType.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import jakarta.xml.bind.annotation.XmlEnum; /** * This enum represents different hash type for user passwords. * Allows lazy migration of users from different sources. * <ul> * <li>{@link #crypt} is used in the old MyCoRe user system * <li>{@link #md5} is used in the old miless user system * <li>{@link #sha1} was the default hash type of mycore-user2 * <li>{@link #sha256} is the default hash type of mycore-user2 * </ul> * @author Thomas Scheffler (yagee) * */ @XmlEnum public enum MCRPasswordHashType { crypt, md5, sha1, sha256 }
1,306
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRealmResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRealmResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.List; import java.util.Objects; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; /** * Implements URIResolver for realms * * realm:{realmID} * returns information about this realm * realm:local * returns information about the local realm * realm:all * returns all realms * * @author Thomas Scheffler (yagee) * */ public class MCRRealmResolver implements URIResolver { /* (non-Javadoc) * @see javax.xml.transform.URIResolver#resolve(java.lang.String, java.lang.String) */ @Override public Source resolve(final String href, final String base) { String realmID = href.split(":")[1]; if (Objects.equals(realmID, "all")) { return MCRRealmFactory.getRealmsSource(); } else if (Objects.equals(realmID, "local")) { realmID = MCRRealmFactory.getLocalRealm().getID(); } return new JDOMSource(getElement(MCRRealmFactory.getRealm(realmID).getID())); } private Element getElement(final String id) { Document realmsDocument = MCRRealmFactory.getRealmsDocument(); List<Element> realms = realmsDocument.getRootElement().getChildren("realm"); return realms.stream() .filter(realm -> id.equals(realm.getAttributeValue("id"))) .findAny() .orElse(null); } }
2,214
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRoleResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRoleResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.access.MCRAccessException; import org.mycore.access.MCRAccessManager; import org.mycore.datamodel.classifications2.MCRLabel; /** * @author Thomas Scheffler (yagee) * */ public class MCRRoleResolver implements URIResolver { private static final Logger LOGGER = LogManager.getLogger(MCRRoleResolver.class); public static Element getAssignableGroupsForUser() throws MCRAccessException { LOGGER.warn("Please fix http://sourceforge.net/p/mycore/bugs/568/"); List<MCRRole> groupIDs = null; // The list of assignable groups depends on the privileges of the // current user. if (MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION)) { groupIDs = MCRRoleManager.listSystemRoles(); } else if (MCRAccessManager.checkPermission(MCRUser2Constants.USER_CREATE_PERMISSION)) { final MCRUser currentUser = MCRUserManager.getCurrentUser(); groupIDs = new ArrayList<>(currentUser.getSystemRoleIDs().size()); for (final String id : currentUser.getSystemRoleIDs()) { groupIDs.add(MCRRoleManager.getRole(id)); } } else { throw MCRAccessException.missingPrivilege("List asignable groups for new user.", MCRUser2Constants.USER_ADMIN_PERMISSION, MCRUser2Constants.USER_CREATE_PERMISSION); } // Loop over all assignable groups final Element root = new Element("items"); for (final MCRRole group : groupIDs) { String label = group.getName(); MCRLabel groupLabel = group.getLabel(); if (groupLabel != null && groupLabel.getText() != null) { label = groupLabel.getText(); } final Element item = new Element("item").setAttribute("value", group.getName()).setAttribute("label", label); root.addContent(item); } return root; } /* (non-Javadoc) * @see javax.xml.transform.URIResolver#resolve(java.lang.String, java.lang.String) */ @Override public Source resolve(final String href, final String base) throws TransformerException { final String target = href.substring(href.indexOf(":") + 1); final String[] part = target.split(":"); final String method = part[0]; try { if (Objects.equals(method, "getAssignableGroupsForUser")) { return new JDOMSource(getAssignableGroupsForUser()); } } catch (final MCRAccessException exc) { throw new TransformerException(exc); } throw new TransformerException(new IllegalArgumentException("Unknown method " + method + " in uri " + href)); } }
3,860
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import static org.mycore.user2.utils.MCRUserTransformer.JAXB_CONTEXT; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.TimeZone; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJAXBContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.datamodel.common.MCRISO8601Date; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.services.i18n.MCRTranslation; import org.mycore.user2.utils.MCRUserTransformer; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Provides functionality to search for users, list users, * retrieve, delete or update user data. * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ public class MCRUserServlet extends MCRServlet { private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC"); private static final long serialVersionUID = 1L; /** The logger */ private static final Logger LOGGER = LogManager.getLogger(MCRUserServlet.class); /** * Handles requests. The parameter 'action' selects what to do, possible * values are show, save, delete, password (with id as second parameter). * The default is to search and list users. */ public void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); if (forbidIfGuest(res)) { return; } String action = Optional.ofNullable(req.getParameter("action")).orElse("listUsers"); String uid = req.getParameter("id"); MCRUser user; if ((uid == null) || (uid.trim().length() == 0)) { user = MCRUserManager.getCurrentUser(); uid = user != null ? String.valueOf(user.getUserID()) : null; if (!(user instanceof MCRTransientUser)) { //even reload current user, so that owner is correctly initialized user = MCRUserManager.getUser(uid); } } else { user = MCRUserManager.getUser(uid); } switch (action) { case "show" -> showUser(req, res, user, uid); case "save" -> saveUser(req, res); case "saveCurrentUser" -> saveCurrentUser(req, res); case "changeMyPassword" -> redirectToPasswordChangePage(req, res); case "password" -> changePassword(req, res, user, uid); case "delete" -> deleteUser(req, res, user); case "listUsers" -> listUsers(req, res); default -> throw new ServletException("unknown action: " + action); } } private void redirectToPasswordChangePage(HttpServletRequest req, HttpServletResponse res) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!checkUserIsNotNull(res, currentUser, null)) { return; } if (checkUserIsLocked(res, currentUser) || checkUserIsDisabled(res, currentUser)) { return; } String url = currentUser.getRealm().getPasswordChangeURL(); if (url == null) { String msg = MCRTranslation.translate("component.user2.UserServlet.missingRealPasswortChangeURL", currentUser.getRealmID()); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } else { res.sendRedirect(url); } } private static boolean checkUserIsNotNull(HttpServletResponse res, MCRUser currentUser, String userID) throws IOException { if (currentUser == null) { String uid = userID == null ? MCRSessionMgr.getCurrentSession().getUserInformation().getUserID() : userID; String msg = MCRTranslation.translate("component.user2.UserServlet.currentUserUnknown", uid); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return false; } return true; } private static boolean checkUserIsLocked(HttpServletResponse res, MCRUser currentUser) throws IOException { if (currentUser.isLocked()) { String userName = currentUser.getUserID(); String msg = MCRTranslation.translate("component.user2.UserServlet.isLocked", userName); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return true; } return false; } private static boolean checkUserIsDisabled(HttpServletResponse res, MCRUser currentUser) throws IOException { if (currentUser.isDisabled()) { String userName = currentUser.getUserID(); String msg = MCRTranslation.translate("component.user2.UserServlet.isDisabled", userName); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return true; } return false; } private static boolean forbidIfGuest(HttpServletResponse res) throws IOException { if (MCRSessionMgr.getCurrentSession().getUserInformation().getUserID() .equals(MCRSystemUserInformation.getGuestInstance().getUserID())) { String msg = MCRTranslation.translate("component.user2.UserServlet.noGuestAction"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return true; } return false; } /** * Handles MCRUserServlet?action=show&id={userID}. * Outputs user data for the given id using user.xsl. */ private void showUser(HttpServletRequest req, HttpServletResponse res, MCRUser user, String uid) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!checkUserIsNotNull(res, currentUser, null) || !checkUserIsNotNull(res, user, uid)) { return; } boolean allowed = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION) || currentUser.equals(user) || currentUser.equals(user.getOwner()); if (!allowed) { String msg = MCRTranslation.translate("component.user2.UserServlet.noAdminPermission"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } LOGGER.info("show user {} {} {}", user.getUserID(), user.getUserName(), user.getRealmID()); getLayoutService().doLayout(req, res, getContent(user)); } /** * Invoked by editor form user-editor.xed to check for a valid * login user name. */ public static boolean checkUserName(String userName) { String realmID = MCRRealmFactory.getLocalRealm().getID(); // Check for required fields is done in the editor form itself, not here if ((userName == null) || (realmID == null)) { return true; } // In all other cases, combination of userName and realm must not exist return !MCRUserManager.exists(userName, realmID); } private void saveCurrentUser(HttpServletRequest req, HttpServletResponse res) throws IOException { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!checkUserIsNotNull(res, currentUser, null)) { return; } if (checkUserIsLocked(res, currentUser) || checkUserIsDisabled(res, currentUser)) { return; } if (!currentUser.hasNoOwner() && currentUser.isLocked()) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } Document doc = (Document) (req.getAttribute("MCRXEditorSubmission")); Element u = doc.getRootElement(); updateBasicUserInfo(u, currentUser); MCRUserManager.updateUser(currentUser); res.sendRedirect(res.encodeRedirectURL("MCRUserServlet?action=show")); } /** * Handles MCRUserServlet?action=save&id={userID}. * This is called by user-editor.xml editor form to save the * changed user data from editor submission. Redirects to * show user data afterwards. */ private void saveUser(HttpServletRequest req, HttpServletResponse res) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!checkUserIsNotNull(res, currentUser, null)) { return; } boolean hasAdminPermission = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION); boolean allowed = hasAdminPermission || MCRAccessManager.checkPermission(MCRUser2Constants.USER_CREATE_PERMISSION); if (!allowed) { String msg = MCRTranslation.translate("component.user2.UserServlet.noCreatePermission"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } Document doc = (Document) (req.getAttribute("MCRXEditorSubmission")); Element u = doc.getRootElement(); String userName = u.getAttributeValue("name"); String realmID = MCRRealmFactory.getLocalRealm().getID(); if (hasAdminPermission) { realmID = u.getAttributeValue("realm"); } MCRUser user; boolean userExists = MCRUserManager.exists(userName, realmID); if (!userExists) { user = new MCRUser(userName, realmID); LOGGER.info("create new user {} {}", userName, realmID); // For new local users, set password String pwd = u.getChildText("password"); if ((pwd != null) && (pwd.trim().length() > 0) && user.getRealm().equals(MCRRealmFactory.getLocalRealm())) { MCRUserManager.updatePasswordHashToSHA256(user, pwd); } } else { user = MCRUserManager.getUser(userName, realmID); if (!(hasAdminPermission || currentUser.equals(user) || currentUser.equals(user.getOwner()))) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } XPathExpression<Attribute> hintPath = XPathFactory.instance().compile("password/@hint", Filters.attribute()); Attribute hintAttr = hintPath.evaluateFirst(u); String hint = hintAttr == null ? null : hintAttr.getValue(); if ((hint != null) && (hint.trim().length() == 0)) { hint = null; } user.setHint(hint); updateBasicUserInfo(u, user); if (hasAdminPermission) { boolean locked = "true".equals(u.getAttributeValue("locked")); user.setLocked(locked); boolean disabled = "true".equals(u.getAttributeValue("disabled")); user.setDisabled(disabled); Element o = u.getChild("owner"); if (o != null && !o.getAttributes().isEmpty()) { String ownerName = o.getAttributeValue("name"); String ownerRealm = o.getAttributeValue("realm"); MCRUser owner = MCRUserManager.getUser(ownerName, ownerRealm); if (!checkUserIsNotNull(res, owner, ownerName + "@" + ownerRealm)) { return; } user.setOwner(owner); } else { user.setOwner(null); } String validUntilText = u.getChildTextTrim("validUntil"); if (validUntilText == null || validUntilText.length() == 0) { user.setValidUntil(null); } else { String dateInUTC = validUntilText; if (validUntilText.length() == 10) { dateInUTC = convertToUTC(validUntilText, "yyyy-MM-dd"); } MCRISO8601Date date = new MCRISO8601Date(dateInUTC); user.setValidUntil(date.getDate()); } } else { // save read user of creator user.setRealm(MCRRealmFactory.getLocalRealm()); user.setOwner(currentUser); } Element gs = u.getChild("roles"); if (gs != null) { user.getSystemRoleIDs().clear(); user.getExternalRoleIDs().clear(); List<Element> groupList = gs.getChildren("role"); for (Element group : groupList) { String groupName = group.getAttributeValue("name"); if (hasAdminPermission || currentUser.isUserInRole(groupName)) { user.assignRole(groupName); } else { LOGGER.warn("Current user {} has not the permission to add user to group {}", currentUser.getUserID(), groupName); } } } if (userExists) { MCRUserManager.updateUser(user); } else { MCRUserManager.createUser(user); } res.sendRedirect(res.encodeRedirectURL("MCRUserServlet?action=show&id=" + URLEncoder.encode(user.getUserID(), StandardCharsets.UTF_8))); } private String convertToUTC(String validUntilText, String format) throws ParseException { DateFormat inputFormat = new SimpleDateFormat(format, Locale.ROOT); inputFormat.setTimeZone(UTC_TIME_ZONE); DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ROOT); Date d = inputFormat.parse(validUntilText); outputFormat.setTimeZone(UTC_TIME_ZONE); return outputFormat.format(d); } private void updateBasicUserInfo(Element u, MCRUser user) { String name = u.getChildText("realName"); if ((name != null) && (name.trim().length() == 0)) { name = null; } user.setRealName(name); String eMail = u.getChildText("eMail"); if ((eMail != null) && (eMail.trim().length() == 0)) { eMail = null; } user.setEMail(eMail); List<Element> attributeList = Optional.ofNullable(u.getChild("attributes")) .map(attributes -> attributes.getChildren("attribute")) .orElse(Collections.emptyList()); Set<MCRUserAttribute> newAttrs = attributeList.stream() .map(a -> new MCRUserAttribute(a.getAttributeValue("name"), a.getAttributeValue("value"))) .collect(Collectors.toSet()); user.getAttributes().retainAll(newAttrs); newAttrs.removeAll(user.getAttributes()); user.getAttributes().addAll(newAttrs); } /** * Handles MCRUserServlet?action=save&id={userID}. * This is called by user-editor.xml editor form to save the * changed user data from editor submission. Redirects to * show user data afterwards. */ private void changePassword(HttpServletRequest req, HttpServletResponse res, MCRUser user, String uid) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!checkUserIsNotNull(res, currentUser, null) || !checkUserIsNotNull(res, user, uid)) { return; } boolean allowed = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION) || currentUser.equals(user.getOwner()) || currentUser.equals(user) && !currentUser.isLocked(); if (!allowed) { String msg = MCRTranslation.translate("component.user2.UserServlet.noAdminPermission"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } LOGGER.info("change password of user {} {} {}", user.getUserID(), user.getUserName(), user.getRealmID()); Document doc = (Document) (req.getAttribute("MCRXEditorSubmission")); String password = doc.getRootElement().getChildText("password"); MCRUserManager.setPassword(user, password); res.sendRedirect(res.encodeRedirectURL("MCRUserServlet?action=show&XSL.step=changedPassword&id=" + URLEncoder.encode(user.getUserID(), StandardCharsets.UTF_8))); } /** * Handles MCRUserServlet?action=delete&id={userID}. * Deletes the user. * Outputs user data of the deleted user using user.xsl afterwards. */ private void deleteUser(HttpServletRequest req, HttpServletResponse res, MCRUser user) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); boolean allowed = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION) || currentUser.equals(user.getOwner()); if (!allowed) { String msg = MCRTranslation.translate("component.user2.UserServlet.noAdminPermission"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } LOGGER.info("delete user {} {} {}", user.getUserID(), user.getUserName(), user.getRealmID()); MCRUserManager.deleteUser(user); getLayoutService().doLayout(req, res, getContent(user)); } private MCRJAXBContent<MCRUser> getContent(MCRUser user) { return new MCRJAXBContent<>(JAXB_CONTEXT, user.getSafeCopy()); } /** * Handles MCRUserServlet?search={pattern}, which is an optional parameter. * Searches for users matching the pattern in user name or real name and outputs * the list of results using users.xsl. The search pattern may contain * and ? * wildcard characters. The property MCR.user2.Users.MaxResults (default 100) specifies * the maximum number of users to return. When there are more hits, just the * number of results is returned. * * When current user is not admin, the search pattern will be ignored and only all * the users the current user is owner of will be listed. */ private void listUsers(HttpServletRequest req, HttpServletResponse res) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); List<MCRUser> ownUsers = MCRUserManager.listUsers(currentUser); boolean hasAdminPermission = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION); boolean allowed = hasAdminPermission || MCRAccessManager.checkPermission(MCRUser2Constants.USER_CREATE_PERMISSION) || !ownUsers.isEmpty(); if (!allowed) { String msg = MCRTranslation.translate("component.user2.UserServlet.noCreatePermission"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } Element users = new Element("users"); List<MCRUser> results = null; if (hasAdminPermission) { String search = req.getParameter("search"); String pattern; if (search == null || search.isBlank()) { pattern = null; } else { users.setAttribute("search", search); pattern = "*" + search + "*"; } LOGGER.info("search users like {}", search); int max = MCRConfiguration2.getInt(MCRUser2Constants.CONFIG_PREFIX + "Users.MaxResults").orElse(100); int num = MCRUserManager.countUsers(pattern, null, pattern, pattern, null, pattern); if ((num < max) && (num > 0)) { results = MCRUserManager.listUsers(pattern, null, pattern, pattern, null, pattern, 0, Integer.MAX_VALUE); } users.setAttribute("num", String.valueOf(num)); users.setAttribute("max", String.valueOf(max)); } else { LOGGER.info("list owned users of {} {}", currentUser.getUserName(), currentUser.getRealmID()); results = ownUsers; } if (results != null) { for (MCRUser user : results) { Element u = MCRUserTransformer.buildBasicXML(user).detachRootElement(); addString(u, "realName", user.getRealName()); addString(u, "eMail", user.getEMailAddress()); users.addContent(u); } } getLayoutService().doLayout(req, res, new MCRJDOMContent(users)); } private void addString(Element parent, String name, String value) { if ((value != null) && (value.trim().length() > 0)) { parent.addContent(new Element(name).setText(value.trim())); } } }
21,628
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserAttributeMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttributeMapper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.MCRUserInformation; import org.mycore.user2.annotation.MCRUserAttribute; import org.mycore.user2.annotation.MCRUserAttributeJavaConverter; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlValue; /** * This class is used to map attributes on {@link MCRUser} or {@link MCRUserInformation} * to annotated properties or methods. * <br><br> * You can configure the mapping within <code>realms.xml</code> like this: * <br> * <pre> * <code> * &lt;realms local="local"&gt; * ... * &lt;realm ...&gt; * ... * &lt;attributeMapping&gt; * &lt;attribute name="userName" mapping="eduPersonPrincipalName" /&gt; * &lt;attribute name="realName" mapping="displayName" /&gt; * &lt;attribute name="eMail" mapping="mail" /&gt; * &lt;attribute name="roles" mapping="eduPersonAffiliation" separator="," * converter="org.mycore.user2.utils.MCRRolesConverter"&gt; * &lt;valueMapping name="employee"&gt;editor&lt;/valueMapping&gt; * &lt;/attribute&gt; * &lt;/attributeMapping&gt; * ... * &lt;/realm&gt; * ... * &lt;/realms&gt; * </code> * </pre> * * @author René Adler (eagle) * */ public class MCRUserAttributeMapper { private static Logger LOGGER = LogManager.getLogger(MCRUserAttributeMapper.class); private HashMap<String, List<Attribute>> attributeMapping = new HashMap<>(); public static MCRUserAttributeMapper instance(Element attributeMapping) { try { JAXBContext jaxb = JAXBContext.newInstance(Mappings.class.getPackage().getName(), Mappings.class.getClassLoader()); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); Mappings mappings = (Mappings) unmarshaller.unmarshal(new JDOMSource(attributeMapping)); MCRUserAttributeMapper uam = new MCRUserAttributeMapper(); uam.attributeMapping.putAll(mappings.getAttributeMap()); return uam; } catch (Exception e) { return null; } } /** * Maps configured attributes to {@link Object}. * * @param object the {@link Object} * @param attributes a collection of attributes to map * @return <code>true</code> if any attribute was changed */ @SuppressWarnings({ "rawtypes", "unchecked" }) public boolean mapAttributes(final Object object, final Map<String, ?> attributes) throws Exception { boolean changed = false; for (Object annotated : getAnnotated(object)) { MCRUserAttribute attrAnno = null; if (annotated instanceof Field field) { attrAnno = field.getAnnotation(MCRUserAttribute.class); } else if (annotated instanceof Method method) { attrAnno = method.getAnnotation(MCRUserAttribute.class); } if (attrAnno != null) { final String name = attrAnno.name().isEmpty() ? getAttriutebName(annotated) : attrAnno.name(); final List<Attribute> attribs = attributeMapping.get(name); if (attributes != null) { for (Attribute attribute : attribs) { if (attributes.containsKey(attribute.mapping)) { Object value = attributes.get(attribute.mapping); if(value == null){ LOGGER.warn("Could not apply mapping for {}", attribute.mapping); } MCRUserAttributeJavaConverter aConv = null; if (annotated instanceof Field field) { aConv = field.getAnnotation(MCRUserAttributeJavaConverter.class); } else if (annotated instanceof Method method) { aConv = method.getAnnotation(MCRUserAttributeJavaConverter.class); } Class<? extends MCRUserAttributeConverter> convCls = null; if (attribute.converter != null) { convCls = (Class<? extends MCRUserAttributeConverter>) Class .forName(attribute.converter); } else if (aConv != null) { convCls = aConv.value(); } if (convCls != null) { MCRUserAttributeConverter converter = convCls.getDeclaredConstructor().newInstance(); LOGGER.debug("convert value \"{}\" with \"{}\"", value, converter.getClass().getName()); value = converter.convert(value, attribute.separator != null ? attribute.separator : attrAnno.separator(), attribute.getValueMap()); } if (value != null || ((attrAnno.nullable() || attribute.nullable) && value == null)) { Object oldValue = getValue(object, annotated); if (oldValue != null && oldValue.equals(value)) { continue; } if (annotated instanceof Field field) { LOGGER.debug("map attribute \"{}\" with value \"{}\" to field \"{}\"", attribute.mapping, value, field.getName()); field.setAccessible(true); field.set(object, value); changed = true; } else if (annotated instanceof Method method) { LOGGER.debug("map attribute \"{}\" with value \"{}\" to method \"{}\"", attribute.mapping, value, method.getName()); method.setAccessible(true); method.invoke(object, value); changed = true; } } else { throw new IllegalArgumentException( "A not nullable attribute \"" + name + "\" was null."); } } } } } } return changed; } /** * Returns a collection of mapped attribute names. * * @return a collection of mapped attribute names */ public Set<String> getAttributeNames() { Set<String> mAtt = new HashSet<>(); for (final String name : attributeMapping.keySet()) { attributeMapping.get(name).forEach(a -> mAtt.add(a.mapping)); } return mAtt; } private List<Object> getAnnotated(final Object obj) { List<Object> al = new ArrayList<>(); al.addAll(getAnnotatedFields(obj.getClass())); al.addAll(getAnnotatedMethods(obj.getClass())); if (obj.getClass().getSuperclass() != null) { al.addAll(getAnnotatedFields(obj.getClass().getSuperclass())); al.addAll(getAnnotatedMethods(obj.getClass().getSuperclass())); } return al; } private List<Object> getAnnotatedFields(final Class<?> cls) { return Arrays.stream(cls.getDeclaredFields()) .filter(field -> field.getAnnotation(MCRUserAttribute.class) != null) .collect(Collectors.toList()); } private List<Object> getAnnotatedMethods(final Class<?> cls) { return Arrays.stream(cls.getDeclaredMethods()) .filter(method -> method.getAnnotation(MCRUserAttribute.class) != null) .collect(Collectors.toList()); } private String getAttriutebName(final Object annotated) { if (annotated instanceof Field field) { return field.getName(); } else if (annotated instanceof Method method) { String name = method.getName(); if (name.startsWith("set")) { name = name.substring(3); } return name.substring(0, 1).toLowerCase(Locale.ROOT) + name.substring(1); } return null; } private Object getValue(final Object object, final Object annotated) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException { Object value = null; if (annotated instanceof Field field) { field.setAccessible(true); value = field.get(object); } else if (annotated instanceof Method annMethod) { Method method = null; String name = annMethod.getName(); if (name.startsWith("get")) { name = "s" + name.substring(1); method = object.getClass().getMethod(name); } if (method != null) { method.setAccessible(true); value = method.invoke(object); } } return value; } @XmlRootElement(name = "realm") @XmlAccessorType(XmlAccessType.FIELD) private static class Mappings { @XmlElementWrapper(name = "attributeMapping") @XmlElement(name = "attribute") List<Attribute> attributes; Map<String, List<Attribute>> getAttributeMap() { return attributes.stream().collect(Collectors.groupingBy(attrib -> attrib.name)); } } @XmlRootElement(name = "attribute") @XmlAccessorType(XmlAccessType.FIELD) private static class Attribute { @XmlAttribute(required = true) String name; @XmlAttribute(required = true) String mapping; @XmlAttribute String separator; @XmlAttribute boolean nullable; @XmlAttribute String converter; @XmlElement List<ValueMapping> valueMapping; Map<String, String> getValueMap() { if (valueMapping == null) { return null; } Map<String, String> map = new HashMap<>(); for (ValueMapping vm : valueMapping) { map.put(vm.name, vm.mapping); } return map; } } @XmlRootElement(name = "valueMapping") @XmlAccessorType(XmlAccessType.FIELD) private static class ValueMapping { @XmlAttribute(required = true) String name; @XmlValue String mapping; } }
12,422
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTransientUser.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRTransientUser.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRUserInformation; /** * @author Thomas Scheffler (yagee) * */ public class MCRTransientUser extends MCRUser { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRTransientUser.class); private MCRUserInformation userInfo; public MCRTransientUser(MCRUserInformation userInfo) { super(); this.userInfo = userInfo; setLocked(true); String userName = userInfo.getUserID(); if (userName.contains("@")) { userName = userName.substring(0, userName.indexOf("@")); } String realmId = getUserAttribute(MCRRealm.USER_INFORMATION_ATTR); super.setUserName(userName); super.setRealmID(realmId); super.setLastLogin(new Date(MCRSessionMgr.getCurrentSession().getLoginTime())); if (realmId != null && !MCRRealmFactory.getLocalRealm().equals(MCRRealmFactory.getRealm(realmId))) { MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(realmId); if (attributeMapper != null) { Map<String, Object> attributes = new HashMap<>(); for (String key : attributeMapper.getAttributeNames()) { attributes.put(key, userInfo.getUserAttribute(key)); } try { attributeMapper.mapAttributes(this, attributes); } catch (Exception e) { throw new MCRException(e.getMessage(), e); } } } else { super.setRealName(getUserAttribute(MCRUserInformation.ATT_REAL_NAME)); for (MCRRole role : MCRRoleManager.listSystemRoles()) { LOGGER.debug("Test is in role: {}", role.getName()); if (userInfo.isUserInRole(role.getName())) { assignRole(role.getName()); } } } } @Override public String getUserAttribute(String attribute) { return this.userInfo.getUserAttribute(attribute); } }
3,092
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessManager; import org.mycore.backend.jpa.MCREntityManagerProvider; 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.MCRUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventManager; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRISO8601Format; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import jakarta.persistence.metamodel.SingularAttribute; /** * Manages all users using a database table. * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ public class MCRUserManager { private static final int HASH_ITERATIONS = MCRConfiguration2 .getInt(MCRUser2Constants.CONFIG_PREFIX + "HashIterations").orElse(1000); private static final Logger LOGGER = LogManager.getLogger(); private static final SecureRandom SECURE_RANDOM; static { try { SECURE_RANDOM = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new MCRException("Could not initialize secure SECURE_RANDOM number", e); } } /** The table that stores login user information */ static String table; /** * Returns the user with the given userName, in the default realm * * @param userName the unique userName within the default realm * @return the user with the given login name, or null */ public static MCRUser getUser(String userName) { if (!userName.contains("@")) { return getUser(userName, MCRRealmFactory.getLocalRealm()); } else { String[] parts = userName.split("@"); if (parts.length == 2) { return getUser(parts[0], parts[1]); } else { return null; } } } /** * Returns the user with the given userName, in the given realm * * @param userName the unique userName within the given realm * @param realm the realm the user belongs to * @return the user with the given login name, or null */ public static MCRUser getUser(String userName, MCRRealm realm) { return getUser(userName, realm.getID()); } /** * Returns the user with the given userName, in the given realm * * @param userName the unique userName within the given realm * @param realmId the ID of the realm the user belongs to * @return the user with the given login name, or null */ public static MCRUser getUser(String userName, String realmId) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); return getByNaturalID(em, userName, realmId) .map(MCRUserManager::setRoles) .orElseGet(() -> { LOGGER.warn("Could not find requested user: {}@{}", userName, realmId); return null; }); } /** * Returns a Stream of users where the user has a given attribute. * @param attrName name of the user attribute * @param attrValue value of the user attribute */ public static Stream<MCRUser> getUsers(String attrName, String attrValue) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); TypedQuery<MCRUser> propertyQuery = em.createNamedQuery("MCRUser.byPropertyValue", MCRUser.class); propertyQuery.setParameter("name", attrName); propertyQuery.setParameter("value", attrValue); MCRUserAttribute attr = new MCRUserAttribute(attrName, attrValue); return propertyQuery.getResultList() .stream() .filter(u -> u.getAttributes().contains(attr)) .peek(em::refresh); //fixes MCR-1885 } private static MCRUser setRoles(MCRUser mcrUser) { Collection<MCRCategoryID> roleIDs = MCRRoleManager.getRoleIDs(mcrUser); mcrUser.getSystemRoleIDs().clear(); mcrUser.getExternalRoleIDs().clear(); for (MCRCategoryID roleID : roleIDs) { if (roleID.getRootID().equals(MCRUser2Constants.ROLE_CLASSID.getRootID())) { mcrUser.getSystemRoleIDs().add(roleID.getId()); } else { mcrUser.getExternalRoleIDs().add(roleID.toString()); } } return mcrUser; } /** * Checks if a user with the given login name exists in the default realm. * * @param userName the login user name. * @return true, if a user with the given login name exists. */ public static boolean exists(String userName) { return exists(userName, MCRRealmFactory.getLocalRealm()); } /** * Checks if a user with the given login name exists in the given realm. * * @param userName the login user name. * @param realm the realm the user belongs to * @return true, if a user with the given login name exists. */ public static boolean exists(String userName, MCRRealm realm) { return exists(userName, realm.getID()); } /** * Checks if a user with the given login name exists in the given realm. * * @param userName the login user name. * @param realm the ID of the realm the user belongs to * @return true, if a user with the given login name exists. */ public static boolean exists(String userName, String realm) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Number> query = cb.createQuery(Number.class); Root<MCRUser> users = query.from(MCRUser.class); return em.createQuery( query .select(cb.count(users)) .where(getUserRealmCriterion(cb, users, userName, realm))) .getSingleResult().intValue() > 0; } /** * Creates and stores a new login user in the database. * This will also store role membership information. * * @param user the user to create in the database. */ public static void createUser(MCRUser user) { if (isInvalidUser(user)) { throw new MCRException("User is invalid: " + user.getUserID()); } if (user instanceof MCRTransientUser transientUser) { createUser(transientUser); return; } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.persist(user); LOGGER.info(() -> "user saved: " + user.getUserID()); MCRRoleManager.storeRoleAssignments(user); MCREvent evt = new MCREvent(MCREvent.ObjectType.USER, MCREvent.EventType.CREATE); evt.put(MCREvent.USER_KEY, user); MCREventManager.instance().handleEvent(evt); } /** * Creates and store a new login user in the database, do also attribute mapping is needed. * This will also store role membership information. * * @param user the user to create in the database. */ public static void createUser(MCRTransientUser user) { if (isInvalidUser(user)) { throw new MCRException("User is invalid: " + user.getUserID()); } createUser(user.clone()); } /** * Checks whether the user is invalid. * * MCRUser is not allowed to overwrite information returned by {@link MCRSystemUserInformation#getGuestInstance()} * or {@link MCRSystemUserInformation#getSystemUserInstance()}. * @return true if {@link #createUser(MCRUser)} or {@link #updateUser(MCRUser)} would reject the given user */ public static boolean isInvalidUser(MCRUser user) { if (MCRSystemUserInformation.getGuestInstance().getUserID().equals(user.getUserID())) { return true; } return MCRSystemUserInformation.getSystemUserInstance().getUserID().equals(user.getUserID()); } /** * Updates an existing login user in the database. * This will also update role membership information. * * @param user the user to update in the database. */ public static void updateUser(MCRUser user) { if (isInvalidUser(user)) { throw new MCRException("User is invalid: " + user.getUserID()); } EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); Optional<MCRUser> inDb = getByNaturalID(em, user.getUserName(), user.getRealmID()); if (!inDb.isPresent()) { createUser(user); return; } inDb.ifPresent(db -> { user.internalID = db.internalID; em.merge(user); MCRRoleManager.unassignRoles(user); MCRRoleManager.storeRoleAssignments(user); MCREvent evt = new MCREvent(MCREvent.ObjectType.USER, MCREvent.EventType.UPDATE); evt.put(MCREvent.USER_KEY, user); MCREventManager.instance().handleEvent(evt); }); } /** * Deletes a user from the given database * * @param userName the login name of the user to delete, in the default realm. */ public static void deleteUser(String userName) { if (!userName.contains("@")) { deleteUser(userName, MCRRealmFactory.getLocalRealm()); } else { String[] parts = userName.split("@"); deleteUser(parts[0], parts[1]); } } /** * Deletes a user from the given database * * @param userName the login name of the user to delete, in the given realm. * @param realm the realm the user belongs to */ public static void deleteUser(String userName, MCRRealm realm) { deleteUser(userName, realm.getID()); } /** * Deletes a user from the given database * * @param userName the login name of the user to delete, in the given realm. * @param realmId the ID of the realm the user belongs to */ public static void deleteUser(String userName, String realmId) { MCRUser user = getUser(userName, realmId); MCREvent evt = new MCREvent(MCREvent.ObjectType.USER, MCREvent.EventType.DELETE); evt.put(MCREvent.USER_KEY, user); MCREventManager.instance().handleEvent(evt); MCRRoleManager.unassignRoles(user); EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); em.remove(user); } /** * Deletes a user from the given database * * @param user the user to delete */ public static void deleteUser(MCRUser user) { deleteUser(user.getUserName(), user.getRealmID()); } /** * Returns a list of all users the given user is owner of. * * @param owner the user that owns other users */ public static List<MCRUser> listUsers(MCRUser owner) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRUser> query = cb.createQuery(MCRUser.class); Root<MCRUser> users = query.from(MCRUser.class); users.fetch(MCRUser_.owner); return em.createQuery( query .distinct(true) .where(cb.equal(users.get(MCRUser_.owner), owner))) .getResultList(); } private static String buildSearchPattern(String searchPattern) { searchPattern = searchPattern.replace('*', '%'); searchPattern = searchPattern.replace('?', '_'); return searchPattern.toLowerCase(MCRSessionMgr.getCurrentSession().getLocale()); } private static boolean isValidSearchPattern(String searchPattern) { return StringUtils.isNotEmpty(searchPattern); } private static Predicate[] buildCondition(CriteriaBuilder cb, Root<MCRUser> root, String userPattern, String realm, String namePattern, String mailPattern, String attributeNamePattern, String attributeValuePattern) { ArrayList<Predicate> predicates = new ArrayList<>(2); addEqualsPredicate(cb, root, MCRUser_.realmID, realm, predicates); ArrayList<Predicate> searchPredicates = new ArrayList<>(3); addSearchPredicate(cb, root, MCRUser_.userName, userPattern, searchPredicates); addSearchPredicate(cb, root, MCRUser_.realName, namePattern, searchPredicates); addSearchPredicate(cb, root, MCRUser_.EMail, mailPattern, searchPredicates); if (isValidSearchPattern(attributeNamePattern) || isValidSearchPattern(attributeValuePattern)) { Join<MCRUser, MCRUserAttribute> userAttributeJoin = root.join(MCRUser_.attributes, JoinType.LEFT); if (isValidSearchPattern(attributeNamePattern)) { searchPredicates.add(cb.like(cb.lower(userAttributeJoin.get(MCRUserAttribute_.name)), buildSearchPattern(attributeNamePattern))); } if (isValidSearchPattern(attributeValuePattern)) { searchPredicates.add(cb.like(cb.lower(userAttributeJoin.get(MCRUserAttribute_.value)), buildSearchPattern(attributeValuePattern))); } } if (!searchPredicates.isEmpty()) { if (searchPredicates.size() == 1) { predicates.add(searchPredicates.get(0)); } else { predicates.add(cb.or(searchPredicates.toArray(Predicate[]::new))); } } return predicates.toArray(Predicate[]::new); } private static void addEqualsPredicate(CriteriaBuilder cb, Root<MCRUser> root, SingularAttribute<MCRUser, String> attribute, String string, ArrayList<Predicate> predicates) { if (isValidSearchPattern(string)) { predicates.add(cb.equal(root.get(attribute), string)); } } private static void addSearchPredicate(CriteriaBuilder cb, Root<MCRUser> root, SingularAttribute<MCRUser, String> attribute, String searchPattern, ArrayList<Predicate> predicates) { if (isValidSearchPattern(searchPattern)) { predicates.add(buildSearchPredicate(cb, root, attribute, searchPattern)); } } private static Predicate buildSearchPredicate(CriteriaBuilder cb, Root<MCRUser> root, SingularAttribute<MCRUser, String> attribute, String searchPattern) { return cb.like(cb.lower(root.get(attribute)), buildSearchPattern(searchPattern)); } /** * Searches for users in the database and returns a list of matching users. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * Pay attention that no role information is attached to user data. If you need * this information call {@link MCRUserManager#getUser(String, String)}. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @return a list of all matching users * @deprecated Use {@link MCRUserManager#listUsers(String, String, String, String)} instead. */ @Deprecated public static List<MCRUser> listUsers(String userPattern, String realm, String namePattern) { return listUsers(userPattern, realm, namePattern, null); } /** * Searches for users in the database and returns a list of all matching users. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * Pay attention that no role information is attached to user data. If you need * this information call {@link MCRUserManager#getUser(String, String)}. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @param mailPattern a wildcard pattern for the person's email, may be null * @return a list of all matching users */ public static List<MCRUser> listUsers(String userPattern, String realm, String namePattern, String mailPattern) { return listUsers(userPattern, realm, namePattern, mailPattern, null, null, 0, Integer.MAX_VALUE); } /** * Searches for users in the database and returns a list of matching users. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * Pay attention that no role information is attached to user data. If you need * this information call {@link MCRUserManager#getUser(String, String)}. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @param mailPattern a wildcard pattern for the person's email, may be null * @param attributeNamePattern a wildcard pattern for person's attribute names, may be null * @param offset an offset for matching users * @param limit a limit for matching users * @return a list of matching users in offset and limit range */ public static List<MCRUser> listUsers(String userPattern, String realm, String namePattern, String mailPattern, String attributeNamePattern, int offset, int limit) { return listUsers(userPattern, realm, namePattern, mailPattern, attributeNamePattern, null, offset, limit); } /** * Searches for users in the database and returns a list of matching users. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * Pay attention that no role information is attached to user data. If you need * this information call {@link MCRUserManager#getUser(String, String)}. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @param mailPattern a wildcard pattern for the person's email, may be null * @param attributeNamePattern a wildcard pattern for person's attribute names, may be null * @param attributeValuePattern a wildcard pattern for person's attribute values, may be null * @param offset an offset for matching users * @param limit a limit for matching users * @return a list of matching users in offset and limit range */ public static List<MCRUser> listUsers(String userPattern, String realm, String namePattern, String mailPattern, String attributeNamePattern, String attributeValuePattern, int offset, int limit) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRUser> query = cb.createQuery(MCRUser.class); Root<MCRUser> user = query.from(MCRUser.class); return em .createQuery( query .distinct(true) .where( buildCondition(cb, user, userPattern, realm, namePattern, mailPattern, attributeNamePattern, attributeValuePattern))) .setFirstResult(offset) .setMaxResults(limit) .getResultList(); } /** * Counts users in the database that match the given criteria. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @return the number of matching users * @deprecated Use {@link MCRUserManager#countUsers(String, String, String, String)} instead. */ @Deprecated public static int countUsers(String userPattern, String realm, String namePattern) { return countUsers(userPattern, realm, namePattern, null); } /** * Counts users in the database that match the given criteria. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @param mailPattern a wildcard pattern for the person's email, may be null * @return the number of matching users */ public static int countUsers(String userPattern, String realm, String namePattern, String mailPattern) { return countUsers(userPattern, realm, namePattern, mailPattern, null, null); } /** * Counts users in the database that match the given criteria. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @param mailPattern a wildcard pattern for the person's email, may be null * @param attributeNamePattern a wildcard pattern for person's attribute names, may be null * @return the number of matching users */ public static int countUsers(String userPattern, String realm, String namePattern, String mailPattern, String attributeNamePattern) { return countUsers(userPattern, realm, namePattern, mailPattern, attributeNamePattern, null); } /** * Counts users in the database that match the given criteria. * Wildcards containing * and ? for single character may be used for searching * by login user name or real name. * * @param userPattern a wildcard pattern for the login user name, may be null * @param realm the realm the user belongs to, may be null * @param namePattern a wildcard pattern for the person's real name, may be null * @param mailPattern a wildcard pattern for the person's email, may be null * @param attributeNamePattern a wildcard pattern for person's attribute names, may be null * @param attributeValuePattern a wildcard pattern for person's attribute names, may be null * @return the number of matching users */ public static int countUsers(String userPattern, String realm, String namePattern, String mailPattern, String attributeNamePattern, String attributeValuePattern) { EntityManager em = MCREntityManagerProvider.getCurrentEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Number> query = cb.createQuery(Number.class); Root<MCRUser> user = query.from(MCRUser.class); return em .createQuery( query .select(cb.count(user)) .distinct(true) .where( buildCondition(cb, user, userPattern, realm, namePattern, mailPattern, attributeNamePattern, attributeValuePattern))) .getSingleResult().intValue(); } /** * Checks the password of a login user in the default realm. * * @param userName the login user name * @param password the password entered in the GUI * @return true, if the password matches. */ public static MCRUser login(String userName, String password) { return login(userName, password, Collections.emptyList()); } /** * Checks the password of a login user and if the user has at least one of the allowed roles in the default realm. * * @param userName the login user name * @param password the password entered in the GUI * @param allowedRoles list of allowed roles * @return true, if the password matches. */ public static MCRUser login(String userName, String password, List<String> allowedRoles) { MCRUser user = checkPassword(userName, password); if (user == null) { return null; } if (!allowedRoles.isEmpty()) { Collection<String> userRoles = user.getSystemRoleIDs(); LOGGER.info("Comparing user roles " + userRoles + " against list of allowed roles " + allowedRoles); boolean hasAnyAllowedRole = userRoles.stream().anyMatch(allowedRoles::contains); if (!hasAnyAllowedRole) { return null; } } user.setLastLogin(); updateUser(user); MCRSessionMgr.getCurrentSession().setUserInformation(user); return user; } /** * Returns instance of MCRUser if current user is present in this user system * @return MCRUser instance or null */ public static MCRUser getCurrentUser() { MCRUserInformation userInformation = MCRSessionMgr.getCurrentSession().getUserInformation(); if (userInformation instanceof MCRUser mcrUser) { return mcrUser; } else { return new MCRTransientUser(userInformation); } } /** * Returns a {@link MCRUser} instance if the login succeeds. * This method will return <code>null</code> if the user does not exist, no password was given or * the login is disabled. * If the {@link MCRUser#getHashType()} is {@link MCRPasswordHashType#crypt}, {@link MCRPasswordHashType#md5} or * {@link MCRPasswordHashType#sha1} the hash value is automatically upgraded to {@link MCRPasswordHashType#sha256}. * @param userName Name of the user to login. * @param password clear text password. * @return authenticated {@link MCRUser} instance or <code>null</code>. */ public static MCRUser checkPassword(String userName, String password) { MCRUser user = getUser(userName); if (user == null || user.getHashType() == null) { LOGGER.warn(() -> "User not found: " + userName); waitLoginPanalty(); return null; } if (password == null) { LOGGER.warn("No password for user {} entered", userName); waitLoginPanalty(); return null; } if (!user.loginAllowed()) { if (user.isDisabled()) { LOGGER.warn("User {} was disabled!", user.getUserID()); } else { LOGGER.warn("Password expired for user {} on {}", user.getUserID(), MCRXMLFunctions.getISODate(user.getValidUntil(), MCRISO8601Format.COMPLETE_HH_MM_SS.toString())); } return null; } try { switch (user.getHashType()) { case crypt -> { //Wahh! did we ever thought about what "salt" means for passwd management? String passwdHash = user.getPassword(); String salt = passwdHash.substring(0, 3); if (!MCRUtils.asCryptString(salt, password).equals(passwdHash)) { //login failed waitLoginPanalty(); return null; } //update to SHA-256 updatePasswordHashToSHA256(user, password); } case md5 -> { if (!MCRUtils.asMD5String(1, null, password).equals(user.getPassword())) { waitLoginPanalty(); return null; } //update to SHA-256 updatePasswordHashToSHA256(user, password); } case sha1 -> { if (!MCRUtils.asSHA1String(HASH_ITERATIONS, Base64.getDecoder().decode(user.getSalt()), password) .equals(user.getPassword())) { waitLoginPanalty(); return null; } //update to SHA-256 updatePasswordHashToSHA256(user, password); } case sha256 -> { if (!MCRUtils.asSHA256String(HASH_ITERATIONS, Base64.getDecoder().decode(user.getSalt()), password) .equals(user.getPassword())) { waitLoginPanalty(); return null; } } default -> throw new MCRException("Cannot validate hash type " + user.getHashType()); } } catch (NoSuchAlgorithmException e) { throw new MCRException("Error while validating login", e); } return user; } private static void waitLoginPanalty() { try { Thread.sleep(3000); } catch (InterruptedException e) { } } /** * Sets password of 'user' to 'password'. * * Automatically updates the user in database. */ public static void setPassword(MCRUser user, String password) { MCRSession session = MCRSessionMgr.getCurrentSession(); MCRUserInformation currentUser = session.getUserInformation(); MCRUser myUser = getUser(user.getUserName(), user.getRealmID()); //only update password boolean allowed = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION) || currentUser.equals(myUser.getOwner()) || (currentUser.equals(user) && myUser.hasNoOwner() || !myUser.isLocked()); if (!allowed) { throw new MCRException("You are not allowed to change password of user: " + user); } updatePasswordHashToSHA256(myUser, password); updateUser(myUser); } static void updatePasswordHashToSHA256(MCRUser user, String password) { String newHash; byte[] salt = generateSalt(); try { newHash = MCRUtils.asSHA256String(HASH_ITERATIONS, salt, password); } catch (Exception e) { throw new MCRException("Could not update user password hash to SHA-256.", e); } user.setSalt(Base64.getEncoder().encodeToString(salt)); user.setHashType(MCRPasswordHashType.sha256); user.setPassword(newHash); } private static byte[] generateSalt() { return SECURE_RANDOM.generateSeed(8); } private static Optional<MCRUser> getByNaturalID(EntityManager em, String userName, String realmId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRUser> query = cb.createQuery(MCRUser.class); Root<MCRUser> users = query.from(MCRUser.class); users.fetch(MCRUser_.owner.getName(), JoinType.LEFT); try { return Optional .of(em .createQuery(query .distinct(true) .where(getUserRealmCriterion(cb, users, userName, realmId))) .getSingleResult()); } catch (NoResultException e) { return Optional.empty(); } } private static Predicate[] getUserRealmCriterion(CriteriaBuilder cb, Root<MCRUser> root, String user, String realmId) { if (realmId == null) { realmId = MCRRealmFactory.getLocalRealm().getID(); } return new Predicate[] { cb.equal(root.get(MCRUser_.userName), user), cb.equal(root.get(MCRUser_.realmID), realmId) }; } }
33,569
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserAttributeConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttributeConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.Map; /** * @author René Adler (eagle) * */ public interface MCRUserAttributeConverter<ValueType, BoundType> { /** * Convert a given value to the specified type. * * @param value the value of type <code>&lt;ValueType&gt;</code>, to convert * @param separator the value separator or <code>null</code> * @param valueMapping the value mapping or <code>null</code> * @return the converted value of type <code>&lt;BoundType&gt;</code> */ BoundType convert(ValueType value, String separator, Map<String, String> valueMapping); }
1,342
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUser2Constants.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUser2Constants.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.classifications2.MCRCategoryID; /** * @author Thomas Scheffler (yagee) * */ public final class MCRUser2Constants { /** * {@link MCRCategoryID} root ID for system roles. */ public static final String ROLE_ROOT_ID = "mcr-roles"; static final String USER_ADMIN_PERMISSION = "administrate-users"; static final String USER_CREATE_PERMISSION = "create-users"; /** * @return the userAdminPermission */ public static String getUserAdminPermission() { return USER_ADMIN_PERMISSION; } /** * @return the userCreatePermission */ public static String getUserCreatePermission() { return USER_CREATE_PERMISSION; } /** * @return the roleRootId */ public static String getRoleRootId() { return ROLE_ROOT_ID; } static final MCRCategoryID ROLE_CLASSID = MCRCategoryID.rootID(ROLE_ROOT_ID); static final String CATEG_LINK_TYPE = "mcr-user"; /** * {@link MCRConfiguration2} prefix for all properties used by this MyCoRe component. */ public static final String CONFIG_PREFIX = "MCR.user2."; private MCRUser2Constants() { //do not allow instantiation } }
2,038
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRealmFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRealmFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.transform.JDOMSource; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRFileContent; import org.mycore.common.content.MCRSourceContent; import org.mycore.common.xml.MCRXMLParserFactory; /** * Handles {@link MCRRealm} instantiation. * Will create a file <code>${MCR.datadir}/realms.xml</code> if that file does not exist. * You can redefine the location if you define a URI in <code>MCR.users2.Realms.URI</code>. * This class monitors the source file for changes and adapts at runtime. * @author Thomas Scheffler (yagee) * */ public class MCRRealmFactory { static final String RESOURCE_REALMS_URI = "resource:realms.xml"; static final String REALMS_URI_CFG_KEY = MCRUser2Constants.CONFIG_PREFIX + "Realms.URI"; private static final Logger LOGGER = LogManager.getLogger(MCRRealm.class); private static final int REFRESH_DELAY = 5000; private static long lastModified = 0; /** Map of defined realms, key is the ID of the realm */ private static HashMap<String, MCRRealm> realmsMap = new HashMap<>(); private static HashMap<String, MCRUserAttributeMapper> attributeMapper = new HashMap<>(); /** List of defined realms */ private static List<MCRRealm> realmsList = new ArrayList<>(); /** The local realm, which is the default realm */ private static MCRRealm localRealm; private static URI realmsURI; private static File realmsFile; private static long lastChecked; private static Document realmsDocument; static { String dataDirProperty = "MCR.datadir"; String dataDir = MCRConfiguration2.getString(dataDirProperty).orElse(null); if (dataDir == null) { LOGGER.warn("{} is undefined.", dataDirProperty); try { realmsURI = new URI(MCRConfiguration2.getString(REALMS_URI_CFG_KEY).orElse(RESOURCE_REALMS_URI)); } catch (URISyntaxException e) { throw new MCRException(e); } } else { File dataDirFile = new File(dataDir); String realmsCfg = MCRConfiguration2.getString(REALMS_URI_CFG_KEY) .orElse(dataDirFile.toURI() + "realms.xml"); try { realmsURI = new URI(realmsCfg); LOGGER.info("Using realms defined in {}", realmsURI); if ("file".equals(realmsURI.getScheme())) { realmsFile = new File(realmsURI); LOGGER.info("Loading realms from file: {}", realmsFile); } else { LOGGER.info("Try loading realms with URIResolver for scheme {}", realmsURI); } } catch (URISyntaxException e) { throw new MCRException(e); } } loadRealms(); } private static void loadRealms() { Element root; try { root = getRealms().getRootElement(); } catch (JDOMException | TransformerException | IOException e) { throw new MCRException("Could not load realms from URI: " + realmsURI); } String localRealmID = root.getAttributeValue("local"); HashMap<String, MCRRealm> realmsMap = new HashMap<>(); HashMap<String, MCRUserAttributeMapper> attributeMapper = new HashMap<>(); List<MCRRealm> realmsList = new ArrayList<>(); List<Element> realms = root.getChildren("realm"); for (Element child : realms) { String id = child.getAttributeValue("id"); MCRRealm realm = new MCRRealm(id); List<Element> labels = child.getChildren("label"); for (Element label : labels) { String text = label.getTextTrim(); String lang = label.getAttributeValue("lang", Namespace.XML_NAMESPACE); realm.setLabel(lang, text); } realm.setPasswordChangeURL(child.getChildTextTrim("passwordChangeURL")); Element login = child.getChild("login"); if (login != null) { realm.setLoginURL(login.getAttributeValue("url")); realm.setRedirectParameter(login.getAttributeValue("redirectParameter")); realm.setRealmParameter(login.getAttributeValue("realmParameter")); } Element createElement = child.getChild("create"); if (createElement != null) { realm.setCreateURL(createElement.getAttributeValue("url")); } attributeMapper.put(id, MCRUserAttributeMapper.instance(child)); realmsMap.put(id, realm); realmsList.add(realm); if (localRealmID.equals(id)) { localRealm = realm; } } MCRRealmFactory.realmsDocument = root.getDocument(); MCRRealmFactory.realmsMap = realmsMap; MCRRealmFactory.realmsList = realmsList; MCRRealmFactory.attributeMapper = attributeMapper; } private static Document getRealms() throws JDOMException, TransformerException, IOException { if (realmsFile == null) { return MCRSourceContent.getInstance(realmsURI.toASCIIString()).asXML(); } if (!realmsFile.exists() || realmsFile.length() == 0) { LOGGER.info("Creating {}...", realmsFile.getAbsolutePath()); MCRSourceContent realmsContent = MCRSourceContent.getInstance(RESOURCE_REALMS_URI); realmsContent.sendTo(realmsFile); } updateLastModified(); return MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(realmsFile)); } /** * Returns the realm with the given ID. * * @param id the ID of the realm * @return the realm with that ID, or null */ public static MCRRealm getRealm(String id) { reInitIfNeeded(); return realmsMap.get(id); } public static MCRUserAttributeMapper getAttributeMapper(String id) { reInitIfNeeded(); return attributeMapper.get(id); } /** * Returns a list of all defined realms. * * @return a list of all realms. */ public static List<MCRRealm> listRealms() { reInitIfNeeded(); return realmsList; } /** * Returns the Realms JDOM document clone. */ public static Document getRealmsDocument() { reInitIfNeeded(); return realmsDocument.clone(); } /** * Returns the Realms JDOM document as a {@link Source} useful for transformation processes. */ static Source getRealmsSource() { reInitIfNeeded(); return new JDOMSource(realmsDocument); } /** * Returns the local default realm, as specified by the attribute 'local' in realms.xml * * @return the local default realm. */ public static MCRRealm getLocalRealm() { reInitIfNeeded(); return localRealm; } private static boolean reloadingRequired() { boolean reloading = false; long now = System.currentTimeMillis(); if (now > lastChecked + REFRESH_DELAY) { lastChecked = now; if (hasChanged()) { reloading = true; } } return reloading; } private static boolean hasChanged() { if (realmsFile == null || !realmsFile.exists()) { return false; } return realmsFile.lastModified() > lastModified; } private static void updateLastModified() { if (realmsFile == null || !realmsFile.exists()) { return; } lastModified = realmsFile.lastModified(); } private static void reInitIfNeeded() { if (reloadingRequired()) { loadRealms(); } } }
9,058
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUser.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUser.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.hibernate.annotations.SortNatural; import org.mycore.common.MCRException; import org.mycore.common.MCRUserInformation; import org.mycore.user2.annotation.MCRUserAttributeJavaConverter; import org.mycore.user2.utils.MCRRolesConverter; import org.mycore.user2.utils.MCRUserNameConverter; import jakarta.persistence.Access; import jakarta.persistence.AccessType; import jakarta.persistence.CollectionTable; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Index; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.NamedQueries; import jakarta.persistence.NamedQuery; import jakarta.persistence.Table; import jakarta.persistence.Transient; import jakarta.persistence.UniqueConstraint; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; /** * Represents a login user. Each user has a unique numerical ID. * Each user belongs to a realm. The user name must be unique within a realm. * Any changes made to an instance of this class does not persist automatically. * Use {@link MCRUserManager#updateUser(MCRUser)} to achieve this. * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) * @author René Adler (eagle) */ @Entity @Access(AccessType.PROPERTY) @Table(name = "MCRUser", uniqueConstraints = @UniqueConstraint(columnNames = { "userName", "realmID" })) @NamedQueries(@NamedQuery(name = "MCRUser.byPropertyValue", query = "SELECT u FROM MCRUser u JOIN FETCH u.attributes ua WHERE ua.name = :name AND ua.value = :value")) @XmlRootElement(name = "user") @XmlAccessorType(XmlAccessType.NONE) @XmlType(propOrder = { "ownerId", "realName", "eMail", "lastLogin", "validUntil", "roles", "attributes", "password" }) public class MCRUser implements MCRUserInformation, Cloneable, Serializable { private static final long serialVersionUID = 3378645055646901800L; /** The unique user ID */ int internalID; /** if locked, user may not change this instance */ @XmlAttribute(name = "locked") private boolean locked; @XmlAttribute(name = "disabled") private boolean disabled; /** The login user name */ @org.mycore.user2.annotation.MCRUserAttribute @MCRUserAttributeJavaConverter(MCRUserNameConverter.class) @XmlAttribute(name = "name") private String userName; @XmlElement private Password password; /** The realm the user comes from */ @XmlAttribute(name = "realm") private String realmID; /** The ID of the user that owns this user, or 0 */ private MCRUser owner; /** The name of the person that this login user represents */ @org.mycore.user2.annotation.MCRUserAttribute @XmlElement private String realName; /** The E-Mail address of the person that this login user represents */ @org.mycore.user2.annotation.MCRUserAttribute @XmlElement private String eMail; /** The last time the user logged in */ @XmlElement private Date lastLogin; @XmlElement private Date validUntil; private SortedSet<MCRUserAttribute> attributes; @Transient private Collection<String> systemRoles; @Transient private Collection<String> externalRoles; protected MCRUser() { this(null); } /** * Creates a new user. * * @param userName the login user name * @param mcrRealm the realm this user belongs to */ public MCRUser(String userName, MCRRealm mcrRealm) { this(userName, mcrRealm.getID()); } /** * Creates a new user. * * @param userName the login user name * @param realmID the ID of the realm this user belongs to */ public MCRUser(String userName, String realmID) { this.userName = userName; this.realmID = realmID; this.systemRoles = new HashSet<>(); this.externalRoles = new HashSet<>(); this.attributes = new TreeSet<>(); this.password = new Password(); } /** * Creates a new user in the default realm. * * @param userName the login user name */ public MCRUser(String userName) { this(userName, MCRRealmFactory.getLocalRealm().getID()); } /** * @return the internalID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column int getInternalID() { return internalID; } /** * @param internalID the internalID to set */ void setInternalID(int internalID) { this.internalID = internalID; } @Column(name = "locked") public boolean isLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked != null && locked; } /** * @return the disabled */ @Column(name = "disabled") public boolean isDisabled() { return disabled; } /** * @param disabled the disabled to set */ public void setDisabled(Boolean disabled) { this.disabled = disabled != null && disabled; } /** * Returns the login user name. The user name is * unique within its realm. * * @return the login user name. */ @Column(name = "userName", nullable = false) public String getUserName() { return userName; } /** * Sets the login user name. The login user name * can be changed as long as it is unique within * its realm and the user ID is not changed. * * @param userName the new login user name */ void setUserName(String userName) { this.userName = userName; } /** * Returns the realm the user belongs to. * * @return the realm the user belongs to. */ @Transient public MCRRealm getRealm() { return MCRRealmFactory.getRealm(realmID); } /** * Sets the realm this user belongs to. * The realm can be changed as long as the login user name * is unique within the new realm. * * @param realm the realm the user belongs to. */ void setRealm(MCRRealm realm) { this.realmID = realm.getID(); } /** * Returns the ID of the realm the user belongs to. * * @return the ID of the realm the user belongs to. */ @Column(name = "realmID", length = 128, nullable = false) public String getRealmID() { return realmID; } /** * Sets the realm this user belongs to. * The realm can be changed as long as the login user name * is unique within the new realm. * * @param realmID the ID of the realm the user belongs to. */ void setRealmID(String realmID) { if (realmID == null) { setRealm(MCRRealmFactory.getLocalRealm()); } else { setRealm(MCRRealmFactory.getRealm(realmID)); } } /** * @return the hash */ @Column(name = "password") public String getPassword() { return password == null ? null : password.hash; } /** * @param password the hash value to set */ public void setPassword(String password) { this.password.hash = password; } /** * @return the salt */ @Column(name = "salt") public String getSalt() { return password == null ? null : password.salt; } /** * @param salt the salt to set */ public void setSalt(String salt) { this.password.salt = salt; } /** * @return the hashType */ @Column(name = "hashType") @Enumerated(EnumType.STRING) public MCRPasswordHashType getHashType() { return password == null ? null : password.hashType; } /** * @param hashType the hashType to set */ public void setHashType(MCRPasswordHashType hashType) { this.password.hashType = hashType; } /** * Returns the user that owns this user, or null * if the user is independent and has no owner. * * @return the user that owns this user. */ @ManyToOne @JoinColumn(name = "owner") public MCRUser getOwner() { return owner; } /** * Sets the user that owns this user. * Setting this to null makes the user independent. * * @param owner the owner of the user. */ public void setOwner(MCRUser owner) { this.owner = owner; } /** * Returns true if this user has no owner and therefore * is independent. Independent users may change their passwords * etc., owned users may not, they are created to limit read access * in general. * * @return true if this user has no owner */ public boolean hasNoOwner() { return owner == null; } /** * Returns the name of the person this login user represents. * * @return the name of the person this login user represents. */ @Column(name = "realName") public String getRealName() { return realName; } /** * Sets the name of the person this login user represents. * * @param realName the name of the person this login user represents. */ public void setRealName(String realName) { this.realName = realName; } /** * Returns the E-Mail address of the person this login user represents. * * @return the E-Mail address of the person this login user represents. */ @Transient public String getEMailAddress() { return eMail; } @Column(name = "eMail") @SuppressWarnings("unused") private String getEMail() { return eMail; } /** * Sets the E-Mail address of the person this user represents. * * @param eMail the E-Mail address */ public void setEMail(String eMail) { this.eMail = eMail; } /** * Returns a hint the user has stored in case of forgotten hash. * * @return a hint the user has stored in case of forgotten hash. */ @Column(name = "hint") public String getHint() { return password == null ? null : password.hint; } /** * Sets a hint to store in case of hash loss. * * @param hint a hint for the user in case hash is forgotten. */ public void setHint(String hint) { this.password.hint = hint; } /** * Returns the last time the user has logged in. * * @return the last time the user has logged in. */ @Column(name = "lastLogin") public Date getLastLogin() { if (lastLogin == null) { return null; } return new Date(lastLogin.getTime()); } /** * Sets the time of last login. * * @param lastLogin the last time the user logged in. */ public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin == null ? null : new Date(lastLogin.getTime()); } /** * Sets the time of last login to now. */ public void setLastLogin() { this.lastLogin = new Date(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MCRUser other)) { return false; } if (realmID == null) { if (other.realmID != null) { return false; } } else if (!realmID.equals(other.realmID)) { return false; } if (userName == null) { return other.userName == null; } else { return userName.equals(other.userName); } } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((realmID == null) ? 0 : realmID.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); return result; } @Transient @Override public String getUserID() { String cuid = this.getUserName(); if (!getRealm().equals(MCRRealmFactory.getLocalRealm())) { cuid += "@" + getRealmID(); } return cuid; } /** * Returns additional user attributes. * This methods handles {@link MCRUserInformation#ATT_REAL_NAME} and * all attributes defined in {@link #getAttributes()}. */ @Override public String getUserAttribute(String attribute) { switch (attribute) { case MCRUserInformation.ATT_REAL_NAME -> { return getRealName(); } case MCRUserInformation.ATT_EMAIL -> { return getEMailAddress(); } default -> { Set<MCRUserAttribute> attrs = attributes.stream() .filter(a -> a.getName().equals(attribute)) .collect(Collectors.toSet()); if (attrs.size() > 1) { throw new MCRException(getUserID() + ": user attribute " + attribute + " is not unique"); } return attrs.stream() .map(MCRUserAttribute::getValue) .findAny().orElse(null); } } } @Override public boolean isUserInRole(final String role) { boolean directMember = getSystemRoleIDs().contains(role) || getExternalRoleIDs().contains(role); if (directMember) { return true; } return MCRRoleManager.isAssignedToRole(this, role); } /** * @param attributes the attributes to set */ public void setAttributes(SortedSet<MCRUserAttribute> attributes) { this.attributes = attributes; } @ElementCollection(fetch = FetchType.EAGER) @CollectionTable(name = "MCRUserAttr", joinColumns = @JoinColumn(name = "id"), indexes = { @Index(name = "MCRUserAttributes", columnList = "name, value"), @Index(name = "MCRUserValues", columnList = "value") }) @SortNatural @XmlElementWrapper(name = "attributes") @XmlElement(name = "attribute") public SortedSet<MCRUserAttribute> getAttributes() { return this.attributes; } /** * Returns a collection any system role ID this user is member of. * @see MCRRole#isSystemRole() */ @Transient public Collection<String> getSystemRoleIDs() { return systemRoles; } /** * Returns a collection any external role ID this user is member of. * @see MCRRole#isSystemRole() */ @Transient public Collection<String> getExternalRoleIDs() { return externalRoles; } /** * Adds this user to the given role. * @param roleName the role the user should be added to (must already exist) */ public void assignRole(String roleName) { MCRRole mcrRole = MCRRoleManager.getRole(roleName); if (mcrRole == null) { throw new MCRException("Could not find role " + roleName); } assignRole(mcrRole); } private void assignRole(MCRRole mcrRole) { if (mcrRole.isSystemRole()) { getSystemRoleIDs().add(mcrRole.getName()); } else { getExternalRoleIDs().add(mcrRole.getName()); } } /** * Removes this user from the given role. * @param roleName the role the user should be removed from (must already exist) */ public void unassignRole(String roleName) { MCRRole mcrRole = MCRRoleManager.getRole(roleName); if (mcrRole == null) { throw new MCRException("Could not find role " + roleName); } if (mcrRole.isSystemRole()) { getSystemRoleIDs().remove(mcrRole.getName()); } else { getExternalRoleIDs().remove(mcrRole.getName()); } } /** * Enable login for this user. */ public void enableLogin() { setDisabled(false); } /** * Disable login for this user. */ public void disableLogin() { setDisabled(true); } /** * Returns true if logins are allowed for this user. */ public boolean loginAllowed() { return !disabled && (validUntil == null || validUntil.after(new Date())); } /** * Returns a {@link Date} when this user can not login anymore. */ @Column(name = "validUntil") public Date getValidUntil() { if (validUntil == null) { return null; } return new Date(validUntil.getTime()); } /** * Sets a {@link Date} when this user can not login anymore. * @param validUntil the validUntil to set */ public void setValidUntil(Date validUntil) { this.validUntil = validUntil == null ? null : new Date(validUntil.getTime()); } //This is used for MCRUserAttributeMapper @Transient Collection<String> getRolesCollection() { return Arrays.stream(getRoles()).map(MCRRole::getName).collect(Collectors.toSet()); } @org.mycore.user2.annotation.MCRUserAttribute(name = "roles", separator = ";") @MCRUserAttributeJavaConverter(MCRRolesConverter.class) void setRolesCollection(Collection<String> roles) { for (String role : roles) { assignRole(role); } } //This is code to get JAXB work @Transient @XmlElementWrapper(name = "roles") @XmlElement(name = "role") private MCRRole[] getRoles() { if (getSystemRoleIDs().isEmpty() && getExternalRoleIDs().isEmpty()) { return null; } ArrayList<String> roleIds = new ArrayList<>(getSystemRoleIDs().size() + getExternalRoleIDs().size()); Collection<MCRRole> roles = new ArrayList<>(roleIds.size()); roleIds.addAll(getSystemRoleIDs()); roleIds.addAll(getExternalRoleIDs()); for (String roleName : roleIds) { MCRRole role = MCRRoleManager.getRole(roleName); if (role == null) { throw new MCRException("Could not load role: " + roleName); } roles.add(role); } return roles.toArray(MCRRole[]::new); } @SuppressWarnings("unused") private void setRoles(MCRRole[] roles) { Stream.of(roles) .map(MCRRole::getName) .map(roleName -> { //check if role does exist, so we wont lose it on export MCRRole role = MCRRoleManager.getRole(roleName); if (role == null) { throw new MCRException("Could not load role: " + roleName); } return role; }) .forEach(this::assignRole); } public void setUserAttribute(String name, String value) { Optional<MCRUserAttribute> anyMatch = getAttributes().stream() .filter(a -> a.getName().equals(Objects.requireNonNull(name))) .findAny(); if (anyMatch.isPresent()) { MCRUserAttribute attr = anyMatch.get(); attr.setValue(value); getAttributes().removeIf(a -> a.getName().equals(name) && a != attr); } else { getAttributes().add(new MCRUserAttribute(name, value)); } } @Transient @XmlElement(name = "owner") private UserIdentifier getOwnerId() { if (owner == null) { return null; } UserIdentifier userIdentifier = new UserIdentifier(); userIdentifier.name = owner.getUserName(); userIdentifier.realm = owner.getRealmID(); return userIdentifier; } @SuppressWarnings("unused") private void setOwnerId(UserIdentifier userIdentifier) { if (userIdentifier.name.equals(this.userName) && userIdentifier.realm.equals(this.realmID)) { setOwner(this); return; } MCRUser owner = MCRUserManager.getUser(userIdentifier.name, userIdentifier.realm); setOwner(owner); } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override public MCRUser clone() { MCRUser copy = getSafeCopy(); if (copy.password == null) { copy.password = new Password(); } copy.password.hashType = this.password.hashType; copy.password.hash = this.password.hash; copy.password.salt = this.password.salt; return copy; } /** * Returns this MCRUser with basic information. * Same as {@link #getSafeCopy()} but without these informations: * <ul> * <li>real name * <li>eMail * <li>attributes * <li>role information * <li>last login * <li>valid until * <li>password hint * </ul> * @return a clone copy of this instance */ @Transient public MCRUser getBasicCopy() { MCRUser copy = new MCRUser(userName, realmID); copy.locked = locked; copy.disabled = disabled; copy.owner = this.equals(this.owner) ? copy : this.owner; copy.setAttributes(null); copy.password = null; return copy; } /** * Returns this MCRUser with safe information. * Same as {@link #clone()} but without these informations: * <ul> * <li>password hash type * <li>password hash value * <li>password salt * </ul> * @return a clone copy of this instance */ @Transient public MCRUser getSafeCopy() { MCRUser copy = getBasicCopy(); if (getHint() != null) { copy.password = new Password(); copy.password.hint = getHint(); } copy.setAttributes(new TreeSet<>()); copy.eMail = this.eMail; copy.lastLogin = this.lastLogin; copy.validUntil = this.validUntil; copy.realName = this.realName; copy.systemRoles.addAll(this.systemRoles); copy.externalRoles.addAll(this.externalRoles); copy.attributes.addAll(this.attributes); return copy; } private static class Password implements Serializable { private static final long serialVersionUID = 8068063832119405080L; @XmlAttribute private String hash; //base64 encoded @XmlAttribute private String salt; @XmlAttribute private MCRPasswordHashType hashType; /** A hint stored by the user in case hash is forgotten */ @XmlAttribute private String hint; } private static class UserIdentifier implements Serializable { private static final long serialVersionUID = 4654103884660408929L; @XmlAttribute public String name; @XmlAttribute public String realm; } }
24,501
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserCommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRFileContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.cli.MCRAbstractCommands; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.user2.utils.MCRRoleTransformer; import org.mycore.user2.utils.MCRUserTransformer; /** * This class provides a set of commands for the org.mycore.user2 management which can be used by the command line * interface. * * @author Thomas Scheffler (yagee) */ @MCRCommandGroup( name = "User Commands") public class MCRUserCommands extends MCRAbstractCommands { /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRUserCommands.class.getName()); private static final String SYSTEM = MCRConfiguration2.getStringOrThrow("MCR.CommandLineInterface.SystemName") + ":"; /** * This command changes the user of the session context to a new user. * * @param user * the new user ID * @param password * the password of the new user */ @MCRCommand( syntax = "change to user {0} with {1}", help = "Changes to the user {0} with the given password {1}.", order = 10) public static void changeToUser(String user, String password) { MCRSession session = MCRSessionMgr.getCurrentSession(); System.out.println(SYSTEM + " The old user ID is " + session.getUserInformation().getUserID()); if (MCRUserManager.login(user, password) != null) { System.out.println(SYSTEM + " The new user ID is " + session.getUserInformation().getUserID()); } else { LOGGER.warn("Wrong password, no changes of user ID in session context!"); } } /** * This command changes the user of the session context to a new user. * * @param user * the new user ID */ @MCRCommand( syntax = "login {0}", help = "Starts the login dialog for the user {0}.", order = 20) public static void login(String user) { char[] password = {}; do { password = System.console().readPassword("{0} Enter password for user {1} :> ", SYSTEM, user); } while (password.length == 0); changeToUser(user, String.valueOf(password)); } /** * This method initializes the user and role system an creates a superuser with values set in * mycore.properties.private As 'super' default, if no properties were set, mcradmin with password mycore will be * used. */ @MCRCommand( syntax = "init superuser", help = "Initializes the user system. This command runs only if the user database does not exist.", order = 30) public static List<String> initSuperuser() { final String suser = MCRConfiguration2.getStringOrThrow("MCR.Users.Superuser.UserName"); final String spasswd = MCRConfiguration2.getStringOrThrow("MCR.Users.Superuser.UserPasswd"); final Optional<String> semail = MCRConfiguration2.getString("MCR.Users.Superuser.UserEmail"); final String srole = MCRConfiguration2.getStringOrThrow("MCR.Users.Superuser.GroupName"); if (MCRUserManager.exists(suser)) { LOGGER.error("The superuser already exists!"); return null; } // the superuser role try { Set<MCRLabel> labels = new HashSet<>(); labels.add(new MCRLabel("en", "The superuser role", null)); MCRRole mcrRole = new MCRRole(srole, labels); MCRRoleManager.addRole(mcrRole); } catch (Exception e) { throw new MCRException("Can't create the superuser role.", e); } LOGGER.info("The role {} is installed.", srole); // the superuser try { MCRUser mcrUser = new MCRUser(suser); mcrUser.setRealName("Superuser"); semail.ifPresent(mcrUser::setEMail); mcrUser.assignRole(srole); MCRUserManager.updatePasswordHashToSHA256(mcrUser, spasswd); MCRUserManager.createUser(mcrUser); } catch (Exception e) { throw new MCRException("Can't create the superuser.", e); } LOGGER.info("The user {} with password {} is installed.", suser, spasswd); return Collections.singletonList("change to user " + suser + " with " + spasswd); } /** * This method invokes {@link MCRRoleManager#deleteRole(String)} and permanently removes a role from the system. * * @param roleID * the ID of the role which will be deleted */ @MCRCommand( syntax = "delete role {0}", help = "Deletes the role {0} from the user system, but only if it has no user assigned.", order = 80) public static void deleteRole(String roleID) { MCRRoleManager.deleteRole(roleID); } /** * Exports a single role to the specified directory. * @throws FileNotFoundException if target directory does not exist */ @MCRCommand( syntax = "export role {0} to directory {1}", help = "Export the role {0} to the directory {1}. The filename will be {0}.xml") public static void exportRole(String roleID, String directory) throws IOException { MCRRole mcrRole = MCRRoleManager.getRole(roleID); File targetFile = new File(directory, roleID + ".xml"); try (FileOutputStream fout = new FileOutputStream(targetFile)) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat().setEncoding(MCRConstants.DEFAULT_ENCODING)); xout.output(MCRRoleTransformer.buildExportableXML(mcrRole), fout); } } /** * Loads XML from a user and looks for roles currently not present in the system and creates them. * * @param fileName * a valid user XML file */ @MCRCommand( syntax = "import role from file {0}", help = "Imports a role from file, if that role does not exist", order = 90) public static void addRole(String fileName) throws IOException, JDOMException { LOGGER.info("Reading file {} ...", fileName); Document doc = MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(fileName)); MCRRole role = MCRRoleTransformer.buildMCRRole(doc.getRootElement()); if (MCRRoleManager.getRole(role.getName()) == null) { MCRRoleManager.addRole(role); } else { LOGGER.info("Role {} does already exist.", role.getName()); } } /** * This method invokes MCRUserMgr.deleteUser() and permanently removes a user from the system. * * @param userID * the ID of the user which will be deleted */ @MCRCommand( syntax = "delete user {0}", help = "Delete the user {0}.", order = 110) public static void deleteUser(String userID) { MCRUserManager.deleteUser(userID); } /** * This method invokes MCRUserMgr.enableUser() that enables a user * * @param userID * the ID of the user which will be enabled */ @MCRCommand( syntax = "enable user {0}", help = "Enables the user for the access.", order = 60) public static void enableUser(String userID) { MCRUser mcrUser = MCRUserManager.getUser(userID); mcrUser.enableLogin(); MCRUserManager.updateUser(mcrUser); } /** * A given XML file containing user data with cleartext passwords must be converted prior to loading the user data * into the system. This method reads all user objects in the given XML file, encrypts the passwords and writes them * back to a file with name original-file-name_encrypted.xml. * * @param oldFile * the filename of the user data input * @param newFile * the filename of the user data output (encrypted passwords) */ @MCRCommand( syntax = "encrypt passwords in user xml file {0} to file {1}", help = "A migration tool to change old plain text password entries to encrpted entries.", order = 40) public static void encryptPasswordsInXMLFile(String oldFile, String newFile) throws IOException, JDOMException { File inputFile = getCheckedFile(oldFile); if (inputFile == null) { return; } LOGGER.info("Reading file {} ...", inputFile.getAbsolutePath()); Document doc = MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(inputFile)); Element rootelm = doc.getRootElement(); MCRUser mcrUser = MCRUserTransformer.buildMCRUser(rootelm); if (mcrUser == null) { throw new MCRException("These data do not correspond to a user."); } MCRUserManager.updatePasswordHashToSHA256(mcrUser, mcrUser.getPassword()); try (FileOutputStream outFile = new FileOutputStream(newFile)) { saveToXMLFile(mcrUser, outFile); } } /** * This method invokes MCRUserMgr.disableUser() that disables a user * * @param userID * the ID of the user which will be enabled */ @MCRCommand( syntax = "disable user {0}", help = "Disables access of the user {0}", order = 70) public static void disableUser(String userID) { MCRUser mcrUser = MCRUserManager.getUser(userID); mcrUser.disableLogin(); MCRUserManager.updateUser(mcrUser); } /** * This method invokes MCRUserMgr.getAllUserIDs() and retrieves a ArrayList of all users stored in the persistent * datastore. */ @MCRCommand( syntax = "list all users", help = "Lists all users.", order = 160) public static void listAllUsers() { List<MCRUser> users = MCRUserManager.listUsers(null, null, null, null); for (MCRUser uid : users) { listUser(uid); } } /** * This method invokes MCRUserMgr.getAllUserIDs() and retrieves a ArrayList of all users stored in the persistent * datastore. */ @MCRCommand( syntax = "list users like {0}", help = "Lists users like {0} (in the same way as the user servlet, except w/o limit).", order = 160) public static void listAllUsers(String search) throws Exception { String pattern = "*" + search + "*"; List<MCRUser> users = MCRUserManager.listUsers(pattern, null, pattern, pattern, null, pattern, 0, Integer.MAX_VALUE); for (MCRUser uid : users) { listUser(uid); } } /** * This method invokes {@link MCRRoleManager#listSystemRoles()} and retrieves a list of all roles stored in the * persistent datastore. */ @MCRCommand( syntax = "list all roles", help = "List all roles.", order = 140) public static void listAllRoles() { List<MCRRole> roles = MCRRoleManager.listSystemRoles(); for (MCRRole role : roles) { listRole(role); } } /** * This command takes a userID and file name as a parameter, retrieves the user from MCRUserMgr as JDOM document and * export this to the given file. * * @param userID * ID of the user to be saved * @param filename * Name of the file to store the exported user */ @MCRCommand( syntax = "export user {0} to file {1}", help = "Exports the data of user {0} to the file {1}.", order = 180) public static void exportUserToFile(String userID, String filename) throws IOException { MCRUser user = MCRUserManager.getUser(userID); if (user.getSystemRoleIDs().isEmpty()) { LOGGER.warn("User {} has not any system roles.", user.getUserID()); } try (FileOutputStream outFile = new FileOutputStream(filename)) { LOGGER.info("Writing to file {} ...", filename); saveToXMLFile(user, outFile); } } @MCRCommand( syntax = "export all users to directory {0}", help = "Exports the data of all users to the directory {0}.") public static List<String> exportAllUserToDirectory(String directory) { File dir = new File(directory); if (!dir.exists() || !dir.isDirectory()) { throw new MCRException("Directory does not exist: " + dir.getAbsolutePath()); } List<MCRUser> users = MCRUserManager.listUsers(null, null, null, null); ArrayList<String> commands = new ArrayList<>(users.size()); for (MCRUser user : users) { File userFile = new File(dir, user.getUserID() + ".xml"); commands.add("export user " + user.getUserID() + " to file " + userFile.getAbsolutePath()); } return commands; } @MCRCommand( syntax = "import all users from directory {0}", help = "Imports all users from directory {0}.") public static List<String> importAllUsersFromDirectory(String directory) throws FileNotFoundException { return batchLoadFromDirectory("import user from file", directory); } @MCRCommand( syntax = "update all users from directory {0}", help = "Updates all users from directory {0}.") public static List<String> updateAllUsersFromDirectory(String directory) throws FileNotFoundException { return batchLoadFromDirectory("update user from file", directory); } public static List<String> batchLoadFromDirectory(String cmd, String directory) throws FileNotFoundException { File dir = new File(directory); if (!dir.isDirectory()) { throw new FileNotFoundException(dir.getAbsolutePath() + " is not a directory."); } File[] listFiles = dir .listFiles(pathname -> pathname.isFile() && pathname.getName().endsWith(".xml")); if (listFiles.length == 0) { LOGGER.warn("Did not find any user files in {}", dir.getAbsolutePath()); return null; } Arrays.sort(listFiles); ArrayList<String> cmds = new ArrayList<>(listFiles.length); for (File file : listFiles) { cmds.add(new MessageFormat("{0} {1}", Locale.ROOT).format(new Object[] { cmd, file.getAbsolutePath() })); } return cmds; } /** * This command takes a file name as a parameter, creates the MCRUser instances stores it in the database if it does * not exists. * * @param filename * Name of the file to import user from */ @MCRCommand( syntax = "import user from file {0}", help = "Imports a user from file {0}.") public static void importUserFromFile(String filename) throws IOException, JDOMException { MCRUser user = getMCRUserFromFile(filename); if (MCRUserManager.exists(user.getUserName(), user.getRealmID())) { throw new MCRException("User already exists: " + user.getUserID()); } MCRUserManager.createUser(user); } /** * This method invokes MCRUserMgr.retrieveUser() and then works with the retrieved user object to change the * password. * * @param userID * the ID of the user for which the password will be set */ @MCRCommand( syntax = "set password for user {0} to {1}", help = "Sets a new password for the user. You must be this user or you must have administrator access.", order = 50) public static void setPassword(String userID, String password) throws MCRException { MCRUser user = MCRUserManager.getUser(userID); MCRUserManager.updatePasswordHashToSHA256(user, password); MCRUserManager.updateUser(user); } /** * This method invokes {@link MCRRoleManager#getRole(String)} and then works with the retrieved role object to get * an XML-Representation. * * @param roleID * the ID of the role for which the XML-representation is needed */ @MCRCommand( syntax = "list role {0}", help = "Lists the role {0}.", order = 150) public static void listRole(String roleID) throws MCRException { MCRRole role = MCRRoleManager.getRole(roleID); listRole(role); } public static void listRole(MCRRole role) { StringBuilder sb = new StringBuilder(); sb.append(" role=").append(role.getName()); for (MCRLabel label : role.getLabels()) { sb.append("\n ").append(label); } Collection<String> userIds = MCRRoleManager.listUserIDs(role); for (String userId : userIds) { sb.append("\n user assigned to role=").append(userId); } LOGGER.info(sb.toString()); } /** * This method invokes MCRUserMgr.retrieveUser() and then works with the retrieved user object to get an * XML-Representation. * * @param userID * the ID of the user for which the XML-representation is needed */ @MCRCommand( syntax = "list user {0}", help = "Lists the user {0}.", order = 170) public static void listUser(String userID) throws MCRException { MCRUser user = MCRUserManager.getUser(userID); listUser(user); } public static void listUser(MCRUser user) { StringBuilder sb = new StringBuilder("\n"); sb.append(" user=").append(user.getUserName()).append(" real name=").append(user.getRealName()) .append('\n').append(" loginAllowed=").append(user.loginAllowed()).append('\n'); List<String> roles = new ArrayList<>(user.getSystemRoleIDs()); roles.addAll(user.getExternalRoleIDs()); for (String rid : roles) { sb.append(" assigned to role=").append(rid).append('\n'); } LOGGER.info(sb.toString()); } /** * Check the file name * * @param filename * the filename of the user data input * @return true if the file name is okay */ private static File getCheckedFile(String filename) { if (!filename.endsWith(".xml")) { LOGGER.warn("{} ignored, does not end with *.xml", filename); return null; } File file = new File(filename); if (!file.isFile()) { LOGGER.warn("{} ignored, is not a file.", filename); return null; } return file; } /** * This method invokes MCRUserMgr.createUser() with data from a file. * * @param filename * the filename of the user data input */ public static void createUserFromFile(String filename) throws IOException, JDOMException { MCRUser user = getMCRUserFromFile(filename); MCRUserManager.createUser(user); } /** * This method invokes MCRUserMgr.updateUser() with data from a file. * * @param filename * the filename of the user data input * @throws JDOMException * if file could not be parsed */ @MCRCommand( syntax = "update user from file {0}", help = "Updates a user from file {0}.", order = 200) public static void updateUserFromFile(String filename) throws IOException, JDOMException { MCRUser user = getMCRUserFromFile(filename); MCRUserManager.updateUser(user); } private static MCRUser getMCRUserFromFile(String filename) throws IOException, JDOMException { File inputFile = getCheckedFile(filename); if (inputFile == null) { return null; } LOGGER.info("Reading file {} ...", inputFile.getAbsolutePath()); Document doc = MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(inputFile)); return MCRUserTransformer.buildMCRUser(doc.getRootElement()); } /** * This method adds a user as a member to a role * * @param userID * the ID of the user which will be a member of the role represented by roleID * @param roleID * the ID of the role to which the user with ID mbrUserID will be added */ @MCRCommand( syntax = "assign user {0} to role {1}", help = "Adds a user {0} as secondary member in the role {1}.", order = 120) public static void assignUserToRole(String userID, String roleID) throws MCRException { try { MCRUser user = MCRUserManager.getUser(userID); user.assignRole(roleID); MCRUserManager.updateUser(user); } catch (Exception e) { throw new MCRException("Error while assigning " + userID + " to role " + roleID + ".", e); } } /** * This method removes a member user from a role * * @param userID * the ID of the user which will be removed from the role represented by roleID * @param roleID * the ID of the role from which the user with ID mbrUserID will be removed */ @MCRCommand( syntax = "unassign user {0} from role {1}", help = "Removes the user {0} as secondary member from the role {1}.", order = 130) public static void unassignUserFromRole(String userID, String roleID) throws MCRException { try { MCRUser user = MCRUserManager.getUser(userID); user.unassignRole(roleID); MCRUserManager.updateUser(user); } catch (Exception e) { throw new MCRException("Error while unassigning " + userID + " from role " + roleID + ".", e); } } /** * This method just saves a JDOM document to a file automatically closes {@link OutputStream}. * * @param mcrUser * the JDOM XML document to be printed * @param outFile * a FileOutputStream object for the output * @throws IOException * if output file can not be closed */ private static void saveToXMLFile(MCRUser mcrUser, FileOutputStream outFile) throws IOException { // Create the output XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat().setEncoding(MCRConstants.DEFAULT_ENCODING)); outputter.output(MCRUserTransformer.buildExportableXML(mcrUser), outFile); } }
24,165
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.List; import java.util.Objects; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.mycore.user2.utils.MCRUserTransformer; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.util.JAXBSource; /** * Implements URIResolver for use in editor form user-editor.xml * * user:{userID} * returns detailed user data including owned users and groups * user:current * returns detailed user data of the user currently logged in * * @author Thomas Scheffler (yagee) */ public class MCRUserResolver implements URIResolver { @Override public Source resolve(String href, String base) throws TransformerException { String[] hrefParts = href.split(":"); String userID = hrefParts[1]; MCRUser user = null; try { if (Objects.equals(userID, "current")) { user = MCRUserManager.getCurrentUser(); } else if (Objects.equals(userID, "getOwnedUsers")) { return getOwnedUsers(hrefParts[2]); } else { user = MCRUserManager.getUser(userID); } if (user == null) { return null; } return new JAXBSource(MCRUserTransformer.JAXB_CONTEXT, user.getSafeCopy()); } catch (JAXBException e) { throw new TransformerException(e); } } private Source getOwnedUsers(String userName) throws JAXBException { MCRUser owner = MCRUserManager.getUser(userName); List<MCRUser> listUsers = MCRUserManager.listUsers(owner); MCROwns mcrOwns = new MCROwns(); int userCount = listUsers.size(); mcrOwns.users = new MCRUser[userCount]; for (int i = 0; i < userCount; i++) { mcrOwns.users[i] = listUsers.get(i).getBasicCopy(); } return new JAXBSource(MCRUserTransformer.JAXB_CONTEXT, mcrOwns); } @XmlRootElement(name = "owns") @XmlAccessorType(XmlAccessType.FIELD) private static class MCROwns { @XmlElement(name = "user") MCRUser[] users; } }
3,109
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRoleServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRoleServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import org.jdom2.Document; import org.jdom2.Element; import org.mycore.access.MCRAccessManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJDOMContent; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.services.i18n.MCRTranslation; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This servlet is used in the role sub select for when administrate a user. * The property <code>MCR.user2.RoleCategories</code> can hold any category IDs * that could be possible roots for roles. * @author Thomas Scheffler (yagee) * */ public class MCRRoleServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final String LAYOUT_ELEMENT_KEY = MCRRoleServlet.class.getName() + ".layoutElement"; private boolean roleClassificationsDefined; private List<MCRCategoryID> roleCategories; private MCRCategoryDAO categoryDao; /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#init() */ @Override public void init() throws ServletException { super.init(); roleClassificationsDefined = false; roleCategories = new ArrayList<>(); roleCategories.add(MCRUser2Constants.ROLE_CLASSID); String roleCategoriesValue = MCRConfiguration2.getString(MCRUser2Constants.CONFIG_PREFIX + "RoleCategories") .orElse(null); if (roleCategoriesValue == null) { return; } String[] roleCategoriesSplitted = roleCategoriesValue.split(","); for (String roleID : roleCategoriesSplitted) { String categoryId = roleID.trim(); if (categoryId.length() > 0) { roleCategories.add(MCRCategoryID.fromString(categoryId)); } } roleClassificationsDefined = roleCategories.size() > 1; categoryDao = MCRCategoryDAOFactory.getInstance(); } /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#think(org.mycore.frontend.servlets.MCRServletJob) */ @Override protected void think(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); if (!MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION)) { final String errorMessage = MCRTranslation.translate("component.user2.message.notAllowedChangeRole"); job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage); } String action = getProperty(request, "action"); if (Objects.equals(action, "chooseCategory") || !roleClassificationsDefined) { chooseCategory(request); } else { chooseRoleRoot(request); } } private void chooseRoleRoot(HttpServletRequest request) { Element rootElement = getRootElement(request); rootElement.addContent(getRoleElements()); request.setAttribute(LAYOUT_ELEMENT_KEY, new Document(rootElement)); } private Collection<Element> getRoleElements() { ArrayList<Element> list = new ArrayList<>(roleCategories.size()); for (MCRCategoryID categID : roleCategories) { Element role = new Element("role"); role.setAttribute("categID", categID.toString()); MCRCategory category = categoryDao.getCategory(categID, 0); if (category == null) { continue; } role.setAttribute("label", category.getCurrentLabel().map(MCRLabel::getText).orElse(categID.getId())); list.add(role); } return list; } private static Element getRootElement(HttpServletRequest request) { Element rootElement = new Element("roles"); rootElement.setAttribute("queryParams", request.getQueryString()); return rootElement; } private static void chooseCategory(HttpServletRequest request) { MCRCategoryID categoryID; String categID = getProperty(request, "categID"); if (categID != null) { categoryID = MCRCategoryID.fromString(categID); } else { String rootID = getProperty(request, "classID"); categoryID = (rootID == null) ? MCRUser2Constants.ROLE_CLASSID : MCRCategoryID.rootID(rootID); } Element rootElement = getRootElement(request); rootElement.setAttribute("classID", categoryID.getRootID()); if (!categoryID.isRootID()) { rootElement.setAttribute("categID", categoryID.getId()); } request.setAttribute(LAYOUT_ELEMENT_KEY, new Document(rootElement)); } /* (non-Javadoc) * @see org.mycore.frontend.servlets.MCRServlet#render(org.mycore.frontend.servlets.MCRServletJob, java.lang.Exception) */ @Override protected void render(MCRServletJob job, Exception ex) throws Exception { if (ex != null) { //do not handle error here throw ex; } getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent((Document) job.getRequest().getAttribute(LAYOUT_ELEMENT_KEY))); } }
6,441
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRealm.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRealm.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import org.mycore.common.MCRConstants; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; /** * Represents a realm of users. Each user belongs to a realm. Realms are configured * in the file realms.xml. A realm determines the method that is used to login the user. * There is always a local default realm, which is defined by the attribute local in realms.xml. * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ public class MCRRealm { /** The unique ID of the realm, e.g. 'local' */ private String id; /** The labels of the realm */ private HashMap<String, String> labels = new HashMap<>(); /** The URL where users from this realm can change their password */ private String passwordChangeURL; /** The URL where users from this realm can login */ private String loginURL; /** The URL where new users may create an account for this realm */ private String createURL; private String redirectParameter; private String realmParameter; private static String DEFAULT_LANG = MCRConfiguration2.getString("MCR.Metadata.DefaultLang") .orElse(MCRConstants.DEFAULT_LANG); public static final String USER_INFORMATION_ATTR = "realmId"; /** * Creates a new realm. * * @param id the unique ID of the realm */ MCRRealm(String id) { this.id = id; } /** * Returns the unique ID of the realm. * * @return the unique ID of the realm. */ public String getID() { return id; } /** * Returns the label in the current language */ public String getLabel() { String lang = MCRSessionMgr.getCurrentSession().getCurrentLanguage(); String label = labels.get(lang); if (label != null) { return label; } label = labels.get(DEFAULT_LANG); if (label != null) { return label; } return id; } /** * Sets the label for the given language */ void setLabel(String lang, String label) { labels.put(lang, label); } /** * Returns the URL where users from this realm can change their password */ public String getPasswordChangeURL() { return passwordChangeURL; } /** * Sets the URL where users from this realm can change their password */ void setPasswordChangeURL(String url) { this.passwordChangeURL = url; } /** * Returns the URL where users from this realm can login */ public String getLoginURL() { return loginURL; } /** * Sets the URL where users from this realm can login */ void setLoginURL(String url) { this.loginURL = url; } /** * @return the createURL */ public String getCreateURL() { return createURL; } /** * @param createURL the createURL to set */ void setCreateURL(String createURL) { this.createURL = createURL; } @Override public boolean equals(Object obj) { if (obj instanceof MCRRealm realm) { return realm.id.equals(id); } else { return false; } } @Override public int hashCode() { return id.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "id=" + id + ", " + (loginURL != null ? "loginURL=" + loginURL : ""); } /** * Returns the URL where users from this realm can login with redirect URL attached. * If this realm has a attribut <code>redirectParameter</code> defined this method returns * a complete login URL with <code>redirectURL</code> properly configured. * @param redirectURL URL where to redirect to after login succeeds. * @return the same as {@link #getLoginURL()} if <code>redirectParameter</code> is undefined for this realm */ public String getLoginURL(String redirectURL) { LinkedHashMap<String, String> parameter = new LinkedHashMap<>(); String redirect = getRedirectParameter(); if (redirect != null && redirectURL != null) { parameter.put(redirect, redirectURL); } String realmParameter = getRealmParameter(); if (realmParameter != null) { parameter.put(realmParameter, getID()); } if (parameter.isEmpty()) { return getLoginURL(); } StringBuilder loginURL = new StringBuilder(getLoginURL()); boolean firstParameter = !getLoginURL().contains("?"); for (Entry<String, String> entry : parameter.entrySet()) { if (firstParameter) { loginURL.append('?'); firstParameter = false; } else { loginURL.append('&'); } loginURL.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); } return loginURL.toString(); } /** * @return the redirectParameter */ String getRedirectParameter() { return redirectParameter; } /** * @param redirectParameter the redirectParameter to set */ void setRedirectParameter(String redirectParameter) { this.redirectParameter = redirectParameter; } public String getRealmParameter() { return realmParameter; } public void setRealmParameter(String realmParameter) { this.realmParameter = realmParameter; } }
6,532
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserAttribute.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRUserAttribute.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.Comparator; import java.util.Objects; import jakarta.persistence.Column; import jakarta.persistence.Embeddable; import jakarta.persistence.Index; import jakarta.persistence.Table; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlRootElement; @Embeddable @Table(name = "MCRUserAttr", indexes = { @Index(name = "MCRUserAttributes", columnList = "name, value"), @Index(name = "MCRUserValues", columnList = "value") }) @XmlRootElement(name = "attribute") public class MCRUserAttribute implements Comparable<MCRUserAttribute> { private String name; private String value; public static final Comparator<MCRUserAttribute> NATURAL_ORDER_COMPARATOR = Comparator .comparing(MCRUserAttribute::getName) .thenComparing(MCRUserAttribute::getValue); protected MCRUserAttribute() { } public MCRUserAttribute(String name, String value) { setName(name); setValue(value); } @Column(name = "name", length = 128, nullable = false) @XmlAttribute public String getName() { return name; } public void setName(String name) { this.name = Objects.requireNonNull(name); } @Column(name = "value", nullable = false) @XmlAttribute public String getValue() { return value; } public void setValue(String value) { //require non-null MCR-2374 this.value = Objects.requireNonNull(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MCRUserAttribute that)) { return false; } return name.equals(that.name) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(name, value); } @Override public int compareTo(MCRUserAttribute o) { return NATURAL_ORDER_COMPARATOR.compare(this, o); } }
2,749
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRoleManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRoleManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.classifications2.MCRCategLinkReference; import org.mycore.datamodel.classifications2.MCRCategLinkService; import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl; /** * Manages roles and role assignments using a database table. * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ public class MCRRoleManager { private static Logger LOGGER = LogManager.getLogger(MCRRoleManager.class); /** Map of defined roles, key is the unique role name */ private static HashMap<String, MCRRole> rolesByName = new HashMap<>(); /** List of all defined roles */ private static List<MCRRole> rolesList = new ArrayList<>(); private static final MCRCategoryDAO DAO = MCRCategoryDAOFactory.getInstance(); private static long lastLoaded; private static final MCRCategLinkService CATEG_LINK_SERVICE = MCRCategLinkServiceFactory.getInstance(); static { loadSystemRoles(); } private static void loadSystemRoles() { if (lastLoaded == DAO.getLastModified() || !DAO.exist(MCRUser2Constants.ROLE_CLASSID)) { return; } lastLoaded = DAO.getLastModified(); int onlyNonHierarchicalRoles = 1; MCRCategory roleCategory = DAO.getCategory(MCRUser2Constants.ROLE_CLASSID, onlyNonHierarchicalRoles); rolesByName.clear(); rolesList.clear(); if (roleCategory != null) { for (MCRCategory child : roleCategory.getChildren()) { String name = child.getId().getId(); MCRRole role = new MCRRole(name, child.getLabels()); rolesByName.put(name, role); rolesList.add(role); } } } /** * Returns the role with the given role name, or null. * * @param name the unique role name * @return the role with the given role name, or null. */ public static MCRRole getRole(String name) { loadSystemRoles(); MCRRole mcrRole = rolesByName.get(name); if (mcrRole == null) { return getExternalRole(name); } return mcrRole; } /** * Factory for external roles * @param name a valid {@link MCRCategoryID} * @return MCRRole instance or null if category does not exist */ public static MCRRole getExternalRole(String name) { MCRCategoryID categoryID = MCRCategoryID.fromString(name); if (categoryID.isRootID()) { LOGGER.debug("External role may not be a rootCategory: {}", categoryID); return null; } MCRCategory category = DAO.getCategory(categoryID, 0); if (category == null) { LOGGER.debug("Category does not exist: {}", categoryID); return null; } return new MCRRole(name, category.getLabels()); } /** * Returns a role array for the given role names. * @param names unique role names * @return array each element either MCRRole instance, or null */ public static MCRRole[] getRoles(String... names) { loadSystemRoles(); MCRRole[] roles = new MCRRole[names.length]; for (int i = 0; i < names.length; i++) { roles[i] = rolesByName.get(names[i]); if (roles[i] == null) { roles[i] = getExternalRole(names[i]); } } return roles; } /** * Returns a role collection for the given role names. * If a role is not known the returning collection contains fewer items. * @param names unique role names * @return collection each element is MCRRole instance. */ public static Collection<MCRRole> getRoles(Collection<String> names) { loadSystemRoles(); String[] namesArr = names.toArray(String[]::new); MCRRole[] roles = getRoles(namesArr); return Arrays.asList(roles); } /** * Returns a list of all defined roles * * @return a list of all defined roles */ public static List<MCRRole> listSystemRoles() { return rolesList; } /** * Removes user from all roles * * @param user the user to remove from all roles */ static void unassignRoles(MCRUser user) { CATEG_LINK_SERVICE.deleteLink(getLinkID(user)); } /** * Stores role membership information of the user * * @param user the user */ static void storeRoleAssignments(MCRUser user) { MCRCategLinkReference ref = getLinkID(user); List<MCRCategoryID> categories = new ArrayList<>(); for (String roleID : user.getSystemRoleIDs()) { MCRCategoryID categID = new MCRCategoryID(MCRUser2Constants.ROLE_CLASSID.getRootID(), roleID); categories.add(categID); } for (String roleID : user.getExternalRoleIDs()) { MCRCategoryID categID = MCRCategoryID.fromString(roleID); categories.add(categID); } LOGGER.info("Assigning {} to these roles: {}", user.getUserID(), categories); CATEG_LINK_SERVICE.setLinks(ref, categories); } static Collection<MCRCategoryID> getRoleIDs(MCRUser user) { return CATEG_LINK_SERVICE.getLinksFromReference(getLinkID(user)); } static boolean isAssignedToRole(MCRUser user, String roleID) { MCRCategoryID categoryID = MCRCategoryID.fromString(roleID); MCRCategLinkReference linkReference = getLinkID(user); return CATEG_LINK_SERVICE.isInCategory(linkReference, categoryID); } private static MCRCategLinkReference getLinkID(MCRUser user) { return new MCRCategLinkReference(user.getUserName() + "@" + user.getRealmID(), MCRUser2Constants.CATEG_LINK_TYPE); } /** * Adds <code>role</code> to the classification system. * If the representing {@link MCRCategory} already exists this method does nothing. * It will create any category if necessary. */ public static void addRole(MCRRole role) { MCRCategoryID categoryID = null; if (role.isSystemRole()) { categoryID = new MCRCategoryID(MCRUser2Constants.ROLE_CLASSID.getRootID(), role.getName()); } else { categoryID = MCRCategoryID.fromString(role.getName()); } if (DAO.exist(categoryID)) { return; } MCRCategoryID rootID = MCRCategoryID.rootID(categoryID.getRootID()); if (!DAO.exist(rootID)) { MCRCategoryImpl category = new MCRCategoryImpl(); category.setId(rootID); SortedSet<MCRLabel> labels = new TreeSet<>(); labels.add(new MCRLabel("de", "Systemrollen", null)); labels.add(new MCRLabel("en", "system roles", null)); category.setLabels(labels); DAO.addCategory(null, category); } MCRCategoryImpl category = new MCRCategoryImpl(); category.setId(categoryID); category.getLabels().addAll(role.getLabels()); DAO.addCategory(rootID, category); } /** * Deletes a role from the system. * If the role is currently not stored in the classification system this method does nothing. * This method will fail if any objects (e.g. users) are linked to it. */ public static void deleteRole(String roleID) { MCRRole role = MCRRoleManager.getRole(roleID); if (role == null) { //unknown role return; } MCRCategoryID categoryID = null; if (role.isSystemRole()) { categoryID = new MCRCategoryID(MCRUser2Constants.ROLE_CLASSID.getRootID(), role.getName()); } else { categoryID = MCRCategoryID.fromString(role.getName()); } DAO.deleteCategory(categoryID); } /** * Returns a collection of userIDs linked to the given <code>role</code>. * @param role role to list user IDs. */ public static Collection<String> listUserIDs(MCRRole role) { MCRCategoryID categoryID = getCategoryID(role); return CATEG_LINK_SERVICE.getLinksFromCategoryForType(categoryID, MCRUser2Constants.CATEG_LINK_TYPE); } private static MCRCategoryID getCategoryID(MCRRole role) { if (role.isSystemRole()) { return new MCRCategoryID(MCRUser2Constants.ROLE_CLASSID.getRootID(), role.getName()); } return MCRCategoryID.fromString(role.getName()); } }
9,855
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRole.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/MCRRole.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2; import java.util.Collection; import java.util.HashMap; import java.util.Set; import org.mycore.common.MCRSessionMgr; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRLabel; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; /** * Represents a role of users. * Roles are {@link MCRCategory} instances and every category from {@link MCRUser2Constants#ROLE_CLASSID} * {@link MCRRole#isSystemRole()}. * * @author Thomas Scheffler (yagee) */ @XmlRootElement(name = "role") public class MCRRole { /** The unique role name */ private String name; /** The labels of the role */ private HashMap<String, MCRLabel> labels; private boolean isSystemRole; private MCRRole() { this.labels = new HashMap<>(); } /** * Creates a new role instance. * * @param name the unique role ID * @param labels a set of MCRLabel in different languages */ public MCRRole(String name, Set<MCRLabel> labels) { this(); for (MCRLabel label : labels) { this.labels.put(label.getLang(), label); } setName(name); } /** * Returns the roles's name * * @return the roles's name */ @XmlAttribute public String getName() { return name; } /** * Returns the label in the current language. */ public MCRLabel getLabel() { String lang = MCRSessionMgr.getCurrentSession().getCurrentLanguage(); return labels.get(lang); } /** * Returns all labels available for this role. */ public Collection<MCRLabel> getLabels() { return labels.values(); } /** * Returns true if this role is a system role. * A system role is every category in {@link MCRUser2Constants#ROLE_CLASSID}. * @return false if category has not the same root ID as the system role classification. */ public boolean isSystemRole() { return isSystemRole; } @XmlElement(name = "label") @SuppressWarnings("unused") private MCRLabel[] getLabelsArray() { return labels.values().toArray(MCRLabel[]::new); } @SuppressWarnings("unused") private void setLabelsArray(MCRLabel[] labels) { for (MCRLabel label : labels) { this.labels.put(label.getLang(), label); } } private void setName(String name) { this.name = name; this.isSystemRole = !name.contains(":") || name.startsWith(MCRUser2Constants.ROLE_CLASSID.getRootID() + ":"); } @Override public boolean equals(Object obj) { return obj instanceof MCRRole role && role.getName().equals(this.getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return getName(); } }
3,730
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/annotation/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author René Adler (eagle) * */ package org.mycore.user2.annotation;
805
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserAttributeJavaConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/annotation/MCRUserAttributeJavaConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.annotation; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.mycore.user2.MCRUserAttributeConverter; /** * @author René Adler (eagle) * */ @Retention(RUNTIME) @Target({ METHOD, FIELD }) public @interface MCRUserAttributeJavaConverter { /** * Points to the class that converts a value type to a bound type or vice versa. * See {@link MCRUserAttributeConverter} for more details. */ Class<? extends MCRUserAttributeConverter> value(); }
1,425
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserAttribute.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/annotation/MCRUserAttribute.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.annotation; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * @author René Adler (eagle) * */ @Retention(RUNTIME) @Target({ METHOD, FIELD }) public @interface MCRUserAttribute { /** * (Optional) The name of the attribute. Defaults to * the property or field name. */ String name() default ""; /** * (Optional) Allow a <code>null</code> value. */ boolean nullable() default true; /** * (Optional) The attribute values separator. */ String separator() default ","; }
1,488
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDFNDisplayNameConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/MCRDFNDisplayNameConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.utils; import java.nio.charset.StandardCharsets; import java.util.Map; import org.mycore.user2.MCRUserAttributeConverter; /** * @author René Adler (eagle) */ public class MCRDFNDisplayNameConverter implements MCRUserAttributeConverter<String, String> { @Override public String convert(String value, String separator, Map<String, String> valueMapping) { return value != null ? new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8) : null; } }
1,247
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRoleTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/MCRRoleTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.utils; import java.io.IOException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.MCRException; import org.mycore.common.content.MCRJAXBContent; import org.mycore.user2.MCRRole; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; /** * @author Thomas Scheffler (yagee) * */ public abstract class MCRRoleTransformer { private static final String ROLE_ELEMENT_NAME = "role"; private static final JAXBContext JAXB_CONTEXT = initContext(); private static JAXBContext initContext() { try { return JAXBContext.newInstance(MCRRole.class.getPackage().getName(), MCRRole.class.getClassLoader()); } catch (JAXBException e) { throw new MCRException("Could not instantiate JAXBContext.", e); } } /** * Builds an xml element containing all information on the given role. */ public static Document buildExportableXML(MCRRole role) { MCRJAXBContent<MCRRole> content = new MCRJAXBContent<>(JAXB_CONTEXT, role); try { return content.asXML(); } catch (IOException e) { throw new MCRException("Exception while transforming MCRRole " + role.getName() + " to JDOM document.", e); } } /** * Builds an MCRRole instance from the given element. * @param element as generated by {@link #buildExportableXML(MCRRole)}. */ public static MCRRole buildMCRRole(Element element) { if (!element.getName().equals(ROLE_ELEMENT_NAME)) { throw new IllegalArgumentException("Element is not a mycore role element."); } try { Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); return (MCRRole) unmarshaller.unmarshal(new JDOMSource(element)); } catch (JAXBException e) { throw new MCRException("Exception while transforming Element to MCRUser.", e); } } }
2,782
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** Provides classes not directly related to user and group management */ package org.mycore.user2.utils;
833
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRolesConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/MCRRolesConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.utils; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Map; import org.mycore.user2.MCRUserAttributeConverter; /** * @author René Adler (eagle) * */ public class MCRRolesConverter implements MCRUserAttributeConverter<String, Collection<String>> { @Override public Collection<String> convert(String value, String separator, Map<String, String> valueMapping) { Collection<String> roles = new HashSet<>(); if (value != null) { for (final String v : value.split(separator)) { final String role = v.contains("@") ? v.substring(0, v.indexOf("@")) : v; if (valueMapping != null) { final String[] mapping = valueMapping.containsKey(role) ? valueMapping.get(role).split(",") : null; if (mapping != null) { roles.addAll(Arrays.asList(mapping)); } } } } return roles; } }
1,772
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDateXMLAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/MCRDateXMLAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.utils; import java.time.Instant; import java.time.temporal.TemporalAccessor; import java.util.Date; import org.mycore.datamodel.common.MCRISO8601Format; import org.mycore.datamodel.common.MCRISO8601FormatChooser; import jakarta.xml.bind.annotation.adapters.XmlAdapter; /** * @author Thomas Scheffler (yagee) */ public class MCRDateXMLAdapter extends XmlAdapter<String, Date> { @Override public Date unmarshal(String v) { TemporalAccessor dateTime = MCRISO8601FormatChooser.getFormatter(v, null).parse(v); Instant instant = Instant.from(dateTime); return Date.from(instant); } @Override public String marshal(Date v) { TemporalAccessor dt = v.toInstant(); return MCRISO8601FormatChooser.getFormatter(null, MCRISO8601Format.COMPLETE_HH_MM_SS).format(dt); } }
1,582
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/MCRUserTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.utils; import java.io.IOException; import java.util.Comparator; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.transform.JDOMSource; import org.mycore.common.MCRException; import org.mycore.common.content.MCRJAXBContent; import org.mycore.user2.MCRUser; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; /** * @author Thomas Scheffler (yagee) * */ public abstract class MCRUserTransformer { private static final String USER_ELEMENT_NAME = "user"; public static final JAXBContext JAXB_CONTEXT = initContext(); private MCRUserTransformer() { } private static JAXBContext initContext() { try { return JAXBContext.newInstance(MCRUser.class.getPackage().getName(), MCRUser.class.getClassLoader()); } catch (JAXBException e) { throw new MCRException("Could not instantiate JAXBContext.", e); } } private static Document getDocument(MCRUser user) { MCRJAXBContent<MCRUser> content = new MCRJAXBContent<>(JAXB_CONTEXT, user); try { Document userXML = content.asXML(); sortAttributes(userXML); return userXML; } catch (IOException e) { throw new MCRException("Exception while transforming MCRUser " + user.getUserID() + " to JDOM document.", e); } } private static void sortAttributes(Document userXML) { Element attributes = userXML.getRootElement().getChild("attributes"); if (attributes == null) { return; } attributes.sortChildren(Comparator.comparing(o -> o.getAttributeValue("name"))); } /** * Builds an xml element containing basic information on user. * This includes user ID, login name and realm. */ public static Document buildBasicXML(MCRUser mcrUser) { return getDocument(mcrUser.getBasicCopy()); } /** * Builds an xml element containing all information on the given user except password info. * same as {@link #buildExportableXML(MCRUser)} without owned users resolved */ public static Document buildExportableSafeXML(MCRUser mcrUser) { return getDocument(mcrUser.getSafeCopy()); } /** * Builds an xml element containing all information on the given user. * same as {@link #buildExportableSafeXML(MCRUser)} but with password info if available */ public static Document buildExportableXML(MCRUser mcrUser) { return getDocument(mcrUser); } /** * Builds an MCRUser instance from the given element. * @param element as generated by {@link #buildExportableXML(MCRUser)}. */ public static MCRUser buildMCRUser(Element element) { if (!element.getName().equals(USER_ELEMENT_NAME)) { throw new IllegalArgumentException("Element is not a mycore user element."); } try { Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); return (MCRUser) unmarshaller.unmarshal(new JDOMSource(element)); } catch (JAXBException e) { throw new MCRException("Exception while transforming Element to MCRUser.", e); } } }
4,013
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUserNameConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/utils/MCRUserNameConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.utils; import java.util.Map; import org.mycore.user2.MCRUserAttributeConverter; /** * @author René Adler (eagle) * */ public class MCRUserNameConverter implements MCRUserAttributeConverter<String, String> { @Override public String convert(String value, String separator, Map<String, String> valueMapping) { return (value != null && value.contains("@")) ? value.substring(0, value.indexOf("@")) : value; } }
1,186
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRCASServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRCASServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jasig.cas.client.authentication.AttributePrincipal; import org.jasig.cas.client.validation.Assertion; import org.jasig.cas.client.validation.Cas20ProxyTicketValidator; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUser2Constants; import org.mycore.user2.MCRUserManager; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Login user with JA-SIG Central Authentication Service (CAS). * The servlet validates the ticket returned from CAS and * builds a User object to login to the current session. * * For /servlets/MCRCASServlet, a authentication filter must be defined * in web.xml. The following properties must be configured in * mycore.properties: * * The URL of the CAS Client Servlet: * MCR.user2.CAS.ClientURL=http://localhost:8291/servlets/MCRCASServlet * * The Base URL of the CAS Server * MCR.user2.CAS.ServerURL=https://cas.uni-duisburg-essen.de/cas * * The realm the CAS Server authenticates for, as in realms.xml * MCR.user2.CAS.RealmID=ude * * Configure store of trusted SSL (https) server certificates * MCR.user2.CAS.SSL.TrustStore=/path/to/java/lib/security/cacerts * MCR.user2.CAS.SSL.TrustStore.Password=changeit * * After successful login, MCRCASServlet queries an LDAP server for * the user's properties. * * @author Frank L\u00fctzenkirchen */ public class MCRCASServlet extends MCRServlet { private static final long serialVersionUID = 1L; /** The logger */ private static Logger LOGGER = LogManager.getLogger(); /** The URL of THIS servlet */ private String clientURL; /** The base URL of the CAS Server */ private String serverURL; /** The realm the CAS Server authenticates for, as in realms.xml */ private String realmID; @Override public void init() throws ServletException { super.init(); clientURL = MCRConfiguration2.getStringOrThrow(MCRUser2Constants.CONFIG_PREFIX + "CAS.ClientURL"); serverURL = MCRConfiguration2.getStringOrThrow(MCRUser2Constants.CONFIG_PREFIX + "CAS.ServerURL"); realmID = MCRConfiguration2.getStringOrThrow(MCRUser2Constants.CONFIG_PREFIX + "CAS.RealmID"); // Set properties to enable SSL connection to CAS and accept certificates String trustStore = MCRConfiguration2.getStringOrThrow(MCRUser2Constants.CONFIG_PREFIX + "CAS.SSL.TrustStore"); String trustStorePassword = MCRConfiguration2 .getStringOrThrow(MCRUser2Constants.CONFIG_PREFIX + "CAS.SSL.TrustStore.Password"); System.setProperty("javax.net.ssl.trustStore", trustStore); System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); } public void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); String ticket = req.getParameter("ticket"); if ((ticket == null) || (ticket.trim().length() == 0)) { res.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // Validate ticket at CAS server Cas20ProxyTicketValidator sv = new Cas20ProxyTicketValidator(serverURL); sv.setAcceptAnyProxy(true); Assertion a = sv.validate(ticket, clientURL); AttributePrincipal principal = a.getPrincipal(); // Get user name logged in String userName = principal.getName(); LOGGER.info("Login {}", userName); MCRUser user; boolean userExists = MCRUserManager.exists(userName, realmID); if (userExists) { user = MCRUserManager.getUser(userName, realmID); } else { user = new MCRUser(userName, realmID); } // Get user properties from LDAP server boolean userChanged = MCRLDAPClient.instance().updateUserProperties(user); if (userChanged && userExists) { MCRUserManager.updateUser(user); } // Store login user in session and redirect browser to target url MCRSessionMgr.getCurrentSession().setUserInformation(user); // MCR-1154 req.changeSessionId(); MCRLoginServlet.redirect(res); } }
5,295
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** Provides classes implementing login functionality */ package org.mycore.user2.login;
816
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLogin.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRLogin.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import org.mycore.common.MCRUserInformation; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; /** * @author Thomas Scheffler (yagee) * */ @XmlRootElement(name = "login") @XmlType(name = "user2-login") @XmlAccessorType(XmlAccessType.FIELD) public class MCRLogin extends org.mycore.frontend.support.MCRLogin { @XmlAttribute(required = true) String realm; @XmlAttribute String realmParameter; @XmlAttribute boolean loginFailed; @XmlElement String returnURL; @XmlElement String errorMessage; public MCRLogin() { super(); } public MCRLogin(MCRUserInformation userInformation, String returnURL, String formAction) { super(userInformation, formAction); this.returnURL = returnURL; } public String getRealm() { return realm; } public void setRealm(String realm) { this.realm = realm; } public String getRealmParameter() { return realmParameter; } public void setRealmParameter(String realmParameter) { this.realmParameter = realmParameter; } public boolean isLoginFailed() { return loginFailed; } public void setLoginFailed(boolean loginFailed) { this.loginFailed = loginFailed; } public String getReturnURL() { return returnURL; } public void setReturnURL(String returnURL) { this.returnURL = returnURL; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
2,612
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRServlet3LoginServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRServlet3LoginServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import static org.mycore.user2.login.MCRLoginServlet.HTTPS_ONLY_PROPERTY; import static org.mycore.user2.login.MCRLoginServlet.LOCAL_LOGIN_SECURE_ONLY; import java.io.IOException; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.content.MCRJAXBContent; import org.mycore.frontend.filter.MCRRequestAuthenticationFilter; import org.mycore.frontend.servlets.MCRContainerLoginServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.user2.MCRRealm; import org.xml.sax.SAXException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; /** * @author Thomas Scheffler (yagee) * */ public class MCRServlet3LoginServlet extends MCRContainerLoginServlet { private static final long serialVersionUID = 1L; private static Logger LOGGER = LogManager.getLogger(); @Override public void init() throws ServletException { if (!LOCAL_LOGIN_SECURE_ONLY) { LOGGER.warn("Login over unsecure connection is permitted. Set '" + HTTPS_ONLY_PROPERTY + "=true' to prevent cleartext transmissions of passwords."); } super.init(); } @Override protected void think(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); if (LOCAL_LOGIN_SECURE_ONLY && !req.isSecure()) { res.sendError(HttpServletResponse.SC_FORBIDDEN, getErrorI18N("component.user2.login", "httpsOnly")); return; } String uid = getProperty(req, "uid"); String pwd = getProperty(req, "pwd"); String realm = getProperty(req, "realm"); if (uid != null && pwd != null) { MCRSession session = MCRSessionMgr.getCurrentSession(); req.login(uid, pwd); session.setUserInformation(new Servlet3ContainerUserInformation(session, realm)); req.getSession().setAttribute(MCRRequestAuthenticationFilter.SESSION_KEY, Boolean.TRUE); LOGGER.info("Logged in: {}", session.getUserInformation().getUserID()); } } @Override protected void render(MCRServletJob job, Exception ex) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); if (ex != null) { if (ex instanceof ServletException se) { //Login failed presentLoginForm(req, res, se); } else { throw ex; } } if (!res.isCommitted()) { String uid = getProperty(req, "uid"); if (uid == null) { presentLoginForm(req, res, null); } if (!job.getResponse().isCommitted()) { super.render(job, ex); } } } private void presentLoginForm(HttpServletRequest req, HttpServletResponse res, ServletException ex) throws IOException, TransformerException, SAXException, JAXBException { String returnURL = MCRLoginServlet.getReturnURL(req); String formAction = req.getRequestURI(); MCRLogin loginForm = new MCRLogin(MCRSessionMgr.getCurrentSession().getUserInformation(), returnURL, formAction); MCRLoginServlet.addCurrentUserInfo(loginForm); String realm = getProperty(req, "realm"); if (realm != null) { req.setAttribute("XSL.Realm", realm); } MCRLoginServlet.addFormFields(loginForm, realm); if (ex != null) { //Login failed res.setStatus(HttpServletResponse.SC_BAD_REQUEST); loginForm.setLoginFailed(true); loginForm.setErrorMessage(ex.getMessage()); } getLayoutService().doLayout(req, res, new MCRJAXBContent<>(JAXBContext.newInstance(MCRLogin.class), loginForm)); } private static class Servlet3ContainerUserInformation extends ContainerUserInformation { private String realm; Servlet3ContainerUserInformation(MCRSession session, String realm) { super(session); this.realm = realm; } @Override public String getUserAttribute(String attribute) { if (attribute.equals(MCRRealm.USER_INFORMATION_ATTR)) { return this.realm; } return super.getUserAttribute(attribute); } } }
5,479
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRShibbolethLoginServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRShibbolethLoginServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import java.util.HashMap; import java.util.Map; 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.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.user2.MCRRealmFactory; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserAttributeMapper; import org.mycore.user2.MCRUserManager; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * * @author René Adler (eagle) */ public class MCRShibbolethLoginServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static Logger LOGGER = LogManager.getLogger(MCRShibbolethLoginServlet.class); public void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); String msg = null; String uid = (String) req.getAttribute("uid"); String userId = uid != null ? uid : req.getRemoteUser(); if (userId != null) { final String realmId = userId.contains("@") ? userId.substring(userId.indexOf("@") + 1) : null; if (realmId != null && MCRRealmFactory.getRealm(realmId) != null) { userId = realmId != null ? userId.replace("@" + realmId, "") : userId; final Map<String, Object> attributes = new HashMap<>(); final MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(realmId); for (final String key : attributeMapper.getAttributeNames()) { final Object value = req.getAttribute(key); if (value != null) { LOGGER.info("received {}:{}", key, value); attributes.put(key, value); } } MCRUserInformation userinfo; MCRUser user = MCRUserManager.getUser(userId, realmId); if (user != null) { LOGGER.debug("login existing user \"{}\"", user.getUserID()); attributeMapper.mapAttributes(user, attributes); user.setLastLogin(); MCRUserManager.updateUser(user); userinfo = user; } else { userinfo = new MCRShibbolethUserInformation(userId, realmId, attributes); } MCRSessionMgr.getCurrentSession().setUserInformation(userinfo); // MCR-1154 req.changeSessionId(); res.sendRedirect(res.encodeRedirectURL(req.getParameter("url"))); return; } else { msg = "Login from realm \"" + realmId + "\" is not allowed."; } } else { msg = "Principal could not be received from IDP."; } job.getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED, msg); } }
3,857
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRShibbolethUserInformation.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRShibbolethUserInformation.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import org.mycore.common.MCRUserInformation; import org.mycore.user2.MCRRealm; import org.mycore.user2.MCRRealmFactory; import org.mycore.user2.MCRUserAttributeMapper; import org.mycore.user2.annotation.MCRUserAttribute; import org.mycore.user2.annotation.MCRUserAttributeJavaConverter; import org.mycore.user2.utils.MCRRolesConverter; /** * * @author René Adler (eagle) */ public class MCRShibbolethUserInformation implements MCRUserInformation { private String userId; private String realmId; private Map<String, Object> attributes; @MCRUserAttribute private String realName; private Set<String> roles = new HashSet<>(); public MCRShibbolethUserInformation(String userId, String realmId, Map<String, Object> attributes) throws Exception { this.userId = userId; this.realmId = realmId; this.attributes = attributes; MCRUserAttributeMapper attributeMapper = MCRRealmFactory.getAttributeMapper(this.realmId); if (attributeMapper != null) { attributeMapper.mapAttributes(this, attributes); } } /* (non-Javadoc) * @see org.mycore.common.MCRUserInformation#getUserID() */ @Override public String getUserID() { return userId + "@" + realmId; } /* (non-Javadoc) * @see org.mycore.common.MCRUserInformation#isUserInRole(java.lang.String) */ @Override public boolean isUserInRole(String role) { return roles.contains(role); } /* (non-Javadoc) * @see org.mycore.common.MCRUserInformation#getUserAttribute(java.lang.String) */ @Override public String getUserAttribute(String attribute) { return switch (attribute) { case MCRUserInformation.ATT_REAL_NAME -> this.realName; case MCRRealm.USER_INFORMATION_ATTR -> this.realmId; default -> Optional.ofNullable(attributes.get(attribute)) .map(Object::toString) .orElse(null); }; } // This is used for MCRUserAttributeMapper Collection<String> getRoles() { return roles; } @MCRUserAttribute(name = "roles", separator = ";") @MCRUserAttributeJavaConverter(MCRRolesConverter.class) void setRoles(Collection<String> roles) { this.roles.addAll(roles); } }
3,213
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLoginServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRLoginServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; import java.util.stream.Collectors; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.MCRUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJAXBContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.support.MCRLogin.InputField; import org.mycore.services.i18n.MCRTranslation; import org.mycore.user2.MCRRealm; import org.mycore.user2.MCRRealmFactory; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUser2Constants; import org.mycore.user2.MCRUserManager; import org.xml.sax.SAXException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; /** * Provides functionality to select login method, * change login user and show a welcome page. * Login methods and realms are configured in realms.xml. * The login form for local users is login.xml. * * @author Frank L\u00fctzenkirchen * @author Thomas Scheffler (yagee) */ public class MCRLoginServlet extends MCRServlet { protected static final String REALM_URL_PARAMETER = "realm"; static final String HTTPS_ONLY_PROPERTY = MCRUser2Constants.CONFIG_PREFIX + "LoginHttpsOnly"; static final String ALLOWED_ROLES_PROPERTY = MCRUser2Constants.CONFIG_PREFIX + "LoginAllowedRoles"; private static final long serialVersionUID = 1L; private static final String LOGIN_REDIRECT_URL_PARAMETER = "url"; private static final String LOGIN_REDIRECT_URL_KEY = "loginRedirectURL"; protected static final boolean LOCAL_LOGIN_SECURE_ONLY = MCRConfiguration2 .getOrThrow(HTTPS_ONLY_PROPERTY, Boolean::parseBoolean); private static final List<String> ALLOWED_ROLES = MCRConfiguration2 .getString(MCRLoginServlet.ALLOWED_ROLES_PROPERTY) .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElse(Collections.emptyList()); private static Logger LOGGER = LogManager.getLogger(); @Override public void init() throws ServletException { if (!LOCAL_LOGIN_SECURE_ONLY) { LOGGER.warn("Login over unsecure connection is permitted. Set '" + HTTPS_ONLY_PROPERTY + "=true' to prevent cleartext transmissions of passwords."); } super.init(); } /** * MCRLoginServlet handles four actions: * * MCRLoginServlet?url=foo * stores foo as redirect url and displays * a list of login method options. * * MCRLoginServlet?url=foo&amp;realm=ID * stores foo as redirect url and redirects * to the login URL of the given realm. * MCRLoginServlet?action=login * checks input from editor login form and * changes the current login user and redirects * to the stored url. * * MCRLoginServlet?action=cancel * does not change login user, just * redirects to the target url */ public void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); String action = req.getParameter("action"); String realm = req.getParameter(REALM_URL_PARAMETER); job.getResponse().setHeader("Cache-Control", "no-cache"); job.getResponse().setHeader("Pragma", "no-cache"); job.getResponse().setHeader("Expires", "0"); if (Objects.equals(action, "login")) { presentLoginForm(job); } else if (Objects.equals(action, "cancel")) { redirect(res); } else if (realm != null) { loginToRealm(req, res, req.getParameter(REALM_URL_PARAMETER)); } else { chooseLoginMethod(req, res); } } /** * Stores the target url and outputs a list of realms to login to. The list is * rendered using realms.xsl. */ private void chooseLoginMethod(HttpServletRequest req, HttpServletResponse res) throws Exception { storeURL(getReturnURL(req)); // redirect directly to login url if there is only one realm available and the user is not logged in if ((getNumLoginOptions() == 1) && currentUserIsGuest()) { redirectToUniqueRealm(req, res); } else { listRealms(req, res); } } protected static String getReturnURL(HttpServletRequest req) { String returnURL = req.getParameter(LOGIN_REDIRECT_URL_PARAMETER); if (returnURL == null) { String referer = req.getHeader("Referer"); returnURL = (referer != null) ? referer : req.getContextPath() + "/"; } return returnURL; } private void redirectToUniqueRealm(HttpServletRequest req, HttpServletResponse res) throws Exception { String realmID = MCRRealmFactory.listRealms().iterator().next().getID(); loginToRealm(req, res, realmID); } protected void presentLoginForm(MCRServletJob job) throws IOException, TransformerException, SAXException, JAXBException { HttpServletRequest req = job.getRequest(); HttpServletResponse res = job.getResponse(); if (LOCAL_LOGIN_SECURE_ONLY && !req.isSecure()) { res.sendError(HttpServletResponse.SC_FORBIDDEN, getErrorI18N("component.user2.login", "httpsOnly")); return; } String returnURL = getReturnURL(req); String formAction = req.getRequestURI(); MCRLogin loginForm = new MCRLogin(MCRSessionMgr.getCurrentSession().getUserInformation(), returnURL, formAction); String uid = getProperty(req, "uid"); String pwd = getProperty(req, "pwd"); if (uid != null) { MCRUser user = MCRUserManager.login(uid, pwd, ALLOWED_ROLES); if (user == null) { res.setStatus(HttpServletResponse.SC_BAD_REQUEST); loginForm.setLoginFailed(true); } else { //user logged in // MCR-1154 req.changeSessionId(); LOGGER.info("user {} logged in successfully.", uid); res.sendRedirect(res.encodeRedirectURL(getReturnURL(req))); return; } } addFormFields(loginForm, job.getRequest().getParameter(REALM_URL_PARAMETER)); getLayoutService().doLayout(req, res, new MCRJAXBContent<>(JAXBContext.newInstance(MCRLogin.class), loginForm)); } private void listRealms(HttpServletRequest req, HttpServletResponse res) throws IOException, TransformerException, SAXException { String redirectURL = getReturnURL(req); Document realmsDoc = MCRRealmFactory.getRealmsDocument(); Element realms = realmsDoc.getRootElement(); addCurrentUserInfo(realms); List<Element> realmList = realms.getChildren(REALM_URL_PARAMETER); for (Element realm : realmList) { String realmID = realm.getAttributeValue("id"); Element login = realm.getChild("login"); if (login != null) { login.setAttribute("url", MCRRealmFactory.getRealm(realmID).getLoginURL(redirectURL)); } } getLayoutService().doLayout(req, res, new MCRJDOMContent(realmsDoc)); } protected static void addFormFields(MCRLogin login, String loginToRealm) { ArrayList<org.mycore.frontend.support.MCRLogin.InputField> fields = new ArrayList<>(); if (loginToRealm != null) { //realmParameter MCRRealm realm = MCRRealmFactory.getRealm(loginToRealm); InputField realmParameter = new InputField(realm.getRealmParameter(), loginToRealm, null, null, false, true); fields.add(realmParameter); } fields.add(new InputField("action", "login", null, null, false, true)); fields.add(new InputField("url", login.getReturnURL(), null, null, false, true)); String userNameText = MCRTranslation.translate("component.user2.login.form.userName"); fields.add(new InputField("uid", null, userNameText, userNameText, false, false)); String pwdText = MCRTranslation.translate("component.user2.login.form.password"); fields.add(new InputField("pwd", null, pwdText, pwdText, true, false)); login.getForm().getInput().addAll(fields); } static void addCurrentUserInfo(Element rootElement) { MCRUserInformation userInfo = MCRSessionMgr.getCurrentSession().getUserInformation(); rootElement.setAttribute("user", userInfo.getUserID()); String realmId = userInfo instanceof MCRUser mcrUser ? mcrUser.getRealm().getLabel() : userInfo.getUserAttribute(MCRRealm.USER_INFORMATION_ATTR); if (realmId == null) { realmId = MCRRealmFactory.getLocalRealm().getLabel(); } rootElement.setAttribute(REALM_URL_PARAMETER, realmId); rootElement.setAttribute("guest", String.valueOf(currentUserIsGuest())); } static void addCurrentUserInfo(MCRLogin login) { MCRUserInformation userInfo = MCRSessionMgr.getCurrentSession().getUserInformation(); String realmId = userInfo instanceof MCRUser mcrUser ? mcrUser.getRealm().getLabel() : userInfo.getUserAttribute(MCRRealm.USER_INFORMATION_ATTR); if (realmId == null) { realmId = MCRRealmFactory.getLocalRealm().getLabel(); } login.setRealm(realmId); } private static boolean currentUserIsGuest() { return MCRSessionMgr.getCurrentSession().getUserInformation().getUserID() .equals(MCRSystemUserInformation.getGuestInstance().getUserID()); } private int getNumLoginOptions() { int numOptions = 0; for (MCRRealm realm : MCRRealmFactory.listRealms()) { numOptions++; if (realm.getCreateURL() != null) { numOptions++; } } return numOptions; } private void loginToRealm(HttpServletRequest req, HttpServletResponse res, String realmID) throws Exception { String redirectURL = getReturnURL(req); storeURL(redirectURL); MCRRealm realm = MCRRealmFactory.getRealm(realmID); String loginURL = realm.getLoginURL(redirectURL); res.sendRedirect(res.encodeRedirectURL(loginURL)); } /** * Stores the given url in MCRSession. When login is canceled, or after * successful login, the browser is redirected to that url. */ private void storeURL(String url) { if ((url == null) || (url.trim().length() == 0)) { url = MCRFrontendUtil.getBaseURL(); } else if (url.startsWith(MCRFrontendUtil.getBaseURL()) && !url.equals(MCRFrontendUtil.getBaseURL())) { String rest = url.substring(MCRFrontendUtil.getBaseURL().length()); url = MCRFrontendUtil.getBaseURL() + encodePath(rest); } LOGGER.info("Storing redirect URL to session: {}", url); MCRSessionMgr.getCurrentSession().put(LOGIN_REDIRECT_URL_KEY, url); } private String encodePath(String path) { path = path.replace('\\', '/'); StringBuilder result = new StringBuilder(); StringTokenizer st = new StringTokenizer(path, " /?&=", true); while (st.hasMoreTokens()) { String token = st.nextToken(); switch (token) { case " " -> result.append("%20"); case "/", "?", "&", "=" -> result.append(token); default -> result.append(URLEncoder.encode(token, StandardCharsets.UTF_8)); } } return result.toString(); } /** * Redirects the browser to the target url. */ static void redirect(HttpServletResponse res) throws Exception { String url = (String) (MCRSessionMgr.getCurrentSession().get(LOGIN_REDIRECT_URL_KEY)); if (url == null) { LOGGER.warn("Could not get redirect URL from session."); url = MCRFrontendUtil.getBaseURL(); } LOGGER.info("Redirecting to url: {}", url); res.sendRedirect(res.encodeRedirectURL(url)); } }
13,611
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRLDAPClient.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/login/MCRLDAPClient.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.login; import java.util.Hashtable; import java.util.Locale; import javax.naming.Context; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.MCRUsageException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.user2.MCRRole; import org.mycore.user2.MCRRoleManager; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; import org.mycore.user2.utils.MCRUserTransformer; /** * Queries an LDAP server for the user's properties. * * # Timeout when connecting to LDAP server * MCR.user2.LDAP.ReadTimeout=5000 * * # LDAP server * MCR.user2.LDAP.ProviderURL=ldap://idp.uni-duisburg-essen.de * * # Security principal for logging in at LDAP server * MCR.user2.LDAP.SecurityPrincipal=cn=duepublico,dc=idp * * # Security credentials for logging in at LDAP server * MCR.user2.LDAP.SecurityCredentials=XXXXXX * * # Base DN * MCR.user2.LDAP.BaseDN=ou=people,dc=idp * * # Filter for user ID * MCR.user2.LDAP.UIDFilter=(uid=%s) * * # LDAP attribute mappings * * # Mapping from LDAP attribute to real name of user * MCR.user2.LDAP.Mapping.Name=cn * * # Mapping from LDAP attribute to E-Mail address of user * MCR.user2.LDAP.Mapping.E-Mail=mail * * # Mapping of any attribute.value combination to group membership of user * MCR.user2.LDAP.Mapping.Group.eduPersonScopedAffiliation.staff@uni-duisburg-essen.de=creators * * # Default group membership (optional) * MCR.user2.LDAP.Mapping.Group.DefaultGroup=submitters * * @author Frank L\u00fctzenkirchen */ public class MCRLDAPClient { /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRLDAPClient.class); private static MCRLDAPClient instance = new MCRLDAPClient(); /** Base DN */ private String baseDN; /** Filter for user ID */ private String uidFilter; /** Mapping from LDAP attribute to real name of user */ private String mapName; /** Mapping from LDAP attribute to E-Mail address of user */ private String mapEMail; /** Default group of user */ private MCRRole defaultGroup; private Hashtable<String, String> ldapEnv; public static MCRLDAPClient instance() { return instance; } private MCRLDAPClient() { String prefix = "MCR.user2.LDAP."; /* Timeout when connecting to LDAP server */ String readTimeout = MCRConfiguration2.getString(prefix + "ReadTimeout").orElse("10000"); /* LDAP server */ String providerURL = MCRConfiguration2.getStringOrThrow(prefix + "ProviderURL"); /* Security principal for logging in at LDAP server */ String securityPrincipal = MCRConfiguration2.getStringOrThrow(prefix + "SecurityPrincipal"); /* Security credentials for logging in at LDAP server */ String securityCredentials = MCRConfiguration2.getStringOrThrow(prefix + "SecurityCredentials"); baseDN = MCRConfiguration2.getStringOrThrow(prefix + "BaseDN"); uidFilter = MCRConfiguration2.getStringOrThrow(prefix + "UIDFilter"); prefix += "Mapping."; mapName = MCRConfiguration2.getStringOrThrow(prefix + "Name"); mapEMail = MCRConfiguration2.getStringOrThrow(prefix + "E-Mail"); String group = MCRConfiguration2.getString(prefix + "Group.DefaultGroup").orElse(null); if (group != null) { defaultGroup = MCRRoleManager.getRole(group); } ldapEnv = new Hashtable<>(); ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); ldapEnv.put("com.sun.jndi.ldap.read.timeout", readTimeout); ldapEnv.put(Context.PROVIDER_URL, providerURL); ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); ldapEnv.put(Context.SECURITY_PRINCIPAL, securityPrincipal); ldapEnv.put(Context.SECURITY_CREDENTIALS, securityCredentials); } public boolean updateUserProperties(MCRUser user) throws NamingException { String userName = user.getUserName(); boolean userChanged = false; if ((defaultGroup != null) && (!user.isUserInRole((defaultGroup.getName())))) { LOGGER.info("User {} add to group {}", userName, defaultGroup); userChanged = true; user.assignRole(defaultGroup.getName()); } // Get user properties from LDAP server DirContext ctx = new InitialDirContext(ldapEnv); try { SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(baseDN, String.format(Locale.ROOT, uidFilter, userName), controls); while (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); for (NamingEnumeration<String> attributeIDs = attributes.getIDs(); attributeIDs.hasMore();) { String attributeID = attributeIDs.next(); Attribute attribute = attributes.get(attributeID); for (NamingEnumeration<?> values = attribute.getAll(); values.hasMore();) { String attributeValue = values.next().toString(); LOGGER.debug("{}={}", attributeID, attributeValue); if (attributeID.equals(mapName) && (user.getRealName() == null)) { attributeValue = formatName(attributeValue); LOGGER.info("User {} name = {}", userName, attributeValue); user.setRealName(attributeValue); userChanged = true; } if (attributeID.equals(mapEMail) && (user.getEMailAddress() == null)) { LOGGER.info("User {} e-mail = {}", userName, attributeValue); user.setEMail(attributeValue); userChanged = true; } String groupMapping = "MCR.user2.LDAP.Mapping.Group." + attributeID + "." + attributeValue; String group = MCRConfiguration2.getString(groupMapping).orElse(null); if ((group != null) && (!user.isUserInRole((group)))) { LOGGER.info("User {} add to group {}", userName, group); user.assignRole(group); userChanged = true; } } } } } catch (NameNotFoundException ex) { String msg = "LDAP base name not found: " + ex.getMessage() + " " + ex.getExplanation(); throw new MCRConfigurationException(msg, ex); } catch (NamingException ex) { String msg = "Exception accessing LDAP server"; throw new MCRUsageException(msg, ex); } finally { if (ctx != null) { try { ctx.close(); } catch (Exception ignored) { } } } return userChanged; } /** * Formats a user name into "lastname, firstname" syntax. */ private String formatName(String name) { name = name.replaceAll("\\s+", " ").trim(); if (name.contains(",")) { return name; } int pos = name.lastIndexOf(' '); if (pos == -1) { return name; } return name.substring(pos + 1) + ", " + name.substring(0, pos); } public static void main(String[] args) throws Exception { String userName = args[0]; String realmID = args[1]; MCRUser user = MCRUserManager.getUser(userName, realmID); if (user == null) { user = new MCRUser(userName, realmID); } LOGGER.info("\n{}", new XMLOutputter(Format.getPrettyFormat()).outputString(MCRUserTransformer.buildExportableSafeXML(user))); MCRLDAPClient.instance().updateUserProperties(user); LOGGER.info("\n{}", new XMLOutputter(Format.getPrettyFormat()).outputString(MCRUserTransformer.buildExportableSafeXML(user))); } }
9,618
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/events/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author René Adler (eagle) * */ package org.mycore.user2.events;
801
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPersistTransientUserEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-user2/src/main/java/org/mycore/user2/events/MCRPersistTransientUserEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.user2.events; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.user2.MCRTransientUser; import org.mycore.user2.MCRUser; import org.mycore.user2.MCRUserManager; /** * @author René Adler (eagle) * */ public class MCRPersistTransientUserEventHandler extends MCREventHandlerBase { private static Logger LOGGER = LogManager.getLogger(MCRPersistTransientUserEventHandler.class); /** * Persists {@link MCRTransientUser} if an {@link MCRObject} was created. * * @see org.mycore.common.events.MCREventHandlerBase#handleObjectCreated(org.mycore.common.events.MCREvent, org.mycore.datamodel.metadata.MCRObject) */ @Override protected void handleObjectCreated(MCREvent evt, MCRObject obj) { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!MCRUserManager.isInvalidUser(currentUser) && MCRUserManager.getUser(currentUser.getUserID()) == null) { LOGGER.info("create new user \"{}\"", currentUser.getUserID()); MCRUserManager.createUser((MCRTransientUser) currentUser); } } }
2,011
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrUtilsTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/test/java/org/mycore/solr/MCRSolrUtilsTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrUtilsTest { /** * Test method for {@link org.mycore.solr.MCRSolrUtils#escapeSearchValue(java.lang.String)}. */ @Test public final void testEscapeSearchValue() { String restrictedChars = "+-&|!(){}[]^\"~:\\/"; StringBuilder sb = new StringBuilder(); for (char c : restrictedChars.toCharArray()) { sb.append("\\"); sb.append(c); } String escapedChars = sb.toString(); assertEquals("Not all required characters where escaped.", escapedChars, MCRSolrUtils.escapeSearchValue(restrictedChars)); } }
1,495
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrProxyServletTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/test/java/org/mycore/solr/proxy/MCRSolrProxyServletTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.proxy; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Map; import org.apache.solr.common.params.ModifiableSolrParams; import org.junit.Test; import org.mycore.common.MCRTestCase; /** * @author Thomas Scheffler (yagee) */ public class MCRSolrProxyServletTest extends MCRTestCase { /** * Test method for * {@link org.mycore.solr.proxy.MCRSolrProxyServlet#toMultiMap(org.apache.solr.common.params.ModifiableSolrParams)}. */ @Test public final void testToMultiMap() { ModifiableSolrParams params = new ModifiableSolrParams(); String[] paramValues = { "title:junit", "author:john" }; String paramName = "fq"; params.add(paramName, paramValues); Map<String, String[]> multiMap = MCRSolrProxyServlet.toMultiMap(params); System.out.println(Arrays.toString(multiMap.get(paramName))); assertEquals("Expected " + paramValues.length + " values", paramValues.length, multiMap.get(paramName).length); } }
1,777
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRQLSearchUtilsTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/test/java/org/mycore/solr/search/MCRQLSearchUtilsTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import static org.junit.Assert.assertEquals; import org.apache.logging.log4j.LogManager; import org.jdom2.Document; import org.jdom2.Element; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.parsers.bool.MCRCondition; import org.mycore.services.fieldquery.MCRQuery; import org.mycore.services.fieldquery.MCRQueryParser; /** * @author Thomas Scheffler (yagee) */ public class MCRQLSearchUtilsTest extends MCRTestCase { /** * Test method for * {@link MCRSolrSearchUtils#getSolrQuery(MCRQuery, Document, jakarta.servlet.http.HttpServletRequest)} * . */ @Test public final void testGetSolrQuery() { MCRQuery andQuery = getMCRQuery("(state = \"submitted\") AND (state = \"published\")"); assertEquals("+state:\"submitted\" +state:\"published\"", MCRSolrSearchUtils.getSolrQuery(andQuery, andQuery.buildXML(), null).getQuery()); //MCR-994 MCRQuery orQuery = getMCRQuery("(state = \"submitted\") OR (state = \"published\")"); assertEquals("+(state:\"submitted\" state:\"published\")", MCRSolrSearchUtils.getSolrQuery(orQuery, orQuery.buildXML(), null).getQuery()); } private MCRQuery getMCRQuery(String mcrql) { LogManager.getLogger(getClass()).info("Building query from condition: {}", mcrql); Element query = new Element("query").setAttribute("numPerPage", "20"); Element conditions = new Element("conditions").setAttribute("format", "xml"); MCRCondition<Void> condition = new MCRQueryParser().parse(mcrql); query.addContent(conditions); conditions.addContent(condition.toXML()); Document queryDoc = new Document(query); return MCRQLSearchUtils.buildFormQuery(queryDoc.getRootElement()); } }
2,555
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRConditionTransformerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/test/java/org/mycore/solr/search/MCRConditionTransformerTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashSet; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.parsers.bool.MCRAndCondition; import org.mycore.parsers.bool.MCRNotCondition; import org.mycore.parsers.bool.MCROrCondition; import org.mycore.services.fieldquery.MCRQueryCondition; public class MCRConditionTransformerTest extends MCRTestCase { @Test public final void testToSolrQueryString() { HashSet<String> usedFields = new HashSet<>(); MCRQueryCondition inner1 = new MCRQueryCondition("objectType", "=", "mods"); assertEquals("+objectType:\"mods\"", MCRConditionTransformer.toSolrQueryString(inner1, usedFields)); assertTrue("usedFields did not contain 'objectType'", usedFields.contains("objectType")); MCRQueryCondition inner2 = new MCRQueryCondition("objectType", "=", "cbu"); MCROrCondition<Void> orCond = new MCROrCondition<>(inner1, inner2); usedFields.clear(); //MCR-973 check for surrounding brackets on single OR query assertEquals("+(objectType:\"mods\" objectType:\"cbu\")", MCRConditionTransformer.toSolrQueryString(orCond, usedFields)); assertTrue("usedFields did not contain 'objectType'", usedFields.contains("objectType")); MCRQueryCondition inner3 = new MCRQueryCondition("derCount", ">", "0"); MCRAndCondition<Void> andCondition = new MCRAndCondition<>(orCond, inner3); usedFields.clear(); assertEquals("+(objectType:\"mods\" objectType:\"cbu\") +derCount:{0 TO *]", MCRConditionTransformer.toSolrQueryString(andCondition, usedFields)); assertTrue("usedFields did not contain 'objectType'", usedFields.contains("objectType")); assertTrue("usedFields did not contain 'derCount'", usedFields.contains("derCount")); inner3.setOperator(">="); assertEquals("+(objectType:\"mods\" objectType:\"cbu\") +derCount:[0 TO *]", MCRConditionTransformer.toSolrQueryString(andCondition, usedFields)); inner3.setOperator("<"); assertEquals("+(objectType:\"mods\" objectType:\"cbu\") +derCount:[* TO 0}", MCRConditionTransformer.toSolrQueryString(andCondition, usedFields)); inner3.setOperator("<="); assertEquals("+(objectType:\"mods\" objectType:\"cbu\") +derCount:[* TO 0]", MCRConditionTransformer.toSolrQueryString(andCondition, usedFields)); MCRNotCondition<Void> notCond = new MCRNotCondition<>(orCond); andCondition.getChildren().remove(0); andCondition.getChildren().add(0, notCond); assertEquals("-(objectType:\"mods\" objectType:\"cbu\") +derCount:[* TO 0]", MCRConditionTransformer.toSolrQueryString(andCondition, usedFields)); } }
3,601
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrCore.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/MCRSolrCore.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.BinaryRequestWriter; import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.events.MCRShutdownHandler; /** * Core instance of a solr server. * * @author Matthias Eichner */ public class MCRSolrCore { private static final Logger LOGGER = LogManager.getLogger(MCRSolrCore.class); private static boolean USE_CONCURRENT_SERVER; protected String serverURL; protected String name; protected HttpSolrClient solrClient; protected ConcurrentUpdateSolrClient concurrentClient; static { USE_CONCURRENT_SERVER = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "ConcurrentUpdateSolrClient.Enabled", Boolean::parseBoolean); } /** * Creates a new solr server core instance. The last part of this url should be the core. * * @param serverURL * whole url e.g. http://localhost:8296/docportal * @deprecated use {@link #MCRSolrCore(String, String)} instead */ @Deprecated public MCRSolrCore(String serverURL) { if (serverURL.endsWith("/")) { serverURL = serverURL.substring(0, serverURL.length() - 1); } int i = serverURL.lastIndexOf("/") + 1; setup(serverURL.substring(0, i), serverURL.substring(i)); } /** * Creates a new solr server core instance. * * @param serverURL * base url of the solr server e.g. http://localhost:8296 * @param name * name of the core e.g. docportal */ public MCRSolrCore(String serverURL, String name) { setup(serverURL, name); } protected void setup(String serverURL, String name) { if (!serverURL.endsWith("/")) { serverURL += "/"; } this.serverURL = serverURL; this.name = name; String coreURL = getV1CoreURL(); int connectionTimeout = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "SolrClient.ConnectionTimeout", Integer::parseInt); int socketTimeout = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "SolrClient.SocketTimeout", Integer::parseInt); // default server solrClient = new HttpSolrClient.Builder(coreURL) .withConnectionTimeout(connectionTimeout) .withSocketTimeout(socketTimeout) .build(); solrClient.setRequestWriter(new BinaryRequestWriter()); // concurrent server if (USE_CONCURRENT_SERVER) { int queueSize = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "ConcurrentUpdateSolrClient.QueueSize", Integer::parseInt); int threadCount = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "ConcurrentUpdateSolrClient.ThreadCount", Integer::parseInt); concurrentClient = new ConcurrentUpdateSolrClient.Builder(coreURL) .withQueueSize(queueSize) .withConnectionTimeout(connectionTimeout) .withSocketTimeout(socketTimeout) .withThreadCount(threadCount) .build(); concurrentClient.setRequestWriter(new BinaryRequestWriter()); } // shutdown handler MCRShutdownHandler.getInstance().addCloseable(new MCRShutdownHandler.Closeable() { @Override public int getPriority() { return Integer.MIN_VALUE + 5; } @Override public void close() { shutdown(); } }); } public String getV1CoreURL() { return this.serverURL + "solr/" + this.name; } public synchronized void shutdown() { try { shutdownGracefully(solrClient); solrClient = null; } catch (SolrServerException | IOException e) { LOGGER.error("Error while shutting down SOLR client.", e); } try { shutdownGracefully(concurrentClient); concurrentClient = null; } catch (SolrServerException | IOException e) { LOGGER.error("Error while shutting down SOLR client.", e); } LOGGER.info("Solr shutdown process completed."); } private void shutdownGracefully(SolrClient client) throws SolrServerException, IOException { if (client != null) { LOGGER.info("Shutting down solr client: {}", client); client.commit(false, false); client.close(); } } /** * Returns the name of the core. */ public String getName() { return name; } public String getServerURL() { return serverURL; } /** * Returns the default solr client instance. Use this for queries. */ public HttpSolrClient getClient() { return solrClient; } /** * Returns the concurrent solr client instance. Use this for indexing. */ public SolrClient getConcurrentClient() { return concurrentClient != null ? concurrentClient : solrClient; } }
6,240
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrConstants.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/MCRSolrConstants.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr; import org.mycore.common.config.MCRConfiguration2; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrConstants { public static final String SOLR_CONFIG_PREFIX = "MCR.Solr."; // public static final String SOLR_SERVER_URL; public static final String DEFAULT_SOLR_SERVER_URL = MCRConfiguration2 .getStringOrThrow(SOLR_CONFIG_PREFIX + "ServerURL"); public static final String SOLR_CORE_PREFIX = SOLR_CONFIG_PREFIX + "Core."; public static final String SOLR_CORE_NAME_SUFFIX = ".Name"; public static final String SOLR_CORE_SERVER_SUFFIX = ".ServerURL"; public static final String SOLR_QUERY_XML_PROTOCOL_VERSION = MCRConfiguration2 .getStringOrThrow(SOLR_CONFIG_PREFIX + "XMLProtocolVersion"); public static final String SOLR_QUERY_PATH = MCRConfiguration2.getStringOrThrow(SOLR_CONFIG_PREFIX + "SelectPath"); public static final String SOLR_EXTRACT_PATH = MCRConfiguration2 .getStringOrThrow(SOLR_CONFIG_PREFIX + "ExtractPath"); public static final String SOLR_UPDATE_PATH = MCRConfiguration2.getStringOrThrow(SOLR_CONFIG_PREFIX + "UpdatePath"); public static final String SOLR_JOIN_PATTERN = "{!join from=returnId to=id}"; public static final String MAIN_CORE_TYPE = "main"; }
2,029
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/MCRSolrUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.util.regex.Pattern; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrUtils { // private static String specialChars = "!&|+-(){}[]\"~*?:\\/^"; /* '*' and '?' should always be threatened as special character */ private static String specialChars = "!&|+-(){}[]\"~:\\/^"; private static Pattern PATTERN_RESTRICTED = Pattern.compile("([\\Q" + specialChars + "\\E])"); /** * Escapes characters in search values that need to be escaped for SOLR. * @see <a href="http://lucene.apache.org/core/4_3_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#Escaping_Special_Characters">List of special characters</a> * @param value any value to look for in a field * @return null if value is null */ public static String escapeSearchValue(final String value) { if (value == null) { return null; } return PATTERN_RESTRICTED.matcher(value).replaceAll("\\\\$1"); } /** * Checks if the application uses nested documents. If so, each reindex requires * an extra deletion. Using nested documents slows the solr index performance. * * @return true if nested documents are used, otherwise false */ public static boolean useNestedDocuments() { return MCRConfiguration2.getBoolean(SOLR_CONFIG_PREFIX + "NestedDocuments").orElse(true); } public static MCRConfigurationException getCoreConfigMissingException(String coreID) { return new MCRConfigurationException( "Missing property: " + MCRSolrConstants.SOLR_CORE_PREFIX + coreID + MCRSolrConstants.SOLR_CORE_NAME_SUFFIX); } }
2,619
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrClientFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/MCRSolrClientFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; /** * @author shermann * @author Thomas Scheffler (yagee) * @author Matthias Eichner * @author Jens Kupferschmidt */ public final class MCRSolrClientFactory { private static final Logger LOGGER = LogManager.getLogger(MCRSolrClientFactory.class); private static Map<String, MCRSolrCore> CORE_MAP; static { try { CORE_MAP = Collections.synchronizedMap(loadCoresFromProperties()); } catch (Throwable t) { LOGGER.error("Exception creating solr client object", t); } } private MCRSolrClientFactory() { } /** * MCR.Solr.Core.Main.Name=cmo * MCR.Solr.Core.Classfication.Name=cmo-classification * @return a map of all cores defined in the properties. */ private static Map<String, MCRSolrCore> loadCoresFromProperties() { return MCRConfiguration2 .getPropertiesMap() .keySet() .stream() .filter(p -> p.startsWith(MCRSolrConstants.SOLR_CORE_PREFIX)) .map(cp -> cp.substring(MCRSolrConstants.SOLR_CORE_PREFIX.length())) .map(cp -> { int indexOfDot = cp.indexOf("."); return indexOfDot != -1 ? cp.substring(0, indexOfDot) : cp; }) .distinct() .collect(Collectors.toMap(coreID -> coreID, MCRSolrClientFactory::initializeSolrCore)); } private static MCRSolrCore initializeSolrCore(String coreID) { final String coreNameKey = MCRSolrConstants.SOLR_CORE_PREFIX + coreID + MCRSolrConstants.SOLR_CORE_NAME_SUFFIX; final String coreServerKey = MCRSolrConstants.SOLR_CORE_PREFIX + coreID + MCRSolrConstants.SOLR_CORE_SERVER_SUFFIX; String coreName = MCRConfiguration2.getString(coreNameKey) .orElseThrow(() -> new MCRConfigurationException("Missing property " + coreNameKey)); String coreServer = MCRConfiguration2.getString(coreServerKey) .orElse(MCRSolrConstants.DEFAULT_SOLR_SERVER_URL); return new MCRSolrCore(coreServer, coreName); } public static MCRSolrCore addCore(String server, String coreName, String coreID) { final MCRSolrCore core = new MCRSolrCore(server, coreName); CORE_MAP.put(coreID, core); return core; } /** * Add a SOLR core instance to the list * * @param core the MCRSolrCore instance */ public static void add(String coreID, MCRSolrCore core) { CORE_MAP.put(coreID, core); } /** * Remove a SOLR core instance from the list * * @param coreID the name of the MCRSolrCore instance */ public static Optional<MCRSolrCore> remove(String coreID) { return Optional.ofNullable(CORE_MAP.remove(coreID)); } /** * @param coreID the id of the core * @return a core with a specific id */ public static Optional<MCRSolrCore> get(String coreID) { return Optional.ofNullable(CORE_MAP.get(coreID)); } public static MCRSolrCore getMainSolrCore() { return get(MCRSolrConstants.MAIN_CORE_TYPE) .orElseThrow(() -> new MCRConfigurationException("The core main is not configured!")); } /** * Returns the solr client of the default core. */ public static SolrClient getMainSolrClient() { return getMainSolrCore().getClient(); } /** * Returns the concurrent solr client of the default core. */ public static SolrClient getMainConcurrentSolrClient() { return getMainSolrCore().getConcurrentClient(); } /** * @return the read only core map wich contains the coreId and the core */ public static Map<String, MCRSolrCore> getCoreMap() { return Collections.unmodifiableMap(CORE_MAP); } }
4,900
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXMLFunctions.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/MCRXMLFunctions.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr; import java.io.IOException; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; /** * @author shermann * */ public class MCRXMLFunctions { /** * Convenience method for retrieving the result count for a given solr query. * * @param q the query to execute (in solr syntax) * * @return the amount of documents matching the given query */ public static long getNumFound(String q) throws SolrServerException, IOException { if (q == null || q.length() == 0) { throw new IllegalArgumentException("The query string must not be null"); } SolrQuery solrQuery = new SolrQuery(q); solrQuery.set("rows", 0); QueryResponse queryResponse = MCRSolrClientFactory.getMainSolrClient().query(solrQuery); return queryResponse.getResults().getNumFound(); } /** * @param q the query to execute (in solr syntax) * @return the identifier of the first document matching the query */ public static String getIdentifierOfFirst(String q) throws SolrServerException, IOException { if (q == null || q.length() == 0) { throw new IllegalArgumentException("The query string must not be null"); } SolrQuery solrQuery = new SolrQuery(q); solrQuery.set("rows", 1); QueryResponse queryResponse; queryResponse = MCRSolrClientFactory.getMainSolrClient().query(solrQuery); if (queryResponse.getResults().getNumFound() == 0) { return null; } return queryResponse.getResults().get(0).get("id").toString(); } }
2,468
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrConfigReloader.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/schema/MCRSolrConfigReloader.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.schema; import static java.util.Map.entry; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationInputStream; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrCore; import org.mycore.solr.MCRSolrUtils; import com.google.common.io.ByteStreams; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; /** * This class provides methods to reload a SOLR configuration using the SOLR configuration API * see https://lucene.apache.org/solr/guide/8_6/config-api.html * * @author Robert Stephan * @author Jens Kupferschmidt */ public class MCRSolrConfigReloader { /** from https://lucene.apache.org/solr/guide/8_6/config-api.html key = lowercase object name from config api command (add-*, update-* delete-*) value = keyName in SOLR config json (retrieved via URL ../core-name/config) */ private static final Map<String, String> SOLR_CONFIG_OBJECT_NAMES = Map.ofEntries( entry("requesthandler", "requestHandler"), //checked -> id in subfield "name" entry("searchcomponent", "searchComponent"), //checked -> id in subfield "name" entry("initparams", "initParams"), //checked - id in key (TODO special handling) entry("queryresponsewriter", "queryResponseWriter"), //checked -> id in subfield "name" entry("queryparser", "queryParser"), entry("valuesourceparser", "valueSourceParser"), entry("transformer", "transformer"), entry("updateprocessor", "updateProcessor"), //checked -> id in subfield "name" entry("queryconverter", "queryConverter"), entry("listener", "listener"), //checked -> id in subfield "event" -> special handling entry("runtimelib", "runtimeLib")); private static final List<String> SOLR_CONFIG_PROPERTY_COMMANDS = List.of("set-property", "unset-property"); private static final Logger LOGGER = LogManager.getLogger(); private static final String SOLR_CONFIG_UPDATE_FILE_NAME = "solr-config.json"; /** * Removed items from SOLR configuration overlay. This removal works over all in the property * MCR.Solr.ObserverConfigTypes defined SOLR configuration parts. For each entry the * method will process a SOLR delete command via API. * * @param configType the name of the configuration directory containing the SOLR core configuration * @param coreID the ID of the core, which the configuration should be applied to */ public static void reset(String configType, String coreID) { LOGGER.info(() -> "Resetting config definitions for core " + coreID + " using configuration " + configType); String coreURL = MCRSolrClientFactory.get(coreID) .map(MCRSolrCore::getV1CoreURL) .orElseThrow(() -> MCRSolrUtils.getCoreConfigMissingException(coreID)); JsonObject currentSolrConfig = retrieveCurrentSolrConfigOverlay(coreURL); JsonObject configPart = currentSolrConfig.getAsJsonObject("overlay"); for (String observedType : getObserverConfigTypes()) { JsonObject overlaySection = configPart.getAsJsonObject(observedType); if (overlaySection == null) { continue; } Set<Map.Entry<String, JsonElement>> configuredComponents = overlaySection.entrySet(); final String deleteSectionCommand = "delete-" + observedType.toLowerCase(Locale.ROOT); if (configuredComponents.isEmpty() || !isKnownSolrConfigCommmand(deleteSectionCommand)) { continue; } for (Map.Entry<String, JsonElement> configuredComponent : configuredComponents) { final JsonObject deleteCommand = new JsonObject(); deleteCommand.addProperty(deleteSectionCommand, configuredComponent.getKey()); LOGGER.debug(deleteCommand); try { executeSolrCommand(coreURL, deleteCommand); } catch (IOException e) { LOGGER.error(() -> "Exception while executing '" + deleteCommand + "'.", e); } } } } /** * This method modified the SOLR configuration definition based on all solr/{coreType}/solr-config.json * in the MyCoRe-Maven modules resource path. * * @param configType the name of the configuration directory containing the SOLR core configuration * @param coreID the ID of the core, which the configuration should be applied to */ public static void processConfigFiles(String configType, String coreID) { LOGGER.info(() -> "Load config definitions for core " + coreID + " using configuration " + configType); try { String coreURL = MCRSolrClientFactory.get(coreID) .orElseThrow(() -> MCRSolrUtils.getCoreConfigMissingException(coreID)).getV1CoreURL(); List<String> observedTypes = getObserverConfigTypes(); JsonObject currentSolrConfig = retrieveCurrentSolrConfig(coreURL); Map<String, byte[]> configFileContents = MCRConfigurationInputStream.getConfigFileContents( "solr/" + configType + "/" + SOLR_CONFIG_UPDATE_FILE_NAME); for (byte[] configFileData : configFileContents.values()) { String content = new String(configFileData, StandardCharsets.UTF_8); JsonElement json = JsonParser.parseString(content); if (!json.isJsonArray()) { JsonElement e = json; json = new JsonArray(); json.getAsJsonArray().add(e); } for (JsonElement command : json.getAsJsonArray()) { LOGGER.debug(command); processConfigCommand(coreURL, command, currentSolrConfig, observedTypes); } } } catch (IOException e) { LOGGER.error(e); } } /** * get the content of property MCR.Solr.ObserverConfigTypes as List * @return the list of observed SOLR configuration types, a.k.a. top-level sections of config API */ private static List<String> getObserverConfigTypes() { return MCRConfiguration2 .getString("MCR.Solr.ObserverConfigTypes") .map(MCRConfiguration2::splitValue) .orElseGet(Stream::empty) .collect(Collectors.toList()); } /** * processes a single SOLR configuration command * @param coreURL - the URL of the core * @param command - the command in JSON syntax */ private static void processConfigCommand(String coreURL, JsonElement command, JsonObject currentSolrConfig, List<String> observedTypes) { if (command.isJsonObject()) { try { //get first and only? property of the command object final JsonObject commandJsonObject = command.getAsJsonObject(); Entry<String, JsonElement> commandObject = commandJsonObject.entrySet().iterator().next(); final String configCommand = commandObject.getKey(); final String configType = StringUtils.substringAfter(configCommand, "add-"); if (isKnownSolrConfigCommmand(configCommand)) { if (observedTypes.contains(configType) && configCommand.startsWith("add-") && commandObject.getValue() instanceof JsonObject) { final JsonElement configCommandName = commandObject.getValue().getAsJsonObject().get("name"); if (isConfigTypeAlreadyAdded(configType, configCommandName, currentSolrConfig)) { LOGGER.info(() -> "Current configuration has already an " + configCommand + " with name " + configCommandName.getAsString() + ". Rewrite config command as update-" + configType); commandJsonObject.add("update-" + configType, commandJsonObject.get(configCommand)); commandJsonObject.remove(configCommand); } } executeSolrCommand(coreURL, commandJsonObject); } } catch (IOException e) { LOGGER.error(e); } } } /** * Sends a command to SOLR server * @param coreURL to which the command will be send * @param command the command * @throws UnsupportedEncodingException if command encoding is not supported */ private static void executeSolrCommand(String coreURL, JsonObject command) throws UnsupportedEncodingException { HttpPost post = new HttpPost(coreURL + "/config"); post.setHeader("Content-type", "application/json"); post.setEntity(new StringEntity(command.toString())); String commandprefix = command.keySet().stream().findFirst().orElse("unknown command"); HttpResponse response; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { response = httpClient.execute(post); String respContent = new String(ByteStreams.toByteArray(response.getEntity().getContent()), StandardCharsets.UTF_8); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LOGGER.debug(() -> "SOLR config " + commandprefix + " command was successful \n" + respContent); } else { LOGGER .error(() -> "SOLR config " + commandprefix + " error: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase() + "\n" + respContent); } } catch (IOException e) { LOGGER.error(() -> "Could not execute the following Solr config command:\n" + command, e); } } /** * Checks if a given configType with passed name already was added to current SORL configuration * @param configType - Type of localized SOLR component e.g. request handlers, search components * @param name - identification of configuration type * @param solrConfig - current SOLR configuration * @return - Is there already an entry in current SOLR configuration */ private static boolean isConfigTypeAlreadyAdded(String configType, JsonElement name, JsonObject solrConfig) { JsonObject configPart = solrConfig.getAsJsonObject("config"); JsonObject observedConfig = configPart.getAsJsonObject(configType); return observedConfig.has(name.getAsString()); } /** * retrieves the current SOLR configuration for the given core * @param coreURL from which the current SOLR configuration will be load * @return the configuration as JSON object */ private static JsonObject retrieveCurrentSolrConfig(String coreURL) { HttpGet getConfig = new HttpGet(coreURL + "/config"); return getJSON(getConfig); } /** * retrieves the current SOLR configuration overlay for the given core * @param coreURL from which the current SOLR configuration will be load * @return the configuration as JSON object */ private static JsonObject retrieveCurrentSolrConfigOverlay(String coreURL) { HttpGet getConfig = new HttpGet(coreURL + "/config/overlay"); return getJSON(getConfig); } private static JsonObject getJSON(HttpGet getConfig) { JsonObject convertedObject = null; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { CloseableHttpResponse response = httpClient.execute(getConfig); StatusLine statusLine = response.getStatusLine(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String configAsString = EntityUtils.toString(response.getEntity(), "UTF-8"); convertedObject = new Gson().fromJson(configAsString, JsonObject.class); } else { LOGGER.error(() -> "Could not retrieve current Solr configuration from solr server. Http Status: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); } } catch (IOException e) { LOGGER.error("Could not read current Solr configuration", e); } catch (JsonSyntaxException e) { LOGGER.error("Current json configuration is not a valid json", e); } return convertedObject; } /** * * @param cmd the SOLR API command * @return true, if the command is in the list of known SOLR commands. */ private static boolean isKnownSolrConfigCommmand(String cmd) { String cfgObjName = cmd.substring(cmd.indexOf("-") + 1).toLowerCase(Locale.ROOT); return ((cmd.startsWith("add-") || cmd.startsWith("update-") || cmd.startsWith("delete-")) && (SOLR_CONFIG_OBJECT_NAMES.containsKey(cfgObjName))) || SOLR_CONFIG_PROPERTY_COMMANDS.contains(cmd); } }
14,857
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrSchemaReloader.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/schema/MCRSolrSchemaReloader.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.schema; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.schema.SchemaRequest; import org.apache.solr.client.solrj.response.schema.FieldTypeRepresentation; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.config.MCRConfigurationInputStream; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrCore; import org.mycore.solr.MCRSolrUtils; import com.google.common.io.ByteStreams; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; /** * This class provides methods to reload a SOLR schema using the SOLR schema API * see https://lucene.apache.org/solr/guide/7_3/schema-api.html * * @author Robert Stephan * @author Jens Kupferschmidt */ public class MCRSolrSchemaReloader { private static Logger LOGGER = LogManager.getLogger(MCRSolrSchemaReloader.class); private static String SOLR_SCHEMA_UPDATE_FILE_NAME = "solr-schema.json"; private static List<String> SOLR_DEFAULT_FIELDS = Arrays.asList("id", "_version_", "_root_", "_text_"); private static List<String> SOLR_DEFAULT_FIELDTYPES = Arrays.asList( "plong", "string", "text_general"); /** * Removes all fields, dynamicFields, copyFields and fieldTypes in the SOLR schema for the given core. The fields, * dynamicFields, and types in the lists SOLR_DEFAULT_FIELDS, SOLR_DEFAULT_DYNAMIC_FIELDS, * SOLR_DEFAULT_DYNAMIC_FIELDS are excluded from remove. * * @param configType the name of the configuration directory containg the Solr core configuration * @param coreID the ID of the core, which the configuration should be applied to */ public static void reset(String configType, String coreID) { LOGGER.info("Resetting SOLR schema for core " + coreID + " using configuration " + configType); try { SolrClient solrClient = MCRSolrClientFactory.get(coreID).map(MCRSolrCore::getClient) .orElseThrow(() -> new MCRConfigurationException("The core " + coreID + " is not configured!")); deleteCopyFields(solrClient); LOGGER.debug("CopyFields cleaned for core " + coreID + " for configuration " + configType); deleteFields(solrClient); LOGGER.debug("Fields cleaned for core " + coreID + " for configuration " + configType); deleteDynamicFields(solrClient); LOGGER.debug("DynamicFields cleaned for core " + coreID + " for configuration " + configType); deleteFieldTypes(solrClient); LOGGER.debug("FieldTypes cleaned for core " + coreID + " for configuration " + configType); } catch (IOException | SolrServerException e) { LOGGER.error(e); } } private static void deleteFieldTypes(SolrClient solrClient) throws SolrServerException, IOException { SchemaRequest.FieldTypes fieldTypesReq = new SchemaRequest.FieldTypes(); for (FieldTypeRepresentation fieldType : fieldTypesReq.process(solrClient).getFieldTypes()) { String fieldTypeName = fieldType.getAttributes().get("name").toString(); if (!SOLR_DEFAULT_FIELDTYPES.contains(fieldTypeName)) { LOGGER.debug("remove SOLR FieldType " + fieldTypeName); SchemaRequest.DeleteFieldType delField = new SchemaRequest.DeleteFieldType(fieldTypeName); delField.process(solrClient); } } } private static void deleteDynamicFields(SolrClient solrClient) throws SolrServerException, IOException { SchemaRequest.DynamicFields dynFieldsReq = new SchemaRequest.DynamicFields(); for (Map<String, Object> field : dynFieldsReq.process(solrClient).getDynamicFields()) { String fieldName = field.get("name").toString(); LOGGER.debug("remove SOLR DynamicField " + fieldName); SchemaRequest.DeleteDynamicField delField = new SchemaRequest.DeleteDynamicField(fieldName); delField.process(solrClient); } } private static void deleteFields(SolrClient solrClient) throws SolrServerException, IOException { SchemaRequest.Fields fieldsReq = new SchemaRequest.Fields(); for (Map<String, Object> field : fieldsReq.process(solrClient).getFields()) { String fieldName = field.get("name").toString(); if (!SOLR_DEFAULT_FIELDS.contains(fieldName)) { LOGGER.debug("remove SOLR Field " + fieldName); SchemaRequest.DeleteField delField = new SchemaRequest.DeleteField(fieldName); delField.process(solrClient); } } } private static void deleteCopyFields(SolrClient solrClient) throws SolrServerException, IOException { SchemaRequest.CopyFields copyFieldsReq = new SchemaRequest.CopyFields(); for (Map<String, Object> copyField : copyFieldsReq.process(solrClient).getCopyFields()) { String fieldSrc = copyField.get("source").toString(); List<String> fieldDest = new ArrayList<>(); fieldDest.add(copyField.get("dest").toString()); LOGGER.debug("remove SOLR CopyField " + fieldSrc + " --> " + fieldDest.get(0)); SchemaRequest.DeleteCopyField delCopyField = new SchemaRequest.DeleteCopyField(fieldSrc, fieldDest); delCopyField.process(solrClient); } } /** * This method modified the SOLR schema definition based on all solr/{coreType}/solr-schema.json * in the MyCoRe-Maven modules resource path. * * @param configType the name of the configuration directory containg the Solr core configuration * @param coreID the ID of the core, which the configuration should be applied to */ public static void processSchemaFiles(String configType, String coreID) { MCRSolrCore solrCore = MCRSolrClientFactory.get(coreID) .orElseThrow(() -> MCRSolrUtils.getCoreConfigMissingException(coreID)); LOGGER.info("Load schema definitions for core " + coreID + " using configuration " + configType); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { Collection<byte[]> schemaFileContents = MCRConfigurationInputStream.getConfigFileContents( "solr/" + configType + "/" + SOLR_SCHEMA_UPDATE_FILE_NAME).values(); for (byte[] schemaFileData : schemaFileContents) { InputStreamReader schemaReader = new InputStreamReader(new ByteArrayInputStream(schemaFileData), StandardCharsets.UTF_8); JsonElement json = JsonParser.parseReader(schemaReader); if (!json.isJsonArray()) { JsonElement e = json; json = new JsonArray(); json.getAsJsonArray().add(e); } for (JsonElement e : json.getAsJsonArray()) { LOGGER.debug(e); String command = e.toString(); HttpPost post = new HttpPost(solrCore.getV1CoreURL() + "/schema"); post.setHeader("Content-type", "application/json"); post.setEntity(new StringEntity(command)); String commandprefix = command.indexOf('-') != -1 ? command.substring(2, command.indexOf('-')) : "unknown command"; try (CloseableHttpResponse response = httpClient.execute(post)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String respContent = new String(ByteStreams.toByteArray(response.getEntity().getContent()), StandardCharsets.UTF_8); LOGGER.debug("SOLR schema " + commandprefix + " successful \n{}", respContent); } else { String respContent = new String(ByteStreams.toByteArray(response.getEntity().getContent()), StandardCharsets.UTF_8); LOGGER .error("SOLR schema " + commandprefix + " error: {} {}\n{}", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), respContent); } } } } } catch (IOException e) { LOGGER.error(e); } } }
10,035
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrQueryResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/common/xml/MCRSolrQueryResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.common.xml; import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.transform.Source; import javax.xml.transform.URIResolver; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.mycore.common.content.MCRURLContent; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrCore; import org.mycore.solr.search.MCRSolrURL; /** * <pre> * Usage: solr:{optional core}:query * Example: solr:q=%2BobjectType%3Ajpjournal * * Usage: solr:{optional core}:{optional requestHandler:&lt;requestHandler&gt;}:query * Example: solr:requestHandler:browse-inventory:q=%2BobjectType%3Ajpjournal * solr:mysolrcore:requestHandler:browse-inventory:q=%2BobjectType%3Ajpjournal * </pre> * * @author Sebastian Hofmann */ public class MCRSolrQueryResolver implements URIResolver { public static final String QUERY_GROUP_NAME = "query"; public static final String CORE_GROUP_NAME = "core"; private static final String REQUEST_HANDLER_QUALIFIER = "requestHandler"; public static final String REQUEST_HANDLER_GROUP_NAME = REQUEST_HANDLER_QUALIFIER; // not allowed chars for cores are / \ and : according to // https://stackoverflow.com/questions/29977519/what-makes-an-invalid-core-name // assume they are the same for the requestHandler private static final Pattern URI_PATTERN = Pattern .compile("\\Asolr:((?!" + REQUEST_HANDLER_QUALIFIER + ")(?<" + CORE_GROUP_NAME + ">[^/:\\\\]+):)?(" + REQUEST_HANDLER_QUALIFIER + ":(?<" + REQUEST_HANDLER_GROUP_NAME + ">[^/:\\\\]+):)?(?<" + QUERY_GROUP_NAME + ">.+)\\z"); // TODO: remove this pattern in 2023.06 release private static final Pattern OLD_URI_PATTERN = Pattern .compile("\\Asolr:((?!" + REQUEST_HANDLER_QUALIFIER + ")(?<" + CORE_GROUP_NAME + ">[a-zA-Z0-9-_]+):)?(" + REQUEST_HANDLER_QUALIFIER + ":(?<" + REQUEST_HANDLER_GROUP_NAME + ">[a-zA-Z0-9-_]+):)?(?<" + QUERY_GROUP_NAME + ">.+)\\z"); private static final Logger LOGGER = LogManager.getLogger(); @Override public Source resolve(String href, String base) { Matcher matcher = OLD_URI_PATTERN.matcher(href); Matcher newMatcher = URI_PATTERN.matcher(href); if (matcher.matches()) { Optional<String> core = Optional.ofNullable(matcher.group(CORE_GROUP_NAME)); Optional<String> requestHandler = Optional.ofNullable(matcher.group(REQUEST_HANDLER_GROUP_NAME)); Optional<String> query = Optional.ofNullable(matcher.group(QUERY_GROUP_NAME)); if (!newMatcher.matches()) { printMismatchWarning(href); } else { String newCore = newMatcher.group(CORE_GROUP_NAME); String newRequestHandler = newMatcher.group(REQUEST_HANDLER_GROUP_NAME); String newQuery = newMatcher.group(QUERY_GROUP_NAME); if (!Objects.equals(core.orElse(null), newCore) || !Objects.equals(requestHandler.orElse(null), newRequestHandler) || !Objects.equals(query.orElse(null), newQuery)) { printMismatchWarning(href); } } HttpSolrClient client = core.flatMap(MCRSolrClientFactory::get) .map(MCRSolrCore::getClient) .orElse((HttpSolrClient) MCRSolrClientFactory.getMainSolrClient()); if (query.isPresent()) { MCRSolrURL solrURL = new MCRSolrURL(client, query.get()); requestHandler.map("/"::concat).ifPresent(solrURL::setRequestHandler); return new MCRURLContent(solrURL.getUrl()).getSource(); } } throw new IllegalArgumentException("Did not understand uri: " + href); } private void printMismatchWarning(String href) { LOGGER.warn("The uri {} is probably not encoded correctly. See (MCR-2872)", href); } }
4,854
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIDMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/idmapper/MCRSolrIDMapper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.idmapper; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.ModifiableSolrParams; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.annotation.MCRProperty; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.frontend.idmapper.MCRDefaultIDMapper; import org.mycore.frontend.idmapper.MCRIDMapper; import org.mycore.solr.MCRSolrClientFactory; /** * implementation of an MCRIDMapper * * It uses Solr to retrieve the real id from the given input string * * @author Robert Stephan */ public class MCRSolrIDMapper extends MCRDefaultIDMapper implements MCRIDMapper { private static final Logger LOGGER = LogManager.getLogger(); private Set<String> objectSolrFields = Collections.emptySet(); private Set<String> derivateSolrFields = Collections.emptySet(); //property MCR.RestAPI.V2.AlternativeIdentifier.Objects.Keys deprecated in 2024.06 @MCRProperty(name = "ObjectSolrFields", required = false, defaultName = "MCR.RestAPI.V2.AlternativeIdentifier.Objects.Keys") public void setObjectSolrFields(String fields) { objectSolrFields = Stream.ofNullable(fields).flatMap(MCRConfiguration2::splitValue).collect(Collectors.toSet()); } //property MCR.RestAPI.V2.AlternativeIdentifier.Derivate.Keys deprecated in 2024.06 @MCRProperty(name = "DerivateSolrFields", required = false, defaultName = "MCR.RestAPI.V2.AlternativeIdentifier.Derivates.Keys") public void setDerivateSolrFields(String fields) { derivateSolrFields = Stream.ofNullable(fields).flatMap(MCRConfiguration2::splitValue).collect(Collectors.toSet()); } @Override public Optional<MCRObjectID> mapMCRObjectID(String mcrid) { String solrObjid = retrieveMCRObjectIDfromSOLR(mcrid); return super.mapMCRObjectID(solrObjid); } @Override public Optional<MCRObjectID> mapMCRDerivateID(MCRObjectID mcrObjId, String derid) { String solrDerid = retrieveMCRDerivateIDfromSOLR(mcrObjId, derid); return super.mapMCRDerivateID(mcrObjId, solrDerid); } /** * returns the input if the id syntax does not match and no solr keys are defined */ private String retrieveMCRObjectIDfromSOLR(String mcrid) { String result = mcrid; if (mcrid != null && mcrid.contains(":") && !objectSolrFields.isEmpty()) { String key = mcrid.substring(0, mcrid.indexOf(":")); String value = mcrid.substring(mcrid.indexOf(":") + 1); if (objectSolrFields.contains(key)) { ModifiableSolrParams params = new ModifiableSolrParams(); params.set("start", 0); params.set("rows", 1); params.set("fl", "id"); params.set("fq", "objectKind:mycoreobject"); params.set("q", key + ":" + ClientUtils.escapeQueryChars(value)); QueryResponse solrResponse = null; try { solrResponse = MCRSolrClientFactory.getMainSolrClient().query(params); } catch (Exception e) { LOGGER.error("Error retrieving object id from SOLR", e); } if (solrResponse == null) { return result; } SolrDocumentList solrResults = solrResponse.getResults(); if (solrResults.getNumFound() == 1) { result = String.valueOf(solrResults.get(0).getFieldValue("id")); } if (solrResults.getNumFound() == 0) { LOGGER.info("ERROR: No MyCoRe ID found for query " + mcrid); } if (solrResults.getNumFound() > 1) { LOGGER.info("ERROR: Multiple IDs found for query " + mcrid); } } } return result; } /** * returns the input if the id syntax does not match and no solr keys are defined */ private String retrieveMCRDerivateIDfromSOLR(MCRObjectID mcrObjId, String derid) { String result = derid; if (mcrObjId != null && derid != null && derid.contains(":") && !derivateSolrFields.isEmpty()) { String key = derid.substring(0, derid.indexOf(":")); String value = derid.substring(derid.indexOf(":") + 1); if (derivateSolrFields.contains(key)) { ModifiableSolrParams params = new ModifiableSolrParams(); params.set("start", 0); params.set("rows", 1); params.set("fl", "id"); params.set("fq", "objectKind:mycorederivate"); params.set("fq", "returnId:" + mcrObjId.toString()); params.set("q", key + ":" + ClientUtils.escapeQueryChars(value)); params.set("sort", "derivateOrder asc"); QueryResponse solrResponse = null; try { solrResponse = MCRSolrClientFactory.getMainSolrClient().query(params); } catch (Exception e) { LOGGER.error("Error retrieving derivate id from SOLR", e); } if (solrResponse == null) { return result; } SolrDocumentList solrResults = solrResponse.getResults(); if (solrResults.getNumFound() == 1) { result = String.valueOf(solrResults.get(0).getFieldValue("id")); } if (solrResults.getNumFound() == 0) { LOGGER.info("ERROR: No MyCoRe Derivate ID found for query " + derid); } if (solrResults.getNumFound() > 1) { LOGGER.info("ERROR: Multiple IDs found for query " + derid); } } } return result; } }
7,008
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/proxy/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * {@link org.mycore.solr.proxy.MCRSolrProxyServlet} and supporting classes */ package org.mycore.solr.proxy;
878
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrProxyServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/proxy/MCRSolrProxyServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.proxy; import static org.mycore.access.MCRAccessManager.PERMISSION_READ; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import static org.mycore.solr.MCRSolrConstants.SOLR_QUERY_PATH; import static org.mycore.solr.MCRSolrConstants.SOLR_QUERY_XML_PROTOCOL_VERSION; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.text.MessageFormat; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.xml.transform.TransformerException; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.protocol.HTTP; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.MultiMapSolrParams; import org.apache.solr.common.util.NamedList; import org.jdom2.Document; import org.jdom2.Element; import org.mycore.access.MCRAccessManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRStreamContent; import org.mycore.common.xml.MCRLayoutService; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.services.http.MCRHttpUtils; import org.mycore.services.http.MCRIdleConnectionMonitorThread; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrConstants; import org.xml.sax.SAXException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This class implements a proxy for access to the SOLR backend.<br><br> * * With the following configuration properties * you can manipulate the response header. The entries will be replace the attributes of the incomming header. * If the new attribute text is empty, it will be remove the attribute.<br><br> * MCR.Solr.HTTPResponseHeader.{response_header_attribute_name}={new_response_header_attribute} * MCR.Solr.HTTPResponseHeader....=<br><br> * * You can set the maximum of connections to the SOLR server with the property<br><br> * MCR.Solr.SelectProxy.MaxConnections={number} */ public class MCRSolrProxyServlet extends MCRServlet { static final Logger LOGGER = LogManager.getLogger(MCRSolrProxyServlet.class); private static final long serialVersionUID = 1L; /** * Attribute key to store Query parameters as <code>Map&lt;String, String[]&gt;</code> for SOLR. This takes * precedence over any {@link HttpServletRequest} parameter. */ public static final String MAP_KEY = MCRSolrProxyServlet.class.getName() + ".map"; /** * Attribute key to store a {@link SolrQuery}. This takes precedence over {@link #MAP_KEY} or any * {@link HttpServletRequest} parameter. */ public static final String QUERY_KEY = MCRSolrProxyServlet.class.getName() + ".query"; public static final String QUERY_HANDLER_PAR_NAME = "qt"; public static final String QUERY_CORE_PARAMETER = "core"; private static int MAX_CONNECTIONS = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "SelectProxy.MaxConnections", Integer::parseInt); private static Map<String, String> NEW_HTTP_RESPONSE_HEADER = MCRConfiguration2 .getSubPropertiesMap(SOLR_CONFIG_PREFIX + "HTTPResponseHeader."); private CloseableHttpClient httpClient; private MCRIdleConnectionMonitorThread idleConnectionMonitorThread; private Set<String> queryHandlerWhitelist; private PoolingHttpClientConnectionManager httpClientConnectionManager; @Override protected void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); HttpServletResponse resp = job.getResponse(); //handle redirects if (request.getParameter(QUERY_HANDLER_PAR_NAME) != null || request.getAttribute(MAP_KEY) != null) { //redirect to Request Handler redirectToQueryHandler(request, resp); return; } Document input = (Document) request.getAttribute("MCRXEditorSubmission"); if (input != null) { redirectToQueryHandler(input, resp); return; } String queryHandlerPath = request.getPathInfo(); if (queryHandlerPath == null) { boolean refresh = "true".equals(getProperty(request, "refresh")); if (refresh) { updateQueryHandlerMap(resp); return; } redirectToQueryHandler(request, resp); return; } //end of redirects if (!queryHandlerWhitelist.contains(queryHandlerPath)) { // query handler path is not registered and therefore not allowed resp.sendError(HttpServletResponse.SC_FORBIDDEN, "No access to " + queryHandlerPath); return; } String ruleID = "solr:" + queryHandlerPath; if (MCRAccessManager.hasRule(ruleID, PERMISSION_READ) && !MCRAccessManager.checkPermission(ruleID, PERMISSION_READ)) { job.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); return; } handleQuery(queryHandlerPath, request, resp); } /** * redirects to query handler by using value of 'qt' parameter */ private static void redirectToQueryHandler(HttpServletRequest request, HttpServletResponse resp) throws IOException { ModifiableSolrParams solrQueryParameter = getSolrQueryParameter(request); String queryHandlerPath = solrQueryParameter.get(QUERY_HANDLER_PAR_NAME, SOLR_QUERY_PATH); solrQueryParameter.remove(QUERY_HANDLER_PAR_NAME); Map<String, String[]> parameters = toMultiMap(solrQueryParameter); doRedirectToQueryHandler(resp, queryHandlerPath, parameters); } static Map<String, String[]> toMultiMap(ModifiableSolrParams solrQueryParameter) { NamedList<Object> namedList = solrQueryParameter.toNamedList(); //disabled for MCR-953 and https://issues.apache.org/jira/browse/SOLR-7508 //Map<String, String[]> parameters = ModifiableSolrParams.toMultiMap(namedList); HashMap<String, String[]> parameters = new HashMap<>(); for (int i = 0; i < namedList.size(); i++) { String name = namedList.getName(i); Object val = namedList.getVal(i); if (val instanceof String[] strings) { MultiMapSolrParams.addParam(name, strings, parameters); } else { MultiMapSolrParams.addParam(name, val.toString(), parameters); } } //end of fix return parameters; } /** * redirects to query handler by using xeditor input document */ private static void redirectToQueryHandler(Document input, HttpServletResponse resp) throws IOException { LinkedHashMap<String, String[]> parameters = new LinkedHashMap<>(); List<Element> children = input.getRootElement().getChildren(); for (Element param : children) { String attribute = param.getAttributeValue("name"); if (attribute != null) { parameters.put(attribute, new String[] { param.getTextTrim() }); } } String queryHandlerPath = parameters.get(QUERY_HANDLER_PAR_NAME)[0]; parameters.remove("qt"); doRedirectToQueryHandler(resp, queryHandlerPath, parameters); } /** * used by */ private static void doRedirectToQueryHandler(HttpServletResponse resp, String queryHandlerPath, Map<String, String[]> parameters) throws IOException { String requestURL = new MessageFormat("{0}solr{1}{2}", Locale.ROOT) .format(new Object[] { getServletBaseURL(), queryHandlerPath, toSolrParams(parameters).toQueryString() }); LOGGER.info("Redirect to: {}", requestURL); resp.sendRedirect(resp.encodeRedirectURL(requestURL)); } private void handleQuery(String queryHandlerPath, HttpServletRequest request, HttpServletResponse resp) throws IOException, TransformerException, SAXException { ModifiableSolrParams solrParameter = getSolrQueryParameter(request); filterParams(solrParameter); HttpGet solrHttpMethod = MCRSolrProxyServlet.getSolrHttpMethod(queryHandlerPath, solrParameter, Optional.ofNullable(request.getParameter(QUERY_CORE_PARAMETER)).orElse(MCRSolrConstants.MAIN_CORE_TYPE)); try { LOGGER.info("Sending Request: {}", solrHttpMethod.getURI()); HttpResponse response = httpClient.execute(solrHttpMethod); int statusCode = response.getStatusLine().getStatusCode(); // set status code resp.setStatus(statusCode); boolean isXML = response.getFirstHeader(HTTP.CONTENT_TYPE).getValue().contains("/xml"); boolean justCopyInput = !isXML; // set all headers for (Header header : response.getAllHeaders()) { LOGGER.debug("SOLR response header: {} - {}", header.getName(), header.getValue()); String headerName = header.getName(); if (NEW_HTTP_RESPONSE_HEADER.containsKey(headerName)) { String headerValue = NEW_HTTP_RESPONSE_HEADER.get(headerName); if (headerValue != null && headerValue.length() > 0) { resp.setHeader(headerName, headerValue); } } else { resp.setHeader(header.getName(), header.getValue()); } } HttpEntity solrResponseEntity = response.getEntity(); if (solrResponseEntity != null) { try (InputStream solrResponseStream = solrResponseEntity.getContent()) { if (justCopyInput) { // copy solr response to servlet outputstream OutputStream servletOutput = resp.getOutputStream(); IOUtils.copy(solrResponseStream, servletOutput); } else { MCRStreamContent solrResponse = new MCRStreamContent(solrResponseStream, solrHttpMethod.getURI().toString(), "response"); MCRLayoutService.instance().doLayout(request, resp, solrResponse); } } } } catch (IOException ex) { solrHttpMethod.abort(); throw ex; } solrHttpMethod.releaseConnection(); } private void filterParams(ModifiableSolrParams solrParameter) { MCRConfiguration2.getString("MCR.Solr.Disallowed.Facets") .ifPresent(disallowedFacets -> MCRConfiguration2.splitValue(disallowedFacets) .forEach(disallowedFacet -> solrParameter.remove("facet.field", disallowedFacet))); } private void updateQueryHandlerMap(HttpServletResponse resp) throws IOException { this.updateQueryHandlerMap(); PrintWriter writer = resp.getWriter(); queryHandlerWhitelist.forEach(handler -> writer.append(handler).append('\n')); } private void updateQueryHandlerMap() { List<String> whitelistPropertyList = MCRConfiguration2.getString(SOLR_CONFIG_PREFIX + "Proxy.WhiteList") .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElseGet(() -> Collections.singletonList("/select")); this.queryHandlerWhitelist = new HashSet<>(whitelistPropertyList); } /** * Gets a HttpGet to make a request to the Solr-Server. * * @param queryHandlerPath * The query handler path * @param params * Parameters to use with the Request * @return a method to make the request */ private static HttpGet getSolrHttpMethod(String queryHandlerPath, ModifiableSolrParams params, String type) { String serverURL = MCRSolrClientFactory.get(type).get().getV1CoreURL(); return new HttpGet(new MessageFormat("{0}{1}{2}", Locale.ROOT) .format(new Object[] { serverURL, queryHandlerPath, params.toQueryString() })); } private static ModifiableSolrParams getSolrQueryParameter(HttpServletRequest request) { SolrQuery query = (SolrQuery) request.getAttribute(QUERY_KEY); if (query != null) { return query; } @SuppressWarnings("unchecked") Map<String, String[]> solrParameter = (Map<String, String[]>) request.getAttribute(MAP_KEY); if (solrParameter == null) { // good old way solrParameter = request.getParameterMap(); } return toSolrParams(solrParameter); } @Override public void init() throws ServletException { super.init(); this.updateQueryHandlerMap(); httpClientConnectionManager = MCRHttpUtils.getConnectionManager(MAX_CONNECTIONS); httpClient = MCRHttpUtils.getHttpClient(httpClientConnectionManager, MAX_CONNECTIONS); // start thread to monitor stalled connections idleConnectionMonitorThread = new MCRIdleConnectionMonitorThread(httpClientConnectionManager); idleConnectionMonitorThread.start(); } @Override public void destroy() { idleConnectionMonitorThread.shutdown(); try { httpClient.close(); } catch (IOException e) { log("Could not close HTTP client to SOLR server.", e); } httpClientConnectionManager.shutdown(); super.destroy(); } private static ModifiableSolrParams toSolrParams(Map<String, String[]> parameters) { // to maintain order LinkedHashMap<String, String[]> copy = new LinkedHashMap<>(parameters); ModifiableSolrParams solrParams = new ModifiableSolrParams(copy); if (!parameters.containsKey("version") && !parameters.containsKey("wt")) { solrParams.set("version", SOLR_QUERY_XML_PROTOCOL_VERSION); } return solrParams; } }
15,432
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Supplier; import org.apache.commons.lang3.time.StopWatch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.UpdateResponse; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.common.events.MCRShutdownHandler.Closeable; import org.mycore.common.processing.MCRProcessableDefaultCollection; import org.mycore.common.processing.MCRProcessableRegistry; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.solr.MCRSolrUtils; import org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory; import org.mycore.solr.index.handlers.MCRSolrOptimizeIndexHandler; import org.mycore.solr.index.handlers.stream.MCRSolrFilesIndexHandler; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; import org.mycore.solr.search.MCRSolrSearchUtils; import org.mycore.util.concurrent.MCRFixedUserCallable; import org.mycore.util.concurrent.processing.MCRProcessableExecutor; import org.mycore.util.concurrent.processing.MCRProcessableFactory; import org.mycore.util.concurrent.processing.MCRProcessableSupplier; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * Base class for indexing with solr. * * @author shermann * @author Matthias Eichner */ public class MCRSolrIndexer { private static final Logger LOGGER = LogManager.getLogger(MCRSolrIndexer.class); public static final int LOW_PRIORITY = 0; public static final int HIGH_PRIORITY = 10; /** * Specify how many documents will be submitted to solr at a time when rebuilding the metadata index. Default is * 100. */ static final int BULK_SIZE = MCRConfiguration2.getInt(SOLR_CONFIG_PREFIX + "Indexer.BulkSize").orElse(100); static final MCRProcessableExecutor SOLR_EXECUTOR; static final ExecutorService SOLR_SUB_EXECUTOR; static final MCRProcessableDefaultCollection SOLR_COLLECTION; private static final int BATCH_AUTO_COMMIT_WITHIN_MS = 60000; static { MCRProcessableRegistry registry = MCRProcessableRegistry.getSingleInstance(); int poolSize = MCRConfiguration2.getInt(SOLR_CONFIG_PREFIX + "Indexer.ThreadCount").orElse(4); final ExecutorService threadPool = new ThreadPoolExecutor(poolSize, poolSize, 0L, TimeUnit.MILLISECONDS, MCRProcessableFactory.newPriorityBlockingQueue(), new ThreadFactoryBuilder().setNameFormat("SOLR-Indexer-#%d").build()); SOLR_COLLECTION = new MCRProcessableDefaultCollection("Solr Indexer"); SOLR_COLLECTION.setProperty("pool size (threads)", poolSize); SOLR_COLLECTION.setProperty("bulk size", BULK_SIZE); SOLR_COLLECTION.setProperty("commit within (ms)", BATCH_AUTO_COMMIT_WITHIN_MS); registry.register(SOLR_COLLECTION); SOLR_EXECUTOR = MCRProcessableFactory.newPool(threadPool, SOLR_COLLECTION); int poolSize2 = Math.max(1, poolSize / 2); SOLR_SUB_EXECUTOR = new ThreadPoolExecutor(poolSize2, poolSize2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new ThreadFactoryBuilder().setNameFormat("SOLR-Sub-Handler-#%d").build()); MCRShutdownHandler.getInstance().addCloseable(new Closeable() { @Override public void prepareClose() { while (SOLR_COLLECTION.stream().findAny().isPresent()) { Thread.yield(); //wait for index handler } } @Override public int getPriority() { return Integer.MIN_VALUE + 6; } @Override public void close() { //MCR-2349 close after MCRSolrIndexEventHandler SOLR_EXECUTOR.submit(SOLR_EXECUTOR.getExecutor()::shutdown, Integer.MIN_VALUE) .getFuture() .join(); waitForShutdown(SOLR_EXECUTOR.getExecutor()); String documentStats = new MessageFormat("Solr documents: {0}, each: {1} ms.", Locale.ROOT).format( new Object[] { MCRSolrIndexStatisticCollector.DOCUMENTS.getDocuments(), MCRSolrIndexStatisticCollector.DOCUMENTS.reset() }); String metadataStats = new MessageFormat("XML documents: {0}, each: {1} ms.", Locale.ROOT).format( new Object[] { MCRSolrIndexStatisticCollector.XML.getDocuments(), MCRSolrIndexStatisticCollector.XML.reset() }); String fileStats = new MessageFormat("File transfers: {0}, each: {1} ms.", Locale.ROOT).format( new Object[] { MCRSolrIndexStatisticCollector.FILE_TRANSFER.getDocuments(), MCRSolrIndexStatisticCollector.FILE_TRANSFER.reset() }); String operationsStats = new MessageFormat("Other index operations: {0}, each: {1} ms.", Locale.ROOT) .format(new Object[] { MCRSolrIndexStatisticCollector.OPERATIONS.getDocuments(), MCRSolrIndexStatisticCollector.OPERATIONS.reset() }); String msg = new MessageFormat("\nFinal statistics:\n{0}\n{1}\n{2}\n{3}", Locale.ROOT) .format(new Object[] { documentStats, metadataStats, fileStats, operationsStats }); LOGGER.info(msg); } private void waitForShutdown(ExecutorService service) { if (!service.isTerminated()) { try { LOGGER.info("Waiting for shutdown of SOLR Indexer."); service.awaitTermination(10, TimeUnit.MINUTES); LOGGER.info("SOLR Indexer was shut down."); } catch (InterruptedException e) { LOGGER.warn("Error while waiting for shutdown.", e); } } } }); MCRShutdownHandler.getInstance().addCloseable(new Closeable() { @Override public void prepareClose() { SOLR_SUB_EXECUTOR.shutdown(); } @Override public int getPriority() { return Integer.MIN_VALUE + 5; } @Override public void close() { waitForShutdown(SOLR_SUB_EXECUTOR); } private void waitForShutdown(ExecutorService service) { if (!service.isTerminated()) { try { service.awaitTermination(10, TimeUnit.MINUTES); } catch (InterruptedException e) { LOGGER.warn("Error while waiting for shutdown.", e); } } } }); } /** * Deletes nested orphaned nested documents. * * https://issues.apache.org/jira/browse/SOLR-6357 * * @return the response or null if {@link MCRSolrUtils#useNestedDocuments()} returns false * @throws SolrServerException solr server exception * @throws IOException io exception */ public static UpdateResponse deleteOrphanedNestedDocuments(SolrClient solrClient) throws SolrServerException, IOException { if (!MCRSolrUtils.useNestedDocuments()) { return null; } return solrClient.deleteByQuery("-({!join from=id to=_root_ score=none}_root_:*) +_root_:*", 0); } /** * Deletes a list of documents by unique ID. Also removes any nested document of that ID. * * @param solrIDs * the list of solr document IDs to delete */ public static UpdateResponse deleteById(SolrClient client, String... solrIDs) { if (solrIDs == null || solrIDs.length == 0) { return null; } UpdateResponse updateResponse = null; long start = System.currentTimeMillis(); try { LOGGER.debug("Deleting \"{}\" from solr", Arrays.asList(solrIDs)); UpdateRequest req = new UpdateRequest(); //delete all documents rooted at this id if (MCRSolrUtils.useNestedDocuments()) { StringBuilder deleteQuery = new StringBuilder("_root_:("); for (String solrID : solrIDs) { deleteQuery.append('"'); deleteQuery.append(MCRSolrUtils.escapeSearchValue(solrID)); deleteQuery.append("\" "); } deleteQuery.setCharAt(deleteQuery.length() - 1, ')'); req.deleteByQuery(deleteQuery.toString()); } //for document without nested req.deleteById(Arrays.asList(solrIDs)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Delete request: {}", req.getXML()); } updateResponse = req.process(client); client.commit(); } catch (Exception e) { LOGGER.error("Error deleting document from solr", e); } long end = System.currentTimeMillis(); MCRSolrIndexStatistic operations = MCRSolrIndexStatisticCollector.OPERATIONS; operations.addDocument(1); operations.addTime(end - start); return updateResponse; } /** * Convenient method to delete a derivate and all its files at once. * * @param id the derivate id * @return the solr response */ public static UpdateResponse deleteDerivate(SolrClient solrClient, String id) { if (id == null) { return null; } UpdateResponse updateResponse = null; long start = System.currentTimeMillis(); try { LOGGER.debug("Deleting derivate \"{}\" from solr", id); UpdateRequest req = new UpdateRequest(); StringBuilder deleteQuery = new StringBuilder(); deleteQuery.append("id:").append(id).append(' '); deleteQuery.append("derivateID:").append(id); if (MCRSolrUtils.useNestedDocuments()) { deleteQuery.append(' ').append("_root_:").append(id); } req.deleteByQuery(deleteQuery.toString()); updateResponse = req.process(solrClient); solrClient.commit(); } catch (Exception e) { LOGGER.error("Error deleting document from solr", e); } long end = System.currentTimeMillis(); MCRSolrIndexStatistic operations = MCRSolrIndexStatisticCollector.OPERATIONS; operations.addDocument(1); operations.addTime(end - start); return updateResponse; } /** * Checks if the application uses nested documents. Using nested documents requires * additional queries and slows performance. * * @return true if nested documents are used, otherwise false */ protected static boolean useNestedDocuments() { return MCRConfiguration2.getBoolean(SOLR_CONFIG_PREFIX + "NestedDocuments").orElse(true); } /** * Rebuilds solr's metadata index. */ public static void rebuildMetadataIndex(SolrClient solrClient) { rebuildMetadataIndex(MCRXMLMetadataManager.instance().listIDs(), solrClient); } /** * Rebuilds solr's metadata index only for objects of the given type. * * @param type * of the objects to index */ public static void rebuildMetadataIndex(String type, SolrClient solrClient) { List<String> identfiersOfType = MCRXMLMetadataManager.instance().listIDsOfType(type); rebuildMetadataIndex(identfiersOfType, solrClient); } /** * Rebuilds solr's metadata index only for objects of the given base. * * @param base * of the objects to index */ public static void rebuildMetadataIndexForObjectBase(String base, SolrClient solrClient) { List<String> identfiersOfBase = MCRXMLMetadataManager.instance().listIDsForBase(base); rebuildMetadataIndex(identfiersOfBase, solrClient); } /** * Rebuilds solr's metadata index. * * @param list * list of identifiers of the objects to index * @param solrClient * solr server to index */ public static void rebuildMetadataIndex(List<String> list, SolrClient solrClient) { LOGGER.info("Re-building Metadata Index"); if (list.isEmpty()) { LOGGER.info("Sorry, no documents to index"); return; } StopWatch swatch = new StopWatch(); swatch.start(); int totalCount = list.size(); LOGGER.info("Sending {} objects to solr for reindexing", totalCount); MCRXMLMetadataManager metadataMgr = MCRXMLMetadataManager.instance(); MCRSolrIndexStatistic statistic = null; HashMap<MCRObjectID, MCRContent> contentMap = new HashMap<>((int) (BULK_SIZE * 1.4)); int i = 0; for (String id : list) { i++; try { LOGGER.debug("Preparing \"{}\" for indexing", id); MCRObjectID objId = MCRObjectID.getInstance(id); MCRContent content = metadataMgr.retrieveContent(objId); contentMap.put(objId, content); if (i % BULK_SIZE == 0 || totalCount == i) { MCRSolrIndexHandler indexHandler = MCRSolrIndexHandlerFactory.getInstance() .getIndexHandler(contentMap); indexHandler.setCommitWithin(BATCH_AUTO_COMMIT_WITHIN_MS); indexHandler.setSolrServer(solrClient); statistic = indexHandler.getStatistic(); submitIndexHandler(indexHandler); contentMap = new HashMap<>((int) (BULK_SIZE * 1.4)); } } catch (Exception ex) { LOGGER.error("Error creating index thread for object {}", id, ex); } } long durationInMilliSeconds = swatch.getTime(); if (statistic != null) { statistic.addTime(durationInMilliSeconds); } } /** * Rebuilds solr's content index. */ public static void rebuildContentIndex(SolrClient client) { rebuildContentIndex(MCRXMLMetadataManager.instance().listIDsOfType("derivate"), client); } /** * Rebuilds solr's content index. * * @param solrClient * solr client connection * @param list * list of mycore object id's */ public static void rebuildContentIndex(List<String> list, SolrClient solrClient) { rebuildContentIndex(list, solrClient, LOW_PRIORITY); } /** * Rebuilds solr's content index. * * @param solrClient * solr client connection * @param list * list of mycore object id's * @param priority * higher priority means earlier execution */ public static void rebuildContentIndex(List<String> list, SolrClient solrClient, int priority) { LOGGER.info("Re-building Content Index"); if (list.isEmpty()) { LOGGER.info("No objects to index"); return; } long tStart = System.currentTimeMillis(); int totalCount = list.size(); LOGGER.info("Sending content of {} derivates to solr for reindexing", totalCount); for (String id : list) { MCRSolrFilesIndexHandler indexHandler = new MCRSolrFilesIndexHandler(id, solrClient); indexHandler.setCommitWithin(BATCH_AUTO_COMMIT_WITHIN_MS); submitIndexHandler(indexHandler, priority); } long tStop = System.currentTimeMillis(); MCRSolrIndexStatisticCollector.FILE_TRANSFER.addTime(tStop - tStart); } /** * Submits a index handler to the executor service (execute as a thread) with the given priority. * * @param indexHandler * index handler to submit */ public static void submitIndexHandler(MCRSolrIndexHandler indexHandler) { submitIndexHandler(indexHandler, LOW_PRIORITY); } /** * Submits a index handler to the executor service (execute as a thread) with the given priority. * * @param indexHandler * index handler to submit * @param priority * higher priority means earlier execution */ public static void submitIndexHandler(MCRSolrIndexHandler indexHandler, int priority) { MCRFixedUserCallable<List<MCRSolrIndexHandler>> indexTask = new MCRFixedUserCallable<>( new MCRSolrIndexTask(indexHandler), MCRSystemUserInformation.getSystemUserInstance()); MCRProcessableSupplier<List<MCRSolrIndexHandler>> supplier = SOLR_EXECUTOR.submit(indexTask, priority); supplier.getFuture().whenCompleteAsync(afterIndex(indexHandler, priority), SOLR_SUB_EXECUTOR); } private static BiConsumer<? super List<MCRSolrIndexHandler>, ? super Throwable> afterIndex( final MCRSolrIndexHandler indexHandler, final int priority) { return (handlerList, exc) -> { if (exc != null) { LOGGER.error("Error while submitting index handler: " + indexHandler, exc); return; } if (handlerList == null || handlerList.isEmpty()) { return; } int newPriority = priority + 1; for (MCRSolrIndexHandler handler : handlerList) { submitIndexHandler(handler, newPriority); } }; } /** * Drops the current solr index. */ public static void dropIndex(SolrClient client) throws Exception { LOGGER.info("Dropping solr index..."); client.deleteByQuery("*:*", BATCH_AUTO_COMMIT_WITHIN_MS); LOGGER.info("Dropping solr index...done"); } public static void dropIndexByType(String type, SolrClient client) throws Exception { if (!MCRObjectID.isValidType(type) || Objects.equals(type, "data_file")) { LOGGER.warn("The type {} is not a valid type in the actual environment", type); return; } LOGGER.info("Dropping solr index for type {}...", type); String deleteQuery = new MessageFormat("objectType:{0} _root_:*_{1}_*", Locale.ROOT) .format(new Object[] { type, type }); client.deleteByQuery(deleteQuery, BATCH_AUTO_COMMIT_WITHIN_MS); LOGGER.info("Dropping solr index for type {}...done", type); } public static void dropIndexByBase(String base, SolrClient client) throws Exception { String type = base.split("_")[1]; if (!MCRObjectID.isValidType(type) || "data_file".equals(type)) { LOGGER.warn("The type {} of base {} is not a valid type in the actual environment", type, base); return; } LOGGER.info("Dropping solr index for base {}...", base); String deleteQuery = new MessageFormat("objectType:{0} _root_:{1}_*", Locale.ROOT) .format(new Object[] { type, base }); client.deleteByQuery(deleteQuery, BATCH_AUTO_COMMIT_WITHIN_MS); LOGGER.info("Dropping solr index for base {}...done", base); } /** * Sends a signal to the remote solr server to optimize its index. */ public static void optimize(SolrClient client) { try { MCRSolrOptimizeIndexHandler indexHandler = new MCRSolrOptimizeIndexHandler(); indexHandler.setSolrServer(client); indexHandler.setCommitWithin(BATCH_AUTO_COMMIT_WITHIN_MS); submitIndexHandler(indexHandler); } catch (Exception ex) { LOGGER.error("Could not optimize solr index", ex); } } /** * Synchronizes the solr server with the database. As a result the solr server contains the same documents as the * database. All solr zombie documents will be removed, and all not indexed mycore objects will be indexed. */ public static void synchronizeMetadataIndex(SolrClient client) throws IOException, SolrServerException { Collection<String> objectTypes = MCRXMLMetadataManager.instance().getObjectTypes(); for (String objectType : objectTypes) { synchronizeMetadataIndex(client, objectType); } } /** * Synchronizes the solr server with the mycore store for a given object type. As a result the solr server contains * the same documents as the store. All solr zombie documents will be removed, and all not indexed mycore objects * will be indexed. */ public static void synchronizeMetadataIndex(SolrClient client, String objectType) throws IOException, SolrServerException { synchronizeMetadataIndex(client, objectType, () -> MCRXMLMetadataManager.instance().listIDsOfType(objectType), () -> MCRSolrSearchUtils.listIDs(client, "objectType:" + objectType)); } public static void synchronizeMetadataIndexForObjectBase(SolrClient client, String objectBase) throws IOException, SolrServerException { final String solrQuery = "objectType:" + objectBase.split("_")[1] + " _root_:" + objectBase + "_*"; synchronizeMetadataIndex(client, objectBase, () -> MCRXMLMetadataManager.instance().listIDsForBase(objectBase), () -> MCRSolrSearchUtils.listIDs(client, solrQuery)); } private static void synchronizeMetadataIndex(SolrClient client, String synchBase, Supplier<List<String>> localIDListSupplier, Supplier<List<String>> indexIDListSupplier) throws SolrServerException, IOException { LOGGER.info("synchronize {}", synchBase); // get ids from store LOGGER.info("fetching mycore store..."); List<String> storeList = localIDListSupplier.get(); LOGGER.info("there are {} mycore objects", storeList.size()); // get ids from solr LOGGER.info("fetching solr..."); List<String> solrList = indexIDListSupplier.get(); LOGGER.info("there are {} solr objects", solrList.size()); // documents to remove List<String> toRemove = new ArrayList(solrList); toRemove.removeAll(storeList); if (!toRemove.isEmpty()) { LOGGER.info("remove {} zombie objects from solr", toRemove.size()); deleteById(client, toRemove.toArray(String[]::new)); } deleteOrphanedNestedDocuments(client); // documents to add storeList.removeAll(solrList); if (!storeList.isEmpty()) { LOGGER.info("index {} mycore objects", storeList.size()); rebuildMetadataIndex(storeList, client); } } }
24,394
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.Optional; import java.util.concurrent.DelayQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.response.UpdateResponse; import org.mycore.common.MCRSessionMgr; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.datamodel.common.MCRMarkManager; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory; import org.mycore.util.concurrent.MCRDelayedRunnable; import org.mycore.util.concurrent.MCRTransactionableRunnable; /** * @author Thomas Scheffler (yagee) */ public class MCRSolrIndexEventHandler extends MCREventHandlerBase { private static final Logger LOGGER = LogManager.getLogger(MCRSolrIndexEventHandler.class); private static long DELAY_IN_MS = MCRConfiguration2.getLong("MCR.Solr.DelayIndexing_inMS").orElse(2000L); private static DelayQueue<MCRDelayedRunnable> SOLR_TASK_QUEUE = new DelayQueue<>(); private static ScheduledExecutorService SOLR_TASK_EXECUTOR = Executors.newSingleThreadScheduledExecutor(); private static synchronized void putIntoTaskQueue(MCRDelayedRunnable task) { SOLR_TASK_QUEUE.remove(task); SOLR_TASK_QUEUE.add(task); } static { //MCR-2359 make sure that MCRSolrIndexer is initialized //and its ShutdownHandler are registred MCRSolrIndexer.SOLR_EXECUTOR.submit(() -> null); SOLR_TASK_EXECUTOR.scheduleWithFixedDelay(() -> { LOGGER.debug("SOLR Task Executor invoked: " + SOLR_TASK_QUEUE.size() + " Documents to process"); processSolrTaskQueue(); }, DELAY_IN_MS * 2, DELAY_IN_MS * 2, TimeUnit.MILLISECONDS); MCRShutdownHandler.getInstance().addCloseable(new MCRShutdownHandler.Closeable() { @Override public int getPriority() { return Integer.MIN_VALUE + 10; } @Override public void prepareClose() { //MCR-2349 //MCRSolrIndexer requires an early stop of index jobs SOLR_TASK_EXECUTOR.shutdown(); try { SOLR_TASK_EXECUTOR.awaitTermination(10, TimeUnit.MINUTES); } catch (InterruptedException e) { LOGGER.error("Could not shutdown SOLR-Indexing", e); } if (!SOLR_TASK_QUEUE.isEmpty()) { LOGGER.info("There are still {} solr indexing tasks to complete before shutdown", SOLR_TASK_QUEUE.size()); processSolrTaskQueue(); } } @Override public void close() { //all work done in prepareClose phase } }); } private static void processSolrTaskQueue() { while (!SOLR_TASK_QUEUE.isEmpty()) { try { MCRDelayedRunnable processingTask = SOLR_TASK_QUEUE.poll(DELAY_IN_MS, TimeUnit.MILLISECONDS); if (processingTask != null) { LOGGER.info("Sending {} to SOLR...", processingTask.getId()); processingTask.run(); } } catch (InterruptedException e) { LOGGER.error("Error in SOLR indexing", e); } } } @Override protected synchronized void handleObjectCreated(MCREvent evt, MCRObject obj) { addObject(evt, obj); } @Override protected synchronized void handleObjectUpdated(MCREvent evt, MCRObject obj) { addObject(evt, obj); } @Override protected void handleObjectRepaired(MCREvent evt, MCRObject obj) { addObject(evt, obj); } @Override protected synchronized void handleObjectDeleted(MCREvent evt, MCRObject obj) { solrDelete(obj.getId()); } @Override protected void handleDerivateCreated(MCREvent evt, MCRDerivate derivate) { addObject(evt, derivate); } @Override protected void handleDerivateUpdated(MCREvent evt, MCRDerivate derivate) { addObject(evt, derivate); } @Override protected void handleDerivateRepaired(MCREvent evt, MCRDerivate derivate) { addObject(evt, derivate); } @Override protected void handleDerivateDeleted(MCREvent evt, MCRDerivate derivate) { deleteDerivate(derivate); } @Override protected void handlePathCreated(MCREvent evt, Path path, BasicFileAttributes attrs) { addFile(path, attrs); } @Override protected void handlePathUpdated(MCREvent evt, Path path, BasicFileAttributes attrs) { addFile(path, attrs); } @Override protected void updatePathIndex(MCREvent evt, Path file, BasicFileAttributes attrs) { addFile(file, attrs); } @Override protected void handlePathDeleted(MCREvent evt, Path file, BasicFileAttributes attrs) { removeFile(file); } @Override protected void updateDerivateFileIndex(MCREvent evt, MCRDerivate derivate) { MCRSessionMgr.getCurrentSession().onCommit(() -> { //MCR-2349 initialize solr client early enough final SolrClient mainSolrClient = MCRSolrClientFactory.getMainSolrClient(); putIntoTaskQueue(new MCRDelayedRunnable("updateDerivateFileIndex_" + derivate.getId().toString(), DELAY_IN_MS, new MCRTransactionableRunnable( () -> MCRSolrIndexer.rebuildContentIndex(Collections.singletonList(derivate.getId().toString()), mainSolrClient, MCRSolrIndexer.HIGH_PRIORITY)))); }); } @Override protected void handleObjectIndex(MCREvent evt, MCRObject obj) { handleObjectUpdated(evt, obj); } protected synchronized void addObject(MCREvent evt, MCRBase objectOrDerivate) { // do not add objects which are marked for import or deletion if (MCRMarkManager.instance().isMarked(objectOrDerivate)) { return; } MCRSessionMgr.getCurrentSession().onCommit(() -> { long tStart = System.currentTimeMillis(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Solr: submitting data of \"{}\" for indexing", objectOrDerivate.getId()); } putIntoTaskQueue(new MCRDelayedRunnable(objectOrDerivate.getId().toString(), DELAY_IN_MS, new MCRTransactionableRunnable(() -> { try { /*RS: do not use old stuff, get it fresh ... MCRContent content = (MCRContent) evt.get("content"); if (content == null) { content = new MCRBaseContent(objectOrDerivate); }*/ MCRContent content = MCRXMLMetadataManager.instance() .retrieveContent(objectOrDerivate.getId()); MCRSolrIndexHandler indexHandler = MCRSolrIndexHandlerFactory.getInstance() .getIndexHandler(content, objectOrDerivate.getId()); indexHandler.setCommitWithin(1000); MCRSolrIndexer.submitIndexHandler(indexHandler, MCRSolrIndexer.HIGH_PRIORITY); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Solr: submitting data of \"{}\" for indexing done in {}ms ", objectOrDerivate.getId(), System.currentTimeMillis() - tStart); } } catch (Exception ex) { LOGGER.error("Error creating transfer thread for object {}", objectOrDerivate, ex); } }))); }); } protected synchronized void solrDelete(MCRObjectID id) { LOGGER.debug("Solr: submitting data of \"{}\" for deleting", id); MCRSessionMgr.getCurrentSession().onCommit(() -> { //MCR-2349 initialize solr client early enough final SolrClient mainSolrClient = MCRSolrClientFactory.getMainSolrClient(); putIntoTaskQueue(new MCRDelayedRunnable(id.toString(), DELAY_IN_MS, new MCRTransactionableRunnable(() -> MCRSolrIndexer.deleteById(mainSolrClient, id.toString())))); }); } protected synchronized void deleteDerivate(MCRDerivate derivate) { LOGGER.debug("Solr: submitting data of \"{}\" for derivate", derivate.getId()); MCRSessionMgr.getCurrentSession().onCommit(() -> { //MCR-2349 initialize solr client early enough final SolrClient mainSolrClient = MCRSolrClientFactory.getMainSolrClient(); putIntoTaskQueue(new MCRDelayedRunnable(derivate.getId().toString(), DELAY_IN_MS, new MCRTransactionableRunnable( () -> MCRSolrIndexer.deleteDerivate(mainSolrClient, derivate.getId().toString())))); }); } protected synchronized void addFile(Path path, BasicFileAttributes attrs) { if (path instanceof MCRPath mcrPath) { // check if the derivate is marked for deletion String owner = mcrPath.getOwner(); if (MCRObjectID.isValid(owner)) { MCRObjectID mcrObjectID = MCRObjectID.getInstance(owner); if (MCRMarkManager.instance().isMarkedForDeletion(mcrObjectID)) { return; } } } MCRSessionMgr.getCurrentSession().onCommit(() -> { //MCR-2349 initialize solr client early enough final SolrClient mainSolrClient = MCRSolrClientFactory.getMainSolrClient(); putIntoTaskQueue( new MCRDelayedRunnable(path.toUri().toString(), DELAY_IN_MS, new MCRTransactionableRunnable(() -> { try { MCRSolrIndexer .submitIndexHandler( MCRSolrIndexHandlerFactory.getInstance().getIndexHandler(path, attrs, mainSolrClient), MCRSolrIndexer.HIGH_PRIORITY); } catch (Exception ex) { LOGGER.error("Error creating transfer thread for file {}", path, ex); } }))); }); } protected synchronized void removeFile(Path file) { if (isMarkedForDeletion(file)) { return; } MCRSessionMgr.getCurrentSession().onCommit(() -> { //MCR-2349 initialize solr client early enough final SolrClient mainSolrClient = MCRSolrClientFactory.getMainSolrClient(); putIntoTaskQueue( new MCRDelayedRunnable(file.toUri().toString(), DELAY_IN_MS, new MCRTransactionableRunnable(() -> { UpdateResponse updateResponse = MCRSolrIndexer .deleteById(mainSolrClient, file.toUri().toString()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deleted file {}. Response:{}", file, updateResponse); } }))); }); } /** * Returns the derivate identifier for the given path. * * @param path the path * @return the derivate identifier */ protected Optional<MCRObjectID> getDerivateId(Path path) { MCRPath mcrPath = MCRPath.toMCRPath(path); if (MCRObjectID.isValid(mcrPath.getOwner())) { return Optional.of(MCRObjectID.getInstance(mcrPath.getOwner())); } return Optional.empty(); } /** * Checks if the derivate is marked for deletion. * * @param path the path to check */ protected boolean isMarkedForDeletion(Path path) { return getDerivateId(path).map(MCRMarkManager.instance()::isMarkedForDeletion).orElse(false); } }
13,435
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexTask.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexTask.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index; import java.io.IOException; import java.util.List; import java.util.concurrent.Callable; import org.apache.solr.client.solrj.SolrServerException; /** * Solr index task which handles <code>MCRSolrIndexHandler</code>'s. * * @author Matthias Eichner */ public class MCRSolrIndexTask implements Callable<List<MCRSolrIndexHandler>> { protected MCRSolrIndexHandler indexHandler; /** * Creates a new solr index task. * * @param indexHandler * handles the index process */ public MCRSolrIndexTask(MCRSolrIndexHandler indexHandler) { this.indexHandler = indexHandler; } @Override public List<MCRSolrIndexHandler> call() throws SolrServerException, IOException { long start = System.currentTimeMillis(); this.indexHandler.index(); long end = System.currentTimeMillis(); indexHandler.getStatistic().addDocument(indexHandler.getDocuments()); indexHandler.getStatistic().addTime(end - start); return this.indexHandler.getSubHandlers(); } @Override public String toString() { return "Solr: " + this.indexHandler; } }
1,915
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/MCRSolrIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index; import java.io.IOException; import java.util.List; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; /** * General interface to handle a single solr index process. * * @author Matthias Eichner */ public interface MCRSolrIndexHandler { /** * Commits something to solr. */ void index() throws IOException, SolrServerException; /** * Returns a list of index handlers which should be executed after * the default index process. Return an empty list if no sub handlers * are defined. * * @return list of <code>MCRSolrIndexHandler</code> */ List<MCRSolrIndexHandler> getSubHandlers(); /** * Time in milliseconds solr should index the stream. * -1 by default, says that solr decide when to commit. */ void setCommitWithin(int commitWithin); int getCommitWithin(); SolrClient getSolrClient(); void setSolrServer(SolrClient solrClient); MCRSolrIndexStatistic getStatistic(); int getDocuments(); }
1,881
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrAbstractContentStream.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/cs/MCRSolrAbstractContentStream.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.cs; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.common.util.ContentStream; import org.apache.solr.common.util.ContentStreamBase; /** * Wraps objects to be sent to solr in a content stream. * * @see ContentStream * * @author shermann * @author Matthias Eichner * */ public abstract class MCRSolrAbstractContentStream<T> extends ContentStreamBase implements AutoCloseable { static final Logger LOGGER = LogManager.getLogger(MCRSolrAbstractContentStream.class); protected boolean setup; private CheckableInputStream inputStream; protected InputStreamReader streamReader; protected T source; public MCRSolrAbstractContentStream() { this(null); } public MCRSolrAbstractContentStream(T source) { this.inputStream = null; this.streamReader = null; this.setup = false; this.source = source; } @Override public InputStream getStream() throws IOException { doSetup(); return this.inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = new CheckableInputStream(inputStream); } /** * Sets certain properties on a contentStream object. Subclasses must override this method. * <p>Its important to call the following setter methods: * </p> * <ul> * <li>setName</li> * <li>setSize</li> * <li>setSourceInfo</li> * <li>setContentType</li> * <li>setInputStream</li></ul> */ protected abstract void setup() throws IOException; /** * Required for {@link #getReader()} to transform any InputStream into a Reader. * @return null, will default to "UTF-8" */ protected Charset getCharset() { return null; } /** * Checks if the content stream is already set up and ready to use. * * @return true if set up. */ public boolean isSetup() { return this.setup; } private void doSetup() throws IOException { if (!isSetup()) { setup(); this.setup = true; } } @Override public Reader getReader() throws IOException { doSetup(); if (this.streamReader == null) { Charset cs = getCharset(); if (cs == null) { cs = StandardCharsets.UTF_8; } this.streamReader = new InputStreamReader(getStream(), cs); } return this.streamReader; } @Override public Long getSize() { try { doSetup(); } catch (IOException e) { LOGGER.error("Could not setup content stream.", e); } return super.getSize(); } @Override public void close() throws IOException { if (inputStream == null || inputStream.isClosed()) { return; } LOGGER.info("MCR-1911: SOLR leaks resources. Closing open InputStream of {}.", source); inputStream.close(); } public T getSource() { return source; } private static class CheckableInputStream extends FilterInputStream { boolean closed; protected CheckableInputStream(InputStream in) { super(in); closed = false; } @Override public void close() throws IOException { closed = true; super.close(); } public boolean isClosed() { return closed; } } }
4,502
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrPathContentStream.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/cs/MCRSolrPathContentStream.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.cs; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.mycore.datamodel.niofs.MCRContentTypes; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrPathContentStream extends MCRSolrAbstractContentStream<Path> { private BasicFileAttributes attrs; public MCRSolrPathContentStream(Path path, BasicFileAttributes attrs) { super(path); this.attrs = attrs; } @Override protected void setup() throws IOException { Path file = getSource(); this.setName(file.toString()); this.setSourceInfo(file.getClass().getSimpleName()); this.setContentType(MCRContentTypes.probeContentType(file)); this.setSize(attrs.size()); this.setInputStream(Files.newInputStream(file)); } public BasicFileAttributes getAttrs() { return attrs; } }
1,692
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexStatistic.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/statistic/MCRSolrIndexStatistic.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.statistic; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrIndexStatistic { private static final Logger LOGGER = LogManager.getLogger(); final AtomicInteger documents; final AtomicLong accumulatedTime; String name; public MCRSolrIndexStatistic(String name) { this.name = name; this.documents = new AtomicInteger(); this.accumulatedTime = new AtomicLong(); } public long addTime(long time) { LOGGER.debug("{}: adding {} ms", name, time); return accumulatedTime.addAndGet(time); } public int addDocument(int docs) { LOGGER.debug("{}: adding {} documents", name, docs); return documents.addAndGet(docs); } public long getAccumulatedTime() { return accumulatedTime.get(); } public int getDocuments() { return documents.get(); } /** * resets statistic and returns average time in ms per document. */ public synchronized double reset() { synchronized (accumulatedTime) { synchronized (documents) { long time = accumulatedTime.getAndSet(0); int docs = documents.getAndSet(0); if (docs == 0) { return time == 0 ? 0 : Double.MAX_VALUE; } return ((double) time / (double) docs); } } } }
2,337
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/statistic/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * Classes to get index statistics * @author Thomas Scheffler (yagee) */ package org.mycore.solr.index.statistic;
847
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexStatisticCollector.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/statistic/MCRSolrIndexStatisticCollector.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.statistic; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrIndexStatisticCollector { public static final MCRSolrIndexStatistic XML = new MCRSolrIndexStatistic("XML documents"); public static final MCRSolrIndexStatistic DOCUMENTS = new MCRSolrIndexStatistic("Solr documents"); public static final MCRSolrIndexStatistic FILE_TRANSFER = new MCRSolrIndexStatistic("File transfers"); public static final MCRSolrIndexStatistic OPERATIONS = new MCRSolrIndexStatistic("Other Solr operations"); }
1,286
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * Contains classes to generate {@link org.apache.solr.common.SolrInputDocument} */ package org.mycore.solr.index.document;
892
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputDocumentFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrInputDocumentFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.document; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.io.IOException; import java.util.Iterator; import java.util.Map; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRBaseContent; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObjectID; import org.xml.sax.SAXException; /** * @author Thomas Scheffler (yagee) * */ public abstract class MCRSolrInputDocumentFactory { private static MCRSolrInputDocumentFactory instance = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "SolrInputDocument.Factory", MCRConfiguration2::instantiateClass); public static MCRSolrInputDocumentFactory getInstance() { return instance; } public abstract SolrInputDocument getDocument(MCRObjectID id, MCRContent content) throws SAXException, IOException; public abstract Iterator<SolrInputDocument> getDocuments(Map<MCRObjectID, MCRContent> contentMap) throws IOException, SAXException; public SolrInputDocument getDocument(MCRObjectID id) throws SAXException, IOException { MCRContent content = MCRXMLMetadataManager.instance().retrieveContent(id); return getDocument(id, content); } public SolrInputDocument getDocument(MCRBase derOrObj) throws SAXException, IOException { MCRBaseContent content = new MCRBaseContent(derOrObj); return getDocument(derOrObj.getId(), content); } }
2,385
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputDocumentGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrInputDocumentGenerator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.document; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.common.SolrInputDocument; import org.jdom2.Element; import org.mycore.common.MCRException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJAXBContent; import org.mycore.solr.index.document.jaxb.MCRSolrInputDocument; import org.mycore.solr.index.document.jaxb.MCRSolrInputDocumentList; import org.mycore.solr.index.document.jaxb.MCRSolrInputField; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrInputDocumentGenerator { private static Logger LOGGER = LogManager.getLogger(MCRSolrInputDocumentGenerator.class); public static final JAXBContext JAXB_CONTEXT = initContext(); private static JAXBContext initContext() { try { return JAXBContext.newInstance(MCRSolrInputDocument.class.getPackage().getName(), MCRSolrInputDocument.class.getClassLoader()); } catch (JAXBException e) { throw new MCRException("Could not instantiate JAXBContext.", e); } } public static SolrInputDocument getSolrInputDocument(MCRSolrInputDocument jaxbDoc) { SolrInputDocument doc = new SolrInputDocument(); HashSet<MCRSolrInputField> duplicateFilter = new HashSet<>(); for (Object o : jaxbDoc.getFieldOrDoc()) { if (o instanceof MCRSolrInputField field) { if (field.getValue().isEmpty() || duplicateFilter.contains(field)) { continue; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("adding {}={}", field.getName(), field.getValue()); } duplicateFilter.add(field); doc.addField(field.getName(), field.getValue()); } else if (o instanceof MCRSolrInputDocument child) { SolrInputDocument solrChild = getSolrInputDocument(child); doc.addChildDocument(solrChild); } } return doc; } public static List<SolrInputDocument> getSolrInputDocument(MCRContent source) throws JAXBException, IOException { if (source instanceof MCRJAXBContent) { @SuppressWarnings("unchecked") MCRJAXBContent<MCRSolrInputDocumentList> jaxbContent = (MCRJAXBContent<MCRSolrInputDocumentList>) source; return getSolrInputDocuments(jaxbContent.getObject().getDoc()); } Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller(); MCRSolrInputDocumentList solrDocuments = (MCRSolrInputDocumentList) unmarshaller.unmarshal(source.getSource()); return getSolrInputDocuments(solrDocuments.getDoc()); } public static List<SolrInputDocument> getSolrInputDocuments(List<MCRSolrInputDocument> inputDocuments) { ArrayList<SolrInputDocument> returnList = new ArrayList<>(inputDocuments.size()); for (MCRSolrInputDocument doc : inputDocuments) { returnList.add(getSolrInputDocument(doc)); } return returnList; } public static SolrInputDocument getSolrInputDocument(Element input) { SolrInputDocument doc = new SolrInputDocument(); HashSet<MCRSolrInputField> duplicateFilter = new HashSet<>(); List<Element> fieldElements = input.getChildren("field"); for (Element fieldElement : fieldElements) { MCRSolrInputField field = new MCRSolrInputField(); field.setName(fieldElement.getAttributeValue("name")); field.setValue(fieldElement.getText()); if (field.getValue().isEmpty() || duplicateFilter.contains(field)) { continue; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("adding {}={}", field.getName(), field.getValue()); } duplicateFilter.add(field); doc.addField(field.getName(), field.getValue()); } List<Element> docElements = input.getChildren("doc"); for (Element child : docElements) { SolrInputDocument solrChild = getSolrInputDocument(child); doc.addChildDocument(solrChild); } return doc; } }
5,196
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrTransformerInputDocumentFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/MCRSolrTransformerInputDocumentFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.document; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import org.apache.solr.common.SolrInputDocument; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.common.content.transformer.MCRXSL2JAXBTransformer; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.solr.index.document.jaxb.MCRSolrInputDocumentList; import org.xml.sax.SAXException; import jakarta.xml.bind.JAXBException; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrTransformerInputDocumentFactory extends MCRSolrInputDocumentFactory { // private static MCRXSL2JAXBTransformer<JAXBElement<MCRSolrInputDocument>> transformer = getTransformer(); private static MCRContentTransformer transformer = getTransformer(); private static boolean isJAXBTransformer; /* (non-Javadoc) * @see org.mycore.solr.index.document.MCRSolrInputDocumentFactory * #getDocument(org.mycore.datamodel.metadata.MCRObjectID, org.mycore.common.content.MCRContent) */ @Override public SolrInputDocument getDocument(MCRObjectID id, MCRContent content) throws SAXException, IOException { //we need no parameter for searchfields - hopefully try { SolrInputDocument document; if (isJAXBTransformer) { MCRParameterCollector param = new MCRParameterCollector(); @SuppressWarnings("unchecked") MCRSolrInputDocumentList input = ((MCRXSL2JAXBTransformer<MCRSolrInputDocumentList>) transformer) .getJAXBObject(content, param); document = MCRSolrInputDocumentGenerator.getSolrInputDocument(input.getDoc().iterator().next()); } else { MCRContent result = transformer.transform(content); document = MCRSolrInputDocumentGenerator.getSolrInputDocument(result.asXML().getRootElement()); } return document; } catch (TransformerConfigurationException | JAXBException | JDOMException | ParserConfigurationException e) { throw new IOException(e); } } private static MCRContentTransformer getTransformer() { String property = SOLR_CONFIG_PREFIX + "SolrInputDocument.Transformer"; String transformerId = MCRConfiguration2.getStringOrThrow(property); MCRContentTransformer contentTransformer = MCRContentTransformerFactory.getTransformer(transformerId); isJAXBTransformer = contentTransformer instanceof MCRXSL2JAXBTransformer; return contentTransformer; } @Override public Iterator<SolrInputDocument> getDocuments(Map<MCRObjectID, MCRContent> contentMap) throws IOException, SAXException { if (contentMap.isEmpty()) { return Collections.emptyIterator(); } try { Document doc = getMergedDocument(contentMap); if (isJAXBTransformer) { MCRParameterCollector param = new MCRParameterCollector(); @SuppressWarnings("unchecked") MCRSolrInputDocumentList input = ((MCRXSL2JAXBTransformer<MCRSolrInputDocumentList>) transformer) .getJAXBObject(new MCRJDOMContent(doc), param); return MCRSolrInputDocumentGenerator.getSolrInputDocuments(input.getDoc()).iterator(); } else { MCRContent result = transformer.transform(new MCRJDOMContent(doc)); return getSolrInputDocuments(result); } } catch (TransformerConfigurationException | JAXBException | JDOMException | ParserConfigurationException e) { throw new IOException(e); } } private Iterator<SolrInputDocument> getSolrInputDocuments(MCRContent result) throws IOException, JDOMException { final Iterator<Element> delegate; delegate = result.asXML().getRootElement().getChildren("doc").iterator(); return new Iterator<>() { @Override public boolean hasNext() { return delegate.hasNext(); } @Override public SolrInputDocument next() { return MCRSolrInputDocumentGenerator.getSolrInputDocument(delegate .next()); } @Override public void remove() { throw new UnsupportedOperationException("remove() is not supported on this iterator."); } }; } private Document getMergedDocument(Map<MCRObjectID, MCRContent> contentMap) throws IOException, JDOMException { Element rootElement = new Element("add"); Document doc = new Document(rootElement); for (Map.Entry<MCRObjectID, MCRContent> entry : contentMap.entrySet()) { rootElement.addContent(entry.getValue().asXML().detachRootElement()); } return doc; } }
6,255
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputDocument.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/jaxb/MCRSolrInputDocument.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.04.29 at 08:30:43 AM CEST // package org.mycore.solr.index.document.jaxb; import java.util.ArrayList; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElements; import jakarta.xml.bind.annotation.XmlID; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for MCRSolrInputDocument complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MCRSolrInputDocument"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;choice maxOccurs="unbounded" minOccurs="0"&gt; * &lt;element name="field" type="{}MCRSolrInputField"/&gt; * &lt;element name="doc" type="{}MCRSolrInputDocument"/&gt; * &lt;/choice&gt; * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /&gt; * &lt;attribute name="boost" type="{http://www.w3.org/2001/XMLSchema}decimal" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MCRSolrInputDocument", propOrder = { "fieldOrDoc" }) public class MCRSolrInputDocument { @XmlElements({ @XmlElement(name = "field", type = MCRSolrInputField.class), @XmlElement(name = "doc", type = MCRSolrInputDocument.class) }) protected List<Object> fieldOrDoc; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Gets the value of the fieldOrDoc property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the fieldOrDoc property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFieldOrDoc().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MCRSolrInputField } * {@link MCRSolrInputDocument } * */ public List<Object> getFieldOrDoc() { if (fieldOrDoc == null) { fieldOrDoc = new ArrayList<>(); } return this.fieldOrDoc; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
4,293
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/jaxb/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * */ package org.mycore.solr.index.document.jaxb;
819
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputDocumentList.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/jaxb/MCRSolrInputDocumentList.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.06.18 at 04:23:29 PM CEST // package org.mycore.solr.index.document.jaxb; import java.util.ArrayList; import java.util.List; import java.util.Objects; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; /** * <p>Java class for MCRSolrInputDocumentList complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MCRSolrInputDocumentList"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="doc" type="{}MCRSolrInputDocument" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="commitWithin" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="overwrite" type="{http://www.w3.org/2001/XMLSchema}boolean" default="true" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MCRSolrInputDocumentList", propOrder = { "doc" }) @XmlRootElement(name = "add") public class MCRSolrInputDocumentList { protected List<MCRSolrInputDocument> doc; @XmlAttribute(name = "commitWithin") protected Integer commitWithin; @XmlAttribute(name = "overwrite") protected Boolean overwrite; /** * Gets the value of the doc property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the doc property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDoc().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MCRSolrInputDocument } * */ public List<MCRSolrInputDocument> getDoc() { if (doc == null) { doc = new ArrayList<>(); } return this.doc; } /** * Gets the value of the commitWithin property. * * @return * possible object is * {@link Integer } * */ public Integer getCommitWithin() { return commitWithin; } /** * Sets the value of the commitWithin property. * * @param value * allowed object is * {@link Integer } * */ public void setCommitWithin(Integer value) { this.commitWithin = value; } /** * Gets the value of the overwrite property. * * @return * possible object is * {@link Boolean } * */ public boolean isOverwrite() { return Objects.requireNonNullElse(overwrite, true); } /** * Sets the value of the overwrite property. * * @param value * allowed object is * {@link Boolean } * */ public void setOverwrite(Boolean value) { this.overwrite = value; } }
4,397
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputField.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/jaxb/MCRSolrInputField.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.06.18 at 04:23:29 PM CEST // package org.mycore.solr.index.document.jaxb; import java.math.BigDecimal; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlValue; import jakarta.xml.bind.annotation.adapters.CollapsedStringAdapter; import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for MCRSolrInputField complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MCRSolrInputField"&gt; * &lt;simpleContent&gt; * &lt;extension base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}Name" /&gt; * &lt;attribute name="boost" type="{http://www.w3.org/2001/XMLSchema}decimal" /&gt; * &lt;attribute name="update"&gt; * &lt;simpleType&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="add"/&gt; * &lt;enumeration value="set"/&gt; * &lt;enumeration value="inc"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * &lt;/attribute&gt; * &lt;/extension&gt; * &lt;/simpleContent&gt; * &lt;/complexType&gt; * </pre> * */ @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(name = "MCRSolrInputField", propOrder = { "value" }) public class MCRSolrInputField { protected String value; protected String name; protected BigDecimal boost; protected String update; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ @XmlValue public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value.trim(); } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "Name") public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the update property. * * @return * possible object is * {@link String } * */ @XmlAttribute(name = "update") public String getUpdate() { return update; } /** * Sets the value of the update property. * * @param value * allowed object is * {@link String } * */ public void setUpdate(String value) { this.update = value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MCRSolrInputField other)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (value == null) { return other.value == null; } else { return value.equals(other.value); } } }
5,240
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
ObjectFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/document/jaxb/ObjectFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.06.18 at 04:23:29 PM CEST // package org.mycore.solr.index.document.jaxb; import javax.xml.namespace.QName; import jakarta.xml.bind.JAXBElement; import jakarta.xml.bind.annotation.XmlElementDecl; import jakarta.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.mycore.solr.index.document.jaxb package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private static final QName ADD_QNAME = new QName("", "add"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes * for package: org.mycore.solr.index.document.jaxb * */ public ObjectFactory() { } /** * Create an instance of {@link MCRSolrInputDocumentList } * */ public MCRSolrInputDocumentList createMCRSolrInputDocumentList() { return new MCRSolrInputDocumentList(); } /** * Create an instance of {@link MCRSolrInputDocument } * */ public MCRSolrInputDocument createMCRSolrInputDocument() { return new MCRSolrInputDocument(); } /** * Create an instance of {@link MCRSolrInputField } * */ public MCRSolrInputField createMCRSolrInputField() { return new MCRSolrInputField(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MCRSolrInputDocumentList }{@code >}} * */ @XmlElementDecl(namespace = "", name = "add") public JAXBElement<MCRSolrInputDocumentList> createAdd(MCRSolrInputDocumentList value) { return new JAXBElement<>(ADD_QNAME, MCRSolrInputDocumentList.class, null, value); } }
3,147
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrPathDocumentFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrPathDocumentFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.file; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.io.IOException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.MCRPersistenceException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory; import org.mycore.solr.index.handlers.stream.MCRSolrFileIndexHandler; import org.mycore.solr.index.handlers.stream.MCRSolrFilesIndexHandler; /** * @author Thomas Scheffler (yagee) */ public class MCRSolrPathDocumentFactory { private static final String ACCUMULATOR_LIST_PROPERTY_NAME = SOLR_CONFIG_PREFIX + "Indexer.File.AccumulatorList"; private static Logger LOGGER = LogManager.getLogger(MCRSolrPathDocumentFactory.class); private static MCRSolrPathDocumentFactory instance = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "SolrInputDocument.Path.Factory", MCRConfiguration2::instantiateClass); private static final List<MCRSolrFileIndexAccumulator> ACCUMULATOR_LIST = resolveAccumulators(); /** * @return a list of instances of class listet in {@link #ACCUMULATOR_LIST_PROPERTY_NAME} */ private static List<MCRSolrFileIndexAccumulator> resolveAccumulators() { return MCRConfiguration2.getString(ACCUMULATOR_LIST_PROPERTY_NAME) .stream() .flatMap(MCRConfiguration2::splitValue) .map((accumulatorClassRef) -> { try { Class<? extends MCRSolrFileIndexAccumulator> accumulatorClass = Class .forName(accumulatorClassRef) .asSubclass(MCRSolrFileIndexAccumulator.class); return accumulatorClass.getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException e) { throw new MCRConfigurationException( "AccumulatorClass configured in " + ACCUMULATOR_LIST_PROPERTY_NAME + " not found : " + accumulatorClassRef, e); } catch (ReflectiveOperationException e) { throw new MCRConfigurationException( "Constructor of the AccumulatorClass configured in " + ACCUMULATOR_LIST_PROPERTY_NAME + " can not be invoked.", e); } }) .filter(MCRSolrFileIndexAccumulator::isEnabled) .collect(Collectors.toList()); } public static MCRSolrPathDocumentFactory getInstance() { return instance; } /** * Generates a {@link SolrInputDocument} from a {@link MCRPath} instance. * * @see MCRSolrFileIndexHandler * @see MCRSolrFilesIndexHandler * @see MCRSolrIndexHandlerFactory */ public SolrInputDocument getDocument(Path input, BasicFileAttributes attr) throws MCRPersistenceException { SolrInputDocument doc = new SolrInputDocument(); Consumer<? super MCRSolrFileIndexAccumulator> accumulate = (accumulator) -> { LOGGER.debug("{} accumulates {}", accumulator, input); try { accumulator.accumulate(doc, input, attr); } catch (IOException e) { LOGGER.error("Error in Accumulator!", e); } }; ACCUMULATOR_LIST.forEach(accumulate); if (LOGGER.isDebugEnabled()) { LOGGER.debug("MCRFile {} transformed to:\n{}", input, doc); } return doc; } }
4,656
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/file/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * Classes handling MCRFile * @author Thomas Scheffler (yagee) * */ package org.mycore.solr.index.file;
838
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrFileIndexBaseAccumulator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrFileIndexBaseAccumulator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.file; import java.io.IOException; import java.nio.file.Path; import java.nio.file.ProviderMismatchException; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.MCRCache; import org.mycore.datamodel.classifications2.MCRCategLinkReference; import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAO; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.common.MCRISO8601Date; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRContentTypes; import org.mycore.datamodel.niofs.MCRPath; import com.google.common.io.Files; public class MCRSolrFileIndexBaseAccumulator implements MCRSolrFileIndexAccumulator { private static Logger LOGGER = LogManager.getLogger(MCRSolrFileIndexBaseAccumulator.class); private static MCRXMLMetadataManager XML_MANAGER = MCRXMLMetadataManager.instance(); private static final MCRCategoryDAO CATEGORY_DAO = MCRCategoryDAOFactory.getInstance(); private static final MCRCache<String, String> DERIVATE_MODIFIED_CACHE = new MCRCache<>(10000, "derivateID ISODateString cache"); @Override public void accumulate(SolrInputDocument doc, Path input, BasicFileAttributes attr) throws IOException { doc.setField("id", input.toUri().toString()); String absolutePath = '/' + input.subpath(0, input.getNameCount()).toString(); try { MCRPath mcrPath = MCRPath.toMCRPath(input); //check if this is an MCRPath -> more metadata MCRObjectID mcrObjID = MCRMetadataManager.getObjectId(MCRObjectID.getInstance(mcrPath.getOwner()), 10, TimeUnit.SECONDS); if (mcrObjID == null) { LOGGER.warn("Could not determine MCRObject for file {}", absolutePath); doc.setField("returnId", mcrPath.getOwner()); } else { doc.setField("returnId", mcrObjID.toString()); doc.setField("objectProject", mcrObjID.getProjectId()); } String ownerID = mcrPath.getOwner(); doc.setField("derivateID", ownerID); doc.setField("derivateModified", getDerivateModified(ownerID)); Collection<MCRCategoryID> linksFromReference = MCRCategLinkServiceFactory.getInstance() .getLinksFromReference(new MCRCategLinkReference(mcrPath)); HashSet<MCRCategoryID> linkedCategories = new HashSet<>(linksFromReference); for (MCRCategoryID category : linksFromReference) { for (MCRCategory parent : CATEGORY_DAO.getParents(category)) { linkedCategories.add(parent.getId()); } } for (MCRCategoryID category : linkedCategories) { doc.addField("fileCategory", category.toString()); } } catch (ProviderMismatchException e) { LOGGER.warn("Cannot build all fields as input is not an instance of MCRPath: {}", input); } doc.setField("objectType", "data_file"); doc.setField("fileName", input.getFileName().toString()); doc.setField("filePath", absolutePath); doc.setField("stream_size", attr.size()); doc.setField("stream_name", absolutePath); doc.setField("stream_source_info", input.toString()); doc.setField("stream_content_type", MCRContentTypes.probeContentType(input)); doc.setField("extension", Files.getFileExtension(input.getFileName().toString())); MCRISO8601Date iDate = new MCRISO8601Date(); iDate.setDate(new Date(attr.lastModifiedTime().toMillis())); doc.setField("modified", iDate.getISOString()); } /** * returns ISO8601 formated string of when derivate was last modified * * @throws IOException * thrown by {@link MCRCache.ModifiedHandle#getLastModified()} */ private static String getDerivateModified(final String derivateID) throws IOException { MCRObjectID derID = MCRObjectID.getInstance(derivateID); MCRCache.ModifiedHandle modifiedHandle = XML_MANAGER.getLastModifiedHandle(derID, 30, TimeUnit.SECONDS); String modified = DERIVATE_MODIFIED_CACHE.getIfUpToDate(derivateID, modifiedHandle); if (modified == null) { Date date = new Date(modifiedHandle.getLastModified()); MCRISO8601Date date2 = new MCRISO8601Date(); date2.setDate(date); modified = date2.getISOString(); DERIVATE_MODIFIED_CACHE.put(derivateID, modified); } return modified; } }
5,905
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrFileIndexAccumulator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/file/MCRSolrFileIndexAccumulator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.file; import java.io.IOException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.config.MCRConfiguration2; /** * This interface is used to accumulate information of a file to a solr document. * Add instances of this interface to the property <code>MCR.Solr.Indexer.File.AccumulatorList</code> */ public interface MCRSolrFileIndexAccumulator { /** * Adds additional information to a File. * @param document which holds the information * @param filePath to the file in a derivate * @param attributes of the file in a derivate */ void accumulate(SolrInputDocument document, Path filePath, BasicFileAttributes attributes) throws IOException; /** * Returns if this accumulator is enabled. Default is true. * To enable or disable an accumulator, set the property * <code>MCR.Solr.Indexer.File.Accumulator.[SimpleClassName].Enabled</code> to true or false. * @return true if enabled, false otherwise */ default boolean isEnabled() { return MCRConfiguration2 .getBoolean("MCR.Solr.Indexer.File.Accumulator." + this.getClass().getSimpleName() + ".Enabled") .orElse(true); } }
2,039
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * Implementations of the {@link org.mycore.solr.index.MCRSolrIndexHandler} interface * @author Thomas Scheffler (yagee) */ package org.mycore.solr.index.handlers;
897
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrAbstractIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrAbstractIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.UpdateRequest; import org.mycore.common.config.MCRConfiguration2; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.index.MCRSolrIndexHandler; public abstract class MCRSolrAbstractIndexHandler implements MCRSolrIndexHandler { protected SolrClient solrClient; protected int commitWithin; public MCRSolrAbstractIndexHandler() { this(null); } public MCRSolrAbstractIndexHandler(SolrClient solrClient) { this.solrClient = solrClient != null ? solrClient : MCRSolrClientFactory.getMainSolrClient(); this.commitWithin = MCRConfiguration2.getInt("MCR.Solr.commitWithIn").orElseThrow(); } public SolrClient getSolrClient() { return this.solrClient; } public abstract void index() throws IOException, SolrServerException; @Override public List<MCRSolrIndexHandler> getSubHandlers() { return Collections.emptyList(); } /** * Time in milliseconds solr should index the stream. -1 by default, * says that solr decide when to commit. */ public void setCommitWithin(int commitWithin) { this.commitWithin = commitWithin; } public int getCommitWithin() { return commitWithin; } @Override public void setSolrServer(SolrClient solrClient) { this.solrClient = solrClient; } @Override public int getDocuments() { return 1; } protected UpdateRequest getUpdateRequest(String path) { UpdateRequest req = path != null ? new UpdateRequest(path) : new UpdateRequest(); req.setCommitWithin(getCommitWithin()); return req; } }
2,641
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrOptimizeIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrOptimizeIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.UpdateResponse; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrOptimizeIndexHandler extends MCRSolrAbstractIndexHandler { private static final Logger LOGGER = LogManager.getLogger(MCRSolrOptimizeIndexHandler.class); @Override public void index() throws IOException, SolrServerException { LOGGER.info("Sending optimize request to solr"); UpdateResponse response = getSolrClient().optimize(); LOGGER.info("Optimize was {}({}ms)", (response.getStatus() == 0 ? "successful." : "UNSUCCESSFUL!"), response.getElapsedTime()); } @Override public MCRSolrIndexStatistic getStatistic() { return MCRSolrIndexStatisticCollector.OPERATIONS; } @Override public String toString() { return "optimize index"; } }
1,928
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrLazyInputDocumentHandlerFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrLazyInputDocumentHandlerFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers; import java.util.HashMap; import java.util.Map; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.solr.index.MCRSolrIndexHandler; import org.mycore.solr.index.handlers.content.MCRSolrMCRContentIndexHandler; import org.mycore.solr.index.handlers.content.MCRSolrMCRContentMapIndexHandler; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrLazyInputDocumentHandlerFactory extends MCRSolrIndexHandlerFactory { @Override public MCRSolrIndexHandler getIndexHandler(MCRContent content, MCRObjectID id) { return new MCRSolrMCRContentIndexHandler(id, content); } /* (non-Javadoc) * @see org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory#getIndexHandler(java.util.Map) */ @Override public MCRSolrIndexHandler getIndexHandler(Map<MCRObjectID, MCRContent> contentMap) { //contentMap is reused in different threads HashMap<MCRObjectID, MCRContent> copyMap = new HashMap<>(contentMap); return new MCRSolrMCRContentMapIndexHandler(copyMap); } }
1,861
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexHandlerFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/MCRSolrIndexHandlerFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers; import java.io.IOException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.content.MCRBaseContent; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRBase; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.solr.index.MCRSolrIndexHandler; import org.mycore.solr.index.file.MCRSolrPathDocumentFactory; import org.mycore.solr.index.handlers.document.MCRSolrInputDocumentHandler; import org.mycore.solr.index.handlers.stream.MCRSolrFileIndexHandler; import org.mycore.solr.index.strategy.MCRSolrIndexStrategyManager; /** * @author Thomas Scheffler (yagee) * */ public abstract class MCRSolrIndexHandlerFactory { private static final Logger LOGGER = LogManager.getLogger(MCRSolrIndexHandlerFactory.class); private static MCRSolrIndexHandlerFactory instance = new MCRSolrLazyInputDocumentHandlerFactory(); public static MCRSolrIndexHandlerFactory getInstance() { return instance; } public abstract MCRSolrIndexHandler getIndexHandler(MCRContent content, MCRObjectID id); public abstract MCRSolrIndexHandler getIndexHandler(Map<MCRObjectID, MCRContent> contentMap); public MCRSolrIndexHandler getIndexHandler(MCRObjectID... ids) throws IOException { if (ids.length == 1) { MCRContent content = MCRXMLMetadataManager.instance().retrieveContent(ids[0]); return getIndexHandler(content, ids[0]); } HashMap<MCRObjectID, MCRContent> contentMap = new HashMap<>(); for (MCRObjectID id : ids) { MCRContent content = MCRXMLMetadataManager.instance().retrieveContent(id); contentMap.put(id, content); } return getIndexHandler(contentMap); } public MCRSolrIndexHandler getIndexHandler(MCRBase... derOrObjs) { if (derOrObjs.length == 1) { MCRBaseContent content = new MCRBaseContent(derOrObjs[0]); return getIndexHandler(content, derOrObjs[0].getId()); } HashMap<MCRObjectID, MCRContent> contentMap = new HashMap<>(); for (MCRBase derOrObj : derOrObjs) { MCRBaseContent content = new MCRBaseContent(derOrObj); contentMap.put(derOrObj.getId(), content); } return getIndexHandler(contentMap); } public boolean checkFile(Path file, BasicFileAttributes attrs) { return MCRSolrIndexStrategyManager.checkFile(file, attrs); } public MCRSolrIndexHandler getIndexHandler(Path file, BasicFileAttributes attrs, SolrClient solrClient) { return this.getIndexHandler(file, attrs, solrClient, checkFile(file, attrs)); } public MCRSolrIndexHandler getIndexHandler(Path file, BasicFileAttributes attrs, SolrClient solrClient, boolean sendContent) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Solr: submitting file \"{} for indexing", file); } MCRSolrIndexHandler indexHandler; long start = System.currentTimeMillis(); if (sendContent) { /* extract metadata with tika */ indexHandler = new MCRSolrFileIndexHandler(file, attrs, solrClient); } else { SolrInputDocument doc = MCRSolrPathDocumentFactory.getInstance().getDocument(file, attrs); indexHandler = new MCRSolrInputDocumentHandler(doc, solrClient); } long end = System.currentTimeMillis(); indexHandler.getStatistic().addTime(end - start); return indexHandler; } }
4,594
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/document/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * Handler that use client side generated {@link org.apache.solr.common.SolrInputDocument} */ package org.mycore.solr.index.handlers.document;
911
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputDocumentHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/document/MCRSolrInputDocumentHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.document; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrInputDocument; import org.mycore.solr.MCRSolrConstants; import org.mycore.solr.MCRSolrUtils; import org.mycore.solr.index.MCRSolrIndexer; import org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrInputDocumentHandler extends MCRSolrAbstractIndexHandler { private static Logger LOGGER = LogManager.getLogger(MCRSolrInputDocumentHandler.class); SolrInputDocument document; public MCRSolrInputDocumentHandler(SolrInputDocument document) { super(); this.document = document; } public MCRSolrInputDocumentHandler(SolrInputDocument document, SolrClient solrClient) { super(solrClient); this.document = document; } /* (non-Javadoc) * @see org.mycore.solr.index.MCRSolrIndexHandler#index() */ @Override public void index() throws IOException, SolrServerException { String id = String.valueOf(document.getFieldValue("id")); SolrClient solrClient = getSolrClient(); LOGGER.info("Sending {} to SOLR...", id); if (MCRSolrUtils.useNestedDocuments()) { MCRSolrIndexer.deleteById(solrClient, id); } UpdateRequest updateRequest = getUpdateRequest(MCRSolrConstants.SOLR_UPDATE_PATH); updateRequest.add(document); updateRequest.process(solrClient); } /* (non-Javadoc) * @see org.mycore.solr.index.MCRSolrIndexHandler#getStatistic() */ @Override public MCRSolrIndexStatistic getStatistic() { return MCRSolrIndexStatisticCollector.DOCUMENTS; } @Override public String toString() { return "index " + document.getFieldValue("id"); } }
2,931
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrInputDocumentsHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/document/MCRSolrInputDocumentsHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.document; 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.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrClient; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrInputDocument; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrConstants; import org.mycore.solr.index.MCRSolrIndexHandler; import org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrInputDocumentsHandler extends MCRSolrAbstractIndexHandler { Collection<SolrInputDocument> documents; List<MCRSolrIndexHandler> subHandlerList; private static Logger LOGGER = LogManager.getLogger(MCRSolrInputDocumentsHandler.class); public MCRSolrInputDocumentsHandler(Collection<SolrInputDocument> documents) { this(documents, MCRSolrClientFactory.getMainSolrClient()); } public MCRSolrInputDocumentsHandler(Collection<SolrInputDocument> documents, SolrClient solrClient) { super(solrClient); this.documents = documents; } /* (non-Javadoc) * @see org.mycore.solr.index.MCRSolrIndexHandler#getStatistic() */ @Override public MCRSolrIndexStatistic getStatistic() { return MCRSolrIndexStatisticCollector.DOCUMENTS; } /* (non-Javadoc) * @see org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler#index() */ @Override public void index() { if (documents == null || documents.isEmpty()) { LOGGER.warn("No input documents to index."); return; } int totalCount = documents.size(); LOGGER.info("Handling {} documents", totalCount); SolrClient solrClient = getSolrClient(); if (solrClient instanceof ConcurrentUpdateSolrClient) { LOGGER.info("Detected ConcurrentUpdateSolrClient. Split up batch update."); splitDocuments(); //for statistics: documents.clear(); return; } UpdateResponse updateResponse; try { UpdateRequest updateRequest = getUpdateRequest(MCRSolrConstants.SOLR_UPDATE_PATH); updateRequest.add(documents); updateResponse = updateRequest.process(getSolrClient()); } catch (Throwable e) { LOGGER.warn("Error while indexing document collection. Split and retry."); splitDocuments(); return; } if (updateResponse.getStatus() != 0) { LOGGER.error("Error while indexing document collection. Split and retry: {}", updateResponse.getResponse()); splitDocuments(); } else { LOGGER.info("Sending {} documents was successful in {} ms.", totalCount, updateResponse.getElapsedTime()); } } private void splitDocuments() { subHandlerList = new ArrayList<>(documents.size()); for (SolrInputDocument document : documents) { MCRSolrInputDocumentHandler subHandler = new MCRSolrInputDocumentHandler(document, getSolrClient()); subHandler.setCommitWithin(getCommitWithin()); this.subHandlerList.add(subHandler); } } @Override public List<MCRSolrIndexHandler> getSubHandlers() { return subHandlerList == null ? super.getSubHandlers() : subHandlerList; } @Override public int getDocuments() { return documents.size(); } @Override public String toString() { return "index " + this.documents.size() + " mycore documents"; } }
4,699
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * Handler that use solr {@link org.apache.solr.common.util.ContentStream} for client and server side indexing */ package org.mycore.solr.index.handlers.stream;
929
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrFileIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrFileIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.stream; import static org.mycore.solr.MCRSolrConstants.SOLR_EXTRACT_PATH; import java.io.IOException; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import org.apache.solr.common.params.ModifiableSolrParams; import org.mycore.common.MCRUtils; import org.mycore.solr.index.cs.MCRSolrPathContentStream; import org.mycore.solr.index.file.MCRSolrPathDocumentFactory; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; public class MCRSolrFileIndexHandler extends MCRSolrAbstractStreamIndexHandler { static final Logger LOGGER = LogManager.getLogger(MCRSolrFileIndexHandler.class); protected Path file; protected BasicFileAttributes attrs; public MCRSolrFileIndexHandler(Path file, BasicFileAttributes attrs, SolrClient solrClient) { super(solrClient); this.file = file; this.attrs = attrs; } public MCRSolrPathContentStream getStream() { return new MCRSolrPathContentStream(file, attrs); } @Override public void index() throws SolrServerException, IOException { String solrID = file.toUri().toString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Solr: indexing file \"{}\"", file); } /* create the update request object */ ContentStreamUpdateRequest updateRequest = new ContentStreamUpdateRequest(SOLR_EXTRACT_PATH); try (MCRSolrPathContentStream stream = getStream()) { updateRequest.addContentStream(stream); /* set the additional parameters */ updateRequest.setParams(getSolrParams(file, attrs)); updateRequest.setCommitWithin(getCommitWithin()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Solr: sending binary data ({} ({}), size is {}) to solr server.", file, solrID, MCRUtils.getSizeFormatted(attrs.size())); } long t = System.currentTimeMillis(); /* actually send the request */ getSolrClient().request(updateRequest); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Solr: sending binary data \"{} ({})\" done in {}ms", file, solrID, System.currentTimeMillis() - t); } } //MCR-1911: close any open resource } private ModifiableSolrParams getSolrParams(Path file, BasicFileAttributes attrs) { ModifiableSolrParams params = new ModifiableSolrParams(); SolrInputDocument doc = MCRSolrPathDocumentFactory.getInstance().getDocument(file, attrs); for (SolrInputField field : doc) { String name = "literal." + field.getName(); if (field.getValueCount() > 1) { String[] values = getValues(field.getValues()); params.set(name, values); } else { params.set(name, field.getValue().toString()); } } return params; } private String[] getValues(Collection<Object> values) { ArrayList<String> strValues = new ArrayList<>(values.size()); for (Object o : values) { strValues.add(o.toString()); } return strValues.toArray(String[]::new); } @Override public MCRSolrIndexStatistic getStatistic() { return MCRSolrIndexStatisticCollector.FILE_TRANSFER; } @Override public String toString() { return "index " + this.file; } }
4,697
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrFilesIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrFilesIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.stream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.common.SolrInputDocument; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.solr.index.MCRSolrIndexHandler; import org.mycore.solr.index.file.MCRSolrPathDocumentFactory; import org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler; import org.mycore.solr.index.handlers.MCRSolrIndexHandlerFactory; import org.mycore.solr.index.handlers.document.MCRSolrInputDocumentsHandler; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; /** * Commits <code>MCRFile</code> objects to solr, be aware that the files are * not indexed directly, but added to a list of sub index handlers. * * @author Matthias Eichner */ public class MCRSolrFilesIndexHandler extends MCRSolrAbstractIndexHandler { private static final Logger LOGGER = LogManager.getLogger(MCRSolrFilesIndexHandler.class); protected String mcrID; protected List<MCRSolrIndexHandler> subHandlerList; /** * Creates a new solr file index handler. * * @param mcrID id of the derivate or mcrobject, if you put a mcrobject id here * all files of each derivate are indexed * @param solrClient where to index */ public MCRSolrFilesIndexHandler(String mcrID, SolrClient solrClient) { super(solrClient); this.mcrID = mcrID; this.subHandlerList = new ArrayList<>(); } @Override public void index() throws IOException { MCRObjectID mcrID = MCRObjectID.getInstance(getID()); if (!MCRMetadataManager.exists(mcrID)) { LOGGER.warn("Unable to index '{}' cause it doesn't exists anymore!", mcrID); return; } if (mcrID.getTypeId().equals("derivate")) { indexDerivate(mcrID); } else { indexObject(mcrID); } } protected void indexDerivate(MCRObjectID derivateID) throws IOException { MCRPath rootPath = MCRPath.getPath(derivateID.toString(), "/"); final MCRSolrIndexHandlerFactory ihf = MCRSolrIndexHandlerFactory.getInstance(); final List<MCRSolrIndexHandler> subHandlerList = this.subHandlerList; final List<SolrInputDocument> docs = new ArrayList<>(); final SolrClient solrClient = this.solrClient; Files.walkFileTree(rootPath, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { boolean sendContent = ihf.checkFile(file, attrs); try { if (sendContent) { subHandlerList.add(ihf.getIndexHandler(file, attrs, solrClient, true)); } else { SolrInputDocument fileDoc = MCRSolrPathDocumentFactory.getInstance().getDocument(file, attrs); docs.add(fileDoc); } } catch (Exception ex) { LOGGER.error("Error creating transfer thread", ex); } return super.visitFile(file, attrs); } }); int fileCount = subHandlerList.size() + docs.size(); LOGGER.info("Sending {} file(s) for derivate \"{}\"", fileCount, derivateID); if (!docs.isEmpty()) { MCRSolrInputDocumentsHandler subHandler = new MCRSolrInputDocumentsHandler(docs, solrClient); subHandler.setCommitWithin(getCommitWithin()); this.subHandlerList.add(subHandler); } } protected void indexObject(MCRObjectID objectID) throws IOException { List<MCRObjectID> derivateIds = MCRMetadataManager.getDerivateIds(objectID, 0, TimeUnit.MILLISECONDS); for (MCRObjectID derivateID : derivateIds) { indexDerivate(derivateID); } } @Override public List<MCRSolrIndexHandler> getSubHandlers() { return this.subHandlerList; } public String getID() { return mcrID; } @Override public MCRSolrIndexStatistic getStatistic() { return new MCRSolrIndexStatistic("no index operation"); } @Override public int getDocuments() { return 0; } @Override public String toString() { return "index files of " + this.mcrID; } }
5,560
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrAbstractStreamIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/stream/MCRSolrAbstractStreamIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.stream; import org.apache.solr.client.solrj.SolrClient; import org.mycore.solr.index.cs.MCRSolrAbstractContentStream; import org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler; /** * Base class for solr indexing using content streams. */ public abstract class MCRSolrAbstractStreamIndexHandler extends MCRSolrAbstractIndexHandler { protected MCRSolrAbstractStreamIndexHandler() { this(null); } public MCRSolrAbstractStreamIndexHandler(SolrClient solrClient) { super(solrClient); } protected abstract MCRSolrAbstractContentStream<?> getStream(); }
1,365
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
package-info.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Thomas Scheffler (yagee) * Classes that perform lazy conversion of {@link org.mycore.common.content.MCRContent} * to {@link org.apache.solr.common.SolrInputDocument} */ package org.mycore.solr.index.handlers.content;
963
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrMCRContentIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/MCRSolrMCRContentIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.content; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.index.MCRSolrIndexHandler; import org.mycore.solr.index.document.MCRSolrInputDocumentFactory; import org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler; import org.mycore.solr.index.handlers.document.MCRSolrInputDocumentHandler; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; import org.xml.sax.SAXException; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrMCRContentIndexHandler extends MCRSolrAbstractIndexHandler { MCRObjectID id; MCRContent content; private SolrInputDocument document; public MCRSolrMCRContentIndexHandler(MCRObjectID id, MCRContent content) { this(id, content, MCRSolrClientFactory.getMainSolrClient()); } public MCRSolrMCRContentIndexHandler(MCRObjectID id, MCRContent content, SolrClient solrClient) { super(solrClient); this.id = id; this.content = content; } @Override public MCRSolrIndexStatistic getStatistic() { return MCRSolrIndexStatisticCollector.DOCUMENTS; } /* (non-Javadoc) * @see org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler#index() */ @Override public void index() throws IOException { try { this.document = MCRSolrInputDocumentFactory.getInstance().getDocument(id, content); } catch (SAXException e) { throw new IOException(e); } } @Override public List<MCRSolrIndexHandler> getSubHandlers() { MCRSolrIndexHandler mcrSolrIndexHandler = new MCRSolrInputDocumentHandler(document, getSolrClient()); mcrSolrIndexHandler.setCommitWithin(getCommitWithin()); return Collections.singletonList(mcrSolrIndexHandler); } @Override public int getDocuments() { return 0; } @Override public String toString() { return "index " + id; } }
3,047
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrMCRContentMapIndexHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/handlers/content/MCRSolrMCRContentMapIndexHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.handlers.content; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.UpdateResponse; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.index.MCRSolrIndexHandler; import org.mycore.solr.index.document.MCRSolrInputDocumentFactory; import org.mycore.solr.index.handlers.MCRSolrAbstractIndexHandler; import org.mycore.solr.index.handlers.document.MCRSolrInputDocumentHandler; import org.mycore.solr.index.statistic.MCRSolrIndexStatistic; import org.mycore.solr.index.statistic.MCRSolrIndexStatisticCollector; /** * @author Thomas Scheffler (yagee) * */ public class MCRSolrMCRContentMapIndexHandler extends MCRSolrAbstractIndexHandler { private static final Logger LOGGER = LogManager.getLogger(MCRSolrMCRContentMapIndexHandler.class); private List<MCRSolrIndexHandler> subhandlers; private Map<MCRObjectID, MCRContent> contentMap; public MCRSolrMCRContentMapIndexHandler(Map<MCRObjectID, MCRContent> contentMap) { this(contentMap, MCRSolrClientFactory.getMainSolrClient()); } public MCRSolrMCRContentMapIndexHandler(Map<MCRObjectID, MCRContent> contentMap, SolrClient solrClient) { super(); this.contentMap = contentMap; this.subhandlers = new ArrayList<>(contentMap.size()); } @Override public MCRSolrIndexStatistic getStatistic() { return MCRSolrIndexStatisticCollector.DOCUMENTS; } @Override public void index() { int totalCount = contentMap.size(); LOGGER.info("Handling {} documents", totalCount); //multithread processing will result in too many http request UpdateResponse updateResponse; try { Iterator<SolrInputDocument> documents = MCRSolrInputDocumentFactory.getInstance().getDocuments(contentMap); SolrClient solrClient = getSolrClient(); if (solrClient instanceof ConcurrentUpdateSolrClient) { //split up to speed up processing splitup(documents); return; } if (LOGGER.isDebugEnabled()) { ArrayList<SolrInputDocument> debugList = new ArrayList<>(); while (documents.hasNext()) { debugList.add(documents.next()); } LOGGER.debug("Sending these documents: {}", debugList); //recreate documents interator; documents = debugList.iterator(); } if (solrClient instanceof HttpSolrClient) { updateResponse = solrClient.add(documents); } else { ArrayList<SolrInputDocument> docs = new ArrayList<>(totalCount); while (documents.hasNext()) { docs.add(documents.next()); } updateResponse = solrClient.add(docs); } } catch (Throwable e) { LOGGER.warn("Error while indexing document collection. Split and retry.", e); splitup(); return; } if (updateResponse.getStatus() != 0) { LOGGER.error("Error while indexing document collection. Split and retry: {}", updateResponse.getResponse()); splitup(); } else { LOGGER.info("Sending {} documents was successful in {} ms.", totalCount, updateResponse.getElapsedTime()); } } private void splitup(Iterator<SolrInputDocument> documents) { while (documents.hasNext()) { MCRSolrInputDocumentHandler subhandler = new MCRSolrInputDocumentHandler(documents.next()); subhandler.setCommitWithin(getCommitWithin()); subhandlers.add(subhandler); } contentMap.clear(); } private void splitup() { for (Map.Entry<MCRObjectID, MCRContent> entry : contentMap.entrySet()) { MCRSolrMCRContentIndexHandler subHandler = new MCRSolrMCRContentIndexHandler(entry.getKey(), entry.getValue(), getSolrClient()); subHandler.setCommitWithin(getCommitWithin()); subhandlers.add(subHandler); } contentMap.clear(); } @Override public List<MCRSolrIndexHandler> getSubHandlers() { return subhandlers; } @Override public int getDocuments() { return contentMap.size(); } @Override public String toString() { return "bulk index " + contentMap.size() + " documents"; } }
5,691
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrMimeTypeStrategy.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/strategy/MCRSolrMimeTypeStrategy.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.strategy; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.regex.Pattern; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.xml.MCRXMLFunctions; /** * Strategy that depends on a files mime type. By default images are * ignored. You can use the MCR.Solr.MimeTypeStrategy.Pattern property to * set an application specific pattern. Be aware that this is the ignore * pattern, the {@link #check(Path, BasicFileAttributes)} method will return false if it * matches. * * @author Matthias Eichner * @author Thomas Scheffler (yagee) */ public class MCRSolrMimeTypeStrategy implements MCRSolrFileStrategy { private static final Pattern IGNORE_PATTERN; static { String acceptPattern = MCRConfiguration2.getStringOrThrow(SOLR_CONFIG_PREFIX + "MimeTypeStrategy.Pattern"); IGNORE_PATTERN = Pattern.compile(acceptPattern); } @Override public boolean check(Path file, BasicFileAttributes attrs) { String mimeType = MCRXMLFunctions.getMimeType(file.getFileName().toString()); return !IGNORE_PATTERN.matcher(mimeType).matches(); } }
1,987
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrFileStrategy.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/strategy/MCRSolrFileStrategy.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.strategy; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; /** * Base interface for <code>MCRFile</code> specific strategies. * * @author Matthias Eichner * */ public interface MCRSolrFileStrategy { boolean check(Path file, BasicFileAttributes attrs); }
1,054
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrIndexStrategyManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/index/strategy/MCRSolrIndexStrategyManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.index.strategy; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.mycore.common.config.MCRConfiguration2; /** * @author Matthias Eichner * @author Thomas Scheffler (yagee) */ public class MCRSolrIndexStrategyManager { private static final MCRSolrFileStrategy FILE_STRATEGY; static { FILE_STRATEGY = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "FileIndexStrategy", MCRConfiguration2::instantiateClass); } public static boolean checkFile(Path file, BasicFileAttributes attrs) { return FILE_STRATEGY.check(file, attrs); } }
1,445
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/commands/MCRSolrCommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.commands; import static org.mycore.solr.MCRSolrConstants.DEFAULT_SOLR_SERVER_URL; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import static org.mycore.solr.MCRSolrConstants.SOLR_CORE_NAME_SUFFIX; import static org.mycore.solr.MCRSolrConstants.SOLR_CORE_PREFIX; import static org.mycore.solr.MCRSolrConstants.SOLR_CORE_SERVER_SUFFIX; import java.text.MessageFormat; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.mycore.frontend.cli.MCRAbstractCommands; import org.mycore.frontend.cli.MCRObjectCommands; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrCore; import org.mycore.solr.MCRSolrUtils; import org.mycore.solr.classification.MCRSolrClassificationUtil; import org.mycore.solr.index.MCRSolrIndexer; import org.mycore.solr.schema.MCRSolrConfigReloader; import org.mycore.solr.schema.MCRSolrSchemaReloader; import org.mycore.solr.search.MCRSolrSearchUtils; /** * Class provides useful solr related commands. * * @author shermann * @author Sebastian Hofmann */ @MCRCommandGroup( name = "SOLR Commands") public class MCRSolrCommands extends MCRAbstractCommands { private static Logger LOGGER = LogManager.getLogger(); /** * This command displays the MyCoRe properties, * which have to be set, to reload the current Solr / Solr Core configuration * on the next start of the MyCoRe application. */ @MCRCommand( syntax = "show solr configuration", help = "displays MyCoRe properties for the current Solr configuration", order = 10) public static void listConfig() { LOGGER.info("List core configuration: {}{}{}{}", System.lineSeparator(), SOLR_CONFIG_PREFIX + "ServerURL=" + DEFAULT_SOLR_SERVER_URL, System.lineSeparator(), MCRSolrClientFactory.getCoreMap().entrySet().stream().map( (entry) -> { String coreID = entry.getKey(); MCRSolrCore core = entry.getValue(); String format = "{0}{1}{2}={3}"; if (!DEFAULT_SOLR_SERVER_URL.equals(core.getServerURL())) { format += "\n{0}{1}{5}={4}"; } return new MessageFormat(format, Locale.ROOT).format(new String[] { SOLR_CORE_PREFIX, coreID, SOLR_CORE_NAME_SUFFIX, core.getName(), core.getServerURL(), SOLR_CORE_SERVER_SUFFIX, }); }).collect(Collectors.joining("\n"))); } @MCRCommand( syntax = "register solr core with name {0} on server {1} as core {2}", help = "registers a Solr core within MyCoRe", order = 40) public static void registerSolrCore(String coreName, String server, String coreID) { MCRSolrClientFactory.addCore(server, coreName, coreID); } @MCRCommand( syntax = "register solr core with name {0} as core {1}", help = "registers a Solr core on the configured default Solr server within MyCoRe", order = 50) public static void registerSolrCore(String coreName, String coreID) { MCRSolrClientFactory.addCore(DEFAULT_SOLR_SERVER_URL, coreName, coreID); } @MCRCommand( syntax = "switch solr core {0} with core {1}", help = "switches between two Solr core configurations", order = 60) public static void switchSolrCore(String coreID1, String coreID2) { MCRSolrCore core1 = getCore(coreID1); MCRSolrCore core2 = getCore(coreID2); MCRSolrClientFactory.add(coreID1, core2); MCRSolrClientFactory.add(coreID2, core1); } /** * This command recreates the managed-schema.xml and solrconfig.xml files. First it removes all * schema definitions, except for some MyCoRe default types and fields. Second it parses the available * MyCoRe modules and components and adds / updates / deletes the schema definition. * Finally it does the same for the solrconfig.xml definition. * * see https://github.com/MyCoRe-Org/mycore_solr_configset_main * * @param coreID the core type of the core that should be reloaded; the MyCoRe default application * coreID is <b>main</b> */ @MCRCommand( syntax = "reload solr configuration {0} in core {1}", help = "reloads the schema and the configuration in Solr " + "by using the Solr schema api for core with the id {0}", order = 70) public static void reloadSolrConfiguration(String configType, String coreID) { MCRSolrConfigReloader.reset(configType, coreID); MCRSolrSchemaReloader.reset(configType, coreID); MCRSolrSchemaReloader.processSchemaFiles(configType, coreID); MCRSolrConfigReloader.processConfigFiles(configType, coreID); } @MCRCommand( syntax = "rebuild solr metadata and content index in core {0}", help = "rebuilds metadata and content index in Solr for core with the id {0}", order = 110) public static void rebuildMetadataAndContentIndex(String coreID) { MCRSolrCore core = getCore(coreID); HttpSolrClient client = core.getClient(); MCRSolrIndexer.rebuildMetadataIndex(client); MCRSolrIndexer.rebuildContentIndex(client); MCRSolrIndexer.optimize(client); } @MCRCommand( syntax = "rebuild solr metadata index for all objects of type {0} in core {1}", help = "rebuilds the metadata index in Solr for all objects of type {0} in core with the id {1}", order = 130) public static void rebuildMetadataIndexType(String type, String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.rebuildMetadataIndex(type, core.getClient()); } @MCRCommand( syntax = "rebuild solr metadata index for all objects of base {0} in core {1}", help = "rebuilds the metadata index in Solr for all objects of base {0} in core with the id {1}", order = 130) public static void rebuildMetadataIndexBase(String base, String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.rebuildMetadataIndexForObjectBase(base, core.getClient()); } @MCRCommand( syntax = "rebuild solr metadata index for object {0} in core {1}", help = "rebuilds metadata index in Solr for the given object in core with the id {1}", order = 120) public static void rebuildMetadataIndexObject(String object, String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.rebuildMetadataIndex(Stream.of(object).collect(Collectors.toList()), core.getClient()); } @MCRCommand( syntax = "rebuild solr metadata index for selected in core {0}", help = "rebuilds content index in Solr for selected objects and or derivates in core with the id {0}", order = 140) public static void rebuildMetadataIndexForSelected(String coreID) { MCRSolrCore core = getCore(coreID); List<String> selectedObjects = MCRObjectCommands.getSelectedObjectIDs(); MCRSolrIndexer.rebuildMetadataIndex(selectedObjects, core.getClient()); } @MCRCommand( syntax = "rebuild solr metadata index in core {0}", help = "rebuilds metadata index in Solr in core with the id {0}", order = 150) public static void rebuildMetadataIndex(String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.rebuildMetadataIndex(core.getClient()); } @MCRCommand( syntax = "rebuild solr content index for object {0} in core {1}", help = "rebuilds content index in Solr for the all derivates of object with the id {0} " + "in core with the id {1}", order = 160) public static void rebuildContentIndexObject(String objectID, String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.rebuildContentIndex(Stream.of(objectID).collect(Collectors.toList()), core.getClient()); } @MCRCommand( syntax = "rebuild solr content index for selected in core {0}", help = "rebuilds content index in Solr for alll derivates of selected objects in core with the id {0}", order = 170) public static void rebuildContentIndexForSelected(String coreID) { MCRSolrCore core = getCore(coreID); List<String> selectedObjects = MCRObjectCommands.getSelectedObjectIDs(); MCRSolrIndexer.rebuildContentIndex(selectedObjects, core.getClient()); } @MCRCommand( syntax = "rebuild solr content index in core {0}", help = "rebuilds content index in Solr in core with the id {0}", order = 180) public static void rebuildContentIndex(String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.rebuildContentIndex(core.getClient()); } @MCRCommand( syntax = "rebuild solr classification index in core {0}", help = "rebuilds classification index in Solr in the core with the id {0}", order = 190) public static void rebuildClassificationIndex(String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrClassificationUtil.rebuildIndex(core.getClient()); } @MCRCommand( syntax = "clear solr index in core {0}", help = "deletes all entries from index in Solr in core with the id {0}", order = 210) public static void dropIndex(String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.dropIndex(core.getClient()); } @MCRCommand( syntax = "delete from solr index all objects of type {0} in core {1}", help = "deletes all objects of type {0} from index in Solr in core with the id {1}", order = 220) public static void dropIndexByType(String type, String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.dropIndexByType(type, core.getClient()); } @MCRCommand( syntax = "delete from solr index all objects of base {0} in core {1}", help = "deletes all objects of base {0} from index in Solr in core with the id {1}", order = 220) public static void dropIndexByBase(String base, String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.dropIndexByBase(base, core.getClient()); } @MCRCommand( syntax = "delete from solr index object {0} in core {1}", help = "deletes an object with id {0} from index in Solr in core with the id {1}", order = 230) public static void deleteByIdFromSolr(String objectID, String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.deleteById(core.getClient(), objectID); } @MCRCommand( syntax = "select objects with solr query {0} in core {1}", help = "selects mcr objects with a solr query {0} in core with the id {1}", order = 310) public static void selectObjectsWithSolrQuery(String query, String coreID) { MCRSolrCore core = getCore(coreID); MCRObjectCommands.setSelectedObjectIDs(MCRSolrSearchUtils.listIDs(core.getClient(), query)); } /** * This command optimizes the index in Solr in a given core. * The operation works like a hard commit and forces all of the index segments * to be merged into a single segment first. * Depending on the use cases, this operation should be performed infrequently (e.g. nightly) * since it is very expensive and involves reading and re-writing the entire index. */ @MCRCommand( syntax = "optimize solr index in core {0}", help = "optimizes the index in Solr in core with the id {0}. " + "The operation works like a hard commit and forces all of the index segments " + "to be merged into a single segment first. " + "Depending on the use cases, this operation should be performed infrequently (e.g. nightly), " + "since it is very expensive and involves reading and re-writing the entire index", order = 410) public static void optimize(String coreID) { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.optimize(core.getClient()); } private static MCRSolrCore getCore(String coreID) { return MCRSolrClientFactory.get(coreID) .orElseThrow(() -> MCRSolrUtils.getCoreConfigMissingException(coreID)); } @MCRCommand( syntax = "synchronize solr metadata index for all objects of type {0} in core {1}", help = "synchronizes the MyCoRe store and index in Solr in core with the id {1} for objects of type {0}", order = 420) public static void synchronizeMetadataIndex(String objectType, String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.synchronizeMetadataIndex(core.getClient(), objectType); } @MCRCommand( syntax = "synchronize solr metadata index for all objects of base {0} in core {1}", help = "synchronizes the MyCoRe store and index in Solr in core with the id {1} for objects of base {0}", order = 420) public static void synchronizeMetadataIndexForObjectBase(String objectBase, String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.synchronizeMetadataIndexForObjectBase(core.getClient(), objectBase); } @MCRCommand( syntax = "synchronize solr metadata index in core {0}", help = "synchronizes the MyCoRe store and index in Solr in core with the id {0}", order = 430) public static void synchronizeMetadataIndex(String coreID) throws Exception { MCRSolrCore core = getCore(coreID); MCRSolrIndexer.synchronizeMetadataIndex(core.getClient()); } }
14,885
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrURL.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrURL.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import static org.mycore.solr.MCRSolrConstants.SOLR_QUERY_PATH; import static org.mycore.solr.MCRSolrConstants.SOLR_QUERY_XML_PROTOCOL_VERSION; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.Locale; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.impl.HttpSolrClient; /** * Convenience class for holding the parameters for the solr search url. * * @author shermann */ public class MCRSolrURL { private static final Logger LOGGER = LogManager.getLogger(MCRSolrURL.class); public static final String FIXED_URL_PART = new MessageFormat("?version={0}", Locale.ROOT) .format(new Object[] { SOLR_QUERY_XML_PROTOCOL_VERSION }); private HttpSolrClient solrClient; private String urlQuery, q, sortOptions, wt; private int start, rows; boolean returnScore; private Optional<String> requestHandler; private MCRSolrURL() { requestHandler = Optional.empty(); } /** * @param solrClient the solr server connection to use */ public MCRSolrURL(HttpSolrClient solrClient) { this(); this.solrClient = solrClient; start = 0; rows = 10; q = null; wt = null; sortOptions = ""; returnScore = false; } /** * Creates a new solr url using your own url query. Be aware that you cannot * use the MCRSolrURL setter methods to edit your request. Only the urlQuery is * used. * * @param solrClient the solr server connection to use * @param urlQuery e.g. q=allMeta:Hello&amp;rows=20&amp;defType=edismax */ public MCRSolrURL(HttpSolrClient solrClient, String urlQuery) { this(); this.solrClient = solrClient; this.urlQuery = urlQuery; } /** * @param solrClient the solr server connection to use * @param returnScore specify whether to return the score with results; */ public MCRSolrURL(HttpSolrClient solrClient, boolean returnScore) { this(solrClient); this.returnScore = returnScore; } /** * @return a ready to invoke {@link URL} object or null */ public URL getUrl() { try { if (this.urlQuery == null) { return new URI( solrClient.getBaseURL() + getRequestHandler() + FIXED_URL_PART + "&q=" + URLEncoder .encode(q, StandardCharsets.UTF_8) + "&start=" + start + "&rows=" + rows + "&sort=" + URLEncoder.encode(sortOptions, StandardCharsets.UTF_8) + (returnScore ? "&fl=*,score" : "") + (wt != null ? "&wt=" + wt : "")) .toURL(); } else { return new URI(solrClient.getBaseURL() + getRequestHandler() + FIXED_URL_PART + "&" + urlQuery).toURL(); } } catch (Exception urlException) { LOGGER.error("Error building solr url", urlException); } return null; } /** * Invoke this method to get a {@link URL} referring to the luke interface of a solr server. * Under this URL one can find useful information about the solr schema. * * @return a {@link URL} refering to the luke interface or null */ public URL getLukeURL() { try { return new URI(solrClient.getBaseURL() + "/admin/luke").toURL(); } catch (MalformedURLException | URISyntaxException e) { LOGGER.error("Error building solr luke url", e); } return null; } /** * An abbreviation for getUrl().openStream(); */ public InputStream openStream() throws IOException { URL url = this.getUrl(); LOGGER.info(url.toString()); return url.openStream(); } /** * Adds a sort option to the solr url. * * @param sortBy the name of the field to sort by * @param order the sort order, one can use {@link ORDER#asc} or {@link ORDER#desc} */ public void addSortOption(String sortBy, String order) { if (sortOptions.length() > 0) { sortOptions += ","; } sortOptions += sortBy + " " + (order != null ? order : "desc"); } /** * Adds a sort option to the solr url * * @param sort the sort option e.g. 'maintitle desc' */ public void addSortOption(String sort) { if (sort == null || sort.equals("")) { return; } if (sortOptions.length() > 0) { sortOptions += ","; } sortOptions += sort; } /** * Sets the unencoded query parameter. */ public void setQueryParamter(String query) { this.q = query; } /** * @return the query parameter */ public String getQueryParamter() { return this.q; } /** * @return the start parameter */ public int getStart() { return start; } /** * @return the rows parameter */ public int getRows() { return rows; } /** * Sets the start parameter. */ public void setStart(int start) { this.start = start; } /** * Sets the rows parameter. */ public void setRows(int rows) { this.rows = rows; } public void setReturnScore(boolean yesOrNo) { this.returnScore = yesOrNo; } /** * The wt (writer type) parameter is used by Solr to determine which QueryResponseWriter should be * used to process the request. Valid values are any of the names specified by &lt;queryResponseWriter... /&gt; * declarations in solrconfig.xml. The default value is "standard" (xml). */ public void setWriterType(String wt) { this.wt = wt; } /** * @return true if the score is returned with the results, false otherwise */ public boolean returnsScore() { return this.returnScore; } /** * Sets the solr request handler. * * @param requestHandler the name of the request handler to set e.g. /foo * */ public void setRequestHandler(String requestHandler) { this.requestHandler = Optional.ofNullable(requestHandler); } /** * Returns the current request handler. * * @return the solr request handler * */ public String getRequestHandler() { return this.requestHandler.orElse(SOLR_QUERY_PATH); } }
7,574
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRQLSearchUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRQLSearchUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.ElementFilter; import org.mycore.common.MCRUsageException; import org.mycore.parsers.bool.MCRAndCondition; import org.mycore.parsers.bool.MCRCondition; import org.mycore.parsers.bool.MCROrCondition; import org.mycore.parsers.bool.MCRSetCondition; import org.mycore.services.fieldquery.MCRQuery; import org.mycore.services.fieldquery.MCRQueryCondition; import org.mycore.services.fieldquery.MCRQueryParser; import org.mycore.services.fieldquery.MCRSortBy; import jakarta.servlet.http.HttpServletRequest; public class MCRQLSearchUtils { private static final Logger LOGGER = LogManager.getLogger(MCRQLSearchUtils.class); private static HashSet<String> SEARCH_PARAMETER = new HashSet<>(Arrays.asList("search", "query", "maxResults", "numPerPage", "page", "mask", "mode", "redirect", "qt")); /** * Build MCRQuery from editor XML input */ public static MCRQuery buildFormQuery(Element root) { Element conditions = root.getChild("conditions"); if (conditions.getAttributeValue("format", "xml").equals("xml")) { Element condition = conditions.getChildren().get(0); renameElements(condition); // Remove conditions without values List<Element> empty = new ArrayList<>(); for (Iterator<Element> it = conditions.getDescendants(new ElementFilter("condition")); it.hasNext();) { Element cond = it.next(); if (cond.getAttribute("value") == null) { empty.add(cond); } } // Remove empty sort conditions Element sortBy = root.getChild("sortBy"); if (sortBy != null) { for (Element field : sortBy.getChildren("field")) { if (field.getAttributeValue("name", "").length() == 0) { empty.add(field); } } } for (int i = empty.size() - 1; i >= 0; i--) { empty.get(i).detach(); } if (sortBy != null && sortBy.getChildren().size() == 0) { sortBy.detach(); } // Remove empty returnFields Element returnFields = root.getChild("returnFields"); if (returnFields != null && returnFields.getText().length() == 0) { returnFields.detach(); } } return MCRQuery.parseXML(root.getDocument()); } /** * Rename elements conditionN to condition. Transform condition with multiple child values to OR-condition. */ protected static void renameElements(Element element) { if (element.getName().startsWith("condition")) { element.setName("condition"); String field = new StringTokenizer(element.getAttributeValue("field"), " -,").nextToken(); String operator = element.getAttributeValue("operator"); if (operator == null) { LOGGER.warn("No operator defined for field: {}", field); operator = "="; } element.setAttribute("operator", operator); List<Element> values = element.getChildren("value"); if (values != null && values.size() > 0) { element.removeAttribute("field"); element.setAttribute("operator", "or"); element.setName("boolean"); for (Element value : values) { value.setName("condition"); value.setAttribute("field", field); value.setAttribute("operator", operator); value.setAttribute("value", value.getText()); value.removeContent(); } } } else if (element.getName().startsWith("boolean")) { element.setName("boolean"); element.getChildren().forEach(MCRQLSearchUtils::renameElements); } } /** * Search using complex query expression given as text string */ public static MCRQuery buildComplexQuery(String query) { return new MCRQuery(new MCRQueryParser().parse(query)); } /** * Search in default search field specified by MCR.SearchServlet.DefaultSearchField */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static MCRQuery buildDefaultQuery(String search, String defaultSearchField) { String[] fields = defaultSearchField.split(" *, *"); MCROrCondition queryCondition = new MCROrCondition(); for (String fDef : fields) { MCRCondition condition = new MCRQueryCondition(fDef, "=", search); queryCondition.addChild(condition); } return new MCRQuery(MCRQueryParser.normalizeCondition(queryCondition)); } /** * Search using name=value pairs from HTTP request */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static MCRQuery buildNameValueQuery(HttpServletRequest req) { MCRAndCondition condition = new MCRAndCondition(); for (Enumeration<String> names = req.getParameterNames(); names.hasMoreElements();) { String name = names.nextElement(); if (name.endsWith(".operator")) { continue; } if (name.contains(".sortField")) { continue; } if (SEARCH_PARAMETER.contains(name)) { continue; } if (name.startsWith("XSL.")) { continue; } String[] values = req.getParameterValues(name); MCRSetCondition parent = condition; if ((values.length > 1) || name.contains(",")) { // Multiple fields with same name, combine with OR parent = new MCROrCondition(); condition.addChild(parent); } for (String fieldName : name.split(",")) { String operator = getReqParameter(req, fieldName + ".operator", "="); for (String value : values) { parent.addChild(new MCRQueryCondition(fieldName, operator, value)); } } } if (condition.getChildren().isEmpty()) { throw new MCRUsageException("Missing query condition"); } return new MCRQuery(MCRQueryParser.normalizeCondition(condition)); } protected static Document setQueryOptions(MCRQuery query, HttpServletRequest req) { String maxResults = getReqParameter(req, "maxResults", "0"); query.setMaxResults(Integer.parseInt(maxResults)); List<String> sortFields = new ArrayList<>(); for (Enumeration<String> names = req.getParameterNames(); names.hasMoreElements();) { String name = names.nextElement(); if (name.contains(".sortField")) { sortFields.add(name); } } if (sortFields.size() > 0) { sortFields.sort((arg0, arg1) -> { String s0 = arg0.substring(arg0.indexOf(".sortField")); String s1 = arg1.substring(arg1.indexOf(".sortField")); return s0.compareTo(s1); }); List<MCRSortBy> sortBy = new ArrayList<>(); for (String name : sortFields) { String sOrder = getReqParameter(req, name, "ascending"); boolean order = Objects.equals(sOrder, "ascending") ? MCRSortBy.ASCENDING : MCRSortBy.DESCENDING; String fieldName = name.substring(0, name.indexOf(".sortField")); sortBy.add(new MCRSortBy(fieldName, order)); } query.setSortBy(sortBy); } Document xml = query.buildXML(); xml.getRootElement().setAttribute("numPerPage", getReqParameter(req, "numPerPage", "0")); xml.getRootElement().setAttribute("mask", getReqParameter(req, "mask", "-")); return xml; } protected static String getReqParameter(HttpServletRequest req, String name, String defaultValue) { String value = req.getParameter(name); if (value == null || value.trim().length() == 0) { return defaultValue; } else { return value.trim(); } } }
9,421
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRConditionTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRConditionTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.SolrQuery.SortClause; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.parsers.bool.MCRAndCondition; import org.mycore.parsers.bool.MCRCondition; import org.mycore.parsers.bool.MCRNotCondition; import org.mycore.parsers.bool.MCROrCondition; import org.mycore.parsers.bool.MCRSetCondition; import org.mycore.services.fieldquery.MCRQueryCondition; import org.mycore.services.fieldquery.MCRSortBy; import org.mycore.solr.MCRSolrConstants; import org.mycore.solr.MCRSolrUtils; /** * @author Thomas Scheffler (yagee) * @author Jens Kupferschmidt * */ public class MCRConditionTransformer { private static final Logger LOGGER = LogManager.getLogger(MCRConditionTransformer.class); /** * If a condition references fields from multiple indexes, this constant is * returned */ protected static final String MIXED = "--mixed--"; private static HashSet<String> joinFields = null; public static String toSolrQueryString(@SuppressWarnings("rawtypes") MCRCondition condition, Set<String> usedFields) { return toSolrQueryString(condition, usedFields, false).toString(); } public static boolean explicitAndOrMapping() { return MCRConfiguration2.getBoolean("MCR.Solr.ConditionTransformer.ExplicitAndOrMapping").orElse(false); } @SuppressWarnings({ "unchecked", "rawtypes" }) private static StringBuilder toSolrQueryString(MCRCondition condition, Set<String> usedFields, boolean subCondition) { if (condition instanceof MCRQueryCondition qCond) { return handleQueryCondition(qCond, usedFields); } if (condition instanceof MCRSetCondition) { MCRSetCondition<MCRCondition> setCond = (MCRSetCondition<MCRCondition>) condition; return handleSetCondition(setCond, usedFields, subCondition); } if (condition instanceof MCRNotCondition notCond) { return handleNotCondition(notCond, usedFields); } throw new MCRException("Cannot handle MCRCondition class: " + condition.getClass().getCanonicalName()); } private static StringBuilder handleQueryCondition(MCRQueryCondition qCond, Set<String> usedFields) { String field = qCond.getFieldName(); String value = qCond.getValue(); String operator = qCond.getOperator(); usedFields.add(field); return switch (operator) { case "like", "contains" -> getTermQuery(field, value.trim()); case "=", "phrase" -> getPhraseQuery(field, value); case "<" -> getLTQuery(field, value); case "<=" -> getLTEQuery(field, value); case ">" -> getGTQuery(field, value); case ">=" -> getGTEQuery(field, value); default -> throw new UnsupportedOperationException("Do not know how to handle operator: " + operator); }; } @SuppressWarnings("rawtypes") private static StringBuilder handleSetCondition(MCRSetCondition<MCRCondition> setCond, Set<String> usedFields, boolean subCondition) { if (explicitAndOrMapping()) { return handleSetConditionExplicit(setCond, usedFields); } else { return handleSetConditionDefault(setCond, usedFields, subCondition); } } @SuppressWarnings("rawtypes") private static StringBuilder handleSetConditionExplicit(MCRSetCondition<MCRCondition> setCond, Set<String> usedFields) { List<MCRCondition<MCRCondition>> children = setCond.getChildren(); if (children.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); sb.append('('); Iterator<MCRCondition<MCRCondition>> iterator = children.iterator(); StringBuilder subSb = toSolrQueryString(iterator.next(), usedFields, true); sb.append(subSb); while (iterator.hasNext()) { sb.append(' ').append(setCond.getOperator().toUpperCase(Locale.ROOT)).append(' '); subSb = toSolrQueryString(iterator.next(), usedFields, true); sb.append(subSb); } sb.append(')'); return sb; } @SuppressWarnings("rawtypes") private static StringBuilder handleSetConditionDefault(MCRSetCondition<MCRCondition> setCond, Set<String> usedFields, boolean subCondition) { boolean stripPlus; if (setCond instanceof MCROrCondition) { stripPlus = true; } else if (setCond instanceof MCRAndCondition) { stripPlus = false; } else { throw new UnsupportedOperationException("Do not know how to handle " + setCond.getClass().getCanonicalName() + " set operation."); } List<MCRCondition<MCRCondition>> children = setCond.getChildren(); if (children.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); boolean groupRequired = subCondition || setCond instanceof MCROrCondition; if (groupRequired) { sb.append("+("); } Iterator<MCRCondition<MCRCondition>> iterator = children.iterator(); StringBuilder subSb = toSolrQueryString(iterator.next(), usedFields, true); sb.append(stripPlus ? stripPlus(subSb) : subSb); while (iterator.hasNext()) { sb.append(' '); subSb = toSolrQueryString(iterator.next(), usedFields, true); sb.append(stripPlus ? stripPlus(subSb) : subSb); } if (groupRequired) { sb.append(')'); } return sb; } @SuppressWarnings("rawtypes") private static StringBuilder handleNotCondition(MCRNotCondition notCond, Set<String> usedFields) { MCRCondition child = notCond.getChild(); StringBuilder sb = new StringBuilder(); sb.append('-'); StringBuilder solrQueryString = toSolrQueryString(child, usedFields, true); if (!explicitAndOrMapping()) { stripPlus(solrQueryString); } if (solrQueryString == null || solrQueryString.length() == 0) { return null; } sb.append(solrQueryString); return sb; } private static StringBuilder getRangeQuery(String field, String lowerTerm, boolean includeLower, String upperTerm, boolean includeUpper) { StringBuilder sb = new StringBuilder(); sb.append('+'); sb.append(field); sb.append(':'); sb.append(includeLower ? '[' : '{'); sb.append( lowerTerm != null ? (Objects.equals(lowerTerm, "*") ? "\\*" : MCRSolrUtils.escapeSearchValue(lowerTerm)) : "*"); sb.append(" TO "); sb.append( upperTerm != null ? (Objects.equals(upperTerm, "*") ? "\\*" : MCRSolrUtils.escapeSearchValue(upperTerm)) : "*"); sb.append(includeUpper ? ']' : '}'); return sb; } public static StringBuilder getLTQuery(String field, String value) { return getRangeQuery(field, null, true, value, false); } public static StringBuilder getLTEQuery(String field, String value) { return getRangeQuery(field, null, true, value, true); } public static StringBuilder getGTQuery(String field, String value) { return getRangeQuery(field, value, false, null, true); } public static StringBuilder getGTEQuery(String field, String value) { return getRangeQuery(field, value, true, null, true); } public static StringBuilder getTermQuery(String field, String value) { if (value.length() == 0) { return null; } StringBuilder sb = new StringBuilder(); if (!explicitAndOrMapping()) { sb.append('+'); } sb.append(field); sb.append(':'); String replaced = value.replaceAll("\\s+", " AND "); if (value.length() == replaced.length()) { sb.append(MCRSolrUtils.escapeSearchValue(value)); } else { sb.append('('); sb.append(MCRSolrUtils.escapeSearchValue(replaced)); sb.append(')'); } return sb; } public static StringBuilder getPhraseQuery(String field, String value) { StringBuilder sb = new StringBuilder(); if (!explicitAndOrMapping()) { sb.append('+'); } sb.append(field); sb.append(':'); sb.append('"'); sb.append(MCRSolrUtils.escapeSearchValue(value)); sb.append('"'); return sb; } private static StringBuilder stripPlus(StringBuilder sb) { if (sb == null || sb.length() == 0) { return sb; } if (sb.charAt(0) == '+') { sb.deleteCharAt(0); } return sb; } public static SolrQuery getSolrQuery(@SuppressWarnings("rawtypes") MCRCondition condition, List<MCRSortBy> sortBy, int maxResults, List<String> returnFields) { String queryString = getQueryString(condition); SolrQuery q = applySortOptions(new SolrQuery(queryString), sortBy); q.setIncludeScore(true); q.setRows(maxResults == 0 ? Integer.MAX_VALUE : maxResults); if (returnFields != null) { q.setFields(returnFields.size() > 0 ? returnFields.stream().collect(Collectors.joining(",")) : "*"); } String sort = q.getSortField(); LOGGER.info("MyCoRe Query transformed to: {}{} {}", q.getQuery(), sort != null ? " " + sort : "", q.getFields()); return q; } public static String getQueryString(@SuppressWarnings("rawtypes") MCRCondition condition) { Set<String> usedFields = new HashSet<>(); return MCRConditionTransformer.toSolrQueryString(condition, usedFields); } public static SolrQuery applySortOptions(SolrQuery q, List<MCRSortBy> sortBy) { for (MCRSortBy option : sortBy) { SortClause sortClause = new SortClause(option.getFieldName(), option.getSortOrder() ? ORDER.asc : ORDER.desc); q.addSort(sortClause); } return q; } /** * Builds SOLR query. * * Automatically builds JOIN-Query if content search fields are used in query. * @param sortBy sort criteria * @param not true, if all conditions should be negated * @param and AND or OR connective between conditions * @param table conditions per "content" or "metadata" * @param maxHits maximum hits */ @SuppressWarnings("rawtypes") public static SolrQuery buildMergedSolrQuery(List<MCRSortBy> sortBy, boolean not, boolean and, HashMap<String, List<MCRCondition>> table, int maxHits, List<String> returnFields) { List<MCRCondition> queryConditions = table.get("metadata"); MCRCondition combined = buildSubCondition(queryConditions, and, not); SolrQuery solrRequestQuery = getSolrQuery(combined, sortBy, maxHits, returnFields); for (Map.Entry<String, List<MCRCondition>> mapEntry : table.entrySet()) { if (!mapEntry.getKey().equals("metadata")) { MCRCondition combinedFilterQuery = buildSubCondition(mapEntry.getValue(), and, not); SolrQuery filterQuery = getSolrQuery(combinedFilterQuery, sortBy, maxHits, returnFields); solrRequestQuery.addFilterQuery(MCRSolrConstants.SOLR_JOIN_PATTERN + filterQuery.getQuery()); } } return solrRequestQuery; } /** Builds a new condition for all fields from one single index */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected static MCRCondition buildSubCondition(List<MCRCondition> conditions, boolean and, boolean not) { MCRCondition subCond; if (conditions.size() == 1) { subCond = conditions.get(0); } else if (and) { subCond = new MCRAndCondition().addAll(conditions); } else { subCond = new MCROrCondition().addAll(conditions); } if (not) { subCond = new MCRNotCondition(subCond); } return subCond; } /** * Build a table from index ID to a List of conditions referencing this * index */ @SuppressWarnings("rawtypes") public static HashMap<String, List<MCRCondition>> groupConditionsByIndex(MCRSetCondition cond) { HashMap<String, List<MCRCondition>> table = new HashMap<>(); @SuppressWarnings("unchecked") List<MCRCondition> children = cond.getChildren(); for (MCRCondition child : children) { String index = getIndex(child); table.computeIfAbsent(index, k -> new ArrayList<>()).add(child); } return table; } /** * Returns the ID of the index of all fields referenced in this condition. * If the fields come from multiple indexes, the constant mixed is returned. */ @SuppressWarnings("rawtypes") private static String getIndex(MCRCondition cond) { if (cond instanceof MCRQueryCondition queryCondition) { String fieldName = queryCondition.getFieldName(); return getIndex(fieldName); } else if (cond instanceof MCRNotCondition) { return getIndex(((MCRNotCondition) cond).getChild()); } @SuppressWarnings("unchecked") List<MCRCondition> children = ((MCRSetCondition) cond).getChildren(); // mixed indexes here! return children.stream() .map(MCRConditionTransformer::getIndex) .reduce((l, r) -> l.equals(r) ? l : MIXED) .get(); } public static String getIndex(String fieldName) { return getJoinFields().contains(fieldName) ? "content" : "metadata"; } private static HashSet<String> getJoinFields() { if (joinFields == null) { joinFields = MCRConfiguration2.getString(SOLR_CONFIG_PREFIX + "JoinQueryFields") .stream() .flatMap(MCRConfiguration2::splitValue) .collect(Collectors.toCollection(HashSet::new)); } return joinFields; } }
15,484
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrSearchServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import static org.mycore.solr.MCRSolrConstants.SOLR_CONFIG_PREFIX; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.StringTokenizer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.solr.proxy.MCRSolrProxyServlet; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * Used to map a formular-post to a solr request. * <p> * <b>Parameters</b> * </p> * <dl> * <dt><strong>Solr reserved parameters</strong></dt> * <dd>They will directly forwarded to the server.</dd> * <dt><strong>Type parameters</strong></dt> * <dd>They are used to join other documents in the search. They start with * "solr.type.".</dd> * <dt><strong>Sort parameters</strong></dt> * <dd>They are used to sort the results in the right order. They start with * "sort."</dd> * <dt><strong>Query parameters</strong></dt> * <dd>They are used to build the query for solr. All parameters which are not * reserved, type or sort parameters will be stored here.</dd> * </dl> * @author mcrshofm * @author mcrsherm */ public class MCRSolrSearchServlet extends MCRServlet { private static final long serialVersionUID = 1L; private enum QueryType { phrase, term } private enum SolrParameterGroup { QueryParameter, SolrParameter, SortParameter, TypeParameter } private static final Logger LOGGER = LogManager.getLogger(MCRSolrSearchServlet.class); private static final String JOIN_PATTERN = "{!join from=returnId to=id}"; private static final String PHRASE_QUERY_PARAM = "solr.phrase"; /** Parameters that can be used within a select request to solr */ static final List<String> RESERVED_PARAMETER_KEYS; static { String[] parameter = { "q", "qt", "sort", "start", "rows", "pageDoc", "pageScore", "fq", "cache", "fl", "glob", "debug", "explainOther", "defType", "timeAllowed", "omitHeader", "sortOrder", "sortBy", "wt", "qf", "q.alt", "mm", "pf", "ps", "qs", "tie", "bq", "bf", "lang", "facet", "facet.field", "facet.sort", "facet.method", PHRASE_QUERY_PARAM, }; RESERVED_PARAMETER_KEYS = List.of(parameter); } /** * Adds a field with all values to a {@link StringBuilder} An empty field * value will be skipped. * * @param query * represents a solr query * @param fieldValues * containing all the values for the field * @param fieldName * the name of the field */ private void addFieldToQuery(StringBuilder query, String[] fieldValues, String fieldName, QueryType queryType) throws ServletException { for (String fieldValue : fieldValues) { if (fieldValue.length() == 0) { continue; } switch (queryType) { case term -> query.append(MCRConditionTransformer.getTermQuery(fieldName, fieldValue)); case phrase -> query.append(MCRConditionTransformer.getPhraseQuery(fieldName, fieldValue)); default -> throw new ServletException("Query type is unsupported: " + queryType); } query.append(' '); } } /** * @param queryParameters * all parameter where * <code>getParameterGroup.equals(QueryParameter)</code> * @param typeParameters * all parameter where * <code>getParameterGroup.equals(TypeParameter)</code> * @return a map which can be forwarded to {@link MCRSolrProxyServlet} */ protected Map<String, String[]> buildSelectParameterMap(Map<String, String[]> queryParameters, Map<String, String[]> typeParameters, Map<String, String[]> sortParameters, Set<String> phraseQuery) throws ServletException { HashMap<String, String[]> queryParameterMap = new HashMap<>(); HashMap<String, String> fieldTypeMap = createFieldTypeMap(typeParameters); HashMap<String, StringBuilder> filterQueryMap = new HashMap<>(); StringBuilder query = new StringBuilder(); for (Entry<String, String[]> queryParameter : queryParameters.entrySet()) { String fieldName = queryParameter.getKey(); String[] fieldValues = queryParameter.getValue(); QueryType queryType = phraseQuery.contains(fieldName) ? QueryType.phrase : QueryType.term; // Build the q parameter without solr.type.fields if (!fieldTypeMap.containsKey(fieldName)) { addFieldToQuery(query, fieldValues, fieldName, queryType); } else { String fieldType = fieldTypeMap.get(fieldName); StringBuilder filterQueryBuilder = getFilterQueryBuilder(filterQueryMap, fieldType); addFieldToQuery(filterQueryBuilder, fieldValues, fieldName, queryType); } } // put query and all filterquery´s to the map queryParameterMap.put("q", new String[] { query.toString().trim() }); for (StringBuilder filterQueryBuilder : filterQueryMap.values()) { // skip the whole query if no field has been added if (filterQueryBuilder.length() > JOIN_PATTERN.length()) { queryParameterMap.put("fq", new String[] { filterQueryBuilder.toString() }); } } queryParameterMap.put("sort", new String[] { buildSolrSortParameter(sortParameters) }); return queryParameterMap; } private String buildSolrSortParameter(Map<String, String[]> sortParameters) { Set<Entry<String, String[]>> sortParameterEntrys = sortParameters.entrySet(); Map<Integer, String> positionOrderMap = new HashMap<>(); Map<Integer, String> positionFieldMap = new HashMap<>(); for (Entry<String, String[]> sortParameterEntry : sortParameterEntrys) { StringTokenizer st = new StringTokenizer(sortParameterEntry.getKey(), "."); st.nextToken(); // skip sort. Integer position = Integer.parseInt(st.nextToken()); String type = st.nextToken(); String[] valueArray = sortParameterEntry.getValue(); if (valueArray.length > 0) { String value = valueArray[0]; if (Objects.equals(type, "order")) { positionOrderMap.put(position, value); } else if (Objects.equals(type, "field")) { positionFieldMap.put(position, value); } } } ArrayList<Integer> sortedPositions = new ArrayList<>(positionFieldMap.keySet()); Collections.sort(sortedPositions); StringBuilder sortBuilder = new StringBuilder(); for (Integer position : sortedPositions) { sortBuilder.append(','); sortBuilder.append(positionFieldMap.get(position)); String order = positionOrderMap.get(position); sortBuilder.append(' '); if (order == null) { order = "asc"; LOGGER.warn("No sort order found for field with number ''{}'' use default value : ''{}''", position, order); } sortBuilder.append(order); } if (sortBuilder.length() != 0) { sortBuilder.deleteCharAt(0); } return sortBuilder.toString(); } /** * This method is used to create a map wich contains all fields as key and * the type of the field as value. * */ private HashMap<String, String> createFieldTypeMap(Map<String, String[]> typeParameters) { HashMap<String, String> fieldTypeMap = new HashMap<>(); for (Entry<String, String[]> currentType : typeParameters.entrySet()) { for (String typeMember : currentType.getValue()) { fieldTypeMap.put(typeMember, currentType.getKey()); } } return fieldTypeMap; } @Override protected void doGetPost(MCRServletJob job) throws Exception { Map<String, String[]> solrParameters = new HashMap<>(); Map<String, String[]> queryParameters = new HashMap<>(); Map<String, String[]> typeParameters = new HashMap<>(); Map<String, String[]> sortParameters = new HashMap<>(); Set<String> phraseQuery = new HashSet<>(); String[] phraseFields = job.getRequest().getParameterValues(PHRASE_QUERY_PARAM); if (phraseFields != null) { phraseQuery.addAll(Arrays.asList(phraseFields)); } HttpServletRequest request = job.getRequest(); HttpServletResponse response = job.getResponse(); extractParameterList(request.getParameterMap(), queryParameters, solrParameters, typeParameters, sortParameters); Map<String, String[]> buildedSolrParameters = buildSelectParameterMap(queryParameters, typeParameters, sortParameters, phraseQuery); buildedSolrParameters.putAll(solrParameters); request.setAttribute(MCRSolrProxyServlet.MAP_KEY, buildedSolrParameters); LOGGER.info("Forward SOLR Parameters: {}", buildedSolrParameters); RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/servlets/SolrSelectProxy"); requestDispatcher.forward(request, response); } @Override public void init() throws ServletException { super.init(); } /** * Splits the parameters into three groups. * * @param requestParameter * the map of parameters to split. * @param queryParameter * all querys will be stored here. * @param solrParameter * all solr-parameters will be stored here. * @param typeParameter * all type-parameters will be stored here. * @param sortParameter * all sort-parameters will be stored here. */ protected void extractParameterList(Map<String, String[]> requestParameter, Map<String, String[]> queryParameter, Map<String, String[]> solrParameter, Map<String, String[]> typeParameter, Map<String, String[]> sortParameter) { for (Entry<String, String[]> currentEntry : requestParameter.entrySet()) { String parameterName = currentEntry.getKey(); if (PHRASE_QUERY_PARAM.equals(parameterName)) { continue; } SolrParameterGroup parameterGroup = getParameterType(parameterName); switch (parameterGroup) { case SolrParameter -> solrParameter.put(parameterName, currentEntry.getValue()); case TypeParameter -> typeParameter.put(parameterName, currentEntry.getValue()); case QueryParameter -> { String[] strings = currentEntry.getValue(); for (String v : strings) { if (v != null && v.length() > 0) { queryParameter.put(parameterName, currentEntry.getValue()); } } } case SortParameter -> sortParameter.put(parameterName, currentEntry.getValue()); default -> { LOGGER.warn("Unknown parameter group. That should not happen."); continue; } } } } /** * @param filterQueryMap * a map wich contains all {@link StringBuilder} * @return a {@link StringBuilder} for the specific fieldType */ private StringBuilder getFilterQueryBuilder(HashMap<String, StringBuilder> filterQueryMap, String fieldType) { if (!filterQueryMap.containsKey(fieldType)) { filterQueryMap.put(fieldType, new StringBuilder(JOIN_PATTERN)); } return filterQueryMap.get(fieldType); } /** * Returns the {@link SolrParameterGroup} for a specific parameter name. * * @param parameterName * the name of the parameter * @return the parameter group enum */ private SolrParameterGroup getParameterType(String parameterName) { if (isTypeParameter(parameterName)) { LOGGER.debug("Parameter {} is a {}", parameterName, SolrParameterGroup.TypeParameter.toString()); return SolrParameterGroup.TypeParameter; } else if (isSolrParameter(parameterName)) { LOGGER.debug("Parameter {} is a {}", parameterName, SolrParameterGroup.SolrParameter.toString()); return SolrParameterGroup.SolrParameter; } else if (isSortParameter(parameterName)) { LOGGER.debug("Parameter {} is a {}", parameterName, SolrParameterGroup.SolrParameter.toString()); return SolrParameterGroup.SortParameter; } else { LOGGER.debug("Parameter {} is a {}", parameterName, SolrParameterGroup.QueryParameter.toString()); return SolrParameterGroup.QueryParameter; } } /** * Detects if a parameter is a solr parameter * * @param parameterName * the name of the parameter * @return true if the parameter is a solr parameter */ private boolean isSolrParameter(String parameterName) { boolean reservedCustomKey; try { reservedCustomKey = MCRConfiguration2 .getOrThrow(SOLR_CONFIG_PREFIX + "ReservedParameterKeys", MCRConfiguration2::splitValue) .filter(parameterName::equals) .findAny() .isPresent(); } catch (MCRConfigurationException e) { reservedCustomKey = false; } return parameterName.startsWith("XSL.") || RESERVED_PARAMETER_KEYS.contains(parameterName) || reservedCustomKey; } /** * Detects if a parameter is a sort parameter * * @param parameterName * the name of the parameter * @return true if the parameter is a sort parameter */ private boolean isSortParameter(String parameterName) { return parameterName.startsWith("sort."); } /** * Detects if a parameter is a type parameter * * @param parameterName * the name of the parameter * @return true if the parameter is a type parameter */ private boolean isTypeParameter(String parameterName) { return parameterName.startsWith("solr.type."); } }
15,749
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrQueryAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrQueryAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.solr.search; import java.io.IOException; import java.text.MessageFormat; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.mycore.frontend.servlets.MCRClassificationBrowser2.MCRQueryAdapter; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrConstants; import jakarta.servlet.http.HttpServletRequest; public class MCRSolrQueryAdapter implements MCRQueryAdapter { private static final Logger LOGGER = LogManager.getLogger(MCRSolrQueryAdapter.class); private String fieldName; private String restriction = ""; private String objectType = ""; private String category; private boolean filterCategory; private SolrQuery solrQuery; public void filterCategory(boolean filter) { this.filterCategory = filter; } @Override public void setRestriction(String text) { this.restriction = " " + text; } @Override public void setObjectType(String text) { this.objectType = " +objectType:" + text; } @Override public String getObjectType() { return this.objectType.isEmpty() ? null : this.objectType.split(":")[1]; } @Override public void setCategory(String text) { this.category = text; } @Override public long getResultCount() { configureSolrQuery(); LOGGER.debug("query: {}", solrQuery); solrQuery.set("rows", 0); QueryResponse queryResponse; try { queryResponse = MCRSolrClientFactory.getMainSolrClient().query(solrQuery); } catch (SolrServerException | IOException e) { LOGGER.warn("Could not query SOLR.", e); return -1; } return queryResponse.getResults().getNumFound(); } @Override public String getQueryAsString() { configureSolrQuery(); String queryString = solrQuery.toQueryString(); return queryString.isEmpty() ? "" : queryString.substring("?".length()); } public void prepareQuery() { this.solrQuery = new SolrQuery(); } private void configureSolrQuery() { this.solrQuery.clear(); String queryString = filterCategory ? new MessageFormat("{0}{1}", Locale.ROOT).format(new Object[] { objectType, restriction }) : new MessageFormat("+{0}:\"{1}\"{2}{3}", Locale.ROOT) .format(new Object[] { fieldName, category, objectType, restriction }); this.solrQuery.setQuery(queryString.trim()); if (filterCategory) { solrQuery.setFilterQueries(new MessageFormat("{0}+{1}:\"{2}\"", Locale.ROOT) .format(new Object[] { MCRSolrConstants.SOLR_JOIN_PATTERN, fieldName, category })); } } @Override public void setFieldName(String fieldname) { this.fieldName = fieldname; } @Override public void configure(HttpServletRequest request) { String objectType = request.getParameter("objecttype"); if ((objectType != null) && (objectType.trim().length() > 0)) { setObjectType(objectType); } String restriction = request.getParameter("restriction"); if ((restriction != null) && (restriction.trim().length() > 0)) { setRestriction(restriction); } boolean filter = "true".equals(MCRServlet.getProperty(request, "filterCategory")); filterCategory(filter); prepareQuery(); } }
4,448
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z