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
MCRSolrSearchUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRSolrSearchUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.jdom2.Document; 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 jakarta.servlet.http.HttpServletRequest; /** * Some solr search utils. * * @author Matthias Eichner */ public abstract class MCRSolrSearchUtils { private static final Logger LOGGER = LogManager.getLogger(MCRQLSearchUtils.class); /** * Returns the first document. * * @param solrClient solr server connection * @param query solr query * @return first solr document or null * @throws SolrServerException communication with the solr server failed in any way */ public static SolrDocument first(SolrClient solrClient, String query) throws SolrServerException, IOException { ModifiableSolrParams p = new ModifiableSolrParams(); p.set("q", query); p.set("rows", 1); QueryResponse response = solrClient.query(p); return response.getResults().isEmpty() ? null : response.getResults().get(0); } @SuppressWarnings("rawtypes") public static SolrQuery getSolrQuery(MCRQuery query, Document input, HttpServletRequest request) { int rows = query.getNumPerPage(); List<String> returnFields = query.getReturnFields(); MCRCondition condition = query.getCondition(); HashMap<String, List<MCRCondition>> table; if (condition instanceof MCRSetCondition setCondition) { table = MCRConditionTransformer.groupConditionsByIndex(setCondition); } else { // if there is only one condition its no set condition. we don't need to group LOGGER.warn("Condition is not SetCondition."); table = new HashMap<>(); ArrayList<MCRCondition> conditionList = new ArrayList<>(); conditionList.add(condition); table.put("metadata", conditionList); } boolean booleanAnd = !(condition instanceof MCROrCondition<?>); SolrQuery mergedSolrQuery = MCRConditionTransformer.buildMergedSolrQuery(query.getSortBy(), false, booleanAnd, table, rows, returnFields); String qt = input.getRootElement().getAttributeValue("qt"); if (qt != null) { mergedSolrQuery.setParam("qt", qt); } String mask = input.getRootElement().getAttributeValue("mask"); if (mask != null) { mergedSolrQuery.setParam("mask", mask); mergedSolrQuery.setParam("_session", request.getParameter("_session")); } return mergedSolrQuery; } /** * Returns a list of ids found by the given query. Returns an empty list * when nothing is found. * * @param solrClient solr server connection * @param query solr query * @return list of id's */ public static List<String> listIDs(SolrClient solrClient, String query) { ModifiableSolrParams p = new ModifiableSolrParams(); p.set("q", query); p.set("fl", "id"); return stream(solrClient, p).map(doc -> doc.getFieldValue("id").toString()).collect(Collectors.toList()); } /** * Creates a stream of SolrDocument's. * * @param solrClient the client to query * @param params solr parameter * @return stream of solr documents */ public static Stream<SolrDocument> stream(SolrClient solrClient, SolrParams params) { return stream(solrClient, params, true, 1000); } public static Stream<SolrDocument> stream(SolrClient solrClient, SolrParams params, boolean parallel, int rowsPerRequest) { SolrDocumentSpliterator solrDocumentSpliterator = new SolrDocumentSpliterator(solrClient, params, 0, rowsPerRequest); return StreamSupport.stream(solrDocumentSpliterator, parallel); } /** * Spliterator for solr documents. */ public static class SolrDocumentSpliterator implements Spliterator<SolrDocument> { protected SolrClient solrClient; protected SolrParams params; protected long start; protected long rows; protected Long size; protected QueryResponse response; public SolrDocumentSpliterator(SolrClient solrClient, SolrParams params, long start, long rows) { this(solrClient, params, start, rows, null); } public SolrDocumentSpliterator(SolrClient solrClient, SolrParams params, long start, long rows, Long size) { this.solrClient = solrClient; this.params = params; this.start = start; this.rows = rows; this.size = size; } @Override public int characteristics() { return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED; } @Override public long estimateSize() { if (this.size == null) { ModifiableSolrParams sizeParams = new ModifiableSolrParams(this.params); sizeParams.set("start", 0); sizeParams.set("rows", 0); try { QueryResponse response = solrClient.query(sizeParams); this.size = response.getResults().getNumFound(); } catch (SolrServerException | IOException e) { throw new IllegalStateException(e); } } return this.size; } @Override public void forEachRemaining(Consumer<? super SolrDocument> action) { if (action == null) { throw new NullPointerException(); } ModifiableSolrParams p = new ModifiableSolrParams(params); p.set("rows", (int) rows); long start = this.start, size = estimateSize(), fetched = 0; while (fetched < size) { p.set("start", (int) (start + fetched)); response = query(p); SolrDocumentList results = response.getResults(); for (SolrDocument doc : results) { action.accept(doc); } fetched += results.size(); } } protected QueryResponse query(SolrParams params) { try { return solrClient.query(params); } catch (SolrServerException | IOException e) { throw new IllegalStateException(e); } } @Override public boolean tryAdvance(Consumer<? super SolrDocument> action) { if (action == null) { throw new NullPointerException(); } long i = start, size = estimateSize(); if (size > 0) { if (response == null) { ModifiableSolrParams p = new ModifiableSolrParams(params); p.set("start", (int) i); p.set("rows", (int) rows); response = query(p); } action.accept(response.getResults().get(response.getResults().size() - (int) size)); this.start = i + 1; this.size -= 1; return true; } return false; } @Override public Spliterator<SolrDocument> trySplit() { long s = estimateSize(), i = start, l = rows; if (l >= s) { return null; } this.size = l; return new SolrDocumentSpliterator(solrClient, params, i + l, l, s - l); } } }
9,172
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRQLSearchServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/search/MCRQLSearchServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.jdom2.Document; import org.jdom2.output.XMLOutputter; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.services.fieldquery.MCRQuery; import org.mycore.solr.proxy.MCRSolrProxyServlet; import jakarta.servlet.RequestDispatcher; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class MCRQLSearchServlet extends MCRServlet {//extends MCRSearchServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRQLSearchServlet.class); /** Default search field */ private String defaultSearchField; @Override public void init() throws ServletException { super.init(); String prefix = "MCR.SearchServlet."; defaultSearchField = MCRConfiguration2.getString(prefix + "DefaultSearchField").orElse("allMeta"); } @Override public void doGetPost(MCRServletJob job) throws IOException, ServletException { HttpServletRequest request = job.getRequest(); HttpServletResponse response = job.getResponse(); String searchString = getReqParameter(request, "search", null); String queryString = getReqParameter(request, "query", null); Document input = (Document) request.getAttribute("MCRXEditorSubmission"); MCRQuery query; if (input != null) { //xeditor input query = MCRQLSearchUtils.buildFormQuery(input.getRootElement()); } else { if (queryString != null) { query = MCRQLSearchUtils.buildComplexQuery(queryString); } else if (searchString != null) { query = MCRQLSearchUtils.buildDefaultQuery(searchString, defaultSearchField); } else { query = MCRQLSearchUtils.buildNameValueQuery(request); } input = MCRQLSearchUtils.setQueryOptions(query, request); } // Show incoming query document if (LOGGER.isDebugEnabled()) { XMLOutputter out = new XMLOutputter(org.jdom2.output.Format.getPrettyFormat()); LOGGER.debug(out.outputString(input)); } boolean doNotRedirect = "false".equals(getReqParameter(request, "redirect", null)); if (doNotRedirect) { showResults(request, response, query, input); } else { sendRedirect(request, response, query, input); } } protected void showResults(HttpServletRequest request, HttpServletResponse response, MCRQuery query, Document input) throws IOException, ServletException { SolrQuery mergedSolrQuery = MCRSolrSearchUtils.getSolrQuery(query, input, request); request.setAttribute(MCRSolrProxyServlet.QUERY_KEY, mergedSolrQuery); RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/servlets/SolrSelectProxy"); requestDispatcher.forward(request, response); } protected void sendRedirect(HttpServletRequest req, HttpServletResponse res, MCRQuery query, Document input) throws IOException { SolrQuery mergedSolrQuery = MCRSolrSearchUtils.getSolrQuery(query, input, req); String selectProxyURL = MCRServlet.getServletBaseURL() + "SolrSelectProxy" + mergedSolrQuery.toQueryString() + getReservedParameterString(req.getParameterMap()); res.sendRedirect(res.encodeRedirectURL(selectProxyURL)); } /** * This method is used to convert all parameters which starts with XSL. to a {@link String}. * @param requestParameter the map of parameters (not XSL parameter will be skipped) * @return a string which contains all parameters with a leading &amp; */ protected String getReservedParameterString(Map<String, String[]> requestParameter) { StringBuilder sb = new StringBuilder(); Set<Entry<String, String[]>> requestEntrys = requestParameter.entrySet(); for (Entry<String, String[]> entry : requestEntrys) { String parameterName = entry.getKey(); if (parameterName.startsWith("XSL.")) { for (String parameterValue : entry.getValue()) { sb.append('&'); sb.append(parameterName); sb.append('='); sb.append(parameterValue); } } } return sb.toString(); } protected 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(); } } }
5,866
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrCategory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/classification/MCRSolrCategory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classification; import java.util.Deque; import java.util.Set; import org.apache.solr.common.SolrInputDocument; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; public class MCRSolrCategory { private MCRCategory category; public MCRSolrCategory(MCRCategory category) { this.category = category; } public SolrInputDocument toSolrDocument() { SolrInputDocument doc = new SolrInputDocument(); Deque<MCRCategory> ancestors = MCRSolrClassificationUtil.getAncestors(category); MCRCategory parent = !ancestors.isEmpty() ? ancestors.getLast() : null; // ids MCRCategoryID id = category.getId(); doc.setField("id", id.toString()); doc.setField("classification", id.getRootID()); doc.setField("type", "node"); if (category.isCategory()) { doc.setField("category", id.getId()); } // labels Set<MCRLabel> labels = category.getLabels(); for (MCRLabel label : labels) { doc.addField("label." + label.getLang(), label.getText()); } // children if (category.hasChildren()) { for (MCRCategory child : category.getChildren()) { doc.addField("children", child.getId().toString()); } } // parent if (parent != null) { doc.setField("parent", parent.getId().toString()); doc.setField("index", parent.getChildren().indexOf(category)); } // ancestors for (MCRCategory ancestor : ancestors) { doc.addField("ancestors", ancestor.getId().toString()); } return doc; } }
2,543
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrCategoryLink.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/classification/MCRSolrCategoryLink.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classification; import org.apache.solr.common.SolrInputDocument; import org.mycore.datamodel.classifications2.MCRCategLinkReference; import org.mycore.datamodel.classifications2.MCRCategoryID; /** * Simple helper class to handle a classification link in solr. * * @author Matthias Eichner */ public class MCRSolrCategoryLink { private MCRCategoryID categoryId; private MCRCategLinkReference linkReference; /** * Creates a new link object. * * @param categoryId category of the link * @param linkReference the link reference */ public MCRSolrCategoryLink(MCRCategoryID categoryId, MCRCategLinkReference linkReference) { this.categoryId = categoryId; this.linkReference = linkReference; } /** * Transform this link object to a solr document. * <ul> * <li>id - combination of the object id and the category separated by a dollar sign </li> * <li>object - object id</li> * <li>category - category id</li> * <li>type - fix string "link"</li> * <li>linkType - type of the link</li> * </ul> * * @return a new solr document */ public SolrInputDocument toSolrDocument() { SolrInputDocument doc = new SolrInputDocument(); String objectId = linkReference.getObjectID(); String catId = categoryId.toString(); doc.setField("id", objectId + "$" + catId); doc.setField("object", objectId); doc.setField("category", catId); doc.setField("type", "link"); doc.setField("linkType", linkReference.getType()); return doc; } }
2,371
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrClassificationEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/classification/MCRSolrClassificationEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classification; import java.util.Collection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandler; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRClassificationUpdateType; /** * Eventhandler that stores classification and their modifications in a Solr collection * * The implementation is based on MCRSolrCategoryDAO and MCREventedCategoryDAO. * * @author Robert Stephan */ public class MCRSolrClassificationEventHandler implements MCREventHandler { private static final Logger LOGGER = LogManager.getLogger(); @Override public void doHandleEvent(MCREvent evt) throws MCRException { if (evt.getObjectType() == MCREvent.ObjectType.CLASS) { MCRCategory categ = (MCRCategory) evt.get(MCREvent.CLASS_KEY); LOGGER.debug("{} handling {} {}", getClass().getName(), categ.getId(), evt.getEventType()); MCRCategory categParent = (MCRCategory) evt.get("parent"); switch (evt.getEventType()) { case CREATE -> MCRSolrClassificationUtil.reindex(categ, categParent); case UPDATE -> processUpdate(evt, categ, categParent); case DELETE -> MCRSolrClassificationUtil.solrDelete(categ.getId(), categ.getParent()); default -> LOGGER.error("No Method available for {}", evt.getEventType()); } } } private void processUpdate(MCREvent evt, MCRCategory categ, MCRCategory categParent) { switch ((MCRClassificationUpdateType) evt.get(MCRClassificationUpdateType.KEY)) { case MOVE -> MCRSolrClassificationUtil.solrMove(categ.getId(), categParent.getId()); case REPLACE -> { @SuppressWarnings("unchecked") Collection<MCRCategory> replaced = (Collection<MCRCategory>) evt.get("replaced"); MCRSolrClassificationUtil.solrDelete(categ.getId(), categ.getParent()); MCRSolrClassificationUtil.reindex(replaced.toArray(MCRCategory[]::new)); } default -> MCRSolrClassificationUtil.reindex(categ, categParent); } } @Override public void undoHandleEvent(MCREvent evt) throws MCRException { if (evt.getObjectType() == MCREvent.ObjectType.CLASS) { LOGGER.debug("{} handling undo of {} {}", getClass().getName(), ((MCRCategory) evt.get(MCREvent.CLASS_KEY)).getId(), evt.getEventType()); LOGGER.info("Doing nothing for undo of {} {}", ((MCRCategory) evt.get(MCREvent.CLASS_KEY)).getId(), evt.getEventType()); } } }
3,550
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrClassificationUtil.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/classification/MCRSolrClassificationUtil.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classification; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.common.SolrInputDocument; import org.mycore.common.MCRSessionMgr; 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.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrCore; import org.mycore.solr.MCRSolrUtils; import org.mycore.solr.search.MCRSolrSearchUtils; import com.google.common.collect.Lists; /** * Some solr classification utility stuff. * * @author Matthias Eichner */ public abstract class MCRSolrClassificationUtil { private static final Logger LOGGER = LogManager.getLogger(MCRSolrClassificationUtil.class); private static final String CLASSIFICATION_CORE_TYPE = "classification"; /** * Reindex the whole classification system with the default classification solr core. */ public static void rebuildIndex() { rebuildIndex(getCore().getClient()); } /** * Reindex the whole classification system. * * @param client the target solr client */ public static void rebuildIndex(final SolrClient client) { LOGGER.info("rebuild classification index..."); // categories MCRCategoryDAO categoryDAO = MCRCategoryDAOFactory.getInstance(); List<MCRCategoryID> rootCategoryIDs = categoryDAO.getRootCategoryIDs(); for (MCRCategoryID rootID : rootCategoryIDs) { LOGGER.info("rebuild classification '{}'...", rootID); MCRCategory rootCategory = categoryDAO.getCategory(rootID, -1); List<MCRCategory> categoryList = getDescendants(rootCategory); categoryList.add(rootCategory); List<SolrInputDocument> solrDocumentList = toSolrDocument(categoryList); bulkIndex(client, solrDocumentList); } // links MCRCategLinkService linkService = MCRCategLinkServiceFactory.getInstance(); Collection<String> linkTypes = linkService.getTypes(); for (String linkType : linkTypes) { LOGGER.info("rebuild '{}' links...", linkType); bulkIndex(client, linkService.getLinks(linkType) .stream() .map(link -> new MCRSolrCategoryLink(link.getCategory().getId(), link.getObjectReference())) .map(MCRSolrCategoryLink::toSolrDocument) .collect(Collectors.toList())); } } /** * Async bulk index. The collection is split into parts of one thousand. * * @param solrDocumentList the list to index */ public static void bulkIndex(final SolrClient client, List<SolrInputDocument> solrDocumentList) { MCRSessionMgr.getCurrentSession().onCommit(() -> { List<List<SolrInputDocument>> partitionList = Lists.partition(solrDocumentList, 1000); int docNum = solrDocumentList.size(); int added = 0; for (List<SolrInputDocument> part : partitionList) { try { client.add(part, 500); added += part.size(); LOGGER.info("Added {}/{} documents", added, docNum); } catch (SolrServerException | IOException e) { LOGGER.error("Unable to add classification documents.", e); } } }); } /** * Drops the whole solr classification index. */ public static void dropIndex() { try { SolrClient solrClient = getCore().getConcurrentClient(); solrClient.deleteByQuery("*:*"); } catch (Exception exc) { LOGGER.error("Unable to drop solr classification index", exc); } } /** * Returns a list of all descendants. The list is unordered. * * @return list of descendants. */ public static List<MCRCategory> getDescendants(MCRCategory category) { List<MCRCategory> descendants = new ArrayList<>(); for (MCRCategory child : category.getChildren()) { descendants.add(child); if (child.hasChildren()) { descendants.addAll(getDescendants(child)); } } return descendants; } /** * Returns a list of all ancestors. The list is ordered. The first element is * always the root node and the last element is always the parent. If the * element has no ancestor an empty list is returned. * * @return list of ancestors */ public static Deque<MCRCategory> getAncestors(MCRCategory category) { Deque<MCRCategory> ancestors = new ArrayDeque<>(); MCRCategory parent = category.getParent(); while (parent != null) { ancestors.addFirst(parent); parent = parent.getParent(); } return ancestors; } /** * Creates a new list of {@link SolrInputDocument} based on the given category list. */ public static List<SolrInputDocument> toSolrDocument(Collection<MCRCategory> categoryList) { return categoryList.stream() .map(MCRSolrCategory::new) .map(MCRSolrCategory::toSolrDocument) .collect(Collectors.toList()); } /** * Creates a new list of {@link SolrInputDocument} based on the given categories and the link. */ public static List<SolrInputDocument> toSolrDocument(MCRCategLinkReference linkReference, Collection<MCRCategoryID> categories) { return categories.stream() .map(categoryId -> new MCRSolrCategoryLink(categoryId, linkReference)) .map(MCRSolrCategoryLink::toSolrDocument) .collect(Collectors.toList()); } /** * Reindex a bunch of {@link MCRCategory}. Be aware that this method does not fail * if a reindex of a single category causes an exception (its just logged). * * @param categories the categories to reindex */ public static void reindex(MCRCategory... categories) { SolrClient solrClient = getCore().getClient(); for (MCRCategory category : categories) { if (category == null) { continue; } MCRSolrCategory solrCategory = new MCRSolrCategory(category); try { solrClient.add(solrCategory.toSolrDocument()); } catch (Exception exc) { LOGGER.error("Unable to reindex {}", category.getId(), exc); } } try { solrClient.commit(); } catch (Exception exc) { LOGGER.error("Unable to commit reindexed categories", exc); } } /** * Returns a collection of category id instances. * * @param categoryIds list of category ids as string */ public static Collection<MCRCategoryID> fromString(Collection<String> categoryIds) { List<MCRCategoryID> idList = new ArrayList<>(categoryIds.size()); for (String categoyId : categoryIds) { idList.add(MCRCategoryID.fromString(categoyId)); } return idList; } public static void reindex(Collection<MCRCategoryID> categoryIds) { List<MCRCategory> categoryList = new ArrayList<>(categoryIds.size()); MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance(); for (MCRCategoryID categoryId : categoryIds) { MCRCategory category = dao.getCategory(categoryId, 0); categoryList.add(category); } reindex(categoryList.toArray(MCRCategory[]::new)); } /** * Returns the solr classification core. */ public static MCRSolrCore getCore() { Optional<MCRSolrCore> classCore = MCRSolrClientFactory.get(CLASSIFICATION_CORE_TYPE); return classCore.orElseThrow(() -> MCRSolrUtils.getCoreConfigMissingException(CLASSIFICATION_CORE_TYPE)); } /** * Encodes the mycore category id to a solr usable one. * * @param classId the id to encode */ public static String encodeCategoryId(MCRCategoryID classId) { return classId.toString().replaceAll(":", "\\\\:"); } protected static void solrDelete(MCRCategoryID id, MCRCategory parent) { try { // remove all descendants and itself HttpSolrClient solrClient = MCRSolrClassificationUtil.getCore().getClient(); List<String> toDelete = MCRSolrSearchUtils.listIDs(solrClient, "ancestor:" + MCRSolrClassificationUtil.encodeCategoryId(id)); toDelete.add(id.toString()); solrClient.deleteById(toDelete); // reindex parent if (parent != null) { MCRSolrClassificationUtil.reindex(parent); } } catch (Exception exc) { LOGGER.error("Solr: unable to delete categories of parent {}", id); } } protected static void solrMove(MCRCategoryID id, MCRCategoryID newParentID) { try { SolrClient solrClient = MCRSolrClassificationUtil.getCore().getClient(); List<String> reindexList = MCRSolrSearchUtils.listIDs(solrClient, "ancestor:" + MCRSolrClassificationUtil.encodeCategoryId(id)); reindexList.add(id.toString()); reindexList.add(newParentID.toString()); MCRSolrClassificationUtil.reindex(MCRSolrClassificationUtil.fromString(reindexList)); } catch (Exception exc) { LOGGER.error("Solr: unable to move categories of category {} to {}", id, newParentID); } } }
11,081
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrCategLinkService.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/classification/MCRSolrCategLinkService.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classification; import java.io.IOException; 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.SolrServerException; import org.apache.solr.common.SolrInputDocument; import org.mycore.datamodel.classifications2.MCRCategLinkReference; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.impl.MCRCategLinkServiceImpl; /** * Solr extension of the category link service. Updates the solr index on set and delete * operations. * * @see MCRSolrCategoryLink * @author Matthias Eichner */ public class MCRSolrCategLinkService extends MCRCategLinkServiceImpl { private static final Logger LOGGER = LogManager.getLogger(MCRSolrCategLinkService.class); @Override public void setLinks(MCRCategLinkReference objectReference, Collection<MCRCategoryID> categories) { super.setLinks(objectReference, categories); // solr SolrClient solrClient = MCRSolrClassificationUtil.getCore().getClient(); List<SolrInputDocument> solrDocumentList = MCRSolrClassificationUtil .toSolrDocument(objectReference, categories); MCRSolrClassificationUtil.bulkIndex(solrClient, solrDocumentList); } @Override public void deleteLink(MCRCategLinkReference reference) { super.deleteLink(reference); // solr try { SolrClient solrClient = MCRSolrClassificationUtil.getCore().getClient(); delete(solrClient, reference); } catch (Exception exc) { LOGGER.error("Unable to delete links of object {}", reference.getObjectID(), exc); } } @Override public void deleteLinks(Collection<MCRCategLinkReference> references) { super.deleteLinks(references); // solr SolrClient solrClient = MCRSolrClassificationUtil.getCore().getClient(); for (MCRCategLinkReference reference : references) { try { delete(solrClient, reference); } catch (Exception exc) { LOGGER.error("Unable to delete links of object {}", reference.getObjectID(), exc); } } } /** * Delete the given reference in solr. */ protected void delete(SolrClient solrClient, MCRCategLinkReference reference) throws SolrServerException, IOException { solrClient.deleteByQuery("+type:link +object:" + reference.getObjectID(), 500); } }
3,341
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrCategoryDAO.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-solr/src/main/java/org/mycore/solr/classification/MCRSolrCategoryDAO.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should 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.classification; import java.net.URI; import java.util.Collection; import java.util.SortedSet; import org.mycore.datamodel.classifications2.MCRCategory; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.MCRLabel; import org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImpl; import org.mycore.datamodel.classifications2.impl.MCRCategoryImpl; /** * Extends the default category dao with solr support. Every create/write/delete operation * on a classification/category results in a solr reindex additionally. * * @author Matthias Eichner */ public class MCRSolrCategoryDAO extends MCRCategoryDAOImpl { @Override public MCRCategory setURI(MCRCategoryID id, URI uri) { MCRCategory category = super.setURI(id, uri); MCRSolrClassificationUtil.reindex(category); return category; } @Override public MCRCategory setLabel(MCRCategoryID id, MCRLabel label) { MCRCategory category = super.setLabel(id, label); MCRSolrClassificationUtil.reindex(category); return category; } @Override public MCRCategory setLabels(MCRCategoryID id, SortedSet<MCRLabel> labels) { MCRCategory category = super.setLabels(id, labels); MCRSolrClassificationUtil.reindex(category); return category; } @Override public MCRCategory removeLabel(MCRCategoryID id, String lang) { MCRCategory category = super.removeLabel(id, lang); MCRSolrClassificationUtil.reindex(category); return category; } @Override public MCRCategory addCategory(MCRCategoryID parentID, MCRCategory category, int position) { MCRCategory parent = super.addCategory(parentID, category, position); MCRSolrClassificationUtil.reindex(category, parent); return parent; } @Override public void deleteCategory(MCRCategoryID id) { MCRCategory category = MCRCategoryDAOFactory.getInstance().getCategory(id, 0); MCRCategory parent = category.getParent(); super.deleteCategory(id); MCRSolrClassificationUtil.solrDelete(id, parent); } @Override public void moveCategory(MCRCategoryID id, MCRCategoryID newParentID, int index) { super.moveCategory(id, newParentID, index); MCRSolrClassificationUtil.solrMove(id, newParentID); } @Override public Collection<MCRCategoryImpl> replaceCategory(MCRCategory newCategory) throws IllegalArgumentException { Collection<MCRCategoryImpl> replacedCategories = super.replaceCategory(newCategory); // remove all old categories MCRSolrClassificationUtil.solrDelete(newCategory.getId(), newCategory.getParent()); // reindex all new MCRSolrClassificationUtil.reindex(replacedCategories.toArray(MCRCategory[]::new)); return replacedCategories; } }
3,710
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileSystemEventTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/test/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemEventTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SecureDirectoryStream; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mycore.common.MCRTestCase; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.common.events.MCREventManager; import org.mycore.datamodel.ifs2.MCRStoreManager; import org.mycore.datamodel.niofs.MCRAbstractFileSystem; import org.mycore.datamodel.niofs.MCRPath; public class MCRFileSystemEventTest extends MCRTestCase { private EventRegister register; @Rule public TemporaryFolder storeFolder = new TemporaryFolder(); @Rule public TemporaryFolder exportFolder = new TemporaryFolder(); private Path derivateRoot; @Override public void setUp() throws Exception { super.setUp(); register = new EventRegister(); MCREventManager.instance().addEventHandler(MCREvent.ObjectType.PATH, register); derivateRoot = Paths.get(URI.create("ifs2:/junit_derivate_00000001:/")); } @Override public void tearDown() throws Exception { MCREventManager.instance().removeEventHandler(MCREvent.ObjectType.PATH, register); register.clear(); MCRStoreManager.removeStore("IFS2_junit_derivate"); super.tearDown(); } @Override protected Map<String, String> getTestProperties() { final Map<String, String> map = super.getTestProperties(); map.put("MCR.Metadata.Type.derivate", "true"); map.put("MCR.IFS2.Store.IFS2_junit_derivate.BaseDir", storeFolder.getRoot().getAbsolutePath()); return map; } @Override protected boolean isDebugEnabled() { return true; } private long countEvents(MCREvent.EventType type) { return register.getEntries().stream() .map(EventRegisterEntry::getEventType) .filter(type::equals) .count(); } @Test public void testRegister() throws IOException { final Path tmpFile = File.createTempFile(this.getClass().getName(), ".test").toPath(); tmpFile.toFile().deleteOnExit(); final BasicFileAttributes attributes = Files.readAttributes(tmpFile, BasicFileAttributes.class); Assert.assertTrue(register.getEntries().isEmpty()); MCRPathEventHelper.fireFileCreateEvent(tmpFile, attributes); Assert.assertEquals(1, register.getEntries().size()); register.getEntries().forEach(System.out::println); register.clear(); Files.delete(tmpFile); } @Test public void testFiles() throws IOException { Path file = derivateRoot.resolve("File.txt"); Assert.assertTrue(register.getEntries().isEmpty()); Files.createFile(file); Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); register.clear(); Files.writeString(file, "Hello World!", StandardCharsets.UTF_8); Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.UPDATE)); register.clear(); Files.delete(file); Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); register.clear(); Files.writeString(file, "Hello World!", StandardCharsets.UTF_8); Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); register.clear(); final Path newFile = file.getParent().resolve("File.old"); Files.move(file, newFile); //register.getEntries().forEach(System.out::println); Assert.assertEquals(2, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); register.clear(); final byte[] bytes = Files.readAllBytes(newFile); Assert.assertTrue(register.getEntries().isEmpty()); Assert.assertEquals("Hello World!", new String(bytes, StandardCharsets.UTF_8)); } @Test public void testDirectoryStream() throws IOException { Path dir1 = derivateRoot.resolve("dir1"); Path dir2 = derivateRoot.resolve("dir2"); Path file = dir1.resolve("File.txt"); final MCRAbstractFileSystem fileSystem = (MCRAbstractFileSystem) derivateRoot.getFileSystem(); fileSystem.createRoot(MCRPath.toMCRPath(derivateRoot).getOwner()); Files.createDirectory(dir1); Files.createDirectory(dir2); Assert.assertTrue(register.getEntries().isEmpty()); Files.writeString(file, "Hello World!", StandardCharsets.UTF_8); Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); register.clear(); try (DirectoryStream<Path> dir1Stream = Files.newDirectoryStream(dir1); DirectoryStream<Path> dir2Stream = Files.newDirectoryStream(dir2)) { if (!(dir1Stream instanceof SecureDirectoryStream)) { LogManager.getLogger().warn("Current OS ({}) does not provide SecureDirectoryStream.", System.getProperty("os.name")); return; } //further testing SecureDirectoryStream<Path> sDir1Stream = (SecureDirectoryStream<Path>) dir1Stream; SecureDirectoryStream<Path> sDir2Stream = (SecureDirectoryStream<Path>) dir2Stream; //relative -> relative sDir1Stream.move(file.getFileName(), sDir2Stream, file.getFileName()); Assert.assertEquals(2, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); sDir2Stream.move(file.getFileName(), sDir1Stream, file.getFileName()); register.clear(); //absolute -> relative sDir1Stream.move(file, sDir2Stream, file.getFileName()); Assert.assertEquals(2, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); sDir2Stream.move(file.getFileName(), sDir1Stream, file.getFileName()); register.clear(); //relative -> absolute sDir1Stream.move(file.getFileName(), sDir2Stream, dir2.resolve(file.getFileName())); Assert.assertEquals(2, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); sDir2Stream.move(file.getFileName(), sDir1Stream, file.getFileName()); register.clear(); //absolute -> absolute sDir1Stream.move(file, sDir2Stream, dir2.resolve(file.getFileName())); Assert.assertEquals(2, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); sDir2Stream.move(file.getFileName(), sDir1Stream, file.getFileName()); register.clear(); //rename sDir1Stream.move(file.getFileName(), sDir1Stream, dir1.resolve("Junit.txt").getFileName()); Assert.assertEquals(2, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); sDir1Stream.move(dir1.resolve("Junit.txt").getFileName(), sDir1Stream, file.getFileName()); register.clear(); //move to local dir final Path exportDir = exportFolder.getRoot().toPath(); try (DirectoryStream<Path> exportDirStream = Files.newDirectoryStream(exportDir)) { if (exportDirStream instanceof SecureDirectoryStream) { final SecureDirectoryStream<Path> sExportDirStream = (SecureDirectoryStream<Path>) exportDirStream; final Path localFilePath = MCRFileSystemUtils.toNativePath(exportDir.getFileSystem(), file.getFileName()); sDir1Stream.move(file.getFileName(), sExportDirStream, localFilePath); Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.DELETE)); register.clear(); try ( SeekableByteChannel targetChannel = sDir1Stream.newByteChannel(file.getFileName(), Set.of( StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)); FileInputStream fis = new FileInputStream(exportDir.resolve(localFilePath).toFile()); FileChannel inChannel = fis.getChannel()) { long bytesTransferred = 0; while (bytesTransferred < inChannel.size()) { bytesTransferred += inChannel.transferTo(bytesTransferred, inChannel.size(), targetChannel); } } Assert.assertEquals(1, register.getEntries().size()); Assert.assertEquals(1, countEvents(MCREvent.EventType.CREATE)); register.clear(); } } } } private static class EventRegister extends MCREventHandlerBase { private List<EventRegisterEntry> entries; EventRegister() { entries = new ArrayList<>(); } @Override protected void handlePathUpdated(MCREvent evt, Path path, BasicFileAttributes attrs) { addEntry(evt, path, attrs); } @Override protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) { addEntry(evt, path, attrs); } @Override protected void handlePathCreated(MCREvent evt, Path path, BasicFileAttributes attrs) { addEntry(evt, path, attrs); } private void addEntry(MCREvent evt, Path path, BasicFileAttributes attrs) { entries.add(new MCRFileSystemEventTest.EventRegisterEntry(evt.getEventType(), path, attrs)); } void clear() { entries.clear(); } List<EventRegisterEntry> getEntries() { return entries; } } private static class EventRegisterEntry { private Instant time; private MCREvent.EventType eventType; private Path path; private BasicFileAttributes attrs; private final StackTraceElement[] stackTrace; public EventRegisterEntry(MCREvent.EventType eventType, Path path, BasicFileAttributes attrs) { this.time = Instant.now(); this.eventType = eventType; this.path = path; this.attrs = attrs; this.stackTrace = Thread.currentThread().getStackTrace(); } public Instant getTime() { return time; } public MCREvent.EventType getEventType() { return eventType; } public Path getPath() { return path; } public BasicFileAttributes getAttrs() { return attrs; } @Override public String toString() { return "EventRegisterEntry{" + "time=" + time + ", eventType='" + eventType + '\'' + ", path=" + path + ", attrs=" + attrs + '}'; } public String getStackTraceAsString() { return Stream.of(stackTrace) .map(StackTraceElement::toString) .collect(Collectors.joining("\n", "\n", "")); } } }
13,534
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileNameCheckTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/test/java/org/mycore/common/MCRFileNameCheckTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.common; import java.io.IOException; import java.nio.file.Files; import org.junit.Before; import org.junit.Test; import org.mycore.access.MCRAccessException; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.niofs.MCRPath; public class MCRFileNameCheckTest extends MCRIFSTest { private MCRDerivate derivate; @Before public void setup() throws MCRAccessException { MCRObject root = createObject(); derivate = createDerivate(root.getId()); MCRMetadataManager.create(root); MCRMetadataManager.create(derivate); } @Test(expected = IOException.class) public void checkIllegalWindowsFileName() throws IOException { final MCRPath aux = MCRPath.getPath(derivate.toString(), "aux"); Files.createFile(aux); } @Test(expected = IOException.class) public void checkIllegalFileName() throws IOException { final MCRPath info = MCRPath.getPath(derivate.toString(), "info@mycore.de"); Files.createFile(info); } @Test(expected = IOException.class) public void checkIllegalDirectoryName() throws IOException { final MCRPath dirName = MCRPath.getPath(derivate.toString(), "Nur ein \"Test\""); Files.createDirectory(dirName); } }
2,128
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIFSCopyTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/test/java/org/mycore/common/MCRIFSCopyTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.common; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.junit.Test; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.util.concurrent.MCRFixedUserCallable; public class MCRIFSCopyTest extends MCRIFSTest { private MCRObject root; private MCRDerivate derivate; @Test public void sync() throws Exception { create(); copy("/anpassbar.jpg", "anpassbar.jpg", derivate); copy("/nachhaltig.jpg", "nachhaltig.jpg", derivate); copy("/vielseitig.jpg", "vielseitig.jpg", derivate); try (Stream<Path> streamPath = Files.list(MCRPath.getPath(derivate.getId().toString(), "/"))) { assertEquals("the derivate should contain three files", 3, streamPath.count()); } } @Test public void async() throws Exception { // create derivate create(); MCRSessionMgr.getCurrentSession(); MCRTransactionHelper.commitTransaction(); // execute threads MCRSystemUserInformation systemUser = MCRSystemUserInformation.getSystemUserInstance(); ExecutorService executorService = Executors.newFixedThreadPool(3); Future<Exception> future1 = executorService .submit(new MCRFixedUserCallable<>(new CopyTask("anpassbar.jpg", derivate), systemUser)); Future<Exception> future2 = executorService .submit(new MCRFixedUserCallable<>(new CopyTask("nachhaltig.jpg", derivate), systemUser)); Future<Exception> future3 = executorService .submit(new MCRFixedUserCallable<>(new CopyTask("vielseitig.jpg", derivate), systemUser)); throwException(future1.get(5, TimeUnit.SECONDS)); throwException(future2.get(5, TimeUnit.SECONDS)); throwException(future3.get(5, TimeUnit.SECONDS)); try (Stream<Path> streamPath = Files.list(MCRPath.getPath(derivate.getId().toString(), "/"))) { assertEquals("the derivate should contain three files", 3, streamPath.count()); } executorService.awaitTermination(1, TimeUnit.SECONDS); } private void throwException(Exception e) throws Exception { if (e != null) { throw e; } } public void create() throws Exception { root = createObject(); derivate = createDerivate(root.getId()); MCRMetadataManager.create(root); MCRMetadataManager.create(derivate); } @Override public void tearDown() throws Exception { MCRMetadataManager.delete(derivate); MCRMetadataManager.delete(root); super.tearDown(); } public static void copy(String from, String to, MCRDerivate derivate) throws IOException { try (InputStream fileInputStream = MCRIFSTest.class.getResourceAsStream(from)) { assertNotNull("cannot find file " + from, fileInputStream); Files.copy(fileInputStream, MCRPath.getPath(derivate.toString(), to)); } } private static class CopyTask implements Callable<Exception> { private String fileName; private MCRDerivate derivate; CopyTask(String fileName, MCRDerivate derivate) { this.fileName = fileName; this.derivate = derivate; } @Override public Exception call() { try { MCRIFSCopyTest.copy("/" + fileName, fileName, derivate); return null; } catch (Exception exc) { return exc; } } } }
4,785
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIFSTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/test/java/org/mycore/common/MCRIFSTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.common; import java.util.Map; import org.junit.Before; import org.mycore.access.MCRAccessBaseImpl; import org.mycore.access.strategies.MCRAccessCheckStrategy; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventManager; import org.mycore.datamodel.common.MCRXMLMetadataEventHandler; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaIFS; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; public abstract class MCRIFSTest extends MCRStoreTestCase { @Before public void setUp() throws Exception { super.setUp(); MCREventManager.instance().clear().addEventHandler(MCREvent.ObjectType.OBJECT, new MCRXMLMetadataEventHandler()); } @Override protected Map<String, String> getTestProperties() { Map<String, String> testProperties = super.getTestProperties(); testProperties.put("MCR.datadir", "%MCR.basedir%/data"); testProperties .put("MCR.Persistence.LinkTable.Store.Class", "org.mycore.backend.hibernate.MCRHIBLinkTableStore"); testProperties.put("MCR.Access.Class", MCRAccessBaseImpl.class.getName()); testProperties.put("MCR.Access.Strategy.Class", AlwaysTrueStrategy.class.getName()); testProperties.put("MCR.Metadata.Type.object", "true"); testProperties.put("MCR.Metadata.Type.derivate", "true"); return testProperties; } public static MCRObject createObject() { MCRObject object = new MCRObject(); object.setId(MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("mycore_object")); object.setSchema("noSchema"); return object; } public static MCRDerivate createDerivate(MCRObjectID objectHrefId) { MCRDerivate derivate = new MCRDerivate(); derivate.setId(MCRMetadataManager.getMCRObjectIDGenerator().getNextFreeId("mycore_derivate")); derivate.setSchema("datamodel-derivate.xsd"); MCRMetaIFS ifs = new MCRMetaIFS(); ifs.setSubTag("internal"); ifs.setSourcePath(null); derivate.getDerivate().setInternals(ifs); MCRMetaLinkID mcrMetaLinkID = new MCRMetaLinkID(); mcrMetaLinkID.setReference(objectHrefId.toString(), null, null); derivate.getDerivate().setLinkMeta(mcrMetaLinkID); return derivate; } public static class AlwaysTrueStrategy implements MCRAccessCheckStrategy { @Override public boolean checkPermission(String id, String permission) { return true; } } }
3,468
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDerivateTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/test/java/org/mycore/common/MCRDerivateTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.common; import org.junit.Test; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; public class MCRDerivateTest extends MCRIFSTest { MCRObject root; MCRDerivate derivate; @Test public void create() throws Exception { root = createObject(); derivate = createDerivate(root.getId()); MCRMetadataManager.create(root); MCRMetadataManager.create(derivate); } @Override public void tearDown() throws Exception { MCRMetadataManager.delete(derivate); MCRMetadataManager.delete(root); super.tearDown(); } }
1,441
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-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/package-info.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /** * Contains classes to build a {@link java.nio.file.FileSystem} on top of * {@link org.mycore.datamodel.ifs2.MCRStoredNode}. * @author Thomas Scheffler (yagee) * */ package org.mycore.datamodel.niofs.ifs2;
941
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPathEventHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRPathEventHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventManager; class MCRPathEventHelper { private static void fireFileEvent(MCREvent.EventType event, Path file, BasicFileAttributes attrs) { MCREvent fileEvent = new MCREvent(MCREvent.ObjectType.PATH, event); fileEvent.put(MCREvent.PATH_KEY, file); if (attrs != null) { fileEvent.put(MCREvent.FILEATTR_KEY, attrs); } MCREventManager.instance().handleEvent(fileEvent); } static void fireFileCreateEvent(Path file, BasicFileAttributes attrs) { fireFileEvent(MCREvent.EventType.CREATE, file, Objects.requireNonNull(attrs)); } static void fireFileUpdateEvent(Path file, BasicFileAttributes attrs) { fireFileEvent(MCREvent.EventType.UPDATE, file, Objects.requireNonNull(attrs)); } static void fireFileDeleteEvent(Path file) { fireFileEvent(MCREvent.EventType.DELETE, file, null); } }
1,845
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileChannel.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileChannel.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import org.mycore.common.content.streams.MCRMD5InputStream; import org.mycore.datamodel.ifs.MCRContentInputStream; import org.mycore.datamodel.ifs2.MCRFile; import org.mycore.datamodel.niofs.MCRFileAttributes; import org.mycore.datamodel.niofs.MCRPath; /** * @author Thomas Scheffler (yagee) */ public class MCRFileChannel extends FileChannel { private final MCRPath path; private FileChannel baseChannel; private MCRFile file; private boolean write; private boolean modified; private boolean create; /** * MyCoRe implementation of a Java NIO FileChannel * * @param path - the MyCoRe path object * @param file - the MyCoRe file object * @param baseChannel - the base channel * @param write - true, if the FileChannel is writeable * @param create - true, if the FileChannel can create new files * * @see FileChannel */ public MCRFileChannel(MCRPath path, MCRFile file, FileChannel baseChannel, boolean write, boolean create) { this.path = path; this.file = file; this.baseChannel = baseChannel; this.write = write; this.modified = false; this.create = create; if (write && !path.isAbsolute()) { throw new IllegalArgumentException("Path must be absolute with write operations"); } } public void implCloseChannel() throws IOException { baseChannel.close(); //MCR-1003 close before updating metadata, as we read attributes from this file later updateMetadata(); } private void updateMetadata() throws IOException { if (!write || !modified) { if (create) { MCRPathEventHelper.fireFileCreateEvent(path, file.getBasicFileAttributes()); } return; } MessageDigest md5Digest = MCRMD5InputStream.buildMD5Digest(); FileChannel md5Channel = (FileChannel) Files.newByteChannel(file.getLocalPath(), StandardOpenOption.READ); try { long position = 0; long size = md5Channel.size(); while (position < size) { long remainingSize = size - position; final ByteBuffer byteBuffer = md5Channel.map(MapMode.READ_ONLY, position, Math.min(remainingSize, Integer.MAX_VALUE)); while (byteBuffer.hasRemaining()) { md5Digest.update(byteBuffer); } position += byteBuffer.limit(); } } finally { if (!md5Channel.equals(baseChannel)) { md5Channel.close(); } } String md5 = MCRContentInputStream.getMD5String(md5Digest.digest()); file.setMD5(md5); final MCRFileAttributes<String> basicFileAttributes = file.getBasicFileAttributes(); if (create) { MCRPathEventHelper.fireFileCreateEvent(path, basicFileAttributes); } else { MCRPathEventHelper.fireFileUpdateEvent(path, basicFileAttributes); } } //Delegate to baseChannel public int read(ByteBuffer dst) throws IOException { return baseChannel.read(dst); } public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { return baseChannel.read(dsts, offset, length); } public int write(ByteBuffer src) throws IOException { modified = true; return baseChannel.write(src); } public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { modified = true; return baseChannel.write(srcs, offset, length); } public long position() throws IOException { return baseChannel.position(); } public FileChannel position(long newPosition) throws IOException { return baseChannel.position(newPosition); } public long size() throws IOException { return baseChannel.size(); } public FileChannel truncate(long size) throws IOException { modified = true; return baseChannel.truncate(size); } public void force(boolean metaData) throws IOException { baseChannel.force(metaData); } public long transferTo(long position, long count, WritableByteChannel target) throws IOException { return baseChannel.transferTo(position, count, target); } public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException { modified = true; return baseChannel.transferFrom(src, position, count); } public int read(ByteBuffer dst, long position) throws IOException { return baseChannel.read(dst, position); } public int write(ByteBuffer src, long position) throws IOException { modified = true; return baseChannel.write(src, position); } public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException { if (write) { modified = true; } return baseChannel.map(mode, position, size); } public FileLock lock(long position, long size, boolean shared) throws IOException { return baseChannel.lock(position, size, shared); } public FileLock tryLock(long position, long size, boolean shared) throws IOException { return baseChannel.tryLock(position, size, shared); } }
6,500
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDirectoryStreamHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRDirectoryStreamHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.FileInputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.ClosedDirectoryStreamException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileTime; import java.util.Iterator; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.function.MCRThrowFunction; import org.mycore.datamodel.ifs2.MCRDirectory; import org.mycore.datamodel.ifs2.MCRFile; import org.mycore.datamodel.ifs2.MCRFileCollection; import org.mycore.datamodel.ifs2.MCRStoredNode; import org.mycore.datamodel.niofs.MCRAbstractFileSystem; import org.mycore.datamodel.niofs.MCRFileAttributes; import org.mycore.datamodel.niofs.MCRMD5AttributeView; import org.mycore.datamodel.niofs.MCRPath; /** * A {@link SecureDirectoryStream} on internal file system. This implementation uses IFS directly. Do use this class but * stick to the interface. * * @author Thomas Scheffler (yagee) */ class MCRDirectoryStreamHelper { static Logger LOGGER = LogManager.getLogger(); static DirectoryStream<Path> getInstance(MCRDirectory dir, MCRPath path) throws IOException { DirectoryStream.Filter<Path> filter = (dir instanceof MCRFileCollection) ? MCRFileCollectionFilter.FILTER : AcceptAllFilter.FILTER; LOGGER.debug("Dir {}, class {}, filter {}", path, dir.getClass(), filter.getClass()); DirectoryStream<Path> baseDirectoryStream = Files.newDirectoryStream(dir.getLocalPath(), filter); LOGGER.debug("baseStream {}", baseDirectoryStream.getClass()); if (baseDirectoryStream instanceof java.nio.file.SecureDirectoryStream) { LOGGER.debug("Returning SecureDirectoryStream"); return new SecureDirectoryStream(dir, path, (java.nio.file.SecureDirectoryStream<Path>) baseDirectoryStream); } return new SimpleDirectoryStream<>(path, baseDirectoryStream); } private static class AcceptAllFilter implements DirectoryStream.Filter<Path> { static final MCRDirectoryStreamHelper.AcceptAllFilter FILTER = new AcceptAllFilter(); @Override public boolean accept(Path entry) { return true; } } private static class MCRFileCollectionFilter implements DirectoryStream.Filter<Path> { static final MCRDirectoryStreamHelper.MCRFileCollectionFilter FILTER = new MCRFileCollectionFilter(); @Override public boolean accept(Path entry) { return !MCRFileCollection.DATA_FILE.equals(entry.getFileName().toString()); } } private static class SimpleDirectoryStream<T extends DirectoryStream<Path>> implements DirectoryStream<Path> { protected final MCRPath dirPath; protected final T baseStream; boolean isClosed; SimpleDirectoryStream(MCRPath dirPath, T baseStream) { this.dirPath = dirPath; this.baseStream = baseStream; } @Override public Iterator<Path> iterator() { return new SimpleDirectoryIterator(dirPath, baseStream); } @Override public void close() throws IOException { baseStream.close(); isClosed = true; } protected boolean isClosed() { return isClosed; } } private static class SecureDirectoryStream extends SimpleDirectoryStream<java.nio.file.SecureDirectoryStream<Path>> implements java.nio.file.SecureDirectoryStream<Path> { private final MCRDirectory dir; SecureDirectoryStream(MCRDirectory dir, MCRPath dirPath, java.nio.file.SecureDirectoryStream<Path> baseStream) { super(dirPath, baseStream); this.dir = dir; } @Override public java.nio.file.SecureDirectoryStream<Path> newDirectoryStream(Path path, LinkOption... options) throws IOException { checkClosed(); if (path.isAbsolute()) { return (SecureDirectoryStream) Files.newDirectoryStream(path); } MCRStoredNode nodeByPath = resolve(path); if (!nodeByPath.isDirectory()) { throw new NotDirectoryException(nodeByPath.getPath()); } MCRDirectory newDir = (MCRDirectory) nodeByPath; return (java.nio.file.SecureDirectoryStream<Path>) MCRDirectoryStreamHelper.getInstance(newDir, getCurrentSecurePath(newDir)); } private MCRStoredNode resolve(Path path) { checkRelativePath(path); return (MCRStoredNode) dir.getNodeByPath(path.toString()); } /** * always resolves the path to this directory * currently not really secure, but more secure than sticking to <code>dirPath</code> * @param node to get Path from */ private MCRPath getCurrentSecurePath(MCRStoredNode node) { return MCRAbstractFileSystem.getPath(MCRFileSystemUtils.getOwnerID(node), node.getPath(), MCRFileSystemProvider.getMCRIFSFileSystem()); } @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { checkClosed(); if (path.isAbsolute()) { return Files.newByteChannel(path, options); } MCRPath mcrPath = checkRelativePath(path); Path resolved = getCurrentSecurePath(dir).resolve(mcrPath); return Files.newByteChannel(resolved, options); } @Override public void deleteFile(Path path) throws IOException { checkClosed(); if (path.isAbsolute()) { Files.delete(path); } final MCRStoredNode storedNode = resolve(path); final MCRPath mcrPath = getCurrentSecurePath(storedNode); storedNode.delete(); MCRPathEventHelper.fireFileDeleteEvent(mcrPath); } @Override public void deleteDirectory(Path path) throws IOException { checkClosed(); if (path.isAbsolute()) { Files.delete(path); } resolve(path).delete(); } @Override public void move(Path srcpath, java.nio.file.SecureDirectoryStream<Path> targetdir, Path targetpath) throws IOException { checkClosed(); MCRPath src = checkFileSystem(srcpath); MCRFile srcFile = srcpath.isAbsolute() ? MCRFileSystemUtils.getMCRFile(src, false, false, true) : (MCRFile) resolve(srcpath); if (srcFile == null) { throw new NoSuchFileException(this.dirPath.toString(), srcpath.toString(), null); } if (!targetpath.isAbsolute() && targetdir instanceof SecureDirectoryStream that) { LOGGER.debug("Move Case #1"); MCRFile file = getMCRFile(that, targetpath); Files.delete(file.getLocalPath()); //delete for move if (!srcpath.isAbsolute()) { LOGGER.debug("Move Case #1.1"); baseStream.move(toLocalPath(src), that.baseStream, toLocalPath(targetpath)); } else { LOGGER.debug("Move Case #1.2"); baseStream.move(srcFile.getLocalPath(), that.baseStream, toLocalPath(targetpath)); } file.setMD5(srcFile.getMD5()); //restore md5 final MCRPath targetAbsolutePath = that.getCurrentSecurePath(file); final BasicFileAttributes attrs = that.getFileAttributeView(targetpath, BasicFileAttributeView.class) .readAttributes(); MCRPathEventHelper.fireFileCreateEvent(targetAbsolutePath, attrs); } else { LOGGER.debug("Move Case #2"); if (targetpath.isAbsolute()) { LOGGER.debug("Move Case #2.1"); Files.move(srcFile.getLocalPath(), targetpath, StandardCopyOption.COPY_ATTRIBUTES); } else { LOGGER.debug("Move Case #2.2"); try (FileInputStream fis = new FileInputStream(srcFile.getLocalPath().toFile()); FileChannel inChannel = fis.getChannel(); SeekableByteChannel targetChannel = targetdir.newByteChannel(targetpath, Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) { long bytesTransferred = 0; while (bytesTransferred < inChannel.size()) { bytesTransferred += inChannel.transferTo(bytesTransferred, inChannel.size(), targetChannel); } } } } srcFile.delete(); MCRPathEventHelper.fireFileDeleteEvent(this.dirPath.resolve(src)); } private static MCRFile getMCRFile(SecureDirectoryStream ds, Path relativePath) throws IOException { MCRStoredNode storedNode = ds.resolve(relativePath); if (storedNode != null) { throw new FileAlreadyExistsException(ds.dirPath.resolve(relativePath).toString()); } //does not exist, have to create MCRStoredNode parent = ds.dir; if (relativePath.getNameCount() > 1) { parent = (MCRStoredNode) parent.getNodeByPath(relativePath.getParent().toString()); if (parent == null) { throw new NoSuchFileException(ds.dirPath.resolve(relativePath.getParent()).toString()); } if (!(parent instanceof MCRDirectory)) { throw new NotDirectoryException(ds.dirPath.resolve(relativePath.getParent()).toString()); } } return ((MCRDirectory) parent).createFile(relativePath.getFileName().toString()); } @Override public <V extends FileAttributeView> V getFileAttributeView(Class<V> type) { V fileAttributeView = baseStream.getFileAttributeView(type); if (fileAttributeView != null) { return fileAttributeView; } if (type == MCRMD5AttributeView.class) { BasicFileAttributeView baseView = baseStream.getFileAttributeView(BasicFileAttributeView.class); return (V) new MD5FileAttributeViewImpl(baseView, (v) -> dir); } return null; } @Override public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { Path localRelativePath = toLocalPath(path); if (type == MCRMD5AttributeView.class) { BasicFileAttributeView baseView = baseStream.getFileAttributeView(localRelativePath, BasicFileAttributeView.class, options); return (V) new MD5FileAttributeViewImpl(baseView, (v) -> resolve(path)); } return baseStream.getFileAttributeView(localRelativePath, type, options); } private Path toLocalPath(Path path) { return MCRFileSystemUtils.toNativePath(dir.getLocalPath().getFileSystem(), path); } void checkClosed() { if (isClosed) { throw new ClosedDirectoryStreamException(); } } MCRPath checkRelativePath(Path path) { if (path.isAbsolute()) { throw new IllegalArgumentException(path + " is absolute."); } return checkFileSystem(path); } private MCRPath checkFileSystem(Path path) { if (!(path.getFileSystem() instanceof MCRIFSFileSystem)) { throw new IllegalArgumentException(path + " is not from " + MCRIFSFileSystem.class.getSimpleName()); } return MCRPath.toMCRPath(path); } } private static class SimpleDirectoryIterator implements Iterator<Path> { private final Iterator<Path> baseIterator; private final MCRPath dir; SimpleDirectoryIterator(MCRPath dir, DirectoryStream<Path> baseStream) { this.baseIterator = baseStream.iterator(); this.dir = dir; } @Override public boolean hasNext() { return baseIterator.hasNext(); } @Override public Path next() { Path basePath = baseIterator.next(); return dir.resolve(basePath.getFileName().toString()); } } private record MD5FileAttributeViewImpl(BasicFileAttributeView baseAttrView, MCRThrowFunction<Void, MCRStoredNode, IOException> nodeSupplier) implements MCRMD5AttributeView { @Override public String name() { return "md5"; } @Override public BasicFileAttributes readAttributes() { return null; } @Override public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException { baseAttrView.setTimes(lastModifiedTime, lastAccessTime, createTime); } @Override public MCRFileAttributes readAllAttributes() throws IOException { MCRStoredNode node = nodeSupplier.apply(null); if (node instanceof MCRFile file) { return MCRFileAttributes.fromAttributes(baseAttrView.readAttributes(), file.getMD5()); } return MCRFileAttributes.fromAttributes(baseAttrView.readAttributes(), null); } } }
15,185
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileSystemUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.ProviderMismatchException; import java.util.ArrayDeque; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.datamodel.ifs2.MCRDirectory; import org.mycore.datamodel.ifs2.MCRFile; import org.mycore.datamodel.ifs2.MCRFileCollection; import org.mycore.datamodel.ifs2.MCRFileStore; import org.mycore.datamodel.ifs2.MCRStoreManager; import org.mycore.datamodel.ifs2.MCRStoredNode; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRAbstractFileSystem; import org.mycore.datamodel.niofs.MCRPath; /** * @author Thomas Scheffler * */ abstract class MCRFileSystemUtils { private static final Logger LOGGER = LogManager.getLogger(MCRFileSystemUtils.class); private static final String DEFAULT_CONFIG_PREFIX = "MCR.IFS.ContentStore.IFS2."; //todo: rename public static final String STORE_ID_PREFIX = "IFS2_"; private static String getBaseDir() { return MCRConfiguration2.getStringOrThrow(DEFAULT_CONFIG_PREFIX + "BaseDir"); } private static String getDefaultSlotLayout() { return MCRConfiguration2.getString(DEFAULT_CONFIG_PREFIX + "SlotLayout") .orElseGet(() -> { String baseID = "a_a"; String formatID = MCRObjectID.formatID(baseID, 1); int patternLength = formatID.length() - baseID.length() - "_".length(); return patternLength - 4 + "-2-2"; }); } static MCRFileCollection getFileCollection(String owner) throws IOException { MCRObjectID derId = MCRObjectID.getInstance(owner); MCRFileStore fileStore = getStore(derId.getBase()); MCRFileCollection fileCollection = fileStore .retrieve(derId.getNumberAsInteger()); if (fileCollection == null) { throw new NoSuchFileException(null, null, "File collection " + owner + " is not available here: " + fileStore.getBaseDirectory()); } return fileCollection; } static MCRFileStore getStore(String base) { String storeBaseDir = getBaseDir(); String sid = STORE_ID_PREFIX + base; storeBaseDir += File.separatorChar + base.replace("_", File.separator); MCRFileStore store = MCRStoreManager.getStore(sid); if (store == null) { synchronized (MCRStoreManager.class) { store = MCRStoreManager.getStore(sid); if (store == null) { store = createStore(sid, storeBaseDir, base); } } } return store; } private static MCRFileStore createStore(String sid, String storeBaseDir, String base) { try { configureStore(sid, storeBaseDir, base); return MCRStoreManager.createStore(sid, MCRFileStore.class); } catch (Exception ex) { String msg = "Could not create IFS2 file store with ID " + sid; throw new MCRConfigurationException(msg, ex); } } private static void configureStore(String sid, String storeBaseDir, String base) { String storeConfigPrefix = "MCR.IFS2.Store." + sid + "."; configureIfNotSet(storeConfigPrefix + "Class", MCRFileStore.class.getName()); configureIfNotSet(storeConfigPrefix + "BaseDir", storeBaseDir); configureIfNotSet(storeConfigPrefix + "Prefix", base + "_"); configureIfNotSet(storeConfigPrefix + "SlotLayout", getDefaultSlotLayout()); } private static void configureIfNotSet(String property, String value) { MCRConfiguration2.getString(property) .ifPresentOrElse(s -> { //if set, do nothing }, () -> { MCRConfiguration2.set(property, value); LOGGER.info("Configured {}={}", property, value); }); } static MCRPath checkPathAbsolute(Path path) { MCRPath mcrPath = MCRPath.toMCRPath(path); if (!(Objects.requireNonNull(mcrPath.getFileSystem(), "'path' requires a associated filesystem.") .provider() instanceof MCRFileSystemProvider)) { throw new ProviderMismatchException("Path does not match to this provider: " + path); } if (!mcrPath.isAbsolute()) { throw new InvalidPathException(mcrPath.toString(), "'path' must be absolute."); } return mcrPath; } static String getOwnerID(MCRStoredNode node) { MCRFileCollection collection = node.getRoot(); int intValue = collection.getID(); String storeId = collection.getStore().getID(); String baseId = storeId.substring(STORE_ID_PREFIX.length()); return MCRObjectID.formatID(baseId, intValue); } static MCRPath toPath(MCRStoredNode node) { String ownerID = getOwnerID(node); String path = node.getPath(); return MCRAbstractFileSystem.getPath(ownerID, path, MCRFileSystemProvider.getMCRIFSFileSystem()); } static MCRFile getMCRFile(MCRPath ifsPath, boolean create, boolean createNew, boolean fireCreateEvent) throws IOException { if (!ifsPath.isAbsolute()) { throw new IllegalArgumentException("'path' needs to be absolute."); } MCRFile file; MCRDirectory root = null; boolean rootCreated = false; try { try { root = getFileCollection(ifsPath.getOwner()); } catch (NoSuchFileException e) { if (create || createNew) { MCRObjectID derId = MCRObjectID.getInstance(ifsPath.getOwner()); root = getStore(derId.getBase()).create(derId.getNumberAsInteger()); rootCreated = true; } else { throw e; } } MCRPath relativePath = toPath(root).relativize(ifsPath); file = getMCRFile(root, relativePath, create, createNew, fireCreateEvent); } catch (Exception e) { if (rootCreated) { LOGGER.error("Exception while getting MCRFile {}. Removing created filesystem nodes.", ifsPath); try { root.delete(); } catch (Exception de) { LOGGER.fatal("Error while deleting file system node: {}", root.getName(), de); } } throw e; } return file; } private static MCRFile getMCRFile(MCRDirectory baseDir, MCRPath relativePath, boolean create, boolean createNew, boolean fireEvent) throws IOException { MCRPath ifsPath = relativePath; if (relativePath.isAbsolute()) { if (getOwnerID(baseDir).equals(relativePath.getOwner())) { ifsPath = toPath(baseDir).relativize(relativePath); } else { throw new IOException(relativePath + " is absolute does not fit to " + toPath(baseDir)); } } Deque<MCRStoredNode> created = new ArrayDeque<>(); MCRFile file; try { file = (MCRFile) baseDir.getNodeByPath(ifsPath.toString()); if (file != null && createNew) { throw new FileAlreadyExistsException(toPath(baseDir).resolve(ifsPath).toString()); } if (file == null & (create || createNew)) { Path normalized = ifsPath.normalize(); MCRDirectory parent = baseDir; int nameCount = normalized.getNameCount(); int directoryCount = nameCount - 1; int i = 0; while (i < directoryCount) { String curName = normalized.getName(i).toString(); MCRDirectory curDir = (MCRDirectory) parent.getChild(curName); if (curDir == null) { curDir = parent.createDir(curName); created.addFirst(curDir); } i++; parent = curDir; } String fileName = normalized.getFileName().toString(); file = parent.createFile(fileName); created.addFirst(file); if (fireEvent) { MCRPathEventHelper.fireFileCreateEvent(toPath(baseDir).resolve(relativePath), file.getBasicFileAttributes()); } } } catch (Exception e) { if (create || createNew) { LOGGER.error("Exception while getting MCRFile {}. Removing created filesystem nodes.", ifsPath); while (created.peekFirst() != null) { MCRStoredNode node = created.pollFirst(); try { node.delete(); } catch (Exception de) { LOGGER.fatal("Error while deleting file system node: {}", node.getName(), de); } } } throw e; } return file; } @SuppressWarnings("unchecked") static <T extends MCRStoredNode> T resolvePath(MCRPath path) throws IOException { if (path.getNameCount() == 0) { return (T) getFileCollection(path.getOwner()); } //recursive call String fileOrDir = path.getFileName().toString(); MCRDirectory parentDir = doResolveParent(path.getParent()) .map(MCRDirectory.class::cast) .orElseThrow(() -> new NoSuchFileException(path.getParent().toString(), fileOrDir, "parent directory does not exist")); return (T) Optional.ofNullable(parentDir.getChild(fileOrDir)) .map(MCRStoredNode.class::cast) .orElseThrow( () -> new NoSuchFileException(path.getParent().toString(), fileOrDir, "file does not exist")); } static Path toNativePath(FileSystem fs, Path path) { if (fs.equals(path.getFileSystem())) { return path; } if (path.isAbsolute()) { throw new IllegalArgumentException("path is absolute"); } return switch (path.getNameCount()) { case 0 -> fs.getPath(""); case 1 -> fs.getPath(path.toString()); default -> { String[] pathComp = new String[path.getNameCount() - 1]; for (int i = 1; i < pathComp.length; i++) { pathComp[i] = path.getName(i).toString(); } yield fs.getPath(path.getName(0).toString(), pathComp); } }; } private static Optional<MCRDirectory> doResolveParent(MCRPath parent) { if (parent.getNameCount() == 0) { MCRObjectID derId = MCRObjectID.getInstance(parent.getOwner()); return Optional.ofNullable(getStore(derId.getBase())) .map(s -> s.retrieve(derId.getNumberAsInteger())); } //recursive call String dirName = parent.getFileName().toString(); return doResolveParent(parent.getParent()) .map(p -> p.getChild(dirName)) .map(MCRDirectory.class::cast); } static Collection<String> getObjectBaseIds() throws IOException { final Path baseDir = Paths.get(getBaseDir()); if (!Files.isDirectory(baseDir)) { return List.of(); } try (Stream<Path> baseDirEntries = Files.list(baseDir)) { return baseDirEntries .filter(Files::isDirectory) .sorted(Comparator.comparing(Path::getFileName)) .flatMap(dir -> { try (Stream<Path> subDirEntries = Files.list(dir)) { return subDirEntries.toList().stream(); //copy required to close the stream } catch (IOException e) { throw new UncheckedIOException(e); } }) .filter(path -> MCRObjectID.isValidType(path.getFileName().toString())) .filter(Files::isDirectory) .sorted(Comparator.comparing(Path::getFileName)) .map(p -> p.getParent().getFileName().toString() + "_" + p.getFileName().toString()) .collect(Collectors.toList()); } catch (UncheckedIOException e) { throw e.getCause(); } } }
13,859
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileTypeDetector.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileTypeDetector.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.IOException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.spi.FileTypeDetector; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.datamodel.ifs2.MCRDirectory; import org.mycore.datamodel.ifs2.MCRFile; import org.mycore.datamodel.ifs2.MCRStoredNode; import org.mycore.datamodel.niofs.MCRPath; /** * @author Thomas Scheffler (yagee) * */ public class MCRFileTypeDetector extends FileTypeDetector { private static final Logger LOGGER = LogManager.getLogger(); /* (non-Javadoc) * @see java.nio.file.spi.FileTypeDetector#probeContentType(java.nio.file.Path) */ @Override public String probeContentType(Path path) throws IOException { LOGGER.debug(() -> "Probing content type of: " + path); if (!(path.getFileSystem() instanceof MCRIFSFileSystem)) { return null; } MCRStoredNode resolvePath = MCRFileSystemUtils.resolvePath(MCRPath.toMCRPath(path)); if (resolvePath instanceof MCRDirectory) { throw new NoSuchFileException(path.toString()); } MCRFile file = (MCRFile) resolvePath; String mimeType = Files.probeContentType(file.getLocalPath()); LOGGER.debug(() -> "IFS mime-type: " + mimeType); return mimeType; } }
2,159
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIFSFileSystem.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRIFSFileSystem.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.IOException; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileStore; import java.nio.file.FileSystemException; import java.nio.file.Path; import java.util.Comparator; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.mycore.datamodel.ifs2.MCRDirectory; import org.mycore.datamodel.ifs2.MCRStore; import org.mycore.datamodel.ifs2.MCRStoreCenter; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRAbstractFileSystem; import org.mycore.datamodel.niofs.MCRPath; /** * @author Thomas Scheffler (yagee) * */ public class MCRIFSFileSystem extends MCRAbstractFileSystem { private MCRFileSystemProvider provider; MCRIFSFileSystem(MCRFileSystemProvider provider) { super(); this.provider = provider; try { initStores(); } catch (IOException e) { LogManager.getLogger().error("Could not initialize stores. This file system may be degraded.", e); } } private void initStores() throws IOException { MCRFileSystemUtils.getObjectBaseIds() .forEach(MCRFileSystemUtils::getStore); } /* (non-Javadoc) * @see java.nio.file.FileSystem#provider() */ @Override public MCRFileSystemProvider provider() { return provider; } /* (non-Javadoc) * @see java.nio.file.FileSystem#getRootDirectories() */ @Override public Iterable<Path> getRootDirectories() { return MCRStoreCenter.instance().getCurrentStores(org.mycore.datamodel.ifs2.MCRFileStore.class) .filter(s -> s.getID().startsWith(MCRFileSystemUtils.STORE_ID_PREFIX)) .sorted(Comparator.comparing(MCRStore::getID)) .flatMap(s -> s.getStoredIDs() .mapToObj( i -> MCRObjectID.formatID(s.getID().substring(MCRFileSystemUtils.STORE_ID_PREFIX.length()), i))) .map(owner -> MCRAbstractFileSystem.getPath(owner, "/", this)) .map(Path.class::cast)::iterator; } /* (non-Javadoc) * @see java.nio.file.FileSystem#getFileStores() */ @Override public Iterable<FileStore> getFileStores() { return MCRStoreCenter.instance().getCurrentStores(org.mycore.datamodel.ifs2.MCRFileStore.class) .filter(s -> s.getID().startsWith(MCRFileSystemUtils.STORE_ID_PREFIX)) .sorted(Comparator.comparing(MCRStore::getID)) .map(MCRStore::getID) .distinct() .map(storeId -> { try { return MCRFileStore.getInstance(storeId); } catch (IOException e) { LogManager.getLogger().error("Error while iterating FileStores.", e); return null; } }) .filter(Objects::nonNull) .map(FileStore.class::cast)::iterator; } @Override public void createRoot(String owner) throws FileSystemException { MCRObjectID derId = MCRObjectID.getInstance(owner); org.mycore.datamodel.ifs2.MCRFileStore fileStore = MCRFileSystemUtils.getStore(derId.getBase()); MCRPath rootPath = getPath(owner, "", this); try { if (fileStore.retrieve(derId.getNumberAsInteger()) != null) { throw new FileAlreadyExistsException(rootPath.toString()); } try { fileStore.create(derId.getNumberAsInteger()); } catch (RuntimeException e) { LogManager.getLogger(getClass()).warn("Catched RuntimeException while creating new root directory.", e); throw new FileSystemException(rootPath.toString(), null, e.getMessage()); } } catch (FileSystemException e) { throw e; } catch (IOException e) { throw new FileSystemException(rootPath.toString(), null, e.getMessage()); } LogManager.getLogger(getClass()).info("Created root directory: {}", rootPath); } @Override public void removeRoot(String owner) throws FileSystemException { MCRPath rootPath = getPath(owner, "", this); MCRDirectory rootDirectory = null; try { rootDirectory = MCRFileSystemUtils.getFileCollection(owner); if (rootDirectory.hasChildren()) { throw new DirectoryNotEmptyException(rootPath.toString()); } rootDirectory.delete(); } catch (FileSystemException e) { throw e; } catch (IOException e) { throw new FileSystemException(rootPath.toString(), null, e.getMessage()); } catch (RuntimeException e) { LogManager.getLogger(getClass()).warn("Catched RuntimeException while removing root directory.", e); throw new FileSystemException(rootPath.toString(), null, e.getMessage()); } LogManager.getLogger(getClass()).info("Removed root directory: {}", rootPath); } }
5,822
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileStore.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileStore.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.IOException; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileStoreAttributeView; import java.util.concurrent.ExecutionException; import org.apache.logging.log4j.LogManager; import org.mycore.datamodel.ifs2.MCRFile; import org.mycore.datamodel.ifs2.MCRStore; import org.mycore.datamodel.ifs2.MCRStoreManager; import org.mycore.datamodel.ifs2.MCRStoredNode; import org.mycore.datamodel.niofs.MCRAbstractFileStore; import org.mycore.datamodel.niofs.MCRPath; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; /** * IFS2 MyCoRe FileStore implementation */ public class MCRFileStore extends MCRAbstractFileStore { private MCRStore contentStore; private String baseId; private FileStore baseFileStore; private static LoadingCache<String, MCRFileStore> instanceHolder = CacheBuilder.newBuilder().weakKeys() .build(new CacheLoader<>() { @Override public MCRFileStore load(String contentStoreID) throws Exception { MCRStore store = MCRStoreManager.getStore(contentStoreID); return new MCRFileStore(store); } }); private MCRFileStore(MCRStore contentStore) throws IOException { this.contentStore = contentStore; Path baseDir = this.contentStore.getBaseDirectory(); this.baseFileStore = getFileStore(baseDir); this.baseId = contentStore.getID().substring(MCRFileSystemUtils.STORE_ID_PREFIX.length()); if (baseFileStore == null) { String reason = "Cannot access base directory or any parent directory of Content Store " + contentStore.getID(); throw new NoSuchFileException(baseDir.toString(), null, reason); } } private static FileStore getFileStore(Path baseDir) throws IOException { if (baseDir == null) { return null; } //fixes MCR-964 return Files.exists(baseDir) ? Files.getFileStore(baseDir) : getFileStore(baseDir.getParent()); } static MCRFileStore getInstance(String storeId) throws IOException { try { return instanceHolder.get(storeId); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof IOException ioe) { throw ioe; } throw new IOException("Error while geting instance of " + MCRFileStore.class.getSimpleName(), cause); } } /** * creates a new MCRFileStore instance * @param node - the MyCoRe store node * @return the MCRFileStore instance * @throws IOException if the MCRFileStore could not be created */ public static MCRFileStore getInstance(MCRStoredNode node) throws IOException { return getInstance(node.getRoot().getStore().getID()); } @Override public String name() { return contentStore.getID(); } @Override public String type() { return contentStore.getClass().getCanonicalName(); } @Override public boolean isReadOnly() { return baseFileStore.isReadOnly(); } @Override public long getTotalSpace() throws IOException { return baseFileStore.getTotalSpace(); } @Override public long getUsableSpace() throws IOException { return baseFileStore.getUsableSpace(); } @Override public long getUnallocatedSpace() throws IOException { return baseFileStore.getUnallocatedSpace(); } @Override public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) { return this.baseFileStore.supportsFileAttributeView(type); } @Override public boolean supportsFileAttributeView(String name) { return this.baseFileStore.supportsFileAttributeView(name); } @Override public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) { return this.baseFileStore.getFileStoreAttributeView(type); } @Override public Object getAttribute(String attribute) throws IOException { return this.baseFileStore.getAttribute(attribute); } @Override public Path getBaseDirectory() { return this.contentStore.getBaseDirectory(); } @Override public Path getPhysicalPath(MCRPath path) { MCRFileSystemUtils.checkPathAbsolute(path); LogManager.getLogger().warn("Checking if {} is of baseId {}", path, baseId); if (!path.getOwner().startsWith(baseId + "_")) { LogManager.getLogger().warn("{} is not of baseId {}", path, baseId); return null; } try { MCRFile mcrFile = MCRFileSystemUtils.getMCRFile(path, false, false, true); return mcrFile.getLocalPath(); } catch (IOException e) { LogManager.getLogger(getClass()).info(e.getMessage()); return null; } } }
5,918
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRFileSystemProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRFileSystemProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.IOException; import java.net.URI; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.AccessDeniedException; import java.nio.file.AccessMode; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.CopyOption; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.DirectoryStream.Filter; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.FileSystemAlreadyExistsException; import java.nio.file.FileSystemNotFoundException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.spi.FileSystemProvider; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.ifs2.MCRDirectory; import org.mycore.datamodel.ifs2.MCRFile; import org.mycore.datamodel.ifs2.MCRFileCollection; import org.mycore.datamodel.ifs2.MCRStoredNode; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRAbstractFileSystem; import org.mycore.datamodel.niofs.MCRFileAttributes; import org.mycore.datamodel.niofs.MCRMD5AttributeView; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.fileupload.MCRUploadHelper; import com.google.common.collect.Sets; /** * MyCoRe IFS2 FileSystemProvider implementation * * @author Thomas Scheffler (yagee) */ public class MCRFileSystemProvider extends FileSystemProvider { /** * scheme part of the IFS file system URI */ public static final String SCHEME = "ifs2"; /** * base URI of the IFS fiel system */ public static final URI FS_URI = URI.create(SCHEME + ":///"); private static volatile MCRAbstractFileSystem FILE_SYSTEM_INSTANCE; /** * set of supported copy options */ private static final Set<? extends CopyOption> SUPPORTED_COPY_OPTIONS = Collections.unmodifiableSet(EnumSet.of( StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING)); /** * set of supported open options */ private static final Set<? extends OpenOption> SUPPORTED_OPEN_OPTIONS = EnumSet.of(StandardOpenOption.APPEND, StandardOpenOption.DSYNC, StandardOpenOption.READ, StandardOpenOption.SPARSE, StandardOpenOption.SYNC, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#getScheme() */ @Override public String getScheme() { return SCHEME; } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#newFileSystem(java.net.URI, java.util.Map) */ @Override public FileSystem newFileSystem(URI uri, Map<String, ?> env) { throw new FileSystemAlreadyExistsException(); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#getFileSystem(java.net.URI) */ @Override public MCRIFSFileSystem getFileSystem(URI uri) { if (FILE_SYSTEM_INSTANCE == null) { synchronized (FS_URI) { if (FILE_SYSTEM_INSTANCE == null) { FILE_SYSTEM_INSTANCE = new MCRIFSFileSystem(this); } } } return getMCRIFSFileSystem(); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#getPath(java.net.URI) */ @Override public Path getPath(final URI uri) { if (!FS_URI.getScheme().equals(Objects.requireNonNull(uri).getScheme())) { throw new FileSystemNotFoundException("Unkown filesystem: " + uri); } String path = uri.getPath().substring(1);//URI path is absolute -> remove first slash String owner = null; for (int i = 0; i < path.length(); i++) { if (path.charAt(i) == MCRAbstractFileSystem.SEPARATOR) { break; } if (path.charAt(i) == ':') { owner = path.substring(0, i); path = path.substring(i + 1); break; } } return MCRAbstractFileSystem.getPath(owner, path, getMCRIFSFileSystem()); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#newByteChannel(java.nio.file.Path, java.util.Set, java.nio.file.attribute.FileAttribute[]) */ @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { if (attrs.length > 0) { throw new UnsupportedOperationException("Atomically setting of file attributes is not supported."); } MCRPath ifsPath = MCRFileSystemUtils.checkPathAbsolute(path); Set<? extends OpenOption> fileOpenOptions = options.stream() .filter(option -> !(option == StandardOpenOption.CREATE || option == StandardOpenOption.CREATE_NEW)) .collect(Collectors.toSet()); boolean create = options.contains(StandardOpenOption.CREATE); boolean createNew = options.contains(StandardOpenOption.CREATE_NEW); if (create || createNew) { checkNewPathName(ifsPath); for (OpenOption option : fileOpenOptions) { //check before we create any file instance checkOpenOption(option); } } boolean channelCreateEvent = createNew || Files.notExists(ifsPath); MCRFile mcrFile = MCRFileSystemUtils.getMCRFile(ifsPath, create, createNew, !channelCreateEvent); if (mcrFile == null) { throw new NoSuchFileException(path.toString()); } boolean write = options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND); FileChannel baseChannel = (FileChannel) Files.newByteChannel(mcrFile.getLocalPath(), fileOpenOptions); return new MCRFileChannel(ifsPath, mcrFile, baseChannel, write, channelCreateEvent); } private static void checkNewPathName(MCRPath ifsPath) throws IOException { //check property lazy as on initialization of this class MCRConfiguration2 is not ready if (MCRConfiguration2.getBoolean("MCR.NIO.PathCreateNameCheck").orElse(true)) { try { MCRUploadHelper.checkPathName(ifsPath.getFileName().toString(), true); } catch (MCRException e) { throw new IOException(e.getMessage(), e); } } } static void checkOpenOption(OpenOption option) { if (!SUPPORTED_OPEN_OPTIONS.contains(option)) { throw new UnsupportedOperationException("Unsupported OpenOption: " + option.getClass().getSimpleName() + "." + option); } } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#newDirectoryStream(java.nio.file.Path, java.nio.file.DirectoryStream.Filter) */ @Override public DirectoryStream<Path> newDirectoryStream(Path dir, Filter<? super Path> filter) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(dir); MCRStoredNode node = MCRFileSystemUtils.resolvePath(mcrPath); if (node instanceof MCRDirectory mcrDirectory) { return MCRDirectoryStreamHelper.getInstance(mcrDirectory, mcrPath); } throw new NotDirectoryException(dir.toString()); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#createDirectory(java.nio.file.Path, java.nio.file.attribute.FileAttribute[]) */ @Override public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException { if (attrs.length > 0) { throw new UnsupportedOperationException("Setting 'attrs' atomically is unsupported."); } MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(dir); MCRDirectory rootDirectory; if (mcrPath.isAbsolute() && mcrPath.getNameCount() == 0) { MCRObjectID derId = MCRObjectID.getInstance(mcrPath.getOwner()); org.mycore.datamodel.ifs2.MCRFileStore store = MCRFileSystemUtils.getStore(derId.getBase()); if (store.retrieve(derId.getNumberAsInteger()) != null) { throw new FileAlreadyExistsException(mcrPath.toString()); } store.create(derId.getNumberAsInteger()); return; } else { //not root directory checkNewPathName(mcrPath); } rootDirectory = MCRFileSystemUtils.getFileCollection(mcrPath.getOwner()); MCRPath parentPath = mcrPath.getParent(); MCRPath absolutePath = getAbsolutePathFromRootComponent(parentPath); MCRStoredNode childByPath = (MCRStoredNode) rootDirectory.getNodeByPath(absolutePath.toString()); if (childByPath == null) { throw new NoSuchFileException(parentPath.toString(), dir.getFileName().toString(), "parent directory does not exist"); } if (childByPath instanceof MCRFile) { throw new NotDirectoryException(parentPath.toString()); } MCRDirectory parentDir = (MCRDirectory) childByPath; String dirName = mcrPath.getFileName().toString(); if (parentDir.getChild(dirName) != null) { throw new FileAlreadyExistsException(mcrPath.toString()); } parentDir.createDir(dirName); } static MCRPath getAbsolutePathFromRootComponent(MCRPath mcrPath) { if (!mcrPath.isAbsolute()) { throw new InvalidPathException(mcrPath.toString(), "'path' must be absolute."); } String path = mcrPath.toString().substring(mcrPath.getOwner().length() + 1); return MCRAbstractFileSystem.getPath(null, path, mcrPath.getFileSystem()); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#delete(java.nio.file.Path) */ @Override public void delete(Path path) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); MCRStoredNode child = MCRFileSystemUtils.resolvePath(mcrPath); if (child instanceof MCRDirectory && child.hasChildren()) { throw new DirectoryNotEmptyException(mcrPath.toString()); } try { child.delete(); MCRPathEventHelper.fireFileDeleteEvent(path); } catch (RuntimeException e) { throw new IOException("Could not delete: " + mcrPath, e); } } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption[]) */ @Override public void copy(Path source, Path target, CopyOption... options) throws IOException { if (isSameFile(source, target)) { return; //that was easy } checkCopyOptions(options); HashSet<CopyOption> copyOptions = Sets.newHashSet(options); boolean createNew = !copyOptions.contains(StandardCopyOption.REPLACE_EXISTING); MCRPath src = MCRFileSystemUtils.checkPathAbsolute(source); MCRPath tgt = MCRFileSystemUtils.checkPathAbsolute(target); MCRStoredNode srcNode = MCRFileSystemUtils.resolvePath(src); //checkParent of target; if (tgt.getNameCount() == 0 && srcNode instanceof MCRDirectory srcDir) { MCRDirectory tgtDir = MCRFileSystemUtils.getFileCollection(tgt.getOwner()); if (tgtDir != null) { if (tgtDir.hasChildren() && copyOptions.contains(StandardCopyOption.REPLACE_EXISTING)) { throw new DirectoryNotEmptyException(tgt.toString()); } } else { MCRObjectID tgtDerId = MCRObjectID.getInstance(tgt.getOwner()); org.mycore.datamodel.ifs2.MCRFileStore store = MCRFileSystemUtils.getStore(tgtDerId.getBase()); MCRFileCollection tgtCollection = store.create(tgtDerId.getNumberAsInteger()); if (copyOptions.contains(StandardCopyOption.COPY_ATTRIBUTES)) { copyDirectoryAttributes(srcDir, tgtCollection); } } return; //created new root component } if (srcNode instanceof MCRFile srcFile) { copyFile(srcFile, tgt, copyOptions, createNew); } else if (srcNode instanceof MCRDirectory srcDir) { copyDirectory(srcDir, tgt, copyOptions); } } private static void copyFile(MCRFile srcFile, MCRPath target, HashSet<CopyOption> copyOptions, boolean createNew) throws IOException { boolean fireCreateEvent = createNew || Files.notExists(target); MCRFile targetFile = MCRFileSystemUtils.getMCRFile(target, true, createNew, !fireCreateEvent); targetFile.setContent(srcFile.getContent()); if (copyOptions.contains(StandardCopyOption.COPY_ATTRIBUTES)) { copyFileAttributes(srcFile, targetFile); } if (fireCreateEvent) { MCRPathEventHelper.fireFileCreateEvent(target, targetFile.getBasicFileAttributes()); } else { MCRPathEventHelper.fireFileUpdateEvent(target, targetFile.getBasicFileAttributes()); } } private static void copyDirectory(MCRDirectory srcNode, MCRPath target, HashSet<CopyOption> copyOptions) throws IOException { MCRDirectory tgtParentDir = MCRFileSystemUtils.resolvePath(target.getParent()); MCRStoredNode child = (MCRStoredNode) tgtParentDir.getChild(target.getFileName().toString()); if (child != null) { if (!copyOptions.contains(StandardCopyOption.REPLACE_EXISTING)) { throw new FileAlreadyExistsException(tgtParentDir.toString(), target.getFileName().toString(), null); } if (child instanceof MCRFile) { throw new NotDirectoryException(target.toString()); } MCRDirectory tgtDir = (MCRDirectory) child; if (tgtDir.hasChildren() && copyOptions.contains(StandardCopyOption.REPLACE_EXISTING)) { throw new DirectoryNotEmptyException(target.toString()); } if (copyOptions.contains(StandardCopyOption.COPY_ATTRIBUTES)) { copyDirectoryAttributes(srcNode, tgtDir); } } else { //simply create directory @SuppressWarnings("unused") MCRDirectory tgtDir = tgtParentDir.createDir(target.getFileName().toString()); if (copyOptions.contains(StandardCopyOption.COPY_ATTRIBUTES)) { copyDirectoryAttributes(srcNode, tgtDir); } } } private static void copyFileAttributes(MCRFile source, MCRFile target) throws IOException { Path targetLocalFile = target.getLocalPath(); BasicFileAttributeView targetBasicFileAttributeView = Files.getFileAttributeView(targetLocalFile, BasicFileAttributeView.class); BasicFileAttributes srcAttr = Files.readAttributes(source.getLocalPath(), BasicFileAttributes.class); target.setMD5(source.getMD5()); targetBasicFileAttributeView.setTimes(srcAttr.lastModifiedTime(), srcAttr.lastAccessTime(), srcAttr.creationTime()); } private static void copyDirectoryAttributes(MCRDirectory source, MCRDirectory target) throws IOException { Path tgtLocalPath = target.getLocalPath(); Path srcLocalPath = source.getLocalPath(); BasicFileAttributes srcAttrs = Files .readAttributes(srcLocalPath, BasicFileAttributes.class); Files.getFileAttributeView(tgtLocalPath, BasicFileAttributeView.class) .setTimes(srcAttrs.lastModifiedTime(), srcAttrs.lastAccessTime(), srcAttrs.creationTime()); } private void checkCopyOptions(CopyOption[] options) { for (CopyOption option : options) { if (!SUPPORTED_COPY_OPTIONS.contains(option)) { throw new UnsupportedOperationException("Unsupported copy option: " + option); } } } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#move(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption[]) */ @Override public void move(Path source, Path target, CopyOption... options) throws IOException { HashSet<CopyOption> copyOptions = Sets.newHashSet(options); if (copyOptions.contains(StandardCopyOption.ATOMIC_MOVE)) { throw new AtomicMoveNotSupportedException(source.toString(), target.toString(), "ATOMIC_MOVE not supported yet"); } if (Files.isDirectory(source)) { MCRPath src = MCRFileSystemUtils.checkPathAbsolute(source); MCRDirectory srcRootDirectory = MCRFileSystemUtils.getFileCollection(src.getOwner()); if (srcRootDirectory.hasChildren()) { throw new IOException("Directory is not empty"); } } copy(source, target, options); delete(source); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#isSameFile(java.nio.file.Path, java.nio.file.Path) */ @Override public boolean isSameFile(Path path, Path path2) { return MCRFileSystemUtils.checkPathAbsolute(path).equals(MCRFileSystemUtils.checkPathAbsolute(path2)); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#isHidden(java.nio.file.Path) */ @Override public boolean isHidden(Path path) { MCRFileSystemUtils.checkPathAbsolute(path); return false; } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#getFileStore(java.nio.file.Path) */ @Override public FileStore getFileStore(Path path) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); MCRStoredNode node = MCRFileSystemUtils.resolvePath(mcrPath); return MCRFileStore.getInstance(node); } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#checkAccess(java.nio.file.Path, java.nio.file.AccessMode[]) */ @Override public void checkAccess(Path path, AccessMode... modes) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); MCRStoredNode node = MCRFileSystemUtils.resolvePath(mcrPath); if (node == null) { throw new NoSuchFileException(mcrPath.toString()); } if (node instanceof MCRDirectory) { checkDirectoryAccessModes(modes); } else { checkFile((MCRFile) node, modes); } } private void checkDirectoryAccessModes(AccessMode... modes) throws AccessDeniedException { for (AccessMode mode : modes) { switch (mode) { case READ: case WRITE: case EXECUTE: break; default: throw new AccessDeniedException("Unsupported AccessMode: " + mode); } } } private void checkFile(MCRFile file, AccessMode... modes) throws AccessDeniedException { for (AccessMode mode : modes) { switch (mode) { case READ: case WRITE: break; case EXECUTE: throw new AccessDeniedException(MCRFileSystemUtils.toPath(file).toString(), null, "Unsupported AccessMode: " + mode); default: throw new AccessDeniedException("Unsupported AccessMode: " + mode); } } } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#getFileAttributeView(java.nio.file.Path, java.lang.Class, java.nio.file.LinkOption[]) */ @SuppressWarnings("unchecked") @Override public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); //must support BasicFileAttributeView if (type == BasicFileAttributeView.class) { return (V) new BasicFileAttributeViewImpl(mcrPath); } if (type == MCRMD5AttributeView.class) { return (V) new MD5FileAttributeViewImpl(mcrPath); } return null; } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#readAttributes(java.nio.file.Path, java.lang.Class, java.nio.file.LinkOption[]) */ @SuppressWarnings("unchecked") @Override public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); MCRStoredNode node = MCRFileSystemUtils.resolvePath(mcrPath); //must support BasicFileAttributeView if (type == BasicFileAttributes.class || type == MCRFileAttributes.class) { return (A) MCRBasicFileAttributeViewImpl.readAttributes(node); } return null; } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#readAttributes(java.nio.file.Path, java.lang.String, java.nio.file.LinkOption[]) */ @Override public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); String[] s = splitAttrName(attributes); if (s[0].length() == 0) { throw new IllegalArgumentException(attributes); } BasicFileAttributeViewImpl view = switch (s[0]) { case "basic" -> new BasicFileAttributeViewImpl(mcrPath); case "md5" -> new MD5FileAttributeViewImpl(mcrPath); default -> throw new UnsupportedOperationException("View '" + s[0] + "' not available"); }; return view.getAttributeMap(s[1].split(",")); } private static String[] splitAttrName(String attribute) { String[] s = new String[2]; int pos = attribute.indexOf(':'); if (pos == -1) { s[0] = "basic"; s[1] = attribute; } else { s[0] = attribute.substring(0, pos++); s[1] = (pos == attribute.length()) ? "" : attribute.substring(pos); } return s; } /* (non-Javadoc) * @see java.nio.file.spi.FileSystemProvider#setAttribute(java.nio.file.Path, java.lang.String, java.lang.Object, java.nio.file.LinkOption[]) */ @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) { throw new UnsupportedOperationException("setAttributes is not implemented yet."); } /** * @return the MCRIFSFileSystem instance */ public static MCRIFSFileSystem getMCRIFSFileSystem() { return (MCRIFSFileSystem) (FILE_SYSTEM_INSTANCE == null ? MCRAbstractFileSystem.getInstance(SCHEME) : FILE_SYSTEM_INSTANCE); } static class BasicFileAttributeViewImpl extends MCRBasicFileAttributeViewImpl { private static final String SIZE_NAME = "size"; private static final String CREATION_TIME_NAME = "creationTime"; private static final String LAST_ACCESS_TIME_NAME = "lastAccessTime"; private static final String LAST_MODIFIED_TIME_NAME = "lastModifiedTime"; private static final String FILE_KEY_NAME = "fileKey"; private static final String IS_DIRECTORY_NAME = "isDirectory"; private static final String IS_REGULAR_FILE_NAME = "isRegularFile"; private static final String IS_SYMBOLIC_LINK_NAME = "isSymbolicLink"; private static final String IS_OTHER_NAME = "isOther"; private static HashSet<String> allowedAttr = Sets.newHashSet("*", SIZE_NAME, CREATION_TIME_NAME, LAST_ACCESS_TIME_NAME, LAST_MODIFIED_TIME_NAME, FILE_KEY_NAME, IS_DIRECTORY_NAME, IS_REGULAR_FILE_NAME, IS_SYMBOLIC_LINK_NAME, IS_OTHER_NAME); protected MCRPath path; BasicFileAttributeViewImpl(Path path) { this.path = MCRPath.toMCRPath(path); if (!path.isAbsolute()) { throw new InvalidPathException(path.toString(), "'path' must be absolute."); } } @Override protected MCRStoredNode resolveNode() throws IOException { return MCRFileSystemUtils.resolvePath(this.path); } public Map<String, Object> getAttributeMap(String... attributes) throws IOException { Set<String> allowed = getAllowedAttributes(); boolean copyAll = false; for (String attr : attributes) { if (!allowed.contains(attr)) { throw new IllegalArgumentException("'" + attr + "' not recognized"); } if (Objects.equals(attr, "*")) { copyAll = true; } } Set<String> requested = copyAll ? allowed : Sets.newHashSet(attributes); return buildMap(requested, readAttributes()); } protected Map<String, Object> buildMap(Set<String> requested, MCRFileAttributes<String> attrs) { HashMap<String, Object> map = new HashMap<>(); for (String attr : map.keySet()) { switch (attr) { case SIZE_NAME -> map.put(attr, attrs.size()); case CREATION_TIME_NAME -> map.put(attr, attrs.creationTime()); case LAST_ACCESS_TIME_NAME -> map.put(attr, attrs.lastAccessTime()); case LAST_MODIFIED_TIME_NAME -> map.put(attr, attrs.lastModifiedTime()); case FILE_KEY_NAME -> map.put(attr, attrs.fileKey()); case IS_DIRECTORY_NAME -> map.put(attr, attrs.isDirectory()); case IS_REGULAR_FILE_NAME -> map.put(attr, attrs.isRegularFile()); case IS_SYMBOLIC_LINK_NAME -> map.put(attr, attrs.isSymbolicLink()); case IS_OTHER_NAME -> map.put(attr, attrs.isOther()); default -> { } //ignored } } return map; } public void setAttribute(String name, Object value) throws IOException { Set<String> allowed = getAllowedAttributes(); if (Objects.equals(name, "*") || !allowed.contains(name)) { throw new IllegalArgumentException("'" + name + "' not recognized"); } switch (name) { case CREATION_TIME_NAME -> this.setTimes(null, null, (FileTime) value); case LAST_ACCESS_TIME_NAME -> this.setTimes(null, (FileTime) value, null); case LAST_MODIFIED_TIME_NAME -> this.setTimes((FileTime) value, null, null); case SIZE_NAME, FILE_KEY_NAME, IS_DIRECTORY_NAME, IS_REGULAR_FILE_NAME, IS_SYMBOLIC_LINK_NAME, IS_OTHER_NAME -> throw new IllegalArgumentException( "'" + name + "' is a read-only attribute."); default -> { //ignored } } } protected Set<String> getAllowedAttributes() { return allowedAttr; } } private static class MD5FileAttributeViewImpl extends BasicFileAttributeViewImpl implements MCRMD5AttributeView<String> { private static String MD5_NAME = "md5"; private static Set<String> allowedAttr = Sets.union(BasicFileAttributeViewImpl.allowedAttr, Sets.newHashSet(MD5_NAME)); MD5FileAttributeViewImpl(Path path) { super(path); } @Override public MCRFileAttributes<String> readAllAttributes() throws IOException { return readAttributes(); } @Override public String name() { return "md5"; } @Override protected Set<String> getAllowedAttributes() { return allowedAttr; } @Override protected Map<String, Object> buildMap(Set<String> requested, MCRFileAttributes<String> attrs) { Map<String, Object> buildMap = super.buildMap(requested, attrs); if (requested.contains(MD5_NAME)) { buildMap.put(MD5_NAME, attrs.md5sum()); } return buildMap; } @Override public void setAttribute(String name, Object value) throws IOException { if (MD5_NAME.equals(name)) { MCRStoredNode node = resolveNode(); if (node instanceof MCRDirectory) { throw new IOException("Cannot set md5sum on directories: " + path); } ((MCRFile) node).setMD5((String) value); } else { super.setAttribute(name, value); } } } }
30,541
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBasicFileAttributeViewImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-ifs/src/main/java/org/mycore/datamodel/niofs/ifs2/MCRBasicFileAttributeViewImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.datamodel.niofs.ifs2; import java.io.IOException; import java.nio.file.Files; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.FileTime; import org.mycore.datamodel.ifs2.MCRStoredNode; import org.mycore.datamodel.niofs.MCRFileAttributes; abstract class MCRBasicFileAttributeViewImpl implements BasicFileAttributeView { static MCRFileAttributes<String> readAttributes(MCRStoredNode node) throws IOException { return node.getBasicFileAttributes(); } @Override public String name() { return "basic"; } @Override public MCRFileAttributes<String> readAttributes() throws IOException { MCRStoredNode node = resolveNode(); return readAttributes(node); } @Override public void setTimes(FileTime lastModifiedTime, FileTime lastAccessTime, FileTime createTime) throws IOException { MCRStoredNode node = resolveNode(); BasicFileAttributeView localView = Files .getFileAttributeView(node.getLocalPath(), BasicFileAttributeView.class); localView.setTimes(lastModifiedTime, lastAccessTime, createTime); } protected abstract MCRStoredNode resolveNode() throws IOException; }
1,968
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTransferPackage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.impex; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.jdom2.Document; import org.jdom2.Element; import org.mycore.common.MCRUsageException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRPathContent; import org.mycore.datamodel.classifications2.MCRCategoryID; import org.mycore.datamodel.classifications2.utils.MCRClassificationUtils; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.MCRObjectStructure; import org.mycore.datamodel.metadata.MCRObjectUtils; import org.mycore.datamodel.niofs.MCRPath; /** * Basic transfer package containing a {@link MCRObject}, all its descendants, * links, derivates (including their files) and referenced classifications. * <p> * To build a transfer package call {@link #build()}, this initializes * all required objects and checks if they are valid. Call {@link #getContent()} * to retrieve the content afterwards. * </p> * * @author Silvio Hermann * @author Matthias Eichner */ public class MCRTransferPackage { public static final String IMPORT_CONFIG_FILENAME = "import.xml"; public static final String CONTENT_PATH = "content/"; public static final String CLASS_PATH = CONTENT_PATH + "classifications/"; protected MCRObject source; /** * Set of objects including the source, its descendants and all resolved links. * Its linked because the import order matters. */ protected LinkedHashSet<MCRObject> objects; /** * List of transfer package file containers. */ protected List<MCRTransferPackageFileContainer> fileContainers; /** * Set of classifications. */ protected Set<String> classifications; public MCRTransferPackage(MCRObject source) { this.source = source; } /** * Builds the transfer package. * * @throws MCRUsageException is thrown if some of the referenced objects or derivates couldn't be retrieved */ public void build() throws MCRUsageException { LinkedHashMap<MCRObjectID, MCRObject> objectMap = new LinkedHashMap<>(); Set<MCRCategoryID> categories = new HashSet<>(); resolveChildrenAndLinks(source, objectMap, categories); this.objects = new LinkedHashSet<>(objectMap.values()); this.classifications = categories.stream().map(MCRCategoryID::getRootID).distinct().collect(Collectors.toSet()); this.fileContainers = buildFileContainers(source); } /** * Fills the given objectMap with all children and links of the object. The object * itself is also added. * * @param object the source object * @param objectMap the map which will be created */ protected void resolveChildrenAndLinks(MCRObject object, LinkedHashMap<MCRObjectID, MCRObject> objectMap, Set<MCRCategoryID> categories) { // add links for (MCRObject entityLink : MCRObjectUtils.getLinkedObjects(object)) { if (!objectMap.containsKey(entityLink.getId())) { objectMap.put(entityLink.getId(), entityLink); } } // add classifications categories.addAll(MCRObjectUtils.getCategories(object)); // add the object to the objectMap objectMap.put(object.getId(), object); // resolve children for (MCRMetaLinkID metaLinkId : object.getStructure().getChildren()) { MCRObjectID childId = MCRObjectID.getInstance(metaLinkId.toString()); if (!MCRMetadataManager.exists(childId)) { throw new MCRUsageException( "Requested object '" + childId + "' does not exist. Thus a transfer package cannot be created."); } MCRObject child = MCRMetadataManager.retrieveMCRObject(childId); resolveChildrenAndLinks(child, objectMap, categories); } } /** * Builds a list of {@link MCRTransferPackageFileContainer} for all derivate's of the * given object and all its descendants. * * <p>TODO: derivates of linked objects are not added</p> * * @param object the object * @return list of transfer packages file container */ protected List<MCRTransferPackageFileContainer> buildFileContainers(MCRObject object) { List<MCRTransferPackageFileContainer> fileContainerList = new ArrayList<>(); MCRObjectUtils.getDescendantsAndSelf(object) .stream() .map(MCRObject::getStructure) .map(MCRObjectStructure::getDerivates) .flatMap(Collection::stream) .map(MCRMetaLinkID::getXLinkHrefID) .peek(derivateId -> { if (!MCRMetadataManager.exists(derivateId)) { throw new MCRUsageException("Requested derivate '" + derivateId + "' does not exist. Thus a transfer package cannot be created."); } }) .map(MCRTransferPackageFileContainer::new) .forEach(fileContainerList::add); return fileContainerList; } /** * Generates an xml file, which contains import configuration. * * @return import configuration document */ public Document buildImportConfiguration() { Element configElement = new Element("config"); Element orderElement = new Element("order"); for (MCRObject object : objects) { Element e = new Element("object"); e.setText(object.toString()); orderElement.addContent(e); } configElement.addContent(orderElement); return new Document(configElement); } /** * Returns the content for this transfer package. You have to call {@link #build()} * before you can retrieve this data. * * @return a map where key = filename; value = MCRContent */ public Map<String, MCRContent> getContent() throws IOException { Map<String, MCRContent> content = new HashMap<>(); // config content.put(IMPORT_CONFIG_FILENAME, new MCRJDOMContent(buildImportConfiguration())); // objects for (MCRObject object : this.objects) { String fileName = CONTENT_PATH + object.getId() + ".xml"; Document xml = object.createXML(); content.put(fileName, new MCRJDOMContent(xml)); } // file containers for (MCRTransferPackageFileContainer fc : this.fileContainers) { // derivate MCRObjectID derivateId = fc.getDerivateId(); MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateId); Document derivateXML = derivate.createXML(); String folder = CONTENT_PATH + fc.getName(); String derivateFileName = folder + "/" + fc.getName() + ".xml"; content.put(derivateFileName, new MCRJDOMContent(derivateXML)); // files of derivate for (MCRPath file : fc.getFiles()) { //TODO: safe a IO operation to get file attributes with new MCRPathContent(path, attr); content.put(folder + file.getOwnerRelativePath(), new MCRPathContent(file)); } } // classifications for (String classId : this.classifications) { Document classification = MCRClassificationUtils.asDocument(classId); if (classification == null) { LogManager.getLogger().warn("Unable to get classification " + classId); continue; } String path = CLASS_PATH + classId + ".xml"; content.put(path, new MCRJDOMContent(classification)); } return content; } /** * Returns the source of this transfer package. * * @return the source */ public MCRObject getSource() { return source; } @Override public String toString() { return this.source.getId().toString(); } }
9,278
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTransferPackageCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackageCommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.impex; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRUtils; import org.mycore.datamodel.classifications2.utils.MCRClassificationUtils; import org.mycore.datamodel.common.MCRMarkManager; import org.mycore.datamodel.common.MCRMarkManager.Operation; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.services.packaging.MCRPackerManager; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.index.MCRSolrIndexer; import org.mycore.solr.search.MCRSolrSearchUtils; @MCRCommandGroup(name = "Transfer Package Commands") @SuppressWarnings("PMD.ClassNamingConventions") public class MCRTransferPackageCommands { private static final Logger LOGGER = LogManager.getLogger(MCRTransferPackageCommands.class); @MCRCommand(help = "Creates multiple transfer packages which matches the solr query in {0}.", syntax = "create transfer package for objects matching {0}") public static void create(String query) throws MCRAccessException { List<String> ids = MCRSolrSearchUtils.listIDs(MCRSolrClientFactory.getMainSolrClient(), query); for (String objectId : ids) { Map<String, String> parameters = new HashMap<>(); parameters.put("packer", "TransferPackage"); parameters.put("source", objectId); MCRPackerManager.startPacking(parameters); } } @MCRCommand(help = "Imports all transfer packages located in the directory {0}.", syntax = "import transfer packages from directory {0}") public static List<String> importTransferPackagesFromDirectory(String directory) throws Exception { Path dir = Paths.get(directory); if (!(Files.exists(dir) || Files.isDirectory(dir))) { throw new FileNotFoundException(directory + " does not exist or is not a directory."); } List<String> importStatements = new ArrayList<>(); try (Stream<Path> stream = Files.find(dir, 1, (path, attr) -> String.valueOf(path).endsWith(".tar") && Files.isRegularFile(path))) { stream.map(Path::toAbsolutePath).map(Path::toString).forEach(path -> { String subCommand = String.format(Locale.ROOT, "import transfer package from tar %s", path); importStatements.add(subCommand); }); } return importStatements; } @MCRCommand(help = "Imports a transfer package located at {0}. Where {0} is the absolute path to the tar file. ", syntax = "import transfer package from tar {0}") public static List<String> importTransferPackageFromTar(String pathToTar) throws Exception { return importTransferPackageFromTar(pathToTar, null); } @MCRCommand(help = "Imports a transfer package located at {0}. Where {0} is the absolute path to the tar file. " + "The parameter {1} is optional and can be omitted. You can specify a mycore id where the first object of " + "import.xml should be attached.", syntax = "import transfer package from tar {0} to {1}") public static List<String> importTransferPackageFromTar(String pathToTar, String mycoreTargetId) throws Exception { Path tar = Paths.get(pathToTar); if (!Files.exists(tar)) { throw new FileNotFoundException(tar.toAbsolutePath() + " does not exist."); } Path targetDirectory = MCRTransferPackageUtil.getTargetDirectory(tar); List<String> commands = new ArrayList<>(); commands.add("_import transfer package untar " + pathToTar); if (mycoreTargetId != null) { commands.add("_import transfer package from directory " + targetDirectory + " to " + mycoreTargetId); } else { commands.add("_import transfer package from directory " + targetDirectory); } commands.add("_import transfer package clean up " + targetDirectory); return commands; } @MCRCommand(syntax = "_import transfer package untar {0}") public static void untar(String pathToTar) throws Exception { Path tar = Paths.get(pathToTar); Path targetDirectory = MCRTransferPackageUtil.getTargetDirectory(tar); LOGGER.info("Untar {} to {}...", pathToTar, targetDirectory); MCRUtils.untar(tar, targetDirectory); } @MCRCommand(syntax = "_import transfer package from directory {0}") public static List<String> fromDirectory(String sourceDirectory) throws Exception { return fromDirectory(sourceDirectory, null); } @MCRCommand(syntax = "_import transfer package from directory {0} to {1}") public static List<String> fromDirectory(String sourceDirectory, String mycoreTargetId) throws Exception { LOGGER.info("Import transfer package from {}...", sourceDirectory); Path sourcePath = Paths.get(sourceDirectory); List<String> commands = new ArrayList<>(); // load classifications List<Path> classificationPaths = MCRTransferPackageUtil.getClassifications(sourcePath); for (Path pathToClassification : classificationPaths) { commands.add("_import transfer package classification from " + pathToClassification.toAbsolutePath()); } // import objects List<String> mcrObjects = MCRTransferPackageUtil.getMCRObjects(sourcePath); MCRMarkManager markManager = MCRMarkManager.instance(); if (mycoreTargetId != null && !mcrObjects.isEmpty()) { String rootId = mcrObjects.get(0); markManager.mark(MCRObjectID.getInstance(rootId), Operation.IMPORT); commands.add( "_import transfer package object " + rootId + " from " + sourceDirectory + " to " + mycoreTargetId); mcrObjects = mcrObjects.subList(1, mcrObjects.size()); } for (String id : mcrObjects) { markManager.mark(MCRObjectID.getInstance(id), Operation.IMPORT); commands.add("_import transfer package object " + id + " from " + sourceDirectory); } return commands; } @MCRCommand(syntax = "_import transfer package classification from {0}") public static void importObject(String pathToClassification) throws Exception { MCRClassificationUtils.fromPath(Paths.get(pathToClassification)); } @MCRCommand(syntax = "_import transfer package object {0} from {1}") public static List<String> importObject(String objectId, String targetDirectoryPath) throws Exception { return importObject(objectId, targetDirectoryPath, null); } @MCRCommand(syntax = "_import transfer package object {0} from {1} to {2}") public static List<String> importObject(String objectId, String targetDirectoryPath, String parentId) throws Exception { Path targetDirectory = Paths.get(targetDirectoryPath); List<String> derivates = MCRTransferPackageUtil.importObjectCLI(targetDirectory, objectId, parentId); return derivates.stream() .map(derId -> "_import transfer package derivate " + derId + " from " + targetDirectoryPath) .collect(Collectors.toList()); } @MCRCommand(syntax = "_import transfer package derivate {0} from {1}") public static void importDerivate(String derivateId, String targetDirectoryPath) throws Exception { Path targetDirectory = Paths.get(targetDirectoryPath); MCRTransferPackageUtil.importDerivate(targetDirectory, derivateId); } @MCRCommand(syntax = "_import transfer package clean up {0}") public static void cleanUp(String targetDirectoryPath) throws Exception { Path targetDirectory = Paths.get(targetDirectoryPath); // delete mark of imported object List<String> mcrObjects = MCRTransferPackageUtil.getMCRObjects(targetDirectory); MCRMarkManager markManager = MCRMarkManager.instance(); for (String id : mcrObjects) { markManager.remove(MCRObjectID.getInstance(id)); } // index all objects MCRSolrIndexer.rebuildMetadataIndex(mcrObjects, MCRSolrClientFactory.getMainSolrClient()); // deleting expanded directory LOGGER.info("Deleting expanded tar in {}...", targetDirectoryPath); Files.walkFileTree(Paths.get(targetDirectoryPath), MCRRecursiveDeleter.instance()); } }
9,615
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTransferPackageUtil.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackageUtil.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.impex; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Text; import org.jdom2.filter.Filters; import org.jdom2.input.SAXBuilder; import org.jdom2.xpath.XPathExpression; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.MCRUtils; import org.mycore.datamodel.classifications2.utils.MCRClassificationUtils; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaLinkID; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter; import org.xml.sax.SAXParseException; /** * Contains utility methods for handling transfer packages. * * @author Silvio Hermann * @author Matthias Eichner */ public abstract class MCRTransferPackageUtil { private static final Logger LOGGER = LogManager.getLogger(MCRTransferPackageUtil.class); /** * The default lookup path appendix (the subdirectory in the tar where the metadata resides). * With leading and trailing {@link java.io.File#separator} */ public static final String CONTENT_DIRECTORY = "content"; /** * Imports a *.tar transport package from the given path. * * @param pathToTar * path to the *.tar archive * @throws IOException * some file system stuff went wrong * @throws MCRAccessException * if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)} * @throws JDOMException * some jdom parsing went wrong * @throws URISyntaxException * unable to transform the xml * @throws SAXParseException * xml parsing went wrong */ public static void importTar(Path pathToTar) throws IOException, MCRAccessException, JDOMException, SAXParseException, URISyntaxException { if (!Files.exists(pathToTar)) { throw new FileNotFoundException(pathToTar.toAbsolutePath() + " does not exist."); } Path targetDirectory = getTargetDirectory(pathToTar); MCRUtils.untar(pathToTar, targetDirectory); // import the data from the extracted tar MCRTransferPackageUtil.importFromDirectory(targetDirectory); // delete the extracted files, but keep the tar LOGGER.info("Deleting expanded tar in {}", targetDirectory); Files.walkFileTree(targetDirectory, MCRRecursiveDeleter.instance()); } /** * Returns the path where the *.tar will be unzipped. * * @param pathToTar the path to the tar. * @return path to the directory */ public static Path getTargetDirectory(Path pathToTar) { String fileName = pathToTar.getFileName().toString(); return pathToTar.getParent().resolve(fileName.substring(0, fileName.lastIndexOf("."))); } /** * Imports from an unpacked *.tar archive directory. * * @param targetDirectory * the directory where the *.tar was unpacked * @throws JDOMException * some jdom parsing went wrong * @throws IOException * something went wrong while reading from the file system * @throws MCRAccessException * if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)} * @throws URISyntaxException * unable to transform the xml */ public static void importFromDirectory(Path targetDirectory) throws JDOMException, IOException, MCRAccessException, URISyntaxException { // import classifications for (Path pathToClassification : getClassifications(targetDirectory)) { MCRClassificationUtils.fromPath(pathToClassification); } // import objects & derivates List<String> objectImportList = getMCRObjects(targetDirectory); for (String id : objectImportList) { importObject(targetDirectory, id, null); } } /** * Returns a list containing all paths to the classifications which should be imported. * * @param targetDirectory * the directory where the *.tar was unpacked * @return list of paths * @throws IOException * if an I/O error is thrown when accessing one of the files */ public static List<Path> getClassifications(Path targetDirectory) throws IOException { List<Path> classificationPaths = new ArrayList<>(); Path classPath = targetDirectory.resolve(MCRTransferPackage.CLASS_PATH); if (Files.exists(classPath)) { try (Stream<Path> stream = Files.find(classPath, 2, (path, attr) -> path.toString().endsWith(".xml") && Files.isRegularFile(path))) { stream.forEach(classificationPaths::add); } } return classificationPaths; } /** * Imports a object from the targetDirectory path. * * @param targetDirectory * the directory where the *.tar was unpacked * @param objectId * object id to import * @param parentId * The new parent. Should be null if the original parent remains the same. * @throws JDOMException * coulnd't parse the import order xml * @throws IOException * when an I/O error prevents a document from being fully parsed * @throws MCRAccessException * if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)} */ public static void importObject(Path targetDirectory, String objectId, String parentId) throws JDOMException, IOException, MCRAccessException { // import object List<String> derivates = importObjectCLI(targetDirectory, objectId, parentId); // process the saved derivates for (String derivateId : derivates) { importDerivate(targetDirectory, derivateId); } } /** * Same as {@link #importObject(Path, String, String)} but returns a list of derivates which * should be imported afterwards. * * @param targetDirectory * the directory where the *.tar was unpacked * @param objectId * object id to import * @param parentId * The new parent. Should be null if the original parent remains the same. * @throws JDOMException * coulnd't parse the import order xml * @throws IOException * when an I/O error prevents a document from being fully parsed * @throws MCRAccessException * if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)} */ public static List<String> importObjectCLI(Path targetDirectory, String objectId, String parentId) throws JDOMException, IOException, MCRAccessException { SAXBuilder sax = new SAXBuilder(); Path targetXML = targetDirectory.resolve(CONTENT_DIRECTORY).resolve(objectId + ".xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Importing {}", targetXML.toAbsolutePath().toString()); } Document objXML = sax.build(targetXML.toFile()); MCRObject mcr = new MCRObject(objXML); if (parentId != null) { mcr.getStructure().setParent(parentId); } mcr.setImportMode(true); List<String> derivates = new ArrayList<>(); // one must copy the ids before updating the mcr objects for (MCRMetaLinkID id : mcr.getStructure().getDerivates()) { derivates.add(id.getXLinkHref()); } // delete children & derivate -> will be added later mcr.getStructure().clearChildren(); mcr.getStructure().clearDerivates(); // update MCRMetadataManager.update(mcr); // return list of derivates return derivates; } /** * Imports a derivate from the given target directory path. * * @param targetDirectory path to the extracted *.tar archive * @param derivateId the derivate to import * @throws JDOMException derivate xml couldn't be read * @throws IOException some file system stuff went wrong * @throws MCRAccessException you do not have the permissions to do the import */ public static void importDerivate(Path targetDirectory, String derivateId) throws JDOMException, IOException, MCRAccessException { SAXBuilder sax = new SAXBuilder(); Path derivateDirectory = targetDirectory.resolve(CONTENT_DIRECTORY).resolve(derivateId); Path derivatePath = derivateDirectory.resolve(derivateId + ".xml"); LOGGER.info("Importing {}", derivatePath.toAbsolutePath().toString()); MCRDerivate der = new MCRDerivate(sax.build(derivatePath.toFile())); MCRMetadataManager.update(der); MCRPath derRoot = MCRPath.getPath(der.getId().toString(), "/"); if (!Files.isDirectory(derRoot)) { LOGGER.info("Creating missing root directory for {}", der.getId()); derRoot.getFileSystem().createRoot(der.getId().toString()); } try (Stream<Path> stream = Files.find(derivateDirectory, 5, (path, attr) -> !path.toString().endsWith(".md5") && Files.isRegularFile(path) && !path.equals( derivatePath))) { stream.forEach(path -> { String targetPath = derivateDirectory.relativize(path).toString(); try (InputStream in = Files.newInputStream(path)) { Files.copy(in, MCRPath.getPath(derivateId, targetPath), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ioExc) { throw new MCRException("Unable to add file " + path.toAbsolutePath() + " to derivate " + derivateId, ioExc); } }); } } /** * Gets the list of mycore object identifiers from the given directory. * * @param targetDirectory directory where the *.tar was unpacked * @return list of object which lies within the directory */ public static List<String> getMCRObjects(Path targetDirectory) throws JDOMException, IOException { Path importXMLPath = targetDirectory.resolve(MCRTransferPackage.IMPORT_CONFIG_FILENAME); Document xml = new SAXBuilder().build(importXMLPath.toFile()); Element config = xml.getRootElement(); XPathExpression<Text> exp = MCRConstants.XPATH_FACTORY.compile("order/object/text()", Filters.text()); return exp.evaluate(config).stream().map(Text::getText).collect(Collectors.toList()); } }
12,143
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTransferPackagePacker.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackagePacker.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.impex; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRUsageException; import org.mycore.common.MCRUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.services.packaging.MCRPacker; /** * Using the {@link MCRPacker} API to build a {@link MCRTransferPackage}. * * @author Matthias Eichner * @author Silvio Hermann */ public class MCRTransferPackagePacker extends MCRPacker { private static final Logger LOGGER = LogManager.getLogger(MCRTransferPackagePacker.class); private static Path SAVE_DIRECTORY_PATH; static { String alternative = MCRConfiguration2.getStringOrThrow("MCR.datadir") + File.separator + "transferPackages"; String directoryPath = MCRConfiguration2.getString("MCR.TransferPackage.Save.to.Directory").orElse(alternative); SAVE_DIRECTORY_PATH = Paths.get(directoryPath); } /* * (non-Javadoc) * @see org.mycore.services.packaging.MCRPacker#checkSetup() */ @Override public void checkSetup() throws MCRUsageException { build(); } /** * Builds the transfer package and returns it. * * @return the transfer package */ private MCRTransferPackage build() { MCRObject source = getSource(); MCRTransferPackage transferPackage = new MCRTransferPackage(source); transferPackage.build(); return transferPackage; } /** * Returns the source object. * * @return mycore object which should be packed * @throws MCRUsageException something went wrong */ protected MCRObject getSource() throws MCRUsageException { String sourceId = getSourceId(); MCRObjectID mcrId = MCRObjectID.getInstance(sourceId); if (!MCRMetadataManager.exists(mcrId)) { throw new MCRUsageException( "Requested object '" + sourceId + "' does not exist. Thus a transfer package cannot be created."); } return MCRMetadataManager.retrieveMCRObject(mcrId); } /** * Returns the id of the mycore object which should be packed. * * @return mycore object id as string */ private String getSourceId() { String sourceId = getParameters().get("source"); if (sourceId == null) { throw new MCRUsageException("One does not simply provide 'null' as source."); } return sourceId; } /* * (non-Javadoc) * @see org.mycore.services.packaging.MCRPacker#pack() */ @Override public void pack() throws ExecutionException { String sourceId = getSourceId(); try { LOGGER.info("Creating transfer package for {} at {}", sourceId, SAVE_DIRECTORY_PATH.toAbsolutePath()); MCRTransferPackage transferPackage = build(); checkAndCreateSaveDirectory(); buildTar(getTarPath(transferPackage), transferPackage); LOGGER.info("Transfer package for {} created.", sourceId); } catch (Exception exc) { throw new ExecutionException("Unable to pack() transfer package for source " + sourceId, exc); } } /* * (non-Javadoc) * @see org.mycore.services.packaging.MCRPacker#rollback() */ @Override public void rollback() { //do nothing } /** * Returns the path to the tar archive where the transfer package will be stored. * * @return path to the *.tar location */ public Path getTarPath(MCRTransferPackage transferPackage) { return SAVE_DIRECTORY_PATH.resolve(transferPackage.getSource().getId() + ".tar"); } /** * Builds a *.tar archive at the path for the given transfer package. * * @param pathToTar where to store the *.tar * @param transferPackage the package to zip * @throws IOException something went wrong while packing */ private void buildTar(Path pathToTar, MCRTransferPackage transferPackage) throws IOException { FileOutputStream fos = new FileOutputStream(pathToTar.toFile()); try (TarArchiveOutputStream tarOutStream = new TarArchiveOutputStream(fos)) { for (Entry<String, MCRContent> contentEntry : transferPackage.getContent().entrySet()) { String filePath = contentEntry.getKey(); byte[] data = contentEntry.getValue().asByteArray(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Adding '{}' to {}", filePath, pathToTar.toAbsolutePath()); } writeFile(tarOutStream, filePath, data); writeMD5(tarOutStream, filePath + ".md5", data); } } } /** * Writes a file to a *.tar archive. * * @param tarOutStream the stream of the *.tar. * @param fileName the file name to write * @param data of the file * * @throws IOException some writing to the stream went wrong */ private void writeFile(TarArchiveOutputStream tarOutStream, String fileName, byte[] data) throws IOException { TarArchiveEntry tarEntry = new TarArchiveEntry(fileName); tarEntry.setSize(data.length); tarOutStream.putArchiveEntry(tarEntry); tarOutStream.write(data); tarOutStream.closeArchiveEntry(); } /** * Writes a checksum file to a *.tar archive. * * @param tarOutStream the stream of the *.tar. * @param fileName the file name to write * @param data of the file * * @throws IOException some writing to the stream went wrong */ private void writeMD5(TarArchiveOutputStream tarOutStream, String fileName, byte[] data) throws IOException { String md5 = MCRUtils.getMD5Sum(new ByteArrayInputStream(data)); byte[] md5Bytes = md5.getBytes(StandardCharsets.ISO_8859_1); writeFile(tarOutStream, fileName, md5Bytes); } private void checkAndCreateSaveDirectory() throws IOException { if (!Files.exists(SAVE_DIRECTORY_PATH)) { LOGGER.info("Creating directory {}", SAVE_DIRECTORY_PATH.toAbsolutePath()); Files.createDirectories(SAVE_DIRECTORY_PATH); } } }
7,620
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRTransferPackageFileContainer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-impex/src/main/java/org/mycore/impex/MCRTransferPackageFileContainer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.impex; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; /** * Container for derivate files. * * @author Silvio Hermann * @author Matthias Eichner */ public class MCRTransferPackageFileContainer { private MCRObjectID derivateId; private List<MCRPath> fileList; public MCRTransferPackageFileContainer(MCRObjectID derivateId) { if (derivateId == null) { throw new IllegalArgumentException("The derivate parameter must not be null."); } this.derivateId = derivateId; } /** * @return the name of this file container */ public String getName() { return this.derivateId.toString(); } public MCRObjectID getDerivateId() { return derivateId; } /** * @return the list of files hold by this container */ public List<MCRPath> getFiles() throws IOException { if (fileList == null) { this.createFileList(); } return this.fileList; } private void createFileList() throws IOException { final MCRPath derRoot = MCRPath.getPath(this.derivateId.toString(), "/"); try (Stream<Path> files = Files.find(derRoot, Integer.MAX_VALUE, (path, attr) -> attr.isRegularFile())) { this.fileList = files.map(MCRPath::toMCRPath) .sorted(Comparator.comparing(MCRPath::getNameCount) .thenComparing(MCRPath::toString)) .collect(Collectors.toList()); } } @Override public String toString() { return this.getName() + " (" + this.fileList.size() + ")"; } }
2,600
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPandocTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pandoc/src/main/java/org/mycore/pandoc/MCRPandocTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.pandoc; import java.io.IOException; import org.jdom2.Element; 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; /** * Generic transformer using Pandoc * * @author Kai Brandhorst */ public class MCRPandocTransformer extends MCRContentTransformer { private String inputFormat; private String outputFormat; @Override public void init(String id) { super.init(id); inputFormat = MCRConfiguration2.getStringOrThrow("MCR.ContentTransformer." + id + ".InputFormat"); outputFormat = MCRConfiguration2.getStringOrThrow("MCR.ContentTransformer." + id + ".OutputFormat"); } @Override public MCRContent transform(MCRContent source) throws IOException { try { Element pandoc = MCRPandocAPI.convertToXML(source.asString(), inputFormat, outputFormat); if (!pandoc.getChildren().isEmpty()) { pandoc = pandoc.getChildren().get(0).detach(); } return new MCRJDOMContent(pandoc); } catch (Exception ex) { String msg = "Exception transforming from " + inputFormat + " to " + outputFormat + " via Pandoc"; throw new IOException(msg, ex); } } }
2,109
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPandocException.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pandoc/src/main/java/org/mycore/pandoc/MCRPandocException.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.pandoc; import org.mycore.common.MCRException; /** * Pandoc exception * * @author Kai Brandhorst */ public class MCRPandocException extends MCRException { private static final long serialVersionUID = 1L; /** * Creates a new MCRPandocException with message. * * @param message the message */ public MCRPandocException(String message) { super(message); } /** * Creates a new MCRPandocException with message and cause. * * @param message the message * @param cause the cause */ public MCRPandocException(String message, Throwable cause) { super(message, cause); } }
1,407
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPandocAPI.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-pandoc/src/main/java/org/mycore/pandoc/MCRPandocAPI.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.pandoc; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.concurrent.TimeUnit; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.mycore.common.config.MCRConfiguration2; /** * Interface to the command line utility <a href="https://pandoc.org">Pandoc</a>, * which needs to be installed separately. * * @author Kai Brandhorst */ public class MCRPandocAPI { private static final String PANDOC_BASE_COMMAND = MCRConfiguration2.getStringOrThrow("MCR.Pandoc.BaseCommand"); private static final int BUFFER_SIZE = MCRConfiguration2.getInt("MCR.Pandoc.BufferSize").orElse(64 * 1024); private static final int TIMEOUT = MCRConfiguration2.getInt("MCR.Pandoc.Timeout").orElse(5); private static final String LUA_PATH = MCRConfiguration2.getString("MCR.Pandoc.LuaPath") .orElse(Thread.currentThread().getContextClassLoader().getResource("lua").getPath() + "?.lua"); private enum Action { Reader, Writer } /** * Raw Pandoc command invocation * @param args Command line arguments to Pandoc * @param input Input to Pandoc (Stdin) * @return String of parsed output from Pandoc (Stdout) * @throws MCRPandocException in case of unsuccessful call to Pandoc */ public static String call(String args, String input) { String command = PANDOC_BASE_COMMAND.trim() + " " + args.trim(); String[] argsArray = command.split(" "); byte[] inputByteArray = input.getBytes(StandardCharsets.UTF_8); byte[] outputByteArray = callPandoc(argsArray, inputByteArray); String output = new String(outputByteArray, StandardCharsets.UTF_8); return output; } /** * Convenience method for converting between different formats. * If the property MCR.Pandoc.[Reader|Writer].FORMAT and/or MCR.Pandoc.[Reader|Writer].FORMAT.Path * are specified, those values get precedence and are interpreted as file paths. * Otherwise the importFormat and outputFormat are used as is. * @param content Content to be converted (Stdin) * @param importFormat Import format (cf. pandoc -f) * @param outputFormat Output format (cf. pandoc -t) * @return String of output from Pandoc (Stdout) * @throws MCRPandocException in case of unsuccessful call to Pandoc */ public static String convert(String content, String importFormat, String outputFormat) { String pandocArgs = "-f " + convertFormatToPath(Action.Reader, importFormat) + " -t " + convertFormatToPath(Action.Writer, outputFormat); return call(pandocArgs, content); } /** * Convenience method for converting between different formats. * If the property MCR.Pandoc.[Reader|Writer].FORMAT and/or MCR.Pandoc.[Reader|Writer].FORMAT.Path * are specified, those values get precedence and are interpreted as file paths. * Otherwise the importFormat and outputFormat are used as is. * This method wraps the output of Pandoc in a pandoc-element and parses it as XML. * @param content Content to be converted (Stdin) * @param importFormat Import format (cf. pandoc -f) * @param outputFormat Output format (cf. pandoc -t) * @return Element of parsed output from Pandoc (Stdout) * @throws MCRPandocException in case of unsuccessful call to Pandoc */ public static Element convertToXML(String content, String importFormat, String outputFormat) { String output = "<pandoc>" + convert(content, importFormat, outputFormat) + "</pandoc>"; try { return new SAXBuilder().build(new StringReader(output)).getRootElement().detach(); } catch (Exception ex) { String msg = "Exception converting Pandoc output to XML element"; throw new MCRPandocException(msg, ex); } } private static String convertFormatToPath(Action action, String format) { String property = MCRConfiguration2.getString("MCR.Pandoc." + action + "." + format).orElse(""); String path = MCRConfiguration2.getString("MCR.Pandoc." + action + "." + format + ".Path").orElse(""); if (!property.isEmpty()) { if (path.isEmpty()) { return Thread.currentThread().getContextClassLoader().getResource(property).getFile(); } else { return Paths.get(path).resolve(property).toString(); } } else { return format; } } private static byte[] callPandoc(String[] args, byte[] input) { class ThreadWrapper implements Runnable { private volatile byte[] output; private InputStream istream; ThreadWrapper(InputStream is) { istream = is; } @Override public void run() { try { output = readPandocOutput(istream); } catch (IOException ex) { String msg = "Exception reading output from Pandoc"; throw new MCRPandocException(msg, ex); } } public byte[] getOutput() { return output; } } ProcessBuilder pb = new ProcessBuilder(args); pb.environment().put("LUA_PATH", LUA_PATH); Process p; try { p = pb.start(); p.getOutputStream().write(input); p.getOutputStream().close(); } catch (IOException ex) { String msg = "Exception invoking Pandoc " + String.join(" ", args); throw new MCRPandocException(msg, ex); } ThreadWrapper outputThread = new ThreadWrapper(p.getInputStream()); ThreadWrapper errorThread = new ThreadWrapper(p.getErrorStream()); Thread oThread = new Thread(outputThread); Thread eThread = new Thread(errorThread); oThread.start(); eThread.start(); try { if (!p.waitFor(TIMEOUT, TimeUnit.SECONDS)) { p.destroy(); throw new InterruptedException(); } oThread.join(); eThread.join(); } catch (InterruptedException ex) { String msg = "Pandoc process " + String.join(" ", args) + " was terminated after reaching a timeout of " + TIMEOUT + " seconds"; throw new MCRPandocException(msg, ex); } if (p.exitValue() != 0) { String msg = "Pandoc process " + String.join(" ", args) + " terminated with error code " + p.exitValue() + " and error message \n" + new String(errorThread.getOutput(), StandardCharsets.UTF_8); p.destroy(); throw new MCRPandocException(msg); } return outputThread.getOutput(); } private static byte[] readPandocOutput(InputStream s) throws IOException { BufferedInputStream pandocStream = new BufferedInputStream(s); byte[] buffer = new byte[BUFFER_SIZE]; byte[] output = new byte[0]; int readBytes; while ((readBytes = pandocStream.read(buffer, 0, BUFFER_SIZE)) >= 0) { byte[] newOutput = new byte[output.length + readBytes]; System.arraycopy(output, 0, newOutput, 0, output.length); System.arraycopy(buffer, 0, newOutput, output.length, readBytes); output = newOutput; } pandocStream.close(); return output; } }
8,348
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISetManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAISetManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import static org.mycore.oai.pmh.OAIConstants.NS_OAI; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.common.MCRException; import org.mycore.common.MCRSystemUserInformation; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.events.MCRShutdownHandler; import org.mycore.common.xml.MCRURIResolver; import org.mycore.datamodel.classifications2.MCRCategoryDAOFactory; import org.mycore.oai.classmapping.MCRClassificationAndSetMapper; import org.mycore.oai.pmh.Description; import org.mycore.oai.pmh.OAIConstants; import org.mycore.oai.pmh.OAIDataList; import org.mycore.oai.pmh.Set; import org.mycore.oai.set.MCROAISetConfiguration; import org.mycore.oai.set.MCROAISetHandler; import org.mycore.oai.set.MCROAISolrSetConfiguration; import org.mycore.oai.set.MCRSet; import org.mycore.util.concurrent.MCRFixedUserCallable; /** * Manager class to handle OAI-PMH set specific behavior. * For a data provider instance, set support is optional and must be configured as described below. * Typically, sets are mapped to categories of a classification in MyCoRe. The set specifications are read from one or * more URIs using MCRURIResolver. This allows for sets that are typically built by applying an xsl stylesheet to the * output of the classification URI resolver, but also for other ways to dynamically create set specifications, or for * a static set specification that is read from an xml file. * Example: * <pre> * MCR.OAIDataProvider.OAI.Sets.OA=webapp:oai/open_access.xml * MCR.OAIDataProvider.OAI.Sets.DDC=xslStyle:classification2sets:classification:DDC * </pre> * The first line reads a set specification from a static xml file stored in the web application. The DINI certificate * demands that there always is a set open_access that contains all public Open Access documents. Since this set always * exists, its set specification can be read from a static file. The second line uses the classification resolver to * read in a classification, then transforms the xml to build set specifications from the listed categories. It is * recommended not to list sets that are completely empty, to simplify harvesting. The fastest way to accomplish this * is to somehow ensure that no set specifications from empty sets are delivered from the URIs, which means that the * classification resolver filters out empty categories, or the xsl stylesheet somehow decides to filter empty sets. * Another way to filter out empty sets can be activated by setting a property: * <code>MCR.OAIDataProvider.OAI.FilterEmptySets=true</code> When set to true, the MCRSetManager handler filters out * empty sets itself after reading in the URIs. This is done by constructing a query for each set and looking for * matching hits. Set queries are built using the OAI Adapter's buildSetCondition method. Filtering empty sets this way * may be useful for some implementations, but it is slower and should be avoided for large set hierarchies. * * @see MCRURIResolver * @author Frank L\u00fctzenkirchen * @author Matthias Eichner */ public class MCROAISetManager { protected static final Logger LOGGER = LogManager.getLogger(MCROAISetManager.class); protected String configPrefix; protected final Map<String, MCROAISetConfiguration<?, ?, ?>> setConfigurationMap; /** * Time in milliseconds when the classification changed. */ protected long classLastModified; /** * Time in minutes. */ protected int cacheMaxAge; protected final OAIDataList<MCRSet> cachedSetList; public MCROAISetManager() { this.setConfigurationMap = Collections.synchronizedMap(new HashMap<>()); this.cachedSetList = new OAIDataList<>(); this.classLastModified = Long.MIN_VALUE; } public void init(String configPrefix, int cacheMaxAge) { this.configPrefix = configPrefix; this.cacheMaxAge = cacheMaxAge; updateURIs(); if (this.cacheMaxAge != 0) { ScheduledExecutorService updateSetExecutor = Executors.newScheduledThreadPool(1); try { updateCachedSetList(); updateSetExecutor.scheduleWithFixedDelay(getUpdateRunnable(), cacheMaxAge, cacheMaxAge, TimeUnit.MINUTES); } finally { MCRShutdownHandler.getInstance().addCloseable(updateSetExecutor::shutdown); } } } private Runnable getUpdateRunnable() { MCRFixedUserCallable<Object> callable = new MCRFixedUserCallable<>( Executors.callable(this::updateCachedSetList), MCRSystemUserInformation.getSystemUserInstance()); return () -> { try { callable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new MCRException(e); } }; } private void updateCachedSetList() { LOGGER.info("update oai set list"); synchronized (cachedSetList) { OAIDataList<MCRSet> setList = createSetList(); cachedSetList.clear(); cachedSetList.addAll(setList); } } protected void updateURIs() { Map<String, MCROAISolrSetConfiguration> newVersion = getDefinedSetIds().stream() .map(String::trim) .map(setId -> new MCROAISolrSetConfiguration(this.configPrefix, setId)) .collect(Collectors.toMap(MCROAISolrSetConfiguration::getId, c -> c)); setConfigurationMap.entrySet().removeIf(c -> !newVersion.containsKey(c.getKey())); setConfigurationMap.putAll(newVersion); } public List<String> getDefinedSetIds() { return MCRConfiguration2.getString(this.configPrefix + "Sets") .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElseGet(Collections::emptyList); } /** * Returns a list of OAI-PMH sets defined by MyCoRe. * * @return list of oai sets */ @SuppressWarnings("unchecked") public OAIDataList<MCRSet> get() { // no cache if (this.cacheMaxAge == 0) { return createSetList(); } OAIDataList<MCRSet> oaiDataList = getDirectList(); // create a shallow copy of the set list synchronized (oaiDataList) { return (OAIDataList<MCRSet>) oaiDataList.clone(); } } public OAIDataList<MCRSet> getDirectList() { if (this.cacheMaxAge == 0) { return createSetList(); } // cache // check if classification changed long lastModified = MCRCategoryDAOFactory.getInstance().getLastModified(); if (lastModified != this.classLastModified) { this.classLastModified = lastModified; synchronized (this.cachedSetList) { OAIDataList<MCRSet> setList = createSetList(); cachedSetList.clear(); cachedSetList.addAll(setList); } } return cachedSetList; } /** * Returns the {@link MCROAISetConfiguration} for the given set id. * * @param <Q> value of the configuration * @param <R> Result collection type * @param <K> Key value type for a single hit * @param setId the set identifier * @return the configuration for this set */ @SuppressWarnings("unchecked") public <Q, R, K> MCROAISetConfiguration<Q, R, K> getConfig(String setId) { return (MCROAISetConfiguration<Q, R, K>) this.setConfigurationMap.get(setId); } protected OAIDataList<MCRSet> createSetList() { OAIDataList<MCRSet> setList = new OAIDataList<>(); synchronized (this.setConfigurationMap) { for (MCROAISetConfiguration<?, ?, ?> conf : this.setConfigurationMap.values()) { MCROAISetHandler<?, ?, ?> handler = conf.getHandler(); Map<String, MCRSet> setMap = handler.getSetMap(); synchronized (setMap) { setMap.clear(); Element resolved = MCRURIResolver.instance().resolve(conf.getURI()); if (resolved == null) { throw new MCRException( "Could not resolve set URI " + conf.getURI() + " for set " + conf.getId() + "."); } for (Element setElement : resolved.getChildren("set", OAIConstants.NS_OAI)) { MCRSet set = createSet(conf.getId(), setElement); setMap.put(set.getSpec(), set); if (!contains(set.getSpec(), setList)) { if (!handler.filter(set)) { setList.add(set); } } } } } } setList.sort(Comparator.comparing(Set::getSpec)); return setList; } private MCRSet createSet(String setId, Element setElement) { String setSpec = setElement.getChildText("setSpec", NS_OAI); String setName = setElement.getChildText("setName", NS_OAI); MCRSet set = new MCRSet(setId, getSetSpec(setSpec), setName); set.getDescription() .addAll(setElement.getChildren("setDescription", NS_OAI) .stream() //all setDescription .flatMap(e -> e.getChildren().stream().limit(1)) //first childElement of setDescription .peek(Element::detach) .map(d -> (Description) new Description() { @Override public Element toXML() { return d; } @Override public void fromXML(Element descriptionElement) { throw new UnsupportedOperationException(); } }) .collect(Collectors.toList())); return set; } private String getSetSpec(String elementText) { if (elementText.contains(":")) { StringBuilder setSpec = new StringBuilder(); String classID = elementText.substring(0, elementText.indexOf(':')).trim(); classID = MCRClassificationAndSetMapper.mapClassificationToSet(this.configPrefix, classID); setSpec.append(classID).append(elementText.substring(elementText.indexOf(':'))); return setSpec.toString(); } else { return elementText; } } /** * Returns the set with the specified setSpec from the set list or null, if no set with that setSpec is found. * * @param setSpec * identifier of the set * @param setList * list of sets * @return the set with setSpec */ public static <T extends Set> T get(String setSpec, OAIDataList<T> setList) { return setList.stream().filter(s -> s.getSpec().equals(setSpec)).findFirst().orElse(null); } /** * Returns true if setList contains a set with specified setSpec. * * @param setSpec * identifier of the set * @param setList * list of sets * @return true if the list contains the set */ public static boolean contains(String setSpec, OAIDataList<? extends Set> setList) { return get(setSpec, setList) != null; } }
12,556
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import org.mycore.common.config.MCRConfiguration2; import org.mycore.oai.classmapping.MCRClassificationAndSetMapper; public abstract class MCROAIUtils { public static String getDefaultRestriction(String configPrefix) { return MCRConfiguration2.getString(configPrefix + "Search.Restriction").orElse(null); } public static String getDefaultSetQuery(String setSpec, String configPrefix) { if (setSpec.contains(":")) { String categID = setSpec.substring(setSpec.lastIndexOf(':') + 1).trim(); String classID = setSpec.substring(0, setSpec.indexOf(':')).trim(); classID = MCRClassificationAndSetMapper.mapSetToClassification(configPrefix, classID); return "category:" + classID + "\\:" + categID; } else { String id = setSpec; String query = MCRConfiguration2.getString(configPrefix + "MapSetToQuery." + id.replace(":", "_")) .orElse(""); if (!query.equals("")) { return query; } else { id = MCRClassificationAndSetMapper.mapSetToClassification(configPrefix, id); return "category:*" + id + "*"; } } } }
1,973
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIObjectManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIObjectManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.xml.MCRURIResolver; import org.mycore.datamodel.common.MCRXMLMetadataManager; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.history.MCRMetadataHistoryManager; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.Header.Status; import org.mycore.oai.pmh.MetadataFormat; import org.mycore.oai.pmh.OAIConstants; import org.mycore.oai.pmh.Record; import org.mycore.oai.pmh.SimpleMetadata; /** * Provides an interface to the MyCoRe object engine. * * @author Matthias Eichner */ public class MCROAIObjectManager { protected static final Logger LOGGER = LogManager.getLogger(MCROAIObjectManager.class); protected MCROAIIdentify identify; protected String recordUriPattern; /** * Initialize the object manager. Its important to call this method before you * can retrieve records or headers! * * @param identify oai repository identifier */ public void init(MCROAIIdentify identify) { this.identify = identify; String configPrefix = this.identify.getConfigPrefix(); this.recordUriPattern = MCRConfiguration2.getStringOrThrow(configPrefix + "Adapter.RecordURIPattern"); } /** * Converts a oai identifier to a mycore id. * * @param oaiId the oai identifier * @return the mycore identifier */ public String getMyCoReId(String oaiId) { return oaiId.substring(oaiId.lastIndexOf(':') + 1); } /** * Converts a mycore id to a oai id. * * @param mcrId mycore identifier */ public String getOAIId(String mcrId) { return getOAIIDPrefix() + mcrId; } public Record getRecord(Header header, MetadataFormat format) { Element recordElement; if (header.isDeleted()) { return new Record(header); } try { recordElement = getJDOMRecord(getMyCoReId(header.getId()), format); } catch (Exception exc) { LOGGER.error("unable to get record {} ({})", header.getId(), format.getPrefix(), exc); return null; } Record record = new Record(header); if (recordElement.getNamespace().equals(OAIConstants.NS_OAI)) { Element metadataElement = recordElement.getChild("metadata", OAIConstants.NS_OAI); if (metadataElement != null && !metadataElement.getChildren().isEmpty()) { Element metadataChild = metadataElement.getChildren().get(0); record.setMetadata(new SimpleMetadata(metadataChild.detach())); } Element aboutElement = recordElement.getChild("about", OAIConstants.NS_OAI); if (aboutElement != null) { for (Element aboutChild : aboutElement.getChildren()) { record.getAboutList().add(aboutChild.detach()); } } } else { //handle as metadata record.setMetadata(new SimpleMetadata(recordElement)); } return record; } /** * Returns a deleted record without metadata by given MyCoRe identifier or null, if the * record is not deleted. * * @param mcrId id of the deleted record * @return deleted record */ public Record getDeletedRecord(String mcrId) { try { // building the query return MCRMetadataHistoryManager.getLastDeletedDate(MCRObjectID.getInstance(mcrId)) .map(deletedDate -> new Record( new Header(getOAIId(mcrId), deletedDate, Status.deleted))) .orElse(null); } catch (Exception ex) { LOGGER.warn("Error while retrieving deleted record {}", mcrId, ex); } return null; } protected Element getJDOMRecord(String mcrId, MetadataFormat format) { String uri = formatURI(this.recordUriPattern, mcrId, format.getPrefix()); return getURI(uri); } protected Element getURI(String uri) { Element e = MCRURIResolver.instance().resolve(uri).detach(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("get {}", uri); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); LOGGER.debug(out.outputString(e)); } return e; } protected String formatURI(String uri, String id, String metadataPrefix) { MCRObjectID mcrID = MCRObjectID.isValid(id) ? MCRObjectID.getInstance(id) : null; boolean exists; String objectType; if (mcrID != null) { exists = MCRMetadataManager.exists(mcrID); objectType = mcrID.getTypeId(); } else { //TODO remove this code path LOGGER.warn("MCRFileSystemNodes are not supported anymore! id: " + id); exists = false; objectType = "data_file"; } return uri.replace("{id}", id).replace("{format}", metadataPrefix).replace("{objectType}", objectType).replace( ":{flag}", !exists ? ":deletedMcrObject" : ""); } /** * Checks if a mycore object with the given oai identifier exists. * * @param oaiId * e.g. oai:www.mycore.de:Document_document_00000003 * @return true if exists, otherwise false */ protected boolean exists(String oaiId) { String mcrId = oaiId.substring(getOAIIDPrefix().length()); try { MCRObjectID mcrObjId = MCRObjectID.getInstance(mcrId); return MCRXMLMetadataManager.instance().exists(mcrObjId); } catch (Exception ex) { return false; } } private String getOAIIDPrefix() { return "oai:" + this.identify.getIdentifierDescription().getRepositoryIdentifier() + ":"; } }
6,821
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISolrResult.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAISolrResult.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.mycore.oai.pmh.Header; /** * Solr implementation of a MCROAIResult. * * @author Matthias Eichner */ public class MCROAISolrResult implements MCROAIResult { protected QueryResponse response; private Function<SolrDocument, Header> toHeader; public MCROAISolrResult(QueryResponse response, Function<SolrDocument, Header> toHeader) { this.response = response; this.toHeader = toHeader; } @Override public int getNumHits() { return (int) getResponse().getResults().getNumFound(); } @Override public List<Header> list() { SolrDocumentList list = getResponse().getResults(); return list.stream().map(toHeader).collect(Collectors.toList()); } @Override public Optional<String> nextCursor() { return Optional.ofNullable(this.response.getNextCursorMark()); } public QueryResponse getResponse() { return response; } }
1,975
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIIdentify.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIIdentify.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.time.Instant; import java.util.Collection; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Element; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.xml.MCRURIResolver; import org.mycore.oai.pmh.DateUtils; import org.mycore.oai.pmh.Description; import org.mycore.oai.pmh.FriendsDescription; import org.mycore.oai.pmh.Granularity; import org.mycore.oai.pmh.Identify; import org.mycore.oai.pmh.OAIIdentifierDescription; import org.mycore.oai.pmh.SimpleIdentify; /** * Simple MyCoRe implementation of a OAI-PMH {@link Identify} class. Uses the {@link MCRConfiguration2} to retrieve * all important settings. Earliest date stamp is calculated with the 'restriction' query and sort by 'created'. * Also adds custom description elements from URIs configured by MCR.OAIDataProvider.OAI.DescriptionURI * * @author Matthias Eichner * @author Frank L\u00fctzenkirchen */ public class MCROAIIdentify extends SimpleIdentify { protected static final Logger LOGGER = LogManager.getLogger(MCROAIIdentify.class); protected String configPrefix; public MCROAIIdentify(String baseURL, String configPrefix) { this.configPrefix = configPrefix; this.setBaseURL(baseURL); this.setRepositoryName( MCRConfiguration2.getString(configPrefix + "RepositoryName").orElse("Undefined repository name")); String deletedRecordPolicy = MCRConfiguration2.getString(configPrefix + "DeletedRecord") .orElse(DeletedRecordPolicy.Transient.name()); this.setDeletedRecordPolicy(DeletedRecordPolicy.get(deletedRecordPolicy)); String granularity = MCRConfiguration2.getString(configPrefix + "Granularity") .orElse(Granularity.YYYY_MM_DD.name()); this.setGranularity(Granularity.valueOf(granularity)); String adminMail = MCRConfiguration2.getString(configPrefix + "AdminEmail") .orElseGet(() -> MCRConfiguration2.getStringOrThrow("MCR.Mail.Sender")); this.setEarliestDatestamp(calculateEarliestTimestamp()); this.getAdminEmailList().add(adminMail); this.getDescriptionList().add(getIdentifierDescription()); if (!getFriendsDescription().getFriendsList().isEmpty()) { this.getDescriptionList().add(getFriendsDescription()); } addCustomDescriptions(); } private void addCustomDescriptions() { for (final String descriptionURI : getDescriptionURIs()) { this.getDescriptionList().add(new CustomDescription(descriptionURI)); } } /** * Calculates the earliest date stamp. * * @return the create date of the oldest document within the repository */ protected Instant calculateEarliestTimestamp() { MCROAISearcher searcher = MCROAISearchManager.getSearcher(this, null, 1, null, null); return searcher.getEarliestTimestamp().orElse(DateUtils .parse(MCRConfiguration2.getString(this.configPrefix + "EarliestDatestamp").orElse("1970-01-01"))); } public String getConfigPrefix() { return configPrefix; } private Collection<String> getDescriptionURIs() { String descriptionConfig = getConfigPrefix() + "DescriptionURI"; return MCRConfiguration2.getPropertiesMap() .entrySet() .stream() .filter(p -> p.getKey().startsWith(descriptionConfig)) .map(Map.Entry::getValue) .collect(Collectors.toSet()); } public FriendsDescription getFriendsDescription() { FriendsDescription desc = new FriendsDescription(); MCRConfiguration2.getPropertiesMap() .entrySet() .stream() .filter(p -> p.getKey().startsWith(this.configPrefix + "Friends.")) .map(Map.Entry::getValue) .filter(Predicate.not(String::isBlank)) .forEach(desc.getFriendsList()::add); return desc; } public OAIIdentifierDescription getIdentifierDescription() { String reposId = MCRConfiguration2.getStringOrThrow(this.configPrefix + "RepositoryIdentifier"); String sampleId = MCRConfiguration2.getStringOrThrow(this.configPrefix + "RecordSampleID"); return new OAIIdentifierDescription(reposId, sampleId); } static class CustomDescription implements Description { private Element description; CustomDescription(String descriptionURI) { description = MCRURIResolver.instance().resolve(descriptionURI); } @Override public void fromXML(Element description) { this.description = description; } @Override public Element toXML() { return description.getChildren().get(0).clone(); } } }
5,672
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISearchManager.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAISearchManager.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.time.Instant; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; 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.events.MCRShutdownHandler; import org.mycore.oai.pmh.BadResumptionTokenException; import org.mycore.oai.pmh.DefaultResumptionToken; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.MetadataFormat; import org.mycore.oai.pmh.OAIDataList; import org.mycore.oai.pmh.Record; import org.mycore.oai.set.MCRSet; import org.mycore.util.concurrent.MCRTransactionableRunnable; /** * Search manager of the mycore OAI-PMH implementation. Creates a new * {@link MCROAISearcher} instance for each * {@link #searchHeader(MetadataFormat, MCRSet, Instant, Instant)} * and {@link #searchRecord(MetadataFormat, MCRSet, Instant, Instant)} call. * The resumption token created by those methods can be reused for * later calls to the same searcher. A searcher is dropped after an * expiration time. The time increases for each query call. * * <p>Due to token based querying it is not possible to set a current * position for the resumption token. Its always set to -1.</p> * * @author Matthias Eichner */ public class MCROAISearchManager { protected static final Logger LOGGER = LogManager.getLogger(MCROAISearchManager.class); protected static final String TOKEN_DELIMITER = "@"; protected static int MAX_AGE; protected Map<String, MCROAISearcher> resultMap; protected MCROAIIdentify identify; protected MCROAIObjectManager objManager; protected MCROAISetManager setManager; protected int partitionSize; private ExecutorService executorService; private boolean runListRecordsParallel; static { String prefix = MCROAIAdapter.PREFIX + "ResumptionTokens."; MAX_AGE = MCRConfiguration2.getInt(prefix + "MaxAge").orElse(30) * 60 * 1000; } public MCROAISearchManager() { this.resultMap = new ConcurrentHashMap<>(); TimerTask tt = new TimerTask() { @Override public void run() { for (Map.Entry<String, MCROAISearcher> entry : resultMap.entrySet()) { String searchId = entry.getKey(); MCROAISearcher searcher = entry.getValue(); if ((searcher != null) && searcher.isExpired()) { LOGGER.info("Removing expired resumption token {}", searchId); resultMap.remove(searchId); } } } }; new Timer().schedule(tt, new Date(System.currentTimeMillis() + MAX_AGE), MAX_AGE); runListRecordsParallel = MCRConfiguration2 .getOrThrow(MCROAIAdapter.PREFIX + "RunListRecordsParallel", Boolean::parseBoolean); if (runListRecordsParallel) { executorService = Executors.newWorkStealingPool(); MCRShutdownHandler.getInstance().addCloseable(executorService::shutdownNow); } } public void init(MCROAIIdentify identify, MCROAIObjectManager objManager, MCROAISetManager setManager, int partitionSize) { this.identify = identify; this.objManager = objManager; this.setManager = setManager; this.partitionSize = partitionSize; } public Optional<Header> getHeader(String oaiId) { MCROAISearcher searcher = getSearcher(this.identify, null, 1, setManager, objManager); return searcher.getHeader(objManager.getMyCoReId(oaiId)); } public OAIDataList<Header> searchHeader(String resumptionToken) throws BadResumptionTokenException { String searchId = getSearchId(resumptionToken); String tokenCursor = getTokenCursor(resumptionToken); MCROAISearcher searcher = this.resultMap.get(searchId); if (searcher == null || tokenCursor == null || tokenCursor.length() <= 0) { throw new BadResumptionTokenException(resumptionToken); } MCROAIResult result = searcher.query(tokenCursor); return getHeaderList(searcher, result); } public OAIDataList<Record> searchRecord(String resumptionToken) throws BadResumptionTokenException { String searchId = getSearchId(resumptionToken); String tokenCursor = getTokenCursor(resumptionToken); MCROAISearcher searcher = this.resultMap.get(searchId); if (searcher == null || tokenCursor == null || tokenCursor.length() <= 0) { throw new BadResumptionTokenException(resumptionToken); } MCROAIResult result = searcher.query(tokenCursor); return getRecordList(searcher, result); } public OAIDataList<Header> searchHeader(MetadataFormat format, MCRSet set, Instant from, Instant until) { MCROAISearcher searcher = getSearcher(this.identify, format, getPartitionSize(), setManager, objManager); this.resultMap.put(searcher.getID(), searcher); MCROAIResult result = searcher.query(set, from, until); return getHeaderList(searcher, result); } public OAIDataList<Record> searchRecord(MetadataFormat format, MCRSet set, Instant from, Instant until) { MCROAISearcher searcher = getSearcher(this.identify, format, getPartitionSize(), setManager, objManager); this.resultMap.put(searcher.getID(), searcher); MCROAIResult result = searcher.query(set, from, until); return getRecordList(searcher, result); } protected OAIDataList<Record> getRecordList(MCROAISearcher searcher, MCROAIResult result) { OAIDataList<Record> recordList = runListRecordsParallel ? getRecordListParallel(searcher, result) : getRecordListSequential(searcher, result); if (recordList.contains(null)) { if (MCRConfiguration2.getBoolean("MCR.OAIDataProvider.FailOnErrorRecords").orElse(false)) { throw new MCRException( "An internal error occur. Some of the following records are invalid and cannot be processed." + " Please inform the system administrator. " + result.list()); } recordList.removeIf(Objects::isNull); } this.setResumptionToken(recordList, searcher, result); return recordList; } private OAIDataList<Record> getRecordListSequential(MCROAISearcher searcher, MCROAIResult result) { OAIDataList<Record> recordList = new OAIDataList<>(); result.list().forEach(header -> { Record record = this.objManager.getRecord(header, searcher.getMetadataFormat()); recordList.add(record); }); return recordList; } private OAIDataList<Record> getRecordListParallel(MCROAISearcher searcher, MCROAIResult result) { List<Header> headerList = result.list(); int listSize = headerList.size(); Record[] records = new Record[listSize]; @SuppressWarnings("rawtypes") CompletableFuture[] futures = new CompletableFuture[listSize]; MetadataFormat metadataFormat = searcher.getMetadataFormat(); MCRSession mcrSession = MCRSessionMgr.getCurrentSession(); for (int i = 0; i < listSize; i++) { Header header = headerList.get(i); int resultIndex = i; MCRTransactionableRunnable r = new MCRTransactionableRunnable( () -> records[resultIndex] = this.objManager.getRecord(header, metadataFormat), mcrSession); CompletableFuture<Void> future = CompletableFuture.runAsync(r, executorService); futures[i] = future; } CompletableFuture.allOf(futures).join(); OAIDataList<Record> recordList = new OAIDataList<>(); recordList.addAll(Arrays.asList(records)); return recordList; } protected OAIDataList<Header> getHeaderList(MCROAISearcher searcher, MCROAIResult result) { OAIDataList<Header> headerList = new OAIDataList<>(); headerList.addAll(result.list()); this.setResumptionToken(headerList, searcher, result); return headerList; } public String getSearchId(String token) throws BadResumptionTokenException { try { return token.split(TOKEN_DELIMITER)[0]; } catch (Exception exc) { throw new BadResumptionTokenException(token); } } public String getTokenCursor(String token) throws BadResumptionTokenException { try { String[] tokenParts = token.split(TOKEN_DELIMITER); return tokenParts[tokenParts.length - 1]; } catch (Exception exc) { throw new BadResumptionTokenException(token); } } protected void setResumptionToken(OAIDataList<?> dataList, MCROAISearcher searcher, MCROAIResult result) { result.nextCursor().map(cursor -> { DefaultResumptionToken rsToken = new DefaultResumptionToken(); rsToken.setToken(searcher.getID() + TOKEN_DELIMITER + cursor); rsToken.setCompleteListSize(result.getNumHits()); rsToken.setExpirationDate(searcher.getExpirationTime()); return rsToken; }).ifPresent(dataList::setResumptionToken); } public int getPartitionSize() { return partitionSize; } public static MCROAISearcher getSearcher(MCROAIIdentify identify, MetadataFormat format, int partitionSize, MCROAISetManager setManager, MCROAIObjectManager objectManager) { String className = identify.getConfigPrefix() + "Searcher"; MCROAISearcher searcher = MCRConfiguration2.<MCROAISearcher>getInstanceOf(className) .orElseGet(MCROAICombinedSearcher::new); searcher.init(identify, format, MAX_AGE, partitionSize, setManager, objectManager); return searcher; } }
11,023
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIResult.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIResult.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.util.List; import java.util.Optional; import org.mycore.oai.pmh.Header; /** * The result of a searcher query. * * @author Matthias Eichner */ public interface MCROAIResult { /** * Returns a list of mycore object identifiers. * * @return list of mycore object identifiers */ List<Header> list(); /** * Number of all hits * * @return number of hits */ int getNumHits(); /** * @return the next cursor */ Optional<String> nextCursor(); }
1,285
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISolrSearcher.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAISolrSearcher.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.io.IOException; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Date; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.CursorMarkParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.common.MCRISO8601FormatChooser; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.Set; import org.mycore.oai.set.MCROAISetConfiguration; import org.mycore.oai.set.MCROAISetHandler; import org.mycore.oai.set.MCROAISetResolver; import org.mycore.oai.set.MCROAISolrSetHandler; import org.mycore.oai.set.MCRSet; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrUtils; /** * Solr searcher implementation. Uses cursors. * * @author Matthias Eichner */ public class MCROAISolrSearcher extends MCROAISearcher { protected static final Logger LOGGER = LogManager.getLogger(MCROAISolrSearcher.class); private MCRSet set; private Instant from; private Instant until; /** * Solr always returns a nextCursorMark even when the end of the list is reached. * Due to that behavior we query the next result in advance and check if the * marks are equal (which tells us the end is reached). To avoid double querying * we store the result in {@link #nextResult}. For simple forwarding harvesting * this should be efficient. */ private Optional<String> lastCursor; private MCROAISolrResult nextResult; @Override public Optional<Header> getHeader(String mcrId) { SolrQuery query = getBaseQuery(CommonParams.FQ); query.set(CommonParams.Q, "id:" + MCRSolrUtils.escapeSearchValue(mcrId)); query.setRows(1); // do the query SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); try { QueryResponse response = solrClient.query(query); SolrDocumentList results = response.getResults(); if (!results.isEmpty()) { return Optional.of(toHeader(results.get(0), getSetResolver(results))); } } catch (Exception exc) { LOGGER.error("Unable to handle solr request", exc); } return Optional.empty(); } @Override public MCROAIResult query(String cursor) { this.updateRunningExpirationTimer(); Optional<String> currentCursor = Optional.of(cursor); try { return handleResult(currentCursor.equals(this.lastCursor) ? this.nextResult : solrQuery(currentCursor)); } catch (SolrServerException | IOException e) { throw new MCRException("Error while handling query.", e); } } @Override public MCROAIResult query(MCRSet set, Instant from, Instant until) { this.set = set; this.from = from; this.until = until; try { return handleResult(solrQuery(Optional.empty())); } catch (SolrServerException | IOException e) { throw new MCRException("Error while handling query.", e); } } private MCROAIResult handleResult(MCROAISolrResult result) throws SolrServerException, IOException { this.nextResult = solrQuery(result.nextCursor()); this.lastCursor = result.nextCursor(); if (result.nextCursor().equals(this.nextResult.nextCursor())) { return MCROAISimpleResult.from(result).setNextCursor(null); } return result; } protected MCROAISolrResult solrQuery(Optional<String> cursor) throws SolrServerException, IOException { SolrQuery query = getBaseQuery(CommonParams.Q); // set support if (this.set != null) { String setId = this.set.getSetId(); MCROAISetConfiguration<SolrQuery, SolrDocument, String> setConfig = getSetManager().getConfig(setId); setConfig.getHandler().apply(this.set, query); } // from & until if (this.from != null || this.until != null) { String fromUntilCondition = buildFromUntilCondition(this.from, this.until); query.add(CommonParams.FQ, fromUntilCondition); } // cursor query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursor.orElse(CursorMarkParams.CURSOR_MARK_START)); query.set(CommonParams.ROWS, String.valueOf(getPartitionSize())); query.set(CommonParams.SORT, "id asc"); // do the query SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); QueryResponse response = solrClient.query(query); Collection<MCROAISetResolver<String, SolrDocument>> setResolver = getSetResolver(response.getResults()); return new MCROAISolrResult(response, d -> toHeader(d, setResolver)); } private SolrQuery getBaseQuery(String restrictionField) { String configPrefix = this.identify.getConfigPrefix(); SolrQuery query = new SolrQuery(); // query MCRConfiguration2.getString(configPrefix + "Search.Restriction") .ifPresent(restriction -> query.set(restrictionField, restriction)); String[] requiredFields = Stream.concat(Stream.of("id", getModifiedField()), getRequiredFieldNames().stream()) .toArray(String[]::new); query.setFields(requiredFields); // request handler query.setRequestHandler(MCRConfiguration2.getString(configPrefix + "Search.RequestHandler").orElse("/select")); return query; } private Collection<MCROAISetResolver<String, SolrDocument>> getSetResolver(Collection<SolrDocument> result) { return getSetManager().getDefinedSetIds().stream() .map(getSetManager()::getConfig) .map(MCROAISetConfiguration::getHandler) .map(this::cast) .map(h -> h.getSetResolver(result)) .collect(Collectors.toList()); } private Collection<String> getRequiredFieldNames() { return getSetManager().getDefinedSetIds().stream() .map(getSetManager()::getConfig) .map(MCROAISetConfiguration::getHandler) .filter(MCROAISolrSetHandler.class::isInstance) .map(MCROAISolrSetHandler.class::cast) .flatMap(h -> h.getFieldNames().stream()) .collect(Collectors.toSet()); } @SuppressWarnings({ "unchecked", "rawtypes" }) private MCROAISetHandler<SolrQuery, SolrDocument, String> cast(MCROAISetHandler handler) { return handler; } Header toHeader(SolrDocument doc, Collection<MCROAISetResolver<String, SolrDocument>> setResolver) { String docId = doc.getFieldValue("id").toString(); Date modified = (Date) doc.getFieldValue(getModifiedField()); LOGGER.debug("'{}' is '{}' for {}", getModifiedField(), modified, docId); MCROAIObjectManager objectManager = getObjectManager(); String oaiId = objectManager.getOAIId(docId); Header header = new Header(oaiId, modified.toInstant()); header.getSetList().addAll( setResolver.parallelStream() .map(r -> r.getSets(docId)) .flatMap(Collection::stream) .sorted(this::compare) .toList()); return header; } private int compare(Set s1, Set s2) { return s1.getSpec().compareTo(s2.getSpec()); } private String buildFromUntilCondition(Instant from, Instant until) { String fieldFromUntil = getModifiedField(); StringBuilder query = new StringBuilder(" +").append(fieldFromUntil).append(":["); DateTimeFormatter format = MCRISO8601FormatChooser.COMPLETE_HH_MM_SS_FORMAT; if (from == null) { query.append("* TO "); } else { query.append(format.format(from.atZone(ZoneId.of("UTC")))).append(" TO "); } if (until == null) { query.append("*]"); } else { query.append(format.format(until.atZone(ZoneId.of("UTC")))).append(']'); } return query.toString(); } private String getModifiedField() { return MCRConfiguration2.getString(getConfigPrefix() + "Search.FromUntil").orElse("modified"); } @Override public Optional<Instant> getEarliestTimestamp() { ModifiableSolrParams params = new ModifiableSolrParams(); String sortBy = MCRConfiguration2.getString(getConfigPrefix() + "EarliestDatestamp.SortBy") .orElse("modified asc"); params.add(CommonParams.SORT, sortBy); MCRConfiguration2.getString(getConfigPrefix() + "Search.Restriction") .ifPresent(restriction -> params.add(CommonParams.Q, restriction)); String fieldName = MCRConfiguration2.getString(getConfigPrefix() + "EarliestDatestamp.FieldName") .orElse("modified"); params.add(CommonParams.FQ, fieldName + ":[* TO *]"); params.add(CommonParams.FL, fieldName); params.add(CommonParams.ROWS, "1"); SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); try { QueryResponse response = solrClient.query(params); SolrDocumentList list = response.getResults(); if (list.size() >= 1) { Date date = (Date) list.get(0).getFieldValue(fieldName); return Optional.of(date.toInstant()); } } catch (Exception exc) { LOGGER.error("Unable to handle solr request", exc); } return Optional.empty(); } }
10,877
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISearcher.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAISearcher.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.time.Instant; import java.util.Optional; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.MetadataFormat; import org.mycore.oai.set.MCRSet; /** * <p>Base class to query different types of data in the mycore system. * Implementations has to implement the query and the earliest time stamp * methods. The result of a query is a {@link MCROAIResult}.</p> * * <p>Searchers have a unique id and a expiration time which increases * every time a query is fired.</p> * * @author Matthias Eichner */ public abstract class MCROAISearcher { protected static final Logger LOGGER = LogManager.getLogger(MCROAISearcher.class); protected MCROAIIdentify identify; protected MetadataFormat metadataFormat; /** The unique ID of this result set */ protected final String id; protected long expire; /** * Increase every time a {@link #query(String)} is called */ protected long runningExpirationTimer; protected int partitionSize; protected MCROAISetManager setManager; private MCROAIObjectManager objectManager; public MCROAISearcher() { Random random = new Random(System.currentTimeMillis()); this.id = Long.toString(random.nextLong(), 36) + Long.toString(System.currentTimeMillis(), 36); } public void init(MCROAIIdentify identify, MetadataFormat format, long expire, int partitionSize, MCROAISetManager setManager, MCROAIObjectManager objectManager) { this.identify = identify; this.metadataFormat = format; this.expire = expire; this.partitionSize = partitionSize; this.setManager = setManager; this.objectManager = objectManager; updateRunningExpirationTimer(); } public abstract Optional<Header> getHeader(String mcrId); public abstract MCROAIResult query(String cursor); public abstract MCROAIResult query(MCRSet set, Instant from, Instant until); /** * Returns the earliest created/modified record time stamp. If the earliest time stamp cannot be retrieved an * empty optional is returned. * * @return the earliest created/modified time stamp */ public abstract Optional<Instant> getEarliestTimestamp(); public boolean isExpired() { return System.currentTimeMillis() > runningExpirationTimer; } public Instant getExpirationTime() { return Instant.ofEpochMilli(runningExpirationTimer); } public MetadataFormat getMetadataFormat() { return metadataFormat; } public String getID() { return id; } public MCROAISetManager getSetManager() { return setManager; } public MCROAIObjectManager getObjectManager() { return objectManager; } protected String getConfigPrefix() { return this.identify.getConfigPrefix(); } /** * Updates the running expiration timer. */ protected void updateRunningExpirationTimer() { this.runningExpirationTimer = System.currentTimeMillis() + this.expire; } public int getPartitionSize() { return partitionSize; } }
3,998
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISimpleResult.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAISimpleResult.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.mycore.oai.pmh.Header; /** * Simple implementation of a {@link MCROAIResult} with setter * and getter methods. * * @author Matthias Eichner */ public class MCROAISimpleResult implements MCROAIResult { private List<Header> headerList; private int numHits; private String nextCursor; public MCROAISimpleResult() { this.headerList = new ArrayList<>(); this.numHits = 0; this.nextCursor = null; } @Override public List<Header> list() { return this.headerList; } @Override public int getNumHits() { return this.numHits; } @Override public Optional<String> nextCursor() { return Optional.ofNullable(this.nextCursor); } public MCROAISimpleResult setNextCursor(String nextCursor) { this.nextCursor = nextCursor; return this; } public MCROAISimpleResult setNumHits(int numHits) { this.numHits = numHits; return this; } public MCROAISimpleResult setHeaderList(List<Header> headerList) { this.headerList = headerList; return this; } public static MCROAISimpleResult from(MCROAIResult result) { MCROAISimpleResult newResult = new MCROAISimpleResult(); newResult.setHeaderList(result.list()); result.nextCursor().ifPresent(newResult::setNextCursor); newResult.setNumHits(result.getNumHits()); return newResult; } }
2,287
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIAdapter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIAdapter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.StringTokenizer; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.oai.pmh.BadResumptionTokenException; import org.mycore.oai.pmh.CannotDisseminateFormatException; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.IdDoesNotExistException; import org.mycore.oai.pmh.Identify.DeletedRecordPolicy; import org.mycore.oai.pmh.MetadataFormat; import org.mycore.oai.pmh.NoMetadataFormatsException; import org.mycore.oai.pmh.NoRecordsMatchException; import org.mycore.oai.pmh.NoSetHierarchyException; import org.mycore.oai.pmh.OAIDataList; import org.mycore.oai.pmh.Record; import org.mycore.oai.pmh.Set; import org.mycore.oai.pmh.dataprovider.OAIAdapter; import org.mycore.oai.set.MCRSet; /** * Default MyCoRe {@link OAIAdapter} implementation. * * @author Matthias Eichner */ public class MCROAIAdapter implements OAIAdapter { protected static final Logger LOGGER = LogManager.getLogger(MCROAIAdapter.class); protected static final ZoneId UTC_ZONE = ZoneId.of("UTC"); public static final String PREFIX = "MCR.OAIDataProvider."; public static int DEFAULT_PARTITION_SIZE; protected String baseURL; protected MCROAIIdentify identify; protected String configPrefix; protected MCROAISearchManager searchManager; protected MCROAIObjectManager objectManager; protected MCROAISetManager setManager; static { String prefix = MCROAIAdapter.PREFIX + "ResumptionTokens."; DEFAULT_PARTITION_SIZE = MCRConfiguration2.getInt(prefix + "PartitionSize").orElse(50); LOGGER.info(MCROAIAdapter.PREFIX + "ResumptionTokens.PartitionSize is set to {}", DEFAULT_PARTITION_SIZE); } /** * Initialize the adapter. * * @param baseURL * baseURL of the adapter e.g. http://localhost:8291/oai2 * @param oaiConfiguration * specifies the OAI-PMH configuration */ public void init(String baseURL, String oaiConfiguration) { this.baseURL = baseURL; this.configPrefix = PREFIX + oaiConfiguration + "."; } public MCROAISetManager getSetManager() { if (this.setManager == null) { this.setManager = MCRConfiguration2.<MCROAISetManager>getInstanceOf(getConfigPrefix() + "SetManager") .orElseGet(MCROAISetManager::new); int cacheMaxAge = MCRConfiguration2.getInt(this.configPrefix + "SetCache.MaxAge").orElse(0); this.setManager.init(getConfigPrefix(), cacheMaxAge); } return this.setManager; } public boolean moveNamespaceDeclarationsToRoot() { return MCRConfiguration2.getString(this.configPrefix + "MoveNamespaceDeclarationsToRoot") .map(Boolean::parseBoolean) .orElse(true); } public MCROAIObjectManager getObjectManager() { if (this.objectManager == null) { this.objectManager = new MCROAIObjectManager(); this.objectManager.init(getIdentify()); } return this.objectManager; } public MCROAISearchManager getSearchManager() { if (this.searchManager == null) { this.searchManager = new MCROAISearchManager(); int partitionSize = MCRConfiguration2.getInt(getConfigPrefix() + "ResumptionTokens.PartitionSize") .orElse(DEFAULT_PARTITION_SIZE); this.searchManager.init(getIdentify(), getObjectManager(), getSetManager(), partitionSize); } return this.searchManager; } public String getConfigPrefix() { return this.configPrefix; } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getIdentify() */ @Override public MCROAIIdentify getIdentify() { if (this.identify == null) { this.identify = new MCROAIIdentify(this.baseURL, getConfigPrefix()); } return this.identify; } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getSets() */ @Override public OAIDataList<Set> getSets() throws NoSetHierarchyException { MCROAISetManager setManager = getSetManager(); OAIDataList<MCRSet> setList2 = setManager.get(); OAIDataList<Set> setList = cast(setList2); if (setList.isEmpty()) { throw new NoSetHierarchyException(); } return setList; } @SuppressWarnings("unchecked") private OAIDataList<Set> cast(OAIDataList<? extends Set> setList) { return (OAIDataList<Set>) setList; } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getSets(java.lang.String) */ @Override public OAIDataList<Set> getSets(String resumptionToken) throws NoSetHierarchyException, BadResumptionTokenException { MCROAISetManager setManager = getSetManager(); OAIDataList<Set> setList = cast(setManager.get()); if (setList.isEmpty()) { throw new NoSetHierarchyException(); } // TODO: this is like to old oai implementation but actually wrong with a large amount of sets throw new BadResumptionTokenException(); } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getSet(java.lang.String) */ @Override public MCRSet getSet(String setSpec) throws NoSetHierarchyException, NoRecordsMatchException { MCROAISetManager setManager = getSetManager(); OAIDataList<MCRSet> setList = setManager.get(); if (setList.isEmpty()) { throw new NoSetHierarchyException(); } MCRSet set = MCROAISetManager.get(setSpec, setList); if (set == null) { throw new NoRecordsMatchException(); } return set; } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getMetadataFormats() */ @Override public List<MetadataFormat> getMetadataFormats() { return new ArrayList<>(getMetadataFormatMap().values()); } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getMetadataFormat(java.lang.String) */ @Override public MetadataFormat getMetadataFormat(String prefix) throws CannotDisseminateFormatException { MetadataFormat format = getMetadataFormatMap().get(prefix); if (format == null) { throw new CannotDisseminateFormatException(); } return format; } protected Map<String, MetadataFormat> getMetadataFormatMap() { Map<String, MetadataFormat> metdataFormatMap = new HashMap<>(); String formats = MCRConfiguration2.getString(getConfigPrefix() + "MetadataFormats").orElse(""); StringTokenizer st = new StringTokenizer(formats, ", "); while (st.hasMoreTokens()) { String format = st.nextToken(); String namespaceURI = MCRConfiguration2 .getStringOrThrow(PREFIX + "MetadataFormat." + format + ".Namespace"); String schema = MCRConfiguration2.getStringOrThrow(PREFIX + "MetadataFormat." + format + ".Schema"); metdataFormatMap.put(format, new MetadataFormat(format, namespaceURI, schema)); } return metdataFormatMap; } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getMetadataFormats(java.lang.String) */ @Override public List<MetadataFormat> getMetadataFormats(String identifier) throws IdDoesNotExistException, NoMetadataFormatsException { if (!getObjectManager().exists(identifier)) { throw new IdDoesNotExistException(identifier); } Header header = getSearchManager().getHeader(identifier).get(); if (header.isDeleted()) { throw new NoMetadataFormatsException(identifier); } List<MetadataFormat> metadataFormats = getMetadataFormats() .stream() .filter(format -> objectManager.getRecord(header, format) != null) .collect(Collectors.toList()); if (metadataFormats.isEmpty()) { throw new NoMetadataFormatsException(identifier); } return metadataFormats; } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getRecord(java.lang.String, org.mycore.oai.pmh.MetadataFormat) */ @Override public Record getRecord(String identifier, MetadataFormat format) throws CannotDisseminateFormatException, IdDoesNotExistException { //Update set for response header getSetManager().getDirectList(); Optional<Record> possibleRecord = getSearchManager() .getHeader(identifier) .map(h -> objectManager.getRecord(h, format)); if (possibleRecord.isPresent()) { return possibleRecord.get(); } if (!objectManager.exists(identifier)) { DeletedRecordPolicy rP = getIdentify().getDeletedRecordPolicy(); if (DeletedRecordPolicy.Persistent.equals(rP)) { // get deleted item Record deletedRecord = objectManager.getDeletedRecord(objectManager.getMyCoReId(identifier)); if (deletedRecord != null) { return deletedRecord; } } } else { throw new CannotDisseminateFormatException() .setId(identifier) .setMetadataPrefix(format.getPrefix()); } throw new IdDoesNotExistException(identifier); } /* * (non-Javadoc) * @see org.mycore.oai.pmh.dataprovider.OAIAdapter#getRecords(java.lang.String) */ @Override public OAIDataList<Record> getRecords(String resumptionToken) throws BadResumptionTokenException { //Update set for response header getSetManager().getDirectList(); OAIDataList<Record> recordList = getSearchManager().searchRecord(resumptionToken); if (recordList.isEmpty() && getHeaders(resumptionToken).isEmpty()) { throw new BadResumptionTokenException(resumptionToken); } return recordList; } @Override public OAIDataList<Record> getRecords(MetadataFormat format, Set set, Instant from, Instant until) throws NoSetHierarchyException, NoRecordsMatchException { //Update set for response header getSetManager().getDirectList(); OAIDataList<Record> recordList = getSearchManager().searchRecord(format, toMCRSet(set), from, until); if (recordList.isEmpty() && getHeaders(format, set, from, until).isEmpty()) { throw new NoRecordsMatchException(); } return recordList; } private MCRSet toMCRSet(Set set) throws NoSetHierarchyException, NoRecordsMatchException { if (set == null) { return null; } return getSet(set.getSpec()); } @Override public OAIDataList<Header> getHeaders(String resumptionToken) throws BadResumptionTokenException { //Update set for response header getSetManager().getDirectList(); OAIDataList<Header> headerList = getSearchManager().searchHeader(resumptionToken); if (headerList.isEmpty()) { throw new BadResumptionTokenException(resumptionToken); } return headerList; } @Override public OAIDataList<Header> getHeaders(MetadataFormat format, Set set, Instant from, Instant until) throws NoSetHierarchyException, NoRecordsMatchException { //Update set for response header getSetManager().getDirectList(); OAIDataList<Header> headerList = getSearchManager().searchHeader(format, toMCRSet(set), from, until); if (headerList.isEmpty()) { throw new NoRecordsMatchException(); } return headerList; } }
12,878
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIDataProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIDataProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.ProcessingInstruction; import org.jdom2.filter.ElementFilter; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.output.support.AbstractXMLOutputProcessor; import org.jdom2.output.support.FormatStack; import org.jdom2.util.NamespaceStack; import org.mycore.common.MCRClassTools; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.oai.pmh.OAIConstants; import org.mycore.oai.pmh.dataprovider.OAIAdapter; import org.mycore.oai.pmh.dataprovider.OAIProvider; import org.mycore.oai.pmh.dataprovider.OAIRequest; import org.mycore.oai.pmh.dataprovider.OAIResponse; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; /** * Implements an OAI-PMH 2.0 Data Provider as a servlet. * * @author Matthias Eichner */ public class MCROAIDataProvider extends MCRServlet { private static final long serialVersionUID = 1L; protected static final Logger LOGGER = LogManager.getLogger(MCROAIDataProvider.class); /** * Map of all MyCoRe oai adapter. */ private static Map<String, MCROAIAdapter> ADAPTER_MAP; private static final OAIXMLOutputProcessor OAI_XML_OUTPUT_PROCESSOR = new OAIXMLOutputProcessor(); static { ADAPTER_MAP = new HashMap<>(); } private String myBaseURL; private ServiceLoader<OAIProvider> oaiAdapterServiceLoader; @Override public void init() throws ServletException { super.init(); oaiAdapterServiceLoader = ServiceLoader.load(OAIProvider.class, MCRClassTools.getClassLoader()); } @Override protected void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); // get base url if (this.myBaseURL == null) { this.myBaseURL = MCRFrontendUtil.getBaseURL() + request.getServletPath().substring(1); } logRequest(request); // create new oai request OAIRequest oaiRequest = new OAIRequest(fixParameterMap(request.getParameterMap())); // create new oai provider OAIProvider oaiProvider = oaiAdapterServiceLoader .findFirst() .orElseThrow(() -> new ServletException("No implementation of " + OAIProvider.class + " found.")); final OAIAdapter adapter = getOAIAdapter(); oaiProvider.setAdapter(adapter); // handle request OAIResponse oaiResponse = oaiProvider.handleRequest(oaiRequest); // build response Element xmlRespone = oaiResponse.toXML(); if (!(adapter instanceof MCROAIAdapter mcrAdapter) || mcrAdapter.moveNamespaceDeclarationsToRoot()) { moveNamespacesUp(xmlRespone); } // fire job.getResponse().setContentType("text/xml; charset=UTF-8"); XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat(), OAI_XML_OUTPUT_PROCESSOR); xout.output(addXSLStyle(new Document(xmlRespone)), job.getResponse().getOutputStream()); } /** * Converts the servlet parameter map to deal with oaipmh api. * * @param pMap servlet parameter map * @return parameter map with generics and list */ @SuppressWarnings("rawtypes") private Map<String, List<String>> fixParameterMap(Map pMap) { Map<String, List<String>> rMap = new HashMap<>(); for (Object o : pMap.entrySet()) { Map.Entry entry = (Map.Entry) o; List<String> valueList = new ArrayList<>(); Collections.addAll(valueList, (String[]) entry.getValue()); rMap.put((String) entry.getKey(), valueList); } return rMap; } protected void logRequest(HttpServletRequest req) { StringBuilder log = new StringBuilder(this.getServletName()); for (Object o : req.getParameterMap().keySet()) { String name = (String) o; for (String value : req.getParameterValues(name)) { log.append(' ').append(name).append('=').append(value); } } LOGGER.info(log.toString()); } /** * Add link to XSL stylesheet for displaying OAI response in web browser. */ private Document addXSLStyle(Document doc) { String styleSheet = MCROAIAdapter.PREFIX + getServletName() + ".ResponseStylesheet"; String xsl = MCRConfiguration2.getString(styleSheet).orElse("oai/oai2.xsl"); if (!xsl.isEmpty()) { Map<String, String> pairs = new HashMap<>(); pairs.put("type", "text/xsl"); pairs.put("href", MCRFrontendUtil.getBaseURL() + xsl); doc.addContent(0, new ProcessingInstruction("xml-stylesheet", pairs)); } return doc; } private OAIAdapter getOAIAdapter() { String oaiAdapterKey = getServletName(); MCROAIAdapter oaiAdapter = ADAPTER_MAP.get(oaiAdapterKey); if (oaiAdapter == null) { synchronized (this) { // double check because of synchronize block oaiAdapter = ADAPTER_MAP.get(oaiAdapterKey); if (oaiAdapter == null) { String adapter = MCROAIAdapter.PREFIX + oaiAdapterKey + ".Adapter"; oaiAdapter = MCRConfiguration2.<MCROAIAdapter>getInstanceOf(adapter) .orElseGet(MCROAIAdapter::new); oaiAdapter.init(this.myBaseURL, oaiAdapterKey); ADAPTER_MAP.put(oaiAdapterKey, oaiAdapter); } } } return oaiAdapter; } /** * Moves all namespace declarations in the children of target to the target. * * @param target the namespace are bundled here */ private void moveNamespacesUp(Element target) { Map<String, Namespace> existingNamespaces = getNamespaceMap(target); Map<String, Namespace> newNamespaces = new HashMap<>(); target.getDescendants(new ElementFilter()).forEach(child -> { Map<String, Namespace> childNamespaces = getNamespaceMap(child); childNamespaces.forEach((prefix, ns) -> { if (existingNamespaces.containsKey(prefix) || newNamespaces.containsKey(prefix)) { return; } newNamespaces.put(prefix, ns); }); }); newNamespaces.forEach((prefix, ns) -> target.addNamespaceDeclaration(ns)); } private Map<String, Namespace> getNamespaceMap(Element element) { Map<String, Namespace> map = new HashMap<>(); map.put(element.getNamespace().getPrefix(), element.getNamespace()); element.getAdditionalNamespaces().forEach(ns -> map.put(ns.getPrefix(), ns)); return map; } private static final class OAIXMLOutputProcessor extends AbstractXMLOutputProcessor { @Override protected void printElement(Writer out, FormatStack fstack, NamespaceStack nstack, Element element) throws IOException { //MCR-1866 use raw format if element is not in OAI namespace if (!element.getNamespace().equals(OAIConstants.NS_OAI)) { fstack.setTextMode(Format.TextMode.PRESERVE); } super.printElement(out, fstack, nstack, element); } } }
8,541
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAICombinedSearcher.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAICombinedSearcher.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.time.Instant; import java.util.Optional; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.Identify.DeletedRecordPolicy; import org.mycore.oai.pmh.MetadataFormat; import org.mycore.oai.set.MCRSet; /** * <p>Combines the solr searcher and the deleted searcher. Ignores the * deleted searcher if the DeletedRecordPolicy is set to 'No'.</p> * * <p>The deleted records appear after the solr records.</p> * * @author Matthias Eichner */ public class MCROAICombinedSearcher extends MCROAISearcher { private MCROAISolrSearcher solrSearcher; private Optional<MCROAIDeletedSearcher> deletedSearcher = Optional.empty(); private Integer numHits; @Override public void init(MCROAIIdentify identify, MetadataFormat format, long expire, int partitionSize, MCROAISetManager setManager, MCROAIObjectManager objectManager) { super.init(identify, format, expire, partitionSize, setManager, objectManager); this.solrSearcher = new MCROAISolrSearcher(); this.solrSearcher.init(identify, format, expire, partitionSize, setManager, objectManager); if (!identify.getDeletedRecordPolicy().equals(DeletedRecordPolicy.No)) { this.deletedSearcher = Optional.of(new MCROAIDeletedSearcher()); this.deletedSearcher.get().init(identify, format, expire, partitionSize, setManager, objectManager); } } @Override public Optional<Header> getHeader(String mcrId) { Optional<Header> header = this.solrSearcher.getHeader(mcrId); return header.isPresent() ? header : deletedSearcher.flatMap(oais -> oais.getHeader(mcrId)); } @Override public MCROAIResult query(String cursor) { if (!this.deletedSearcher.isPresent()) { return this.solrSearcher.query(cursor); } // deleted query, no need to ask solr if (isDeletedCursor(cursor)) { MCROAISimpleResult result = this.deletedSearcher.get().query(cursor); result.setNumHits(this.numHits); return result; } return getMixedResult(this.solrSearcher.query(cursor)); } @Override public MCROAIResult query(MCRSet set, Instant from, Instant until) { MCROAIResult solrResult = this.solrSearcher.query(set, from, until); if (!this.deletedSearcher.isPresent()) { this.numHits = solrResult.getNumHits(); return solrResult; } MCROAIResult deletedResult = this.deletedSearcher.get().query(set, from, until); this.numHits = solrResult.getNumHits() + deletedResult.getNumHits(); return getMixedResult(solrResult); } @Override public Optional<Instant> getEarliestTimestamp() { Optional<Instant> solrTimestamp = this.solrSearcher.getEarliestTimestamp(); Optional<Instant> deletedTimestamp = deletedSearcher.flatMap(MCROAIDeletedSearcher::getEarliestTimestamp); if (solrTimestamp.isPresent() && deletedTimestamp.isPresent()) { Instant instant1 = solrTimestamp.get(); Instant instant2 = deletedTimestamp.get(); return Optional.of(instant1.isBefore(instant2) ? instant1 : instant2); } return solrTimestamp.map(Optional::of).orElse(deletedTimestamp); } private boolean isDeletedCursor(String cursor) { return cursor != null && cursor.startsWith(MCROAIDeletedSearcher.CURSOR_PREFIX); } private MCROAIResult getMixedResult(MCROAIResult solrResult) { MCROAISimpleResult result = new MCROAISimpleResult(); result.setNumHits(this.numHits); // solr query - not at the end if (solrResult.nextCursor().isPresent()) { result.setNextCursor(solrResult.nextCursor().get()); result.setHeaderList(solrResult.list()); return result; } // solr is at the end of the list, mix with deleted result.setHeaderList(solrResult.list()); int delta = this.getPartitionSize() - solrResult.list().size(); MCROAIDeletedSearcher delSearcher = this.deletedSearcher.get(); if (delta > 0) { String deletedCursor = delSearcher.buildCursor(0, delta); MCROAIResult deletedResult = delSearcher.query(deletedCursor); result.list().addAll(deletedResult.list()); deletedResult.nextCursor().ifPresent(result::setNextCursor); } else if (delSearcher.getDeletedRecords().size() > 0) { result.setNextCursor(delSearcher.buildCursor(0, this.getPartitionSize())); } return result; } }
5,344
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIDeletedSearcher.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/MCROAIDeletedSearcher.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Collectors; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.history.MCRMetadataHistoryManager; import org.mycore.oai.pmh.Header; import org.mycore.oai.pmh.Header.Status; import org.mycore.oai.pmh.Identify.DeletedRecordPolicy; import org.mycore.oai.set.MCRSet; /** * Searcher for deleted records. The schema for the cursor * is <b>deleted_from_rows</b>. * * @author Matthias Eichner */ public class MCROAIDeletedSearcher extends MCROAISearcher { public static final String CURSOR_PREFIX = "deleted"; public static final String CURSOR_DELIMETER = "_"; private List<Header> deletedRecords; @Override public Optional<Header> getHeader(String mcrId) { return MCRMetadataHistoryManager.getLastDeletedDate(MCRObjectID.getInstance(mcrId)) .map(deletedDate -> new Header(getObjectManager().getOAIId(mcrId), deletedDate, Status.deleted)); } @Override public MCROAISimpleResult query(String cursor) { this.updateRunningExpirationTimer(); int from = 0; int rows = this.getPartitionSize(); if (cursor != null) { try { String[] parts = cursor.substring((CURSOR_PREFIX + CURSOR_DELIMETER).length()).split(CURSOR_DELIMETER); from = Integer.parseInt(parts[0]); rows = Integer.parseInt(parts[1]); } catch (Exception exc) { throw new IllegalArgumentException("Invalid cursor " + cursor, exc); } } int numHits = this.deletedRecords.size(); int nextFrom = from + rows; String nextCursor = nextFrom < numHits ? buildCursor(nextFrom, this.getPartitionSize()) : null; MCROAISimpleResult result = new MCROAISimpleResult(); result.setNumHits(numHits); result.setNextCursor(nextCursor); int to = Math.min(nextFrom, numHits); for (int i = from; i < to; i++) { result.list().add(this.deletedRecords.get(i)); } return result; } @Override public MCROAIResult query(MCRSet set, Instant from, Instant until) { this.deletedRecords = this.searchDeleted(from, until); return this.query(null); } @Override public Optional<Instant> getEarliestTimestamp() { return MCRMetadataHistoryManager.getHistoryStart(); } public List<Header> getDeletedRecords() { return deletedRecords; } /** * Builds the cursor in the form of <b>deleted_from_rows</b>. * * @param from where to start * @param rows how many rows * @return the cursor as string */ public String buildCursor(int from, int rows) { return CURSOR_PREFIX + CURSOR_DELIMETER + from + CURSOR_DELIMETER + rows; } /** * Returns a list with identifiers of the deleted objects within the given date boundary. * If the record policy indicates that there is no support for tracking deleted an empty * list is returned. * * @param from from date * @param until to date * * @return a list with identifiers of the deleted objects */ protected List<Header> searchDeleted(Instant from, Instant until) { DeletedRecordPolicy deletedRecordPolicy = this.identify.getDeletedRecordPolicy(); if (from == null || DeletedRecordPolicy.No.equals(deletedRecordPolicy) || DeletedRecordPolicy.Transient.equals(deletedRecordPolicy)) { return new ArrayList<>(); } LOGGER.info("Getting identifiers of deleted items"); Map<MCRObjectID, Instant> deletedItems = MCRMetadataHistoryManager.getDeletedItems(from, Optional.ofNullable(until)); List<String> types = MCRConfiguration2.getString(getConfigPrefix() + "DeletedRecordTypes") .stream() .flatMap(MCRConfiguration2::splitValue) .collect(Collectors.toList()); if (types.isEmpty()) { return deletedItems.entrySet().stream() .map(this::toHeader) .collect(Collectors.toList()); } return deletedItems.entrySet().stream() .filter(e -> types.contains(e.getKey().getTypeId())) .map(this::toHeader) .collect(Collectors.toList()); } private Header toHeader(Entry<MCRObjectID, Instant> p) { return new Header(getObjectManager().getOAIId(p.getKey().toString()), p.getValue(), Status.deleted); } }
5,458
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationAndSetMapper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/classmapping/MCRClassificationAndSetMapper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.classmapping; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; /** * This class maps MyCoRe classification names to set names and vice versa * in OAI implementation. * * The mapping itself is stored in properties * e.g. MCR.OAIDataProvider.OAI2.MapSetToClassification.doc-type=diniPublType * * @author Robert Stephan * */ public class MCRClassificationAndSetMapper { private static final String PROP_CLASS_SUFFIX = ".Classification"; private static final String PROP_SETS_PREFIX = "Sets."; private static String PROP_SUFFIX = "MapSetToClassification."; /** * maps a classification name to an OAI set name * @param prefix - the properties prefix of the OAIAdapter * @param classid - the classification name */ public static String mapClassificationToSet(String prefix, String classid) { String propPrefix = prefix + PROP_SETS_PREFIX; return MCRConfiguration2.getPropertiesMap() .entrySet() .stream() .filter(p -> p.getKey().startsWith(propPrefix)) .filter(e -> e.getKey().endsWith(PROP_CLASS_SUFFIX)) .filter(e -> e.getValue().equals(classid)) .findFirst() .map(Map.Entry::getKey) .map(key -> key.substring(propPrefix.length(), key.length() - PROP_CLASS_SUFFIX.length())) .orElseGet(() -> getSetNameFromDeprecatedProperty(prefix, classid)); } private static String getSetNameFromDeprecatedProperty(String prefix, String classid) { return MCRConfiguration2.getPropertiesMap() .entrySet() .stream() .filter(p -> p.getKey().startsWith(prefix + PROP_SUFFIX)) .filter(entry -> entry.getValue().equals(classid)) .peek(e -> LogManager.getLogger() .warn("Please rename deprecated property '{}' and use '{}' suffix.", e.getKey(), PROP_CLASS_SUFFIX)) .findFirst() .map(Map.Entry::getKey) .map(key -> key.substring(key.lastIndexOf(".") + 1)) .orElse(classid); } /** * maps an OAI set name to a classification name * @param prefix - the property prefix for the OAIAdapter * @param setid - the set name */ public static String mapSetToClassification(String prefix, String setid) { String classProperty = prefix + PROP_SETS_PREFIX + setid + PROP_CLASS_SUFFIX; try { return MCRConfiguration2.getStringOrThrow(classProperty); } catch (MCRConfigurationException mce) { try { String legacyProperty = prefix + PROP_SUFFIX + setid; String legacy = MCRConfiguration2.getStringOrThrow(legacyProperty); LogManager.getLogger().warn("Please rename deprecated property '{}' to '{}'.", legacyProperty, classProperty); return legacy; } catch (MCRConfigurationException e) { // use the given value of setid return setid; } } } }
3,952
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRClassificationMappingEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/classmapping/MCRClassificationMappingEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.classmapping; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.output.XMLOutputter; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; 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.metadata.MCRMetaClassification; import org.mycore.datamodel.metadata.MCRMetaElement; import org.mycore.datamodel.metadata.MCRObject; /** * This class implements an event handler, which reloads classification entries * stored in datafield mappings/mapping. These entries are retrieved from other * classifications where they are stored in as labels with language "x-mapping". * * @author Robert Stephan * */ public class MCRClassificationMappingEventHandler extends MCREventHandlerBase { private static Logger LOGGER = LogManager.getLogger(MCRClassificationMappingEventHandler.class); private MCRMetaElement oldMappings = null; @Override protected void handleObjectCreated(MCREvent evt, MCRObject obj) { createMapping(obj); } @Override protected void handleObjectUpdated(MCREvent evt, MCRObject obj) { createMapping(obj); } @Override protected void handleObjectRepaired(MCREvent evt, MCRObject obj) { createMapping(obj); } @Override protected void undoObjectCreated(MCREvent evt, MCRObject obj) { undo(obj); } @Override protected void undoObjectUpdated(MCREvent evt, MCRObject obj) { undo(obj); } @Override protected void undoObjectRepaired(MCREvent evt, MCRObject obj) { undo(obj); } private void createMapping(MCRObject obj) { MCRMetaElement mappings = obj.getMetadata().getMetadataElement("mappings"); if (mappings != null) { oldMappings = mappings.clone(); obj.getMetadata().removeMetadataElement("mappings"); } Element currentClassElement = null; try { Document doc = new Document(obj.getMetadata().createXML().detach()); XPathExpression<Element> classElementPath = XPathFactory.instance().compile("//*[@categid]", Filters.element()); List<Element> classList = classElementPath.evaluate(doc); if (classList.size() > 0) { mappings = new MCRMetaElement(); mappings.setTag("mappings"); mappings.setClass(MCRMetaClassification.class); mappings.setHeritable(false); mappings.setNotInherit(true); obj.getMetadata().setMetadataElement(mappings); } MCRCategoryDAO dao = MCRCategoryDAOFactory.getInstance(); for (Element classElement : classList) { currentClassElement = classElement; MCRCategory categ = dao.getCategory(new MCRCategoryID(classElement.getAttributeValue("classid"), classElement.getAttributeValue("categid")), 0); addMappings(mappings, categ); } } catch (Exception je) { if (currentClassElement == null) { LOGGER.error("Error while finding classification elements", je); } else { LOGGER.error("Error while finding classification elements for {}", new XMLOutputter().outputString(currentClassElement), je); } } finally { if (mappings == null || mappings.size() == 0) { obj.getMetadata().removeMetadataElement("mappings"); } } } private void addMappings(MCRMetaElement mappings, MCRCategory categ) { if (categ != null) { categ.getLabel("x-mapping").ifPresent(label -> { String[] str = label.getText().split("\\s"); for (String s : str) { if (s.contains(":")) { String[] mapClass = s.split(":"); MCRMetaClassification metaClass = new MCRMetaClassification("mapping", 0, null, mapClass[0], mapClass[1]); mappings.addMetaObject(metaClass); } } }); } } private void undo(MCRObject obj) { if (oldMappings == null) { obj.getMetadata().removeMetadataElement("mappings"); } else { MCRMetaElement mmap = obj.getMetadata().getMetadataElement("mappings"); for (int i = 0; i < oldMappings.size(); i++) { mmap.addMetaObject(oldMappings.getElement(i)); } } } }
5,783
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIParameterQuerySetResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAIParameterQuerySetResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.solr.common.SolrDocument; import org.mycore.oai.pmh.Set; /** * If <code>{OAIPrefix}.Sets.{SetID}.Query</code> is in form <code>{searchField}':{setSpec}', uses {searchField} * to map from SOLR result document to OAI set. * @author Thomas Scheffler (yagee) */ class MCROAIParameterQuerySetResolver extends MCROAISetResolver<String, SolrDocument> { private String queryField; private Map<String, SolrDocument> resultMap; MCROAIParameterQuerySetResolver(String queryField) { super(); this.queryField = queryField; } @Override public void init(String configPrefix, String setId, Map<String, MCRSet> setMap, Collection<SolrDocument> result, Function<SolrDocument, String> identifier) { super.init(configPrefix, setId, setMap, result, identifier); resultMap = getResult().stream().collect(Collectors.toMap(getIdentifier(), d -> d)); } @Override public Collection<Set> getSets(String key) { return Optional.ofNullable(resultMap.get(key) .getFieldValues(queryField)) .orElseGet(Collections::emptySet) .stream() .map(getSetMap()::get) .collect(Collectors.toSet()); } }
2,173
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCRSet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import org.mycore.oai.pmh.Set; public class MCRSet extends Set { private String setId; public MCRSet(String setId, String spec, String name) { super(spec, name); this.setId = setId; } public MCRSet(String setId, String spec) { this(setId, spec, null); } public String getSetId() { return setId; } }
1,119
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISetConfiguration.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISetConfiguration.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; public interface MCROAISetConfiguration<Q, R, K> { String getId(); String getURI(); MCROAISetHandler<Q, R, K> getHandler(); }
898
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISetResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISetResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.mycore.oai.pmh.Set; /** * @author Thomas Scheffler (yagee) * */ public class MCROAISetResolver<K, T> { private String configPrefix; private String setId; private Collection<T> result; private Function<T, K> identifier; private Map<String, MCRSet> setMap; /** * Initializes the set handler with the configPrefix * (MCR.OAIDataProvider.MY_PROVIDER) and a setId * (MCR.OAIDataProvider.MY_PROVIDER.Sets.SET_ID). * * @param configPrefix the config prefix * @param setId the set id without any prefix */ public void init(String configPrefix, String setId, Map<String, MCRSet> setMap, Collection<T> result, Function<T, K> identifier) { LogManager.getLogger("init: " + setId); this.configPrefix = configPrefix; this.setId = setId; this.setMap = setMap; this.result = result; this.identifier = identifier; } /** Returns a collection of Sets for the current SetSpec. * * @param key is the key of the result * @return this implementation returns empty set, should be overwritten */ public Collection<Set> getSets(K key) { return Collections.emptySet(); } protected String getConfigPrefix() { return configPrefix; } protected String getSetId() { return setId; } protected Collection<T> getResult() { return result; } protected Function<T, K> getIdentifier() { return identifier; } protected Map<String, MCRSet> getSetMap() { return setMap; } }
2,522
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISetHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISetHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Map; /** * Base interface to handle mycore oai sets. * * @author Matthias Eichner * * @param <Q> set type * @param <R> Result collection type * @param <K> Result collection key type */ public interface MCROAISetHandler<Q, R, K> { /** * Initializes the set handler with the configPrefix * (MCR.OAIDataProvider.MY_PROVIDER) and a setId * (MCR.OAIDataProvider.MY_PROVIDER.Sets.SET_ID). * * @param configPrefix the config prefix * @param setId the set id without any prefix */ void init(String configPrefix, String setId); /** * Called before {@link #apply(MCRSet, Object)} to check if the * given set should be added to the ListSets view. * * @return false if the given set should be added (the * set is not filtered) */ default boolean filter(MCRSet set) { return false; } Map<String, MCRSet> getSetMap(); void apply(MCRSet set, Q q); MCROAISetResolver<K, R> getSetResolver(Collection<R> result); }
1,829
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISolrSetConfiguration.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISolrSetConfiguration.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import org.apache.logging.log4j.LogManager; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrDocument; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; /** * Default implementation for a set configuration. Loads the information from the * {@link MCRConfiguration2} (MCR.OAIDataProvider.myprovider.Sets.<b>SET_ID</b>). * * @author Matthias Eichner */ public class MCROAISolrSetConfiguration implements MCROAISetConfiguration<SolrQuery, SolrDocument, String> { private static final String SETS_PREFIX = "Sets."; private String id; private String uri; private MCROAISetHandler<SolrQuery, SolrDocument, String> handler; public MCROAISolrSetConfiguration(String configPrefix, String setId) { String setConfigPrefix = configPrefix + SETS_PREFIX + setId; String defaultname = getFallbackHandler(configPrefix, setId); MCROAISetHandler<SolrQuery, SolrDocument, String> handler = defaultname == null ? MCRConfiguration2.getOrThrow(setConfigPrefix + ".Handler", MCRConfiguration2::instantiateClass) : MCRConfiguration2.<MCROAISetHandler<SolrQuery, SolrDocument, String>>getInstanceOf( setConfigPrefix + ".Handler") .orElseGet(() -> MCRConfiguration2.instantiateClass(defaultname)); handler.init(configPrefix, setId); this.id = setId; this.uri = getURI(setConfigPrefix); this.handler = handler; } private String getURI(String setConfigPrefix) { String uriProperty = setConfigPrefix + ".URI"; try { return MCRConfiguration2.getStringOrThrow(uriProperty); } catch (MCRConfigurationException e) { String legacy = MCRConfiguration2.getString(setConfigPrefix).orElseThrow(() -> e); LogManager.getLogger().warn("Please rename deprecated property '{}' to '{}'.", setConfigPrefix, uriProperty); return legacy; } } private String getFallbackHandler(String configPrefix, String setId) { String queryProperty = configPrefix + SETS_PREFIX + setId + ".Query"; if (MCRConfiguration2.getString(queryProperty) .orElse(MCRConfiguration2.getString(configPrefix + "MapSetToQuery." + setId).orElse(null)) != null) { return MCROAIQueryToSetHandler.class.getName(); } String classProperty = configPrefix + SETS_PREFIX + setId + ".Classification"; if (MCRConfiguration2.getString(classProperty) .orElse(MCRConfiguration2.getString(configPrefix + "MapSetToClassification." + setId) .orElse(null)) != null) { return MCROAIClassificationToSetHandler.class.getName(); } if (MCRConfiguration2.getString(configPrefix + SETS_PREFIX + setId + ".Handler").orElse(null) == null) { LogManager.getLogger().error( "Neither '{}' nor '{}' is defined. Please map set '{}' to classification or query.", classProperty, queryProperty, setId); return MCROAIClassificationToSetHandler.class.getName(); } return null; } @Override public String getId() { return this.id; } @Override public String getURI() { return this.uri; } @Override public MCROAISetHandler<SolrQuery, SolrDocument, String> getHandler() { return this.handler; } }
4,255
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIClassificationToSetHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAIClassificationToSetHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Collections; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.mycore.common.config.MCRConfiguration2; import org.mycore.oai.MCROAIUtils; import org.mycore.oai.classmapping.MCRClassificationAndSetMapper; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrUtils; /** * Classification set handler. * * @author Matthias Eichner */ public class MCROAIClassificationToSetHandler extends MCROAISolrSetHandler { protected static final Logger LOGGER = LogManager.getLogger(MCROAIClassificationToSetHandler.class); private String classField; @Override public void init(String configPrefix, String handlerPrefix) { super.init(configPrefix, handlerPrefix); classField = MCRConfiguration2.getString(getConfigPrefix() + "SetSolrField").orElse("category.top"); } public void apply(MCRSet set, SolrQuery query) { String setSpec = set.getSpec(); String classid = MCRClassificationAndSetMapper.mapSetToClassification(getConfigPrefix(), set.getSetId()); //Check: Is it possible for setSpec to NOT contain ":" here? String value = setSpec.contains(":") ? setSpec.substring(setSpec.indexOf(":")) : ":*"; String setFilter = classField + ":" + MCRSolrUtils.escapeSearchValue(classid + value); query.add(CommonParams.FQ, setFilter); } @Override public boolean filter(MCRSet set) { if (!filterEmptySets()) { return false; } SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); ModifiableSolrParams p = new ModifiableSolrParams(); String value = set.getSpec(); p.set(CommonParams.Q, MCROAIUtils.getDefaultSetQuery(value, getConfigPrefix())); String restriction = MCROAIUtils.getDefaultRestriction(getConfigPrefix()); if (restriction != null) { p.set(CommonParams.FQ, restriction); } p.set(CommonParams.ROWS, 1); p.set(CommonParams.FL, "id"); try { QueryResponse response = solrClient.query(p); return response.getResults().isEmpty(); } catch (Exception exc) { LOGGER.error("Unable to get results of solr server", exc); return true; } } @Override public Collection<String> getFieldNames() { if (classField == null) { return super.getFieldNames(); } return Collections.singleton(classField); } private boolean filterEmptySets() { return MCRConfiguration2.getBoolean(getConfigPrefix() + "FilterEmptySets").orElse(true); } @Override public MCROAISetResolver<String, SolrDocument> getSetResolver(Collection<SolrDocument> result) { MCROAIClassificationSetResolver resolver = new MCROAIClassificationSetResolver(); resolver.init(getConfigPrefix(), getHandlerPrefix(), getSetMap(), result, MCROAISolrSetHandler::getIdentifier); return resolver; } }
4,113
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIClassificationSetResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAIClassificationSetResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.solr.common.SolrDocument; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.oai.classmapping.MCRClassificationAndSetMapper; import org.mycore.oai.pmh.Set; /** * Uses <code>{OAIPrefix}.Sets.{SetID}.SetSolrField</code> (defaults to 'category.top') property to map * from SOLR field of the result document to the OAI set * @author Thomas Scheffler (yagee) * @see MCRClassificationAndSetMapper */ class MCROAIClassificationSetResolver extends MCROAISetResolver<String, SolrDocument> { Map<String, SolrDocument> setMap; private String classField; private String classPrefix; @Override public void init(String configPrefix, String setId, Map<String, MCRSet> setMap, Collection<SolrDocument> result, Function<SolrDocument, String> identifier) { super.init(configPrefix, setId, setMap, result, identifier); this.setMap = result.stream().collect(Collectors.toMap(getIdentifier(), d -> d)); String classId = MCRClassificationAndSetMapper.mapSetToClassification(configPrefix, setId); classField = MCRConfiguration2.getString(getConfigPrefix() + "Sets." + setId + "SetSolrField") .orElse("category.top"); classPrefix = classId + ":"; } @Override public Collection<Set> getSets(String key) { SolrDocument solrDocument = setMap.get(key); if (solrDocument == null) { throw new MCRException("Unknown key: " + key); } return Optional.ofNullable(solrDocument.getFieldValues(classField)) .orElseGet(Collections::emptySet) .stream() .map(String.class::cast) .filter(s -> s.startsWith(classPrefix)) .map(s -> s.substring(classPrefix.length())) .map(s -> getSetId() + ":" + s) .map(getSetMap()::get) .filter(Objects::nonNull) .collect(Collectors.toSet()); } }
2,939
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIQuerySetResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAIQuerySetResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.oai.pmh.Set; import org.mycore.solr.MCRSolrClientFactory; import org.mycore.solr.MCRSolrUtils; /** * Fires <code>{OAIPrefix}.Sets.{SetID}.Query</code> and limits results to the <code>id</code>s of the * current result list. Every returned <code>id</code> belong to this OAI set configuration. * @author Thomas Scheffler (yagee) */ class MCROAIQuerySetResolver extends MCROAISetResolver<String, SolrDocument> { private String query; private java.util.Set<String> idsInSet; MCROAIQuerySetResolver(String query) { super(); this.query = query; } @Override public void init(String configPrefix, String setId, Map<String, MCRSet> setMap, Collection<SolrDocument> result, Function<SolrDocument, String> identifier) { super.init(configPrefix, setId, setMap, result, identifier); if (result.isEmpty()) { idsInSet = Collections.emptySet(); return; } SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient(); QueryResponse response; try { response = solrClient.query(getQuery()); } catch (SolrServerException | IOException e) { throw new MCRException("Error while getting set membership.", e); } idsInSet = response.getResults().stream().map(getIdentifier()).collect(Collectors.toSet()); } @Override public Collection<Set> getSets(String key) { if (idsInSet.contains(key)) { return Collections.singleton(getSetMap().get(getSetId())); } return Collections.emptySet(); } private SolrQuery getQuery() { SolrQuery solrQuery = new SolrQuery(); // query String idQuery = getResult().stream() .map(getIdentifier()) .map(MCRSolrUtils::escapeSearchValue) .collect(Collectors.joining(" OR ", "id:(", ")")); solrQuery.setQuery(idQuery); solrQuery.setFilterQueries(query); solrQuery.setFields("id"); solrQuery.setRows(getResult().size()); // request handler solrQuery.setRequestHandler( MCRConfiguration2.getString(getConfigPrefix() + "Search.RequestHandler").orElse("/select")); return solrQuery; } }
3,557
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAISolrSetHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAISolrSetHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrDocument; public abstract class MCROAISolrSetHandler implements MCROAISetHandler<SolrQuery, SolrDocument, String> { private String configPrefix; private String handlerPrefix; private HashMap<String, MCRSet> setMap; @Override public void init(String configPrefix, String handlerPrefix) { this.configPrefix = configPrefix; this.handlerPrefix = handlerPrefix; this.setMap = new HashMap<>(); } public String getConfigPrefix() { return configPrefix; } public String getHandlerPrefix() { return handlerPrefix; } public Collection<String> getFieldNames() { return Collections.emptySet(); } public MCROAISetResolver<String, SolrDocument> getSetResolver(Collection<SolrDocument> result) { MCROAISetResolver<String, SolrDocument> resolver = new MCROAISetResolver<>(); resolver.init(configPrefix, handlerPrefix, getSetMap(), result, MCROAISolrSetHandler::getIdentifier); return resolver; } protected static String getIdentifier(SolrDocument doc) { return doc.getFieldValue("id").toString(); } @Override public Map<String, MCRSet> getSetMap() { return setMap; } }
2,173
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCROAIQueryToSetHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-oai/src/main/java/org/mycore/oai/set/MCROAIQueryToSetHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.oai.set; import java.util.Collection; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.params.CommonParams; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; public class MCROAIQueryToSetHandler extends MCROAISolrSetHandler { private static Pattern SIMPLE_PARAMETER_QUERY = Pattern.compile("^(?<field>[^:]+):\\{setSpec\\}$"); private static final String SET_SPEC_PARAMETER = "{setSpec}"; String searchField; String configQuery; @Override public void init(String configPrefix, String setId) { super.init(configPrefix, setId); configQuery = getSetFilterQuery(setId); if (configQuery.contains(SET_SPEC_PARAMETER)) { this.searchField = getSearchField(configQuery); } else { this.searchField = null; } } private String getSearchField(String simpleQuery) { Matcher fieldMatcher = SIMPLE_PARAMETER_QUERY.matcher(simpleQuery); if (fieldMatcher.matches()) { return fieldMatcher.group("field"); } throw new MCRConfigurationException( "Queries containing '" + SET_SPEC_PARAMETER + "' must be in simple form: fielName:{setSpec}"); } @Override public Collection<String> getFieldNames() { if (searchField == null) { return super.getFieldNames(); } return Collections.singleton(searchField); } @Override public void apply(MCRSet set, SolrQuery solrQuery) { String resolvedQuery = configQuery.replace(SET_SPEC_PARAMETER, set.getSpec()); solrQuery.add(CommonParams.FQ, resolvedQuery); } private String getSetFilterQuery(String setId) { String queryProperty = getConfigPrefix() + "Sets." + setId + ".Query"; String configQuery; try { configQuery = MCRConfiguration2.getStringOrThrow(queryProperty); } catch (MCRConfigurationException e) { String deprecatedProperty = getConfigPrefix() + "MapSetToQuery." + setId; configQuery = MCRConfiguration2.getString(deprecatedProperty).orElse(null); if (configQuery == null) { throw e; } LogManager.getLogger().warn( "Property '{}' is deprecated and support will be removed. Please rename to '{}' soon!", deprecatedProperty, queryProperty); } return configQuery; } @Override public MCROAISetResolver<String, SolrDocument> getSetResolver(Collection<SolrDocument> result) { if (searchField == null) { MCROAIQuerySetResolver resolver = new MCROAIQuerySetResolver(configQuery); resolver.init(getConfigPrefix(), getHandlerPrefix(), getSetMap(), result, MCROAISolrSetHandler::getIdentifier); return resolver; } MCROAIParameterQuerySetResolver resolver = new MCROAIParameterQuerySetResolver(searchField); resolver.init(getConfigPrefix(), getHandlerPrefix(), getSetMap(), result, MCROAISolrSetHandler::getIdentifier); return resolver; } }
4,094
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXEditorTransformerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/MCRXEditorTransformerTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.xml.transform.TransformerException; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.JDOMException; import org.junit.Test; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTestCase; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRSourceContent; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.frontend.MCRFrontendUtil; import org.xml.sax.SAXException; /** * @author Frank Lützenkirchen */ public class MCRXEditorTransformerTest extends MCRTestCase { private MCREditorSession buildEditorSession(String editedXMLFile) { HashMap<String, String[]> parameters = new HashMap<>(); if (editedXMLFile != null) { parameters.put("input", new String[] { editedXMLFile }); } MCRParameterCollector collector = new MCRParameterCollector(false); collector.setParameter("input", editedXMLFile); MCREditorSession editorSession = new MCREditorSession(parameters, collector); editorSession.setID("1"); return editorSession; } private MCREditorSession testTransformation(String inputFile, String editedXMLFile, String expectedOutputFile) throws TransformerException, IOException, JDOMException, SAXException, JaxenException { MCREditorSession editorSession = buildEditorSession(editedXMLFile); testTransformation(inputFile, editedXMLFile, editorSession, expectedOutputFile); return editorSession; } private void testTransformation(String inputFile, String editedXMLFile, MCREditorSession session, String expectedOutputFile) throws TransformerException, IOException, JDOMException, SAXException, JaxenException { MCRParameterCollector pc = new MCRParameterCollector(false); if (editedXMLFile != null) { pc.setParameter("input", editedXMLFile); } MCRContent input = MCRSourceContent.getInstance("resource:" + inputFile); MCRContent transformed = new MCRXEditorTransformer(session, pc).transform(input); Document expected = MCRSourceContent.getInstance("resource:" + expectedOutputFile).asXML(); MCRBinding binding = new MCRBinding("//input[@type='hidden'][@name='_xed_session']/@value", true, new MCRBinding(expected)); binding.setValue(session.getID() + "-" + session.getChangeTracker().getChangeCounter()); binding = new MCRBinding("//form/@action", true, new MCRBinding(expected)); binding.setValue(MCRFrontendUtil.getBaseURL() + "servlets/XEditor"); String msg = "Transformed output is different to " + expectedOutputFile; boolean isEqual = MCRXMLHelper.deepEqual(expected, transformed.asXML()); if (!isEqual) { System.out.println("---------- expected: ----------"); System.out.println(new MCRJDOMContent(expected).asString()); System.out.println("---------- transformed: ----------"); System.out.println(transformed.asString()); } assertTrue(msg, isEqual); } @Test public void testBasicInputComponents() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { testTransformation("testBasicInputComponents-editor.xml", null, "testBasicInputComponents-transformed1.xml"); testTransformation("testBasicInputComponents-editor.xml", "testBasicInputComponents-source.xml", "testBasicInputComponents-transformed2.xml"); } @Test public void testIncludes() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { testTransformation("testIncludes-editor.xml", null, "testIncludes-transformed.xml"); } @Test public void testPreload() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { testTransformation("testPreload-editor.xml", null, "testPreload-transformed.xml"); } @Test public void testRepeats() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { testTransformation("testRepeats-editor.xml", "testBasicInputComponents-source.xml", "testRepeats-transformed.xml"); } @Test public void testXPathSubstitution() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { MCRSessionMgr.getCurrentSession().put("SomeUser", "John Doe"); testTransformation("testXPathSubstitution-editor.xml", "testBasicInputComponents-source.xml", "testXPathSubstitution-transformed.xml"); } @Test public void testNamespaces() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { testTransformation("testNamespaces-editor.xml", "testNamespaces-source.xml", "testNamespaces-transformed.xml"); } @Test public void testConditions() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { MCRSessionMgr.getCurrentSession().put("switch", "on"); MCRSessionMgr.getCurrentSession().put("case", "2"); testTransformation("testConditions-editor.xml", "testBasicInputComponents-source.xml", "testConditions-transformed.xml"); } @Test public void testI18N() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { MCRSessionMgr.getCurrentSession().setCurrentLanguage("en"); testTransformation("testI18N-editor.xml", "testBasicInputComponents-source.xml", "testI18N-transformed-en.xml"); MCRSessionMgr.getCurrentSession().setCurrentLanguage("de"); testTransformation("testI18N-editor.xml", "testBasicInputComponents-source.xml", "testI18N-transformed-de.xml"); } @Test public void testLoadResources() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { MCRSessionMgr.getCurrentSession().put("genre", "article"); MCRSessionMgr.getCurrentSession().put("host", "journal"); testTransformation("testLoadResources-editor.xml", null, "testLoadResources-transformed.xml"); } @Test public void testValidation() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { MCREditorSession session = testTransformation("testValidation-editor.xml", "testBasicInputComponents-source.xml", "testValidation-transformed1.xml"); assertTrue(session.getValidator().isValid()); session = testTransformation("testValidation-editor.xml", null, "testValidation-transformed2.xml"); assertFalse(session.getValidator().isValid()); testTransformation("testValidation-editor.xml", null, session, "testValidation-transformed3.xml"); } @Test public void testDefaultValue() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { MCREditorSession session = testTransformation("testDefaultValue-editor.xml", null, "testDefaultValue-transformed1.xml"); assertEquals("true", session.getEditedXML().getRootElement().getAttributeValue("publish")); session = testTransformation("testDefaultValue-editor.xml", "testDefaultValue-input.xml", "testDefaultValue-transformed2.xml"); assertEquals("false", session.getEditedXML().getRootElement().getAttributeValue("publish")); } @Test public void testSelect() throws IOException, TransformerException, JDOMException, SAXException, JaxenException { testTransformation("testSelect-editor.xml", "testSelect-source.xml", "testSelect-transformed.xml"); } @Override protected Map<String, String> getTestProperties() { final Map<String, String> properties = super.getTestProperties(); properties.put("MCR.URIResolver.CachingResolver.Capacity", "100"); properties.put("MCR.URIResolver.CachingResolver.MaxAge", "3600000"); return properties; } }
9,185
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXMLCleanerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/MCRXMLCleanerTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import static org.junit.Assert.assertTrue; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.JDOMException; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRXMLHelper; /** * @author Frank Lützenkirchen */ public class MCRXMLCleanerTest extends MCRTestCase { @Test public void testUnmodified() throws JDOMException, JaxenException { String xPath1 = "mods:mods[mods:name[@type='personal'][mods:namePart[@type='family']='Musterfrau']]"; cleanAndCompareTo(xPath1, xPath1); String xPath2 = "mods:mods[mods:name[@type='personal']" + "[mods:namePart[@type='family']='Musterfrau'][mods:namePart[@type='given']]]"; cleanAndCompareTo(xPath2, xPath2); } @Test public void testRemoveEmptyNodes() throws JDOMException, JaxenException { String xPath1i = "root[child]"; String xPath1o = "root"; cleanAndCompareTo(xPath1i, xPath1o); String xPath2i = "root[child='a']"; cleanAndCompareTo(xPath2i, xPath2i); String xPath3i = "root[child[@foo='bar']]"; cleanAndCompareTo(xPath3i, xPath3i); String xPath7i = "mods:mods[mods:name[@type='personal']" + "[mods:namePart[@type='family']='Musterfrau'][mods:namePart]]"; String xPath7o = "mods:mods[mods:name[@type='personal'][mods:namePart[@type='family']='Musterfrau']]"; cleanAndCompareTo(xPath7i, xPath7o); String xPath8i = "mods:mods[mods:name[@type='personal']" + "[mods:namePart[@type='family']='Musterfrau'][mods:role/mods:roleTerm[@type]]]"; String xPath8o = "mods:mods[mods:name[@type='personal'][mods:namePart[@type='family']='Musterfrau']]"; cleanAndCompareTo(xPath8i, xPath8o); } @Test public void testRootAlwaysRemains() throws JDOMException, JaxenException { String xPath5i = "mods:mods[mods:name[@type][mods:namePart[@type]][mods:namePart]]"; String xPath5o = "mods:mods"; cleanAndCompareTo(xPath5i, xPath5o); } @Test public void testPreserveStructureAndService() throws JDOMException, JaxenException { String xPathInput = "mycoreobject[structure][metadata/field.title/title][service]"; String xPathExpected = "mycoreobject[structure][service]"; cleanAndCompareTo(xPathInput, xPathExpected); } @Test public void testOverwriteDefaultRules() throws JDOMException, JaxenException { String xPath2i = "mods:mods[mods:name[@type='personal'][mods:namePart[@type='family']='Musterfrau'][mods:namePart[@type='given']][mods:relatedItem/@xlink:href='test']]"; String xPath2o = "mods:mods[mods:name[@type='personal'][mods:namePart[@type='family']='Musterfrau'][mods:relatedItem/@xlink:href='test']]"; MCRCleaningRule removeElementsWithoutChildrenOrText = new MCRCleaningRule("//*", "* or (string-length(text()) > 0)"); MCRCleaningRule keepRelatedItemWithReference = new MCRCleaningRule("//mods:relatedItem", "* or string-length(@xlink:href > 0)"); cleanAndCompareTo(xPath2i, xPath2o, removeElementsWithoutChildrenOrText, keepRelatedItemWithReference); } private void cleanAndCompareTo(String xPathInput, String xPathExpectedOutput, MCRCleaningRule... rules) throws JaxenException { Document xmlToClean = buildTestDocument(xPathInput); Document expectedXML = buildTestDocument(xPathExpectedOutput); MCRXMLCleaner cleaner = new MCRXMLCleaner(); for (MCRCleaningRule rule : rules) { cleaner.addRule(rule); } Document result = cleaner.clean(xmlToClean); assertTrue(MCRXMLHelper.deepEqual(expectedXML, result)); } private Document buildTestDocument(String xPath) throws JaxenException { return new Document(new MCRNodeBuilder().buildElement(xPath, null, null)); } }
4,758
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREditorSubmissionTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/MCREditorSubmissionTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.frontend.xeditor.tracker.MCRChangeTracker; /** * @author Frank Lützenkirchen */ public class MCREditorSubmissionTest extends MCRTestCase { @Test public void testSubmitTextfields() throws JaxenException, JDOMException { String template = "document[title='Titel'][author[@firstName='John'][@lastName='Doe']]"; MCREditorSession session = new MCREditorSession(); session.setEditedXML(new Document(new MCRNodeBuilder().buildElement(template, null, null))); Map<String, String[]> submittedValues = new HashMap<>(); submittedValues.put("/document/title[1]", new String[] { "Title" }); submittedValues.put("/document/author[1]/@firstName", new String[] { "Jim" }); submittedValues.put("/document/author[1]/@lastName", new String[] { "" }); session.getSubmission().setSubmittedValues(submittedValues); session.getSubmission().emptyNotResubmittedNodes(); template = "document[title='Title'][author[@firstName='Jim'][@lastName='']]"; Document expected = new Document(new MCRNodeBuilder().buildElement(template, null, null)); Document result = session.getEditedXML(); result = MCRChangeTracker.removeChangeTracking(result); assertTrue(MCRXMLHelper.deepEqual(expected, result)); } @Test public void testSubmitSingleCheckbox() throws JaxenException, JDOMException { String template = "document[@archive='false']"; MCREditorSession session = new MCREditorSession(); session.setEditedXML(new Document(new MCRNodeBuilder().buildElement(template, null, null))); session.getSubmission().setXPaths2CheckResubmission("@archive"); session.getSubmission().emptyNotResubmittedNodes(); assertEquals("", session.getEditedXML().getRootElement().getAttributeValue("archive")); session.getSubmission().setXPaths2CheckResubmission("@archive"); Map<String, String[]> submittedValues = new HashMap<>(); submittedValues.put("/document/@archive", new String[] { "true" }); session.getSubmission().setSubmittedValues(submittedValues); session.getSubmission().emptyNotResubmittedNodes(); assertEquals("true", session.getEditedXML().getRootElement().getAttributeValue("archive")); } @Test public void testSubmitSelectSingleOption() throws JaxenException, JDOMException { String template = "document[category='a']"; MCREditorSession session = new MCREditorSession(); session.setEditedXML(new Document(new MCRNodeBuilder().buildElement(template, null, null))); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[1]", true, session.getRootBinding())); session.getSubmission().emptyNotResubmittedNodes(); List<Element> categories = session.getEditedXML().getRootElement().getChildren("category"); assertEquals(1, categories.size()); assertEquals("", categories.get(0).getText()); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[1]", true, session.getRootBinding())); Map<String, String[]> submittedValues = new HashMap<>(); submittedValues.put("/document/category[1]", new String[] { "b" }); session.getSubmission().setSubmittedValues(submittedValues); session.getSubmission().emptyNotResubmittedNodes(); categories = session.getEditedXML().getRootElement().getChildren("category"); assertEquals(1, categories.size()); assertEquals("b", categories.get(0).getText()); } @Test public void testSubmitSelectMultipleOptions() throws JaxenException, JDOMException { String template = "document[category[1]='a'][category[2]='b'][category[3]='c']"; MCREditorSession session = new MCREditorSession(); session.setEditedXML(new Document(new MCRNodeBuilder().buildElement(template, null, null))); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[1]", true, session.getRootBinding())); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[2]", true, session.getRootBinding())); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[3]", true, session.getRootBinding())); session.getSubmission().emptyNotResubmittedNodes(); List<Element> categories = session.getEditedXML().getRootElement().getChildren("category"); assertEquals(3, categories.size()); assertEquals("", categories.get(0).getText()); assertEquals("", categories.get(1).getText()); assertEquals("", categories.get(2).getText()); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[1]", true, session.getRootBinding())); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[2]", true, session.getRootBinding())); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[3]", true, session.getRootBinding())); Map<String, String[]> submittedValues = new HashMap<>(); submittedValues.put("/document/category", new String[] { "c", "d" }); session.getSubmission().setSubmittedValues(submittedValues); session.getSubmission().emptyNotResubmittedNodes(); categories = session.getEditedXML().getRootElement().getChildren("category"); assertEquals(3, categories.size()); assertEquals("c", categories.get(0).getText()); assertEquals("d", categories.get(1).getText()); assertEquals("", categories.get(2).getText()); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[1]", true, session.getRootBinding())); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[2]", true, session.getRootBinding())); session.getSubmission() .mark2checkResubmission(new MCRBinding("/document/category[3]", true, session.getRootBinding())); submittedValues.clear(); submittedValues.put("/document/category", new String[] { "a", "b", "c", "d" }); session.getSubmission().setSubmittedValues(submittedValues); session.getSubmission().emptyNotResubmittedNodes(); categories = session.getEditedXML().getRootElement().getChildren("category"); assertEquals(4, categories.size()); assertEquals("a", categories.get(0).getText()); assertEquals("b", categories.get(1).getText()); assertEquals("c", categories.get(2).getText()); assertEquals("d", categories.get(3).getText()); } }
8,027
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBindingTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/MCRBindingTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; /** * @author Frank Lützenkirchen */ public class MCRBindingTest extends MCRTestCase { private MCRBinding binding; @Before @Override public void setUp() throws Exception { super.setUp(); Element root = new Element("document"); root.addContent(new Element("title").setAttribute("type", "main").setText("title1")); root.addContent(new Element("title").setAttribute("type", "alternative").setText("title2")); Element author = new Element("author"); root.addContent(author); author.addContent(new Element("firstName").setText("John")); author.addContent(new Element("lastName").setText("Doe")); binding = new MCRBinding(new Document(root)); } @Test public void testSimpleBindings() throws JaxenException { binding = new MCRBinding("document", true, binding); binding = new MCRBinding("title", true, binding); assertEquals("title1", binding.getValue()); binding = binding.getParent(); binding = binding.getParent(); binding = new MCRBinding("document/title[2]", true, binding); assertEquals("title2", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("document/title[@type='main']", true, binding); assertEquals("title1", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("document/title[@type='alternative']", true, binding); assertEquals("title2", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("document/author", true, binding); binding = new MCRBinding("firstName", true, binding); assertEquals("John", binding.getValue()); binding = binding.getParent(); binding = binding.getParent(); } @Test public void testComplexBindings() throws JaxenException { binding = new MCRBinding("document/title[contains(text(),'1')]", true, binding); assertEquals("title1", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("//title[@type]", true, binding); assertEquals("title1", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("//title[not(@type='main')]", true, binding); assertEquals("title2", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("/document/title[../author/lastName='Doe'][2]", true, binding); assertEquals("title2", binding.getValue()); binding = binding.getParent(); binding = new MCRBinding("//*", true, binding); binding = new MCRBinding("*[name()='title'][2]", true, binding); assertEquals("title2", binding.getValue()); binding = binding.getParent(); binding = binding.getParent(); } @Test public void testHasValue() throws JaxenException { binding = new MCRBinding("document/title", true, binding); assertTrue(binding.hasValue("title1")); assertTrue(binding.hasValue("title2")); assertFalse(binding.hasValue("other")); binding = binding.getParent(); binding = new MCRBinding("document/author/*", true, binding); assertTrue(binding.hasValue("John")); assertTrue(binding.hasValue("Doe")); assertFalse(binding.hasValue("other")); } @Test public void testCollectorVariables() throws JaxenException { Map<String, Object> variables = new HashMap<>(); variables.put("type", "main"); binding = new MCRBinding("document", true, binding); binding.setVariables(variables); binding = new MCRBinding("title[@type=$type]", true, binding); assertTrue(binding.hasValue("title1")); assertEquals(1, binding.getBoundNodes().size()); } @Test public void testDefiningVariables() throws JaxenException { binding = new MCRBinding("document", true, binding); new MCRBinding("title[1]", null, "inheritMe", binding); new MCRBinding("title[2]", null, "overwriteMe", binding); assertEquals("title1", new MCRBinding("$inheritMe", true, binding).getValue()); assertEquals("title2", new MCRBinding("$overwriteMe", true, binding).getValue()); binding = new MCRBinding("author", true, binding); new MCRBinding("firstName", null, "overwriteMe", binding); assertEquals("title1", new MCRBinding("$inheritMe", true, binding).getValue()); assertEquals("John", new MCRBinding("$overwriteMe", true, binding).getValue()); } @Test public void testGroupByReferencedID() throws JaxenException { String builder = "document[name/@id='n1'][note/@href='#n1'][location/@href='#n1'][name[@id='n2']][location[@href='#n2']]"; Element document = new MCRNodeBuilder().buildElement(builder, null, null); MCRBinding rootBinding = new MCRBinding(new Document(document)); MCRBinding documentBinding = new MCRBinding("document", true, rootBinding); MCRBinding id = new MCRBinding("name[@id][1]/@id", null, "id", documentBinding); assertEquals("/document/name[1]/@id", id.getAbsoluteXPath()); assertEquals("n1", id.getValue()); binding = new MCRBinding("note[@href=concat('#',$id)]", true, documentBinding); Element note = (Element) (binding.getBoundNode()); assertEquals("note", note.getName()); assertEquals("#n1", note.getAttributeValue("href")); binding = new MCRBinding("location[@href=concat('#',$id)]", true, documentBinding); Element location = (Element) (binding.getBoundNode()); assertEquals("location", location.getName()); assertEquals("#n1", location.getAttributeValue("href")); id = new MCRBinding("name[@id][2]/@id", null, "id", documentBinding); assertEquals("/document/name[2]/@id", id.getAbsoluteXPath()); assertEquals("n2", id.getValue()); binding = new MCRBinding("note[@href=concat('#',$id)]", true, documentBinding); note = (Element) (binding.getBoundNode()); assertEquals("note", note.getName()); assertEquals("#n2", note.getAttributeValue("href")); binding = new MCRBinding("location[@href=concat('#',$id)]", true, documentBinding); location = (Element) (binding.getBoundNode()); assertEquals("location", location.getName()); assertEquals("#n2", location.getAttributeValue("href")); } }
7,686
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRepeatBindingTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/MCRRepeatBindingTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import static org.junit.Assert.assertEquals; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; /** * @author Frank Lützenkirchen */ public class MCRRepeatBindingTest extends MCRTestCase { @Test public void testRepeatBindingWithComplexPredicate() throws JaxenException, JDOMException { Element template = new MCRNodeBuilder() .buildElement("conditions[condition/@type='bingo'][condition[2]/@type='bongo']", null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRBinding conditions = new MCRBinding("conditions", true, root); MCRRepeatBinding repeat = new MCRRepeatBinding("condition[contains(' foo bar ',concat(' ',@type,' '))]", conditions, 3, 5, "build"); assertEquals(3, repeat.getBoundNodes().size()); MCRBinding binding = repeat.bindRepeatPosition(); assertEquals(1, binding.getBoundNodes().size()); assertEquals("/conditions/condition[3]", binding.getAbsoluteXPath()); ((Element) (binding.getBoundNode())).setAttribute("value", "a"); binding = repeat.bindRepeatPosition(); assertEquals(1, binding.getBoundNodes().size()); assertEquals("/conditions/condition[4]", binding.getAbsoluteXPath()); ((Element) (binding.getBoundNode())).setAttribute("value", "b"); binding = repeat.bindRepeatPosition(); assertEquals(1, binding.getBoundNodes().size()); assertEquals("/conditions/condition[5]", binding.getAbsoluteXPath()); ((Element) (binding.getBoundNode())).setAttribute("value", "c"); repeat.removeBoundNode(0); assertEquals(4, doc.getRootElement().getChildren().size()); assertEquals(2, repeat.getBoundNodes().size()); assertEquals("b", ((Element) (repeat.getBoundNodes().get(0))).getAttributeValue("value")); assertEquals("c", ((Element) (repeat.getBoundNodes().get(1))).getAttributeValue("value")); repeat.cloneBoundElement(0); assertEquals(5, doc.getRootElement().getChildren().size()); assertEquals(3, repeat.getBoundNodes().size()); assertEquals("b", ((Element) (repeat.getBoundNodes().get(0))).getAttributeValue("value")); assertEquals("b", ((Element) (repeat.getBoundNodes().get(1))).getAttributeValue("value")); assertEquals("c", ((Element) (repeat.getBoundNodes().get(2))).getAttributeValue("value")); } }
3,374
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRChangeTrackerTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/tracker/MCRChangeTrackerTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.jaxen.JaxenException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.junit.Test; import org.mycore.common.MCRConstants; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.frontend.xeditor.MCRBinding; public class MCRChangeTrackerTest extends MCRTestCase { @Test public void testAddElement() throws JaxenException { Document doc = new Document(new MCRNodeBuilder().buildElement("document[title][title[2]]", null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Element title = new Element("title"); doc.getRootElement().getChildren().add(1, title); assertEquals(3, doc.getRootElement().getChildren().size()); assertTrue(doc.getRootElement().getChildren().contains(title)); tracker.track(MCRAddedElement.added(title)); tracker.undoChanges(doc); assertEquals(2, doc.getRootElement().getChildren().size()); assertFalse(doc.getRootElement().getChildren().contains(title)); } @Test public void testRemoveElement() throws JaxenException { String template = "document[title][title[2][@type='main'][subTitle]][title[3]]"; Document doc = new Document(new MCRNodeBuilder().buildElement(template, null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Element title = doc.getRootElement().getChildren().get(1); tracker.track(MCRRemoveElement.remove(title)); assertEquals(2, doc.getRootElement().getChildren().size()); assertFalse(doc.getRootElement().getChildren().contains(title)); tracker.undoChanges(doc); assertEquals(3, doc.getRootElement().getChildren().size()); assertEquals("main", doc.getRootElement().getChildren().get(1).getAttributeValue("type")); assertNotNull(doc.getRootElement().getChildren().get(1).getChild("subTitle")); } @Test public void testAddAttribute() throws JaxenException { Document doc = new Document(new MCRNodeBuilder().buildElement("document[title]", null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Attribute id = new Attribute("id", "foo"); doc.getRootElement().setAttribute(id); tracker.track(MCRAddedAttribute.added(id)); tracker.undoChanges(doc); assertNull(doc.getRootElement().getAttribute("id")); } @Test public void testRemoveAttribute() throws JaxenException { Document doc = new Document(new MCRNodeBuilder().buildElement("document[@id='foo']", null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Attribute id = doc.getRootElement().getAttribute("id"); tracker.track(MCRRemoveAttribute.remove(id)); assertNull(doc.getRootElement().getAttribute("id")); tracker.undoChanges(doc); assertEquals("foo", doc.getRootElement().getAttributeValue("id")); } @Test public void testSetAttributeValue() throws JaxenException { Document doc = new Document(new MCRNodeBuilder().buildElement("document[@id='foo']", null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Attribute id = doc.getRootElement().getAttribute("id"); tracker.track(MCRSetAttributeValue.setValue(id, "bar")); assertEquals("bar", id.getValue()); tracker.undoChanges(doc); assertEquals("foo", doc.getRootElement().getAttributeValue("id")); } @Test public void testSetElementText() throws JaxenException { Document doc = new Document( new MCRNodeBuilder().buildElement("document[@id='foo'][titles/title][author]", null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); tracker.track(MCRSetElementText.setText(doc.getRootElement(), "text")); assertEquals("text", doc.getRootElement().getText()); assertEquals("foo", doc.getRootElement().getAttributeValue("id")); tracker.undoChanges(doc); assertEquals("foo", doc.getRootElement().getAttributeValue("id")); assertEquals(2, doc.getRootElement().getChildren().size()); assertEquals("titles", doc.getRootElement().getChildren().get(0).getName()); assertEquals("author", doc.getRootElement().getChildren().get(1).getName()); assertEquals("", doc.getRootElement().getText()); } @Test public void testCompleteUndo() throws JaxenException { String template = "document[titles[title][title[2]]][authors/author[first='John'][last='Doe']]"; Document doc = new Document(new MCRNodeBuilder().buildElement(template, null, null)); Document before = doc.clone(); MCRChangeTracker tracker = new MCRChangeTracker(); Element titles = (Element) (new MCRBinding("document/titles", true, new MCRBinding(doc)).getBoundNode()); Element title = new Element("title").setAttribute("type", "alternative"); titles.addContent(2, title); tracker.track(MCRAddedElement.added(title)); Attribute lang = new Attribute("lang", "de"); doc.getRootElement().setAttribute(lang); tracker.track(MCRAddedAttribute.added(lang)); Element author = (Element) (new MCRBinding("document/authors/author", true, new MCRBinding(doc)) .getBoundNode()); tracker.track(MCRRemoveElement.remove(author)); tracker.undoChanges(doc); assertTrue(MCRXMLHelper.deepEqual(before, doc)); } @Test public void testRemoveChangeTracking() throws JaxenException { String template = "document[titles[title][title[2]]][authors/author[first='John'][last='Doe']]"; Document doc = new Document(new MCRNodeBuilder().buildElement(template, null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Element titles = (Element) (new MCRBinding("document/titles", true, new MCRBinding(doc)).getBoundNode()); Element title = new Element("title").setAttribute("type", "alternative"); titles.addContent(2, title); tracker.track(MCRAddedElement.added(title)); Attribute lang = new Attribute("lang", "de"); doc.getRootElement().setAttribute(lang); tracker.track(MCRAddedAttribute.added(lang)); Element author = (Element) (new MCRBinding("document/authors/author", true, new MCRBinding(doc)) .getBoundNode()); tracker.track(MCRRemoveElement.remove(author)); doc = MCRChangeTracker.removeChangeTracking(doc); assertFalse(doc.getDescendants(Filters.processinginstruction()).iterator().hasNext()); } @Test public void testEscaping() { String pattern = "<?xed-foo ?>"; Document doc = new Document(new Element("document").addContent(new Element("child").setText(pattern))); MCRChangeTracker tracker = new MCRChangeTracker(); tracker.track(MCRRemoveElement.remove(doc.getRootElement().getChildren().get(0))); tracker.undoChanges(doc); assertEquals(pattern, doc.getRootElement().getChildren().get(0).getText()); } @Test public void testNestedChanges() { Element root = new Element("root"); Document doc = new Document(root); MCRChangeTracker tracker = new MCRChangeTracker(); Element title = new Element("title"); root.addContent(title); tracker.track(MCRAddedElement.added(title)); Attribute id = new Attribute("type", "main"); title.setAttribute(id); tracker.track(MCRAddedAttribute.added(id)); Element part = new Element("part"); title.addContent(part); tracker.track(MCRAddedElement.added(part)); tracker.track(MCRRemoveElement.remove(part)); tracker.track(MCRRemoveAttribute.remove(id)); tracker.track(MCRRemoveElement.remove(title)); tracker.undoChanges(doc); } @Test public void testNamespaces() { Element root = new Element("root"); Document doc = new Document(root); MCRChangeTracker tracker = new MCRChangeTracker(); Attribute href = new Attribute("href", "foo", MCRConstants.XLINK_NAMESPACE); root.setAttribute(href); tracker.track(MCRAddedAttribute.added(href)); tracker.track(MCRSetAttributeValue.setValue(href, "bar")); tracker.track(MCRRemoveAttribute.remove(href)); tracker.undoLastChange(doc); assertEquals("bar", root.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE)); tracker.undoChanges(doc); assertNull(root.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE)); Element title = new Element("title", MCRConstants.MODS_NAMESPACE).setText("foo"); root.addContent(title); tracker.track(MCRAddedElement.added(title)); tracker.track(MCRSetElementText.setText(title, "bar")); tracker.undoLastChange(doc); assertEquals("foo", root.getChild("title", MCRConstants.MODS_NAMESPACE).getText()); tracker.track(MCRRemoveElement.remove(title)); tracker.undoLastChange(doc); assertNotNull(root.getChild("title", MCRConstants.MODS_NAMESPACE)); } @Test public void testBreakpoint() { Element root = new Element("root"); Document doc = new Document(root); MCRChangeTracker tracker = new MCRChangeTracker(); Element title = new Element("title"); root.addContent(title); tracker.track(MCRAddedElement.added(title)); tracker.track(MCRBreakpoint.setBreakpoint(root, "Test")); Attribute href = new Attribute("href", "foo", MCRConstants.XLINK_NAMESPACE); root.setAttribute(href); tracker.track(MCRAddedAttribute.added(href)); tracker.track(MCRSetAttributeValue.setValue(href, "bar")); String label = tracker.undoLastBreakpoint(doc); assertEquals("Test", label); assertNull(root.getAttribute("href")); assertEquals(1, tracker.getChangeCounter()); } @Test public void testSwapElements() throws JaxenException { Element root = new MCRNodeBuilder().buildElement("parent[name='a'][note][foo][name[2]='b'][note[2]]", null, null); Document doc = new Document(root); assertEquals("a", root.getChildren().get(0).getText()); assertEquals("b", root.getChildren().get(3).getText()); MCRChangeTracker tracker = new MCRChangeTracker(); tracker.track(MCRSwapElements.swap(root, 0, 3)); assertEquals("b", root.getChildren().get(0).getText()); assertEquals("a", root.getChildren().get(3).getText()); tracker.undoChanges(doc); assertEquals("a", root.getChildren().get(0).getText()); assertEquals("b", root.getChildren().get(3).getText()); } }
11,904
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXEditorValidatorTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/validation/MCRXEditorValidatorTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.output.DOMOutputter; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.MCRTestConfiguration; import org.mycore.common.MCRTestProperty; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCREditorSession; /** * @author Frank Lützenkirchen */ public class MCRXEditorValidatorTest extends MCRTestCase { private MCREditorSession buildSession(String template) throws JaxenException { MCREditorSession session = new MCREditorSession(); Document editedXML = new Document(new MCRNodeBuilder().buildElement(template, null, null)); session.setEditedXML(editedXML); return session; } private void addRule(MCREditorSession session, String baseXPath, String... attributes) throws JDOMException { Element rule = new Element("validation-rule"); for (int i = 0; i < attributes.length;) { rule.setAttribute(attributes[i++], attributes[i++]); } new Document(rule); org.w3c.dom.Element ruleAsDOMElement = new DOMOutputter().output(rule); session.getValidator().addRule(baseXPath, ruleAsDOMElement); } private void checkResult(MCREditorSession session, String xPath, String marker) throws JaxenException, JDOMException { MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding()); session.getValidator().setValidationMarker(binding); assertEquals(marker, session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_MARKER)); } @Test public void testNoValidationRules() throws JDOMException, JaxenException { MCREditorSession session = buildSession("document"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); } @Test public void testRequiredRule() throws JDOMException, JaxenException { MCREditorSession session = buildSession("document[title]"); addRule(session, "/document/title", "required", "true"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/title", MCRValidationResults.MARKER_ERROR); session = buildSession("document[title='foo']"); addRule(session, "/document/title", "required", "true"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/title", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[title][title[2]='foo']"); addRule(session, "/document/title", "required", "true"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/title", MCRValidationResults.MARKER_SUCCESS); } @Test public void testMinIntegerRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[year='1899'][year='2013'][year[3]]"); addRule(session, "/document/year", "min", "2000", "type", "integer"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/year[1]", MCRValidationResults.MARKER_ERROR); checkResult(session, "/document/year[2]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/year[3]", MCRValidationResults.MARKER_DEFAULT); } @Test public void testMaxDecimalRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[price='10.99'][price='20.00'][price[3]]"); addRule(session, "/document/price", "max", "15.0", "type", "decimal", "locale", "en"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/price[1]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/price[2]", MCRValidationResults.MARKER_ERROR); checkResult(session, "/document/price[3]", MCRValidationResults.MARKER_DEFAULT); } @Test public void testMaxDateRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[year='2017'][year='2117'][year[3]]"); addRule(session, "/document/year", "max", "2017", "type", "date", "format", "yyyy"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/year[1]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/year[2]", MCRValidationResults.MARKER_ERROR); checkResult(session, "/document/year[3]", MCRValidationResults.MARKER_DEFAULT); } @Test public void testDateFormatRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[date]"); addRule(session, "/document", "xpath", "//date", "type", "date", "format", "yyyy-MM-dd"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/date", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[date='2017-04-28']"); addRule(session, "/document", "xpath", "//date", "type", "date", "format", "yyyy-MM-dd"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/date", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[date='28.04.2017']"); addRule(session, "/document", "xpath", "//date", "type", "date", "format", "yyyy-MM-dd"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/date", MCRValidationResults.MARKER_ERROR); session = buildSession("document[date='28.04.2017'][date[2]='2017-04-28']"); addRule(session, "/document", "xpath", "//date", "type", "date", "format", "yyyy-MM-dd;dd.MM.yyyy"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/date[1]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/date[2]", MCRValidationResults.MARKER_SUCCESS); } @Test public void testLengthRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[text='12345']"); addRule(session, "/document", "xpath", "//text", "minLength", "3", "maxLength", "5"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/text", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[text='12345']"); addRule(session, "/document", "xpath", "//text", "maxLength", "4"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/text", MCRValidationResults.MARKER_ERROR); } @Test public void testInvalidation() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[year='1899']"); addRule(session, "/document/year", "min", "2000", "type", "integer"); addRule(session, "/document/*", "max", "2010", "type", "integer"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/year", MCRValidationResults.MARKER_ERROR); } @Test public void testGlobalRules() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[year='1899']"); addRule(session, "/", "xpath", "//year", "min", "2000", "type", "integer"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/year", MCRValidationResults.MARKER_ERROR); } @Test public void testMatchesRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[isbn]"); addRule(session, "/document", "xpath", "//isbn", "matches", "^(97(8|9))?\\d{9}(\\d|X)$"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/isbn", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[isbn='9780672317248']"); addRule(session, "/document", "xpath", "//isbn", "matches", "^(97(8|9))?\\d{9}(\\d|X)$"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/isbn", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[isbn='0-672-31724-9']"); addRule(session, "/document", "xpath", "//isbn", "matches", "^(97(8|9))?\\d{9}(\\d|X)$"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/isbn", MCRValidationResults.MARKER_ERROR); } @Test public void testMatchesNotRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[text='12345']"); addRule(session, "/document", "xpath", "//text", "matches-not", "[a-z]+"); assertTrue(session.getValidator().isValid()); assertEquals("false", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/text", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[text='12345']"); addRule(session, "/document", "xpath", "//text", "matches-not", "[0-9]+"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/text", MCRValidationResults.MARKER_ERROR); } @Test public void testXPathTestRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[author='Jim'][author='Charles'][author='John']"); addRule(session, "/document/author", "test", "contains(.,'J')"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/author[1]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/author[2]", MCRValidationResults.MARKER_ERROR); checkResult(session, "/document/author[3]", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[validFrom='2011'][validTo='2009']"); addRule(session, "/document/validTo", "test", "(string-length(.) = 0) or (number(.) >= number(../validFrom))"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/validFrom", MCRValidationResults.MARKER_DEFAULT); checkResult(session, "/document/validTo", MCRValidationResults.MARKER_ERROR); session = buildSession("document[validFrom='2011'][validTo]"); addRule(session, "/document/validTo", "test", "(string-length(.) = 0) or (number(.) >= number(../validFrom))"); assertTrue(session.getValidator().isValid()); session = buildSession("document[password='secret'][passwordRepeated='sacred']"); addRule(session, "/document", "test", "password = passwordRepeated"); assertFalse(session.getValidator().isValid()); session = buildSession("document[password='secret'][passwordRepeated='secret']"); addRule(session, "/document", "test", "password = passwordRepeated"); assertTrue(session.getValidator().isValid()); session = buildSession("document[service='printOnDemand']"); session.getVariables().put("allowedServices", "oai rss"); addRule(session, "/document/service", "test", "contains($allowedServices,.)"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/service", MCRValidationResults.MARKER_ERROR); session = buildSession("document[service='oai']"); session.getVariables().put("allowedServices", "oai rss"); addRule(session, "/document/service", "test", "contains($allowedServices,.)"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/service", MCRValidationResults.MARKER_SUCCESS); } @Test public void testExternalMethodRule() throws JaxenException, JDOMException { MCREditorSession session = buildSession("document[author='Jim'][author[2]='Charles'][author[3]]"); addRule(session, "/document/author", "class", getClass().getName(), "method", "nameStartsWithJ"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/author[1]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/author[2]", MCRValidationResults.MARKER_ERROR); checkResult(session, "/document/author[3]", MCRValidationResults.MARKER_DEFAULT); session = buildSession( "document[author[1][first='John'][last='Doe']][author[2][first='James'][last='Watt']][author[3]]"); addRule(session, "/document/author", "class", getClass().getName(), "method", "authorIsJohnDoe"); assertFalse(session.getValidator().isValid()); assertEquals("true", session.getVariables().get(MCRXEditorValidator.XED_VALIDATION_FAILED)); checkResult(session, "/document/author[1]", MCRValidationResults.MARKER_SUCCESS); checkResult(session, "/document/author[2]", MCRValidationResults.MARKER_ERROR); checkResult(session, "/document/author[3]", MCRValidationResults.MARKER_SUCCESS); } @Test public void testRequiredRelevantIfRule() throws JDOMException, JaxenException { MCREditorSession session; session = buildSession("document[title='Title']"); addRule(session, "/document/title", "required", "true", "relevant-if", "false()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[title]"); addRule(session, "/document/title", "required", "true", "relevant-if", "false()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[title='Title']"); addRule(session, "/document/title", "required", "true", "relevant-if", "true()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[title]"); addRule(session, "/document/title", "required", "true", "relevant-if", "true()"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_ERROR); } @Test public void testMinIntegerRelevantIfRule() throws JDOMException, JaxenException { MCREditorSession session; session = buildSession("document[year='2000']"); addRule(session, "/document/year", "min", "2000", "type", "integer", "relevant-if", "false()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/year", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[year='1999']"); addRule(session, "/document/year", "min", "2000", "type", "integer", "relevant-if", "false()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/year", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[year='2000']"); addRule(session, "/document/year", "min", "2000", "type", "integer", "relevant-if", "true()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/year", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[year='1999']"); addRule(session, "/document/year", "min", "2000", "type", "integer", "relevant-if", "true()"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/year", MCRValidationResults.MARKER_ERROR); } @Test public void testXPathTestRelevantIfRule() throws JDOMException, JaxenException { MCREditorSession session; session = buildSession("document[title='Foo']"); addRule(session, "/document/title", "test", "text()='Foo'", "relevant-if", "false()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[title='Bar']"); addRule(session, "/document/title", "test", "text()='Foo'", "relevant-if", "false()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_DEFAULT); session = buildSession("document[title='Foo']"); addRule(session, "/document/title", "test", "text()='Foo'", "relevant-if", "true()"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[title='Bar']"); addRule(session, "/document/title", "test", "text()='Foo'", "relevant-if", "true()"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/title", MCRValidationResults.MARKER_ERROR); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = "MCR.Pattern.Alphabetic", string = "[a-z]+"), @MCRTestProperty(key = "MCR.Pattern.Numeric", string = "[0-9]+") }) public void testEnableReplacementsRule() throws JDOMException, JaxenException { MCREditorSession session; session = buildSession("document[test='abc']"); addRule(session, "/document/test", "matches", "[a-z]+"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[test='abc']"); addRule(session, "/document/test", "enable-replacements", "false", "matches", "[a-z]+"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[test='abc']"); addRule(session, "/document/test", "enable-replacements", "true", "matches", "{$MCR.Pattern.Alphabetic}"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[test='123']"); addRule(session, "/document/test", "enable-replacements", "true", "matches", "{$MCR.Pattern.Alphabetic}"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_ERROR); session = buildSession("document[test='123']"); addRule(session, "/document/test", "matches", "[1-9]+"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[test='123']"); addRule(session, "/document/test", "enable-replacements", "false", "matches", "[1-9]+"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[test='123']"); addRule(session, "/document/test", "enable-replacements", "true", "matches", "{$MCR.Pattern.Numeric}"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); session = buildSession("document[test='abc']"); addRule(session, "/document/test", "enable-replacements", "true", "matches", "{$MCR.Pattern.Numeric}"); assertFalse(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_ERROR); } @Test @MCRTestConfiguration(properties = { @MCRTestProperty(key = "MCR.Pattern.Dollar", string = "\\$") }) public void testReplacementProcessor() throws JDOMException, JaxenException { MCREditorSession session; session = buildSession("document[test='$']"); addRule(session, "/document/test", "enable-replacements", "true", "matches", "{$MCR.Pattern.Dollar}"); assertTrue(session.getValidator().isValid()); checkResult(session, "/document/test", MCRValidationResults.MARKER_SUCCESS); } public static boolean nameStartsWithJ(String name) { return name.startsWith("J"); } public static boolean authorIsJohnDoe(Element author) { if (author.getChildren().isEmpty()) { return true; } else { return "John".equals(author.getChildText("first")) && "Doe".equals(author.getChildText("last")); } } }
23,576
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSwapInsertTargetTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/target/MCRSwapInsertTargetTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.target; import static org.junit.Assert.assertEquals; import org.jaxen.JaxenException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.frontend.xeditor.MCRBinding; import org.mycore.frontend.xeditor.MCRRepeatBinding; /** * @author Frank Lützenkirchen */ public class MCRSwapInsertTargetTest extends MCRTestCase { @Test public void testSwapParameter() throws JaxenException, JDOMException { Element template = new MCRNodeBuilder().buildElement("parent[name='aa'][name='ab'][name='bc'][name='ac']", null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRRepeatBinding repeat = new MCRRepeatBinding("parent/name[contains(text(),'a')]", root, 0, 0, "build"); assertEquals(3, repeat.getBoundNodes().size()); repeat.bindRepeatPosition(); repeat.bindRepeatPosition(); assertEquals("/parent|1|build|name[contains(text(), \"a\")]", MCRSwapTarget.getSwapParameter(repeat, MCRSwapTarget.MOVE_UP)); assertEquals("/parent|2|build|name[contains(text(), \"a\")]", MCRSwapTarget.getSwapParameter(repeat, MCRSwapTarget.MOVE_DOWN)); } @Test public void testSwap() throws JaxenException, JDOMException { Element template = new MCRNodeBuilder().buildElement("parent[name='a'][note][foo][name='b'][note[2]]", null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRRepeatBinding repeat = new MCRRepeatBinding("parent/name", root, 2, 0, "build"); assertEquals(2, repeat.getBoundNodes().size()); assertEquals("a", doc.getRootElement().getChildren().get(0).getText()); assertEquals("b", doc.getRootElement().getChildren().get(3).getText()); assertEquals("a", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("b", ((Element) (repeat.getBoundNodes().get(1))).getText()); repeat.bindRepeatPosition(); String swapParam = MCRSwapTarget.getSwapParameter(repeat, MCRSwapTarget.MOVE_DOWN); new MCRSwapTarget().handle(swapParam, root); assertEquals("b", doc.getRootElement().getChildren().get(0).getText()); assertEquals("a", doc.getRootElement().getChildren().get(3).getText()); } @Test public void testBuildInsert() throws JaxenException, JDOMException { String x = "mods:mods[mods:name[@type='personal']='p1'][mods:name[@type='personal'][2]='p2']" + "[mods:name[@type='corporate']='c1']"; Element template = new MCRNodeBuilder().buildElement(x, null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRRepeatBinding repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='personal']", root, 3, 10, "build"); assertEquals("mods:name[(@type = \"personal\")]", repeat.getElementNameWithPredicates()); assertEquals(3, repeat.getBoundNodes().size()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(1))).getText()); assertEquals("", ((Element) (repeat.getBoundNodes().get(2))).getText()); assertEquals("name", ((Element) (repeat.getBoundNodes().get(2))).getName()); assertEquals("personal", ((Element) (repeat.getBoundNodes().get(2))).getAttributeValue("type")); repeat.insert(1); assertEquals(4, repeat.getBoundNodes().size()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("", ((Element) (repeat.getBoundNodes().get(1))).getText()); assertEquals("name", ((Element) (repeat.getBoundNodes().get(1))).getName()); assertEquals("personal", ((Element) (repeat.getBoundNodes().get(1))).getAttributeValue("type")); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(2))).getText()); repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='corporate']", root, 1, 10, "build"); assertEquals(1, repeat.getBoundNodes().size()); assertEquals("mods:name[(@type = \"corporate\")]", repeat.getElementNameWithPredicates()); } @Test public void testCloneInsert() throws JaxenException, JDOMException { String x = "mods:mods[mods:name[@type='personal']='p1'][mods:name[@type='personal'][2]='p2']" + "[mods:name[@type='corporate']='c1']"; Element template = new MCRNodeBuilder().buildElement(x, null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRRepeatBinding repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='personal']", root, 3, 10, "clone"); assertEquals("mods:name[(@type = \"personal\")]", repeat.getElementNameWithPredicates()); assertEquals(3, repeat.getBoundNodes().size()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(1))).getText()); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(2))).getText()); assertEquals("name", ((Element) (repeat.getBoundNodes().get(2))).getName()); assertEquals("personal", ((Element) (repeat.getBoundNodes().get(2))).getAttributeValue("type")); repeat.insert(1); assertEquals(4, repeat.getBoundNodes().size()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(1))).getText()); assertEquals("name", ((Element) (repeat.getBoundNodes().get(1))).getName()); assertEquals("personal", ((Element) (repeat.getBoundNodes().get(1))).getAttributeValue("type")); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(2))).getText()); repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='corporate']", root, 1, 10, "build"); assertEquals(1, repeat.getBoundNodes().size()); assertEquals("mods:name[(@type = \"corporate\")]", repeat.getElementNameWithPredicates()); } @Test public void testBuildInsertParam() throws JaxenException, JDOMException { String x = "mods:mods[mods:name[@type='personal']='p1']" + "[mods:name[@type='personal'][2]='p2'][mods:name[@type='corporate']='c1']"; Element template = new MCRNodeBuilder().buildElement(x, null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRRepeatBinding repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='personal']", root, 2, 10, "build"); repeat.bindRepeatPosition(); String insertParam = MCRInsertTarget.getInsertParameter(repeat); assertEquals("/mods:mods|1|build|mods:name[(@type = \"personal\")]", insertParam); repeat.detach(); new MCRInsertTarget().handle(insertParam, root); repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='personal']", root, 1, 10, "build"); assertEquals(3, repeat.getBoundNodes().size()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("", ((Element) (repeat.getBoundNodes().get(1))).getText()); assertEquals("name", ((Element) (repeat.getBoundNodes().get(1))).getName()); assertEquals("personal", ((Element) (repeat.getBoundNodes().get(1))).getAttributeValue("type")); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(2))).getText()); } @Test public void testCloneInsertParam() throws JaxenException, JDOMException { String x = "mods:mods[mods:name[@type='personal']='p1']" + "[mods:name[@type='personal'][2]='p2'][mods:name[@type='corporate']='c1']"; Element template = new MCRNodeBuilder().buildElement(x, null, null); Document doc = new Document(template); MCRBinding root = new MCRBinding(doc); MCRRepeatBinding repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='personal']", root, 2, 10, "clone"); repeat.bindRepeatPosition(); String insertParam = MCRInsertTarget.getInsertParameter(repeat); assertEquals("/mods:mods|1|clone|mods:name[(@type = \"personal\")]", insertParam); repeat.detach(); new MCRInsertTarget().handle(insertParam, root); repeat = new MCRRepeatBinding("mods:mods/mods:name[@type='personal']", root, 1, 10, "build"); assertEquals(3, repeat.getBoundNodes().size()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(0))).getText()); assertEquals("p1", ((Element) (repeat.getBoundNodes().get(1))).getText()); assertEquals("name", ((Element) (repeat.getBoundNodes().get(1))).getName()); assertEquals("personal", ((Element) (repeat.getBoundNodes().get(1))).getAttributeValue("type")); assertEquals("p2", ((Element) (repeat.getBoundNodes().get(2))).getText()); } }
9,902
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJaxenXPathFactoryTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/test/java/org/mycore/frontend/xeditor/jaxen/MCRJaxenXPathFactoryTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.jaxen; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom2.Document; import org.jdom2.Element; import org.junit.Before; import org.junit.Test; import org.mycore.common.MCRTestCase; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRXPathEvaluator; /** * @author Frank Lützenkirchen */ public class MCRJaxenXPathFactoryTest extends MCRTestCase { private MCRXPathEvaluator evaluator; @Before @Override public void setUp() throws Exception { super.setUp(); String builder = "document[name/@id='n1'][note/@href='#n1'][location/@href='#n1'][name[@id='n2']][location[@href='#n2']]"; Element document = new MCRNodeBuilder().buildElement(builder, null, null); new Document(document); Map<String, Object> variables = new HashMap<>(); variables.put("CurrentUser", "gast"); evaluator = new MCRXPathEvaluator(variables, document); } @Test public void testGenerateID() { String id = evaluator.replaceXPathOrI18n("xed:generate-id(/document)"); assertEquals(id, evaluator.replaceXPathOrI18n("xed:generate-id(.)")); assertEquals(id, evaluator.replaceXPathOrI18n("xed:generate-id()")); assertFalse(id.equals(evaluator.replaceXPathOrI18n("xed:generate-id(/document/name[1])"))); id = evaluator.replaceXPathOrI18n("xed:generate-id(/document/name[1])"); assertEquals(id, evaluator.replaceXPathOrI18n("xed:generate-id(/document/name[1])")); assertEquals(id, evaluator.replaceXPathOrI18n("xed:generate-id(/document/name)")); assertFalse(id.equals(evaluator.replaceXPathOrI18n("xed:generate-id(/document/name[2])"))); } @Test public void testJavaCall() { String res = evaluator.replaceXPathOrI18n( "xed:call-java('org.mycore.frontend.xeditor.jaxen.MCRJaxenXPathFactoryTest','testNoArgs')"); assertEquals(testNoArgs(), res); res = evaluator.replaceXPathOrI18n( "xed:call-java('org.mycore.frontend.xeditor.jaxen.MCRJaxenXPathFactoryTest','testOneArg',name[2])"); assertEquals("n2", res); res = evaluator.replaceXPathOrI18n( "xed:call-java('org.mycore.frontend.xeditor.jaxen.MCRJaxenXPathFactoryTest','testTwoArgs',string(name[1]/@id),string(note[1]/@href))"); assertEquals("true", res); res = evaluator.replaceXPathOrI18n( "xed:call-java('org.mycore.frontend.xeditor.jaxen.MCRJaxenXPathFactoryTest','testTwoArgs',string(name[2]/@id),string(note[1]/@href))"); assertEquals("false", res); } public static String testNoArgs() { return "testNoArgs"; } public static String testOneArg(List<Element> nodes) { return nodes.get(0).getAttributeValue("id"); } public static boolean testTwoArgs(String id, String href) { return id.equals(href.substring(1)); } @Test public void testExternalJavaTest() { assertTrue(evaluator.test("xed:call-java('org.mycore.common.xml.MCRXMLFunctions','isCurrentUserGuestUser')")); assertFalse(evaluator.test("xed:call-java('org.mycore.common.xml.MCRXMLFunctions','isCurrentUserSuperUser')")); assertFalse( evaluator.test("xed:call-java('org.mycore.common.xml.MCRXMLFunctions','isCurrentUserInRole','admins')")); } }
4,273
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREditorSubmission.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCREditorSubmission.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jaxen.JaxenException; import org.jdom2.JDOMException; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.common.xml.MCRXMLHelper; import org.mycore.common.xml.MCRXPathBuilder; public class MCREditorSubmission { public static final String PREFIX_DEFAULT_VALUE = "_xed_default_"; public static final String PREFIX_CHECK_RESUBMISSION = "_xed_check"; private static final Logger LOGGER = LogManager.getLogger(); private Set<String> xPaths2CheckResubmission = new LinkedHashSet<>(); private Map<String, String> xPath2DefaultValue = new LinkedHashMap<>(); private MCREditorSession session; public MCREditorSubmission(MCREditorSession session) { this.session = session; } public void clear() { xPaths2CheckResubmission.clear(); xPath2DefaultValue.clear(); } public void mark2checkResubmission(MCRBinding binding) { for (Object node : binding.getBoundNodes()) { xPaths2CheckResubmission.add(MCRXPathBuilder.buildXPath(node)); } } public String getXPaths2CheckResubmission() { StringBuilder sb = new StringBuilder(); for (String xPath : xPaths2CheckResubmission) { String path = xPath.substring(xPath.indexOf("/", 1) + 1); sb.append(path).append(' '); } return sb.toString().trim(); } public void setXPaths2CheckResubmission(String xPaths) { xPaths2CheckResubmission.clear(); String rootXPath = MCRXPathBuilder.buildXPath(session.getEditedXML().getRootElement()) + "/"; if (xPaths != null) { for (String xPath : xPaths.split(" ")) { xPaths2CheckResubmission.add(rootXPath + xPath); } } } public void emptyNotResubmittedNodes() throws JaxenException { for (String xPath : xPaths2CheckResubmission) { MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding()); if (!binding.getBoundNodes().isEmpty()) { binding.setValue(""); } else { LOGGER.warn("Binding does not contain a bound node [MCR-2558]"); } binding.detach(); } } public void markDefaultValue(String xPath, String defaultValue) { xPath2DefaultValue.put(xPath, defaultValue); } public Map<String, String> getDefaultValues() { return xPath2DefaultValue; } public void setSubmittedValues(Map<String, String[]> values) throws JaxenException, JDOMException { String[] xPaths2Check = values.get(PREFIX_CHECK_RESUBMISSION); if ((xPaths2Check != null) && (xPaths2Check.length > 0)) { setXPaths2CheckResubmission(xPaths2Check[0]); } xPath2DefaultValue.clear(); Map<MCRBinding, String[]> valuesToSet = new HashMap<>(); for (String paramName : values.keySet()) { if (paramName.startsWith("/")) { MCRBinding binding = new MCRBinding(paramName, true, session.getRootBinding()); valuesToSet.put(binding, values.get(paramName)); } else if (paramName.startsWith(PREFIX_DEFAULT_VALUE)) { String xPath = paramName.substring(PREFIX_DEFAULT_VALUE.length()); MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding()); boolean noSuchNode = binding.getBoundNodes().isEmpty(); binding.detach(); if (noSuchNode) { continue; } String defaultValue = values.get(paramName)[0]; markDefaultValue(xPath, defaultValue); } } for (MCRBinding binding : valuesToSet.keySet()) { setSubmittedValues(binding, valuesToSet.get(binding)); } emptyNotResubmittedNodes(); setDefaultValues(); session.setBreakpoint("After setting submitted values"); } private void setSubmittedValues(MCRBinding binding, String[] values) { List<Object> boundNodes = binding.getBoundNodes(); while (boundNodes.size() < values.length) { binding.cloneBoundElement(boundNodes.size() - 1); } for (int i = 0; i < values.length; i++) { String value = values[i] == null ? "" : values[i].trim(); value = MCRXMLFunctions.normalizeUnicode(value); value = MCRXMLHelper.removeIllegalChars(value); binding.setValue(i, value); Object node = binding.getBoundNodes().get(i); xPaths2CheckResubmission.remove(MCRXPathBuilder.buildXPath(node)); } binding.detach(); } public void setDefaultValues() throws JaxenException { MCRBinding rootBinding = session.getRootBinding(); for (String xPath : xPath2DefaultValue.keySet()) { String defaultValue = xPath2DefaultValue.get(xPath); MCRBinding binding = new MCRBinding(xPath, false, rootBinding); binding.setDefault(defaultValue); binding.detach(); } } }
6,116
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRPostProcessorXSL.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRPostProcessorXSL.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.io.IOException; import java.util.Map; import java.util.Objects; import javax.xml.transform.TransformerFactory; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Text; import org.jdom2.filter.Filters; import org.mycore.common.MCRClassTools; 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.MCRXSL2XMLTransformer; import org.mycore.common.xml.MCRXMLFunctions; /** * PostProcessor for MyCoRe editor framework * that allows execution of XSLT stylesheets after an editor is closed * * &lt;xed:post-processor class="org.mycore.frontend.xeditor.MCRPostProcessorXSL" * xsl="editor/ir_xeditor2mods.xsl" transformer="saxon" /&gt; * * You can specify with param xsl the stylesheet, which should be processed and * you can specify with parm transformer the XSLStylesheetProcessor ('xalan' or 'saxon'). * If no transformer is specified the default transformer will be used * (property: MCR.LayoutService.TransformerFactoryClass). */ public class MCRPostProcessorXSL implements MCRXEditorPostProcessor { private String transformer; private String stylesheet; public Document process(Document xml) throws IOException, JDOMException { if (stylesheet == null) { return xml.clone(); } Class<? extends TransformerFactory> factoryClass = null; try { if (Objects.equals(transformer, "xalan")) { factoryClass = MCRClassTools .forName("org.apache.xalan.processor.TransformerFactoryImpl"); } if (Objects.equals(transformer, "saxon")) { factoryClass = MCRClassTools .forName("net.sf.saxon.TransformerFactoryImpl"); } } catch (ClassNotFoundException e) { //do nothing, use default } if (factoryClass == null) { factoryClass = MCRConfiguration2 .<TransformerFactory>getClass("MCR.LayoutService.TransformerFactoryClass").orElseThrow(); } final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder"); MCRContent source = new MCRJDOMContent(xml); MCRContent transformed = MCRXSL2XMLTransformer.getInstance(factoryClass, xslFolder + "/" + stylesheet) .transform(source); MCRContent normalized = new MCRNormalizeUnicodeTransformer().transform(transformed); return normalized.asXML(); } @Override public void setAttributes(Map<String, String> attributeMap) { this.stylesheet = attributeMap.get("xsl"); if (attributeMap.containsKey("transformer")) { this.transformer = attributeMap.get("transformer"); } } public void setStylesheet(String stylesheet) { this.stylesheet = stylesheet; } } class MCRNormalizeUnicodeTransformer extends MCRContentTransformer { public MCRJDOMContent transform(MCRContent source) throws IOException { try { Element root = source.asXML().getRootElement().clone(); for (Text text : root.getDescendants(Filters.text())) { text.setText(MCRXMLFunctions.normalizeUnicode(text.getText())); } return new MCRJDOMContent(root); } catch (JDOMException ex) { throw new IOException(ex); } } }
4,363
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXMLCleaner.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXMLCleaner.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; public class MCRXMLCleaner { private static final MCRCleaningRule REMOVE_EMPTY_ATTRIBUTES = new MCRCleaningRule("//@*", "string-length(.) > 0"); private static final MCRCleaningRule REMOVE_EMPTY_ELEMENTS = new MCRCleaningRule("//*", "@* or * or (string-length(text()) > 0)"); private static final MCRCleaningRule PRESERVE_STRUCTURE_AND_SERVICE = new MCRCleaningRule( "/mycoreobject/structure|/mycoreobject/service", "true()"); private List<MCRCleaningRule> rules = new ArrayList<>(); private Map<Object, MCRCleaningRule> nodes2rules = new HashMap<>(); public MCRXMLCleaner() { addRule(REMOVE_EMPTY_ATTRIBUTES); addRule(REMOVE_EMPTY_ELEMENTS); addRule(PRESERVE_STRUCTURE_AND_SERVICE); } public void addRule(String xPathExprNodesToInspect, String xPathExprRelevancyTest) { addRule(new MCRCleaningRule(xPathExprNodesToInspect, xPathExprRelevancyTest)); } public void addRule(MCRCleaningRule rule) { rules.remove(rule); rules.add(rule); } public Document clean(Document xml) { Document clone = xml.clone(); do { mapNodesToRules(clone); } while (clean(clone.getRootElement())); return clone; } private void mapNodesToRules(Document xml) { nodes2rules.clear(); for (MCRCleaningRule rule : rules) { for (Object object : rule.getNodesToInspect(xml)) { nodes2rules.put(object, rule); } } } private boolean clean(Element element) { boolean changed = false; for (Iterator<Element> children = element.getChildren().iterator(); children.hasNext();) { Element child = children.next(); if (clean(child)) { changed = true; } if (!isRelevant(child)) { changed = true; children.remove(); } } for (Iterator<Attribute> attributes = element.getAttributes().iterator(); attributes.hasNext();) { Attribute attribute = attributes.next(); if (!isRelevant(attribute)) { changed = true; attributes.remove(); } } return changed; } private boolean isRelevant(Object node) { MCRCleaningRule rule = nodes2rules.get(node); return (rule == null || rule.isRelevant(node)); } } class MCRCleaningRule { private String xPathExprNodesToInspect; private XPathExpression<Object> xPathNodesToInspect; private XPathExpression<Object> xPathRelevancyTest; MCRCleaningRule(String xPathExprNodesToInspect, String xPathExprRelevancyTest) { this.xPathExprNodesToInspect = xPathExprNodesToInspect; this.xPathNodesToInspect = XPathFactory.instance().compile(xPathExprNodesToInspect, Filters.fpassthrough(), null, MCRConstants.getStandardNamespaces()); this.xPathRelevancyTest = XPathFactory.instance().compile(xPathExprRelevancyTest, Filters.fpassthrough(), null, MCRConstants.getStandardNamespaces()); } public List<Object> getNodesToInspect(Document xml) { return xPathNodesToInspect.evaluate(xml); } public boolean isRelevant(Object node) { Object found = xPathRelevancyTest.evaluateFirst(node); if (found == null) { return false; } else if (found instanceof Boolean b) { return b; } else { return true; // something matching found } } @Override public boolean equals(Object obj) { if (obj instanceof MCRCleaningRule cleaningRule) { return xPathExprNodesToInspect.equals(cleaningRule.xPathExprNodesToInspect); } else { return false; } } @Override public int hashCode() { return xPathExprNodesToInspect.hashCode(); } }
5,066
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXEditorServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.Enumeration; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.frontend.xeditor.target.MCREditorTarget; import jakarta.servlet.http.HttpServletResponse; /** * @author Frank Lützenkirchen */ public class MCRXEditorServlet extends MCRServlet { private static final long serialVersionUID = 1L; protected static final Logger LOGGER = LogManager.getLogger(MCRXEditorServlet.class); private static final String TARGET_PATTERN = "_xed_submit_"; @Override public void doGetPost(MCRServletJob job) throws Exception { String xEditorStepID = job.getRequest().getParameter(MCREditorSessionStore.XEDITOR_SESSION_PARAM); String sessionID = xEditorStepID.split("-")[0]; MCREditorSession session = MCREditorSessionStoreUtils.getSessionStore().getSession(sessionID); if (session == null) { String msg = getErrorI18N("xeditor.error", "noSession", sessionID); job.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, msg); return; } int stepNr = Integer.parseInt(xEditorStepID.split("-")[1]); session.getChangeTracker().undoChanges(session.getEditedXML(), stepNr); sendToTarget(job, session); } private void sendToTarget(MCRServletJob job, MCREditorSession session) throws Exception { String targetID = "debug"; String parameter = ""; for (Enumeration<String> parameters = job.getRequest().getParameterNames(); parameters.hasMoreElements();) { String name = parameters.nextElement(); if (name.startsWith(TARGET_PATTERN)) { if (name.endsWith(".x") || name.endsWith(".y")) {// input type="image" name = name.substring(0, name.length() - 2); } targetID = name.split("[_\\:]")[3].toLowerCase(Locale.ROOT); parameter = name.substring(TARGET_PATTERN.length() + targetID.length()); if (!parameter.isEmpty()) { parameter = parameter.substring(1); } break; } } LOGGER.info("sending submission to target {} {}", targetID, parameter); getTarget(targetID).handleSubmission(getServletContext(), job, session, parameter); } private MCREditorTarget getTarget(String targetID) { String property = "MCR.XEditor.Target." + targetID + ".Class"; return MCRConfiguration2.getOrThrow(property, MCRConfiguration2::instantiateClass); } }
3,520
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRepeatBinding.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRRepeatBinding.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.List; import java.util.Objects; import org.jaxen.BaseXPath; import org.jaxen.JaxenException; import org.jaxen.dom.DocumentNavigator; import org.jaxen.expr.Expr; import org.jaxen.expr.LocationPath; import org.jaxen.expr.Step; import org.jdom2.Element; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.frontend.xeditor.tracker.MCRAddedElement; import org.mycore.frontend.xeditor.tracker.MCRSwapElements; public class MCRRepeatBinding extends MCRBinding { private int repeatPosition; private int maxRepeats; private static final String DEFAULT_METHOD = MCRConfiguration2.getString("MCR.XEditor.InsertTarget.DefaultMethod") .orElse("build"); private String method = DEFAULT_METHOD; // build|clone public MCRRepeatBinding(String xPath, MCRBinding parent, int minRepeats, int maxRepeats, String method) throws JaxenException { this(xPath, parent, method); while (getBoundNodes().size() < minRepeats) { insert(getBoundNodes().size()); } this.maxRepeats = maxRepeats < 1 ? Integer.MAX_VALUE : maxRepeats; this.maxRepeats = Math.max(this.maxRepeats, getBoundNodes().size()); } public MCRRepeatBinding(String xPath, MCRBinding parent, String method) throws JaxenException { super(xPath, true, parent); this.method = Objects.equals(method, "clone") ? "clone" : Objects.equals(method, "build") ? "build" : DEFAULT_METHOD; this.maxRepeats = Integer.MAX_VALUE; } public int getRepeatPosition() { return repeatPosition; } public MCRBinding bindRepeatPosition() { repeatPosition++; return new MCRBinding(repeatPosition, this); } public int getMaxRepeats() { return maxRepeats; } public String getMethod() { return method; } public Element getParentElement() { return ((Element) getBoundNode()).getParentElement(); } @SuppressWarnings("unchecked") public String getElementNameWithPredicates() throws JaxenException { BaseXPath baseXPath = new BaseXPath(xPath, new DocumentNavigator()); Expr rootExpr = baseXPath.getRootExpr(); LocationPath locationPath = (LocationPath) rootExpr; List<Step> steps = locationPath.getSteps(); Step lastStep = steps.get(steps.size() - 1); return MCRNodeBuilder.simplify(lastStep.getText()); } public void swap(int pos) { Element parent = getParentElement(); Element elementA = (Element) (getBoundNodes().get(pos - 1)); Element elementB = (Element) (getBoundNodes().get(pos)); track(MCRSwapElements.swap(parent, elementA, elementB)); } public void insert(int pos) throws JaxenException { if (Objects.equals(method, "build")) { Element parentElement = getParentElement(); Element precedingElement = (Element) (getBoundNodes().get(pos - 1)); int posOfPrecedingInParent = parentElement.indexOf(precedingElement); int targetPos = posOfPrecedingInParent + 1; String pathToBuild = getElementNameWithPredicates(); Element newElement = (Element) (new MCRNodeBuilder().buildNode(pathToBuild, null, null)); parentElement.addContent(targetPos, newElement); boundNodes.add(pos, newElement); track(MCRAddedElement.added(newElement)); } else { cloneBoundElement(pos - 1); } } }
4,317
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREditorSessionStore.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCREditorSessionStore.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.concurrent.atomic.AtomicInteger; import org.mycore.common.MCRCache; import org.mycore.common.config.MCRConfiguration2; /** * @author Frank Lützenkirchen */ public class MCREditorSessionStore { public static final String XEDITOR_SESSION_PARAM = "_xed_session"; private MCRCache<String, MCREditorSession> cachedSessions; private AtomicInteger idGenerator = new AtomicInteger(0); MCREditorSessionStore() { int maxEditorsInSession = MCRConfiguration2.getInt("MCR.XEditor.MaxEditorsInSession").orElse(50); cachedSessions = new MCRCache<>(maxEditorsInSession, "Stored XEditor Sessions"); } public void storeSession(MCREditorSession session) { String id = String.valueOf(idGenerator.incrementAndGet()); cachedSessions.put(id, session); session.setID(id); } public MCREditorSession getSession(String id) { return cachedSessions.get(id); } }
1,710
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBinding.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRBinding.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jaxen.JaxenException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Parent; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.common.xml.MCRNodeBuilder; import org.mycore.common.xml.MCRXPathBuilder; import org.mycore.common.xml.MCRXPathEvaluator; import org.mycore.frontend.xeditor.tracker.MCRAddedAttribute; import org.mycore.frontend.xeditor.tracker.MCRAddedElement; import org.mycore.frontend.xeditor.tracker.MCRChangeData; import org.mycore.frontend.xeditor.tracker.MCRChangeTracker; import org.mycore.frontend.xeditor.tracker.MCRRemoveAttribute; import org.mycore.frontend.xeditor.tracker.MCRRemoveElement; import org.mycore.frontend.xeditor.tracker.MCRSetAttributeValue; import org.mycore.frontend.xeditor.tracker.MCRSetElementText; /** * @author Frank Lützenkirchen */ public class MCRBinding { private static final Logger LOGGER = LogManager.getLogger(MCRBinding.class); protected String name; protected String xPath; protected List<Object> boundNodes = new ArrayList<>(); protected MCRBinding parent; protected List<MCRBinding> children = new ArrayList<>(); protected MCRChangeTracker tracker; private Map<String, Object> staticVariables = null; public MCRBinding(Document document) { this.boundNodes.add(document); } public MCRBinding(Document document, MCRChangeTracker tracker) { this(document); this.tracker = tracker; } private MCRBinding(MCRBinding parent) { this.parent = parent; parent.children.add(this); } public MCRBinding(String xPath, boolean buildIfNotExists, MCRBinding parent) throws JaxenException { this(parent); bind(xPath, buildIfNotExists, null); } public MCRBinding(String xPath, String initialValue, String name, MCRBinding parent) throws JaxenException { this(parent); this.name = (name != null) && !name.isEmpty() ? name : null; bind(xPath, true, initialValue); } private void bind(String xPath, boolean buildIfNotExists, String initialValue) throws JaxenException { this.xPath = xPath; Map<String, Object> variables = buildXPathVariables(); XPathExpression<Object> xPathExpr = XPathFactory.instance().compile(xPath, Filters.fpassthrough(), variables, MCRConstants.getStandardNamespaces()); boundNodes.addAll(xPathExpr.evaluate(parent.getBoundNodes())); for (Object boundNode : boundNodes) { if (!(boundNode instanceof Element || boundNode instanceof Attribute || boundNode instanceof Document)) { throw new TypeNotPresentException( "XPath MUST only bind either element, attribute or document nodes: " + xPath, null); } } LOGGER.debug("Bind to {} selected {} node(s)", xPath, boundNodes.size()); if (boundNodes.isEmpty() && buildIfNotExists) { MCRNodeBuilder builder = new MCRNodeBuilder(variables); Object built = builder.buildNode(xPath, initialValue, (Parent) (parent.getBoundNode())); LOGGER.debug("Bind to {} generated node {}", xPath, MCRXPathBuilder.buildXPath(built)); boundNodes.add(built); trackNodeCreated(builder.getFirstNodeBuilt()); } } public MCRBinding(int pos, MCRBinding parent) { this(parent); boundNodes.add(parent.getBoundNodes().get(pos - 1)); LOGGER.debug("Repeater bind to child [{}]", pos); } public String getXPath() { return xPath; } public List<Object> getBoundNodes() { return boundNodes; } public Object getBoundNode() { return boundNodes.get(0); } public void removeBoundNode(int index) { Object node = boundNodes.remove(index); if (node instanceof Element element) { track(MCRRemoveElement.remove(element)); } else { track(MCRRemoveAttribute.remove((Attribute) node)); } } public Element cloneBoundElement(int index) { Element template = (Element) (boundNodes.get(index)); Element newElement = template.clone(); Element parent = template.getParentElement(); int indexInParent = parent.indexOf(template) + 1; parent.addContent(indexInParent, newElement); boundNodes.add(index + 1, newElement); trackNodeCreated(newElement); return newElement; } private void trackNodeCreated(Object node) { if (node instanceof Element element) { MCRChangeTracker.removeChangeTracking(element); track(MCRAddedElement.added(element)); } else { Attribute attribute = (Attribute) node; track(MCRAddedAttribute.added(attribute)); } } public MCRBinding getParent() { return parent; } public void detach() { if (parent != null) { parent.children.remove(this); this.parent = null; } } public List<MCRBinding> getAncestorsAndSelf() { List<MCRBinding> ancestors = new ArrayList<>(); MCRBinding current = this; do { ancestors.add(0, current); current = current.getParent(); } while (current != null); return ancestors; } public String getValue() { return getValue(getBoundNode()); } public static String getValue(Object node) { if (node instanceof Element element) { return element.getTextTrim(); } else { return ((Attribute) node).getValue(); } } public boolean hasValue(String value) { return boundNodes.stream().map(MCRBinding::getValue).anyMatch(value::equals); } public void setValue(String value) { setValue(getBoundNode(), value); } public void setDefault(String value) { if (getValue().isEmpty()) { setValue(getBoundNode(), value); } } public void setValues(String value) { for (int i = 0; i < boundNodes.size(); i++) { setValue(i, value); } } public void setValue(int index, String value) { setValue(boundNodes.get(index), value); } private void setValue(Object node, String value) { if (value.equals(getValue(node))) { return; } if (node instanceof Attribute attribute) { track(MCRSetAttributeValue.setValue(attribute, value)); } else { track(MCRSetElementText.setText((Element) node, value)); } } public String getName() { return name; } public List<MCRBinding> getChildren() { return children; } private Map<String, Object> getVariables() { if (staticVariables != null) { return staticVariables; } if (parent != null) { return parent.getVariables(); } return Collections.emptyMap(); } public void setVariables(Map<String, Object> variables) { this.staticVariables = variables; } public Map<String, Object> buildXPathVariables() { Map<String, Object> variables = new HashMap<>(getVariables()); for (MCRBinding ancestor : getAncestorsAndSelf()) { for (MCRBinding child : ancestor.getChildren()) { String childName = child.getName(); if (childName != null) { variables.put(childName, child.getBoundNodes()); } } } return variables; } public String getAbsoluteXPath() { return MCRXPathBuilder.buildXPath(getBoundNode()); } public MCRXPathEvaluator getXPathEvaluator() { return new MCRXPathEvaluator(buildXPathVariables(), getBoundNodes()); } public void track(MCRChangeData change) { if (tracker != null) { tracker.track(change); } else if (parent != null) { parent.track(change); } } }
9,163
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRStaticXEditorFileServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRStaticXEditorFileServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.JDOMException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.frontend.servlets.MCRStaticXMLFileServlet; import org.xml.sax.SAXException; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Frank Lützenkirchen */ public class MCRStaticXEditorFileServlet extends MCRStaticXMLFileServlet { private static final long serialVersionUID = 1L; protected static final Logger LOGGER = LogManager.getLogger(MCRStaticXEditorFileServlet.class); /** XML document types that may contain editor forms */ protected Set<String> docTypesIncludingEditors = new HashSet<>(); @Override public void init() throws ServletException { super.init(); List<String> docTypes = MCRConfiguration2.getString("MCR.XEditor.DocTypes") .map(MCRConfiguration2::splitValue) .map(s -> s.collect(Collectors.toList())) .orElseGet(() -> Collections.singletonList("MyCoReWebPage")); docTypesIncludingEditors.addAll(docTypes); } protected boolean mayContainEditorForm(MCRContent content) throws IOException { return docTypesIncludingEditors.contains(content.getDocType()); } /** For defined document types like static webpages, replace editor elements with complete editor definition */ @Override protected MCRContent getResourceContent(HttpServletRequest request, HttpServletResponse response, URL resource) throws IOException, JDOMException, SAXException { MCRContent content = super.getResourceContent(request, response, resource); if (mayContainEditorForm(content)) { content = doExpandEditorElements(content, request, response, request.getParameter(MCREditorSessionStore.XEDITOR_SESSION_PARAM), request.getRequestURL().toString()); } return content; } public static MCRContent doExpandEditorElements(MCRContent content, HttpServletRequest request, HttpServletResponse response, String sessionID, String pageURL) throws IOException { MCRParameterCollector pc = new MCRParameterCollector(request, false); MCREditorSession session = null; if (sessionID != null) { session = MCREditorSessionStoreUtils.getSessionStore().getSession(sessionID); if (session == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Editor session timed out."); return null; } else { session.update(pc); } } else { session = new MCREditorSession(request.getParameterMap(), pc); session.setPageURL(pageURL); MCREditorSessionStoreUtils.getSessionStore().storeSession(session); } return new MCRXEditorTransformer(session, pc).transform(content); } }
4,086
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXEditorTransformer.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorTransformer.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.lang3.StringUtils; import org.apache.xpath.NodeSet; import org.jaxen.BaseXPath; import org.jaxen.JaxenException; import org.jaxen.dom.DocumentNavigator; import org.jaxen.expr.LocationPath; import org.jaxen.expr.NameStep; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.Parent; import org.mycore.common.MCRClassTools; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRWrappedContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.common.content.transformer.MCRParameterizedTransformer; import org.mycore.common.content.transformer.MCRXSLTransformer; import org.mycore.common.xml.MCRURIResolver; import org.mycore.common.xml.MCRXPathEvaluator; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.frontend.xeditor.target.MCRInsertTarget; import org.mycore.frontend.xeditor.target.MCRSubselectTarget; import org.mycore.frontend.xeditor.target.MCRSwapTarget; import org.mycore.frontend.xeditor.validation.MCRValidator; import org.w3c.dom.Attr; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * @author Frank Lützenkirchen */ public class MCRXEditorTransformer { public int anchorID = 0; private MCREditorSession editorSession; private MCRBinding currentBinding; private MCRParameterCollector transformationParameters; private boolean withinSelectElement = false; private boolean withinSelectMultiple = false; public MCRXEditorTransformer(MCREditorSession editorSession, MCRParameterCollector transformationParameters) { this.editorSession = editorSession; this.transformationParameters = transformationParameters; } public MCRContent transform(MCRContent editorSource) throws IOException { editorSession.getValidator().clearRules(); editorSession.getSubmission().clear(); MCRContentTransformer transformer = MCRContentTransformerFactory.getTransformer("xeditor"); if (transformer instanceof MCRParameterizedTransformer parameterizedTransformer) { transformationParameters.setParameter("transformer", this); MCRContent result = parameterizedTransformer.transform(editorSource, transformationParameters); if (result instanceof MCRWrappedContent wrappedContent && result.getClass().getName().contains(MCRXSLTransformer.class.getName())) { //lazy transformation make JUnit tests fail result = wrappedContent.getBaseContent(); } editorSession.getValidator().clearValidationResults(); return result; } else { throw new MCRException("Xeditor needs parameterized MCRContentTransformer: " + transformer); } } public void addNamespace(String prefix, String uri) { MCRConstants.registerNamespace(Namespace.getNamespace(prefix, uri)); } public void readSourceXML(String uri) throws JDOMException, IOException, SAXException, TransformerException { editorSession.setEditedXML(uri); } public void setCancelURL(String cancelURL) { editorSession.setCancelURL(cancelURL); } public void initializePostprocessor(Node postProcessorNode) { NamedNodeMap attributes = postProcessorNode.getAttributes(); int attributesLength = attributes.getLength(); HashMap<String, String> attributeMap = new HashMap<>(); for (int i = 0; i < attributesLength; i++) { Attr item = (Attr) attributes.item(i); // this should be save because we called getAttributes earlier String attrName = item.getName(); String attrValue = item.getValue(); attributeMap.put(attrName, attrValue); } editorSession.getPostProcessor().setAttributes(attributeMap); } public void setPostProcessor(String clazz) { try { MCRXEditorPostProcessor instance = ((MCRXEditorPostProcessor) MCRClassTools.forName(clazz) .getDeclaredConstructor() .newInstance()); editorSession.setPostProcessor(instance); } catch (ReflectiveOperationException e) { throw new MCRException("Could not initialize Post-Processor with class" + clazz, e); } } public String replaceParameters(String uri) { return getXPathEvaluator().replaceXPaths(uri, false); } public void bind(String xPath, String initialValue, String name) throws JaxenException { if (editorSession.getEditedXML() == null) { createEmptyDocumentFromXPath(xPath); } if (currentBinding == null) { currentBinding = editorSession.getRootBinding(); } setCurrentBinding(new MCRBinding(xPath, initialValue, name, currentBinding)); } private void setCurrentBinding(MCRBinding binding) { this.currentBinding = binding; editorSession.getValidator().setValidationMarker(currentBinding); } private void createEmptyDocumentFromXPath(String xPath) throws JaxenException { Element root = createRootElement(xPath); editorSession.setEditedXML(new Document(root)); editorSession.setBreakpoint("Starting with empty XML document"); } private Element createRootElement(String xPath) throws JaxenException { BaseXPath baseXPath = new BaseXPath(xPath, new DocumentNavigator()); LocationPath lp = (LocationPath) (baseXPath.getRootExpr()); NameStep nameStep = (NameStep) (lp.getSteps().get(0)); String prefix = nameStep.getPrefix(); Namespace ns = prefix.isEmpty() ? Namespace.NO_NAMESPACE : MCRConstants.getStandardNamespace(prefix); return new Element(nameStep.getLocalName(), ns); } public void setValues(String value) { currentBinding.setValues(value); } public void setDefault(String value) { currentBinding.setDefault(value); editorSession.getSubmission().markDefaultValue(currentBinding.getAbsoluteXPath(), value); } public void unbind() { setCurrentBinding(currentBinding.getParent()); } public String getAbsoluteXPath() { return currentBinding.getAbsoluteXPath(); } public String getValue() { return currentBinding.getValue(); } public boolean hasValue(String value) { editorSession.getSubmission().mark2checkResubmission(currentBinding); return currentBinding.hasValue(value); } public void toggleWithinSelectElement(String attrMultiple) { withinSelectElement = !withinSelectElement; withinSelectMultiple = Objects.equals(attrMultiple, "multiple"); } public boolean isWithinSelectElement() { return withinSelectElement; } public boolean isWithinSelectMultiple() { return withinSelectMultiple; } public String replaceXPaths(String text) { return getXPathEvaluator().replaceXPaths(text, false); } public String replaceXPathOrI18n(String expression) { return getXPathEvaluator().replaceXPathOrI18n(expression); } public String evaluateXPath(String xPathExpression) { return getXPathEvaluator().evaluateXPath(xPathExpression); } public boolean test(String xPathExpression) { return getXPathEvaluator().test(xPathExpression); } public MCRXPathEvaluator getXPathEvaluator() { if (currentBinding != null) { return currentBinding.getXPathEvaluator(); } else { return new MCRXPathEvaluator(editorSession.getVariables(), (Parent) null); } } public String repeat(String xPath, int minRepeats, int maxRepeats, String method) throws JaxenException { MCRRepeatBinding repeat = new MCRRepeatBinding(xPath, currentBinding, minRepeats, maxRepeats, method); setCurrentBinding(repeat); return StringUtils.repeat("a ", repeat.getBoundNodes().size()); } private MCRRepeatBinding getCurrentRepeat() { MCRBinding binding = currentBinding; while (!(binding instanceof MCRRepeatBinding)) { binding = binding.getParent(); } return (MCRRepeatBinding) binding; } public int getNumRepeats() { return getCurrentRepeat().getBoundNodes().size(); } public int getMaxRepeats() { return getCurrentRepeat().getMaxRepeats(); } public int getRepeatPosition() { return getCurrentRepeat().getRepeatPosition(); } public void bindRepeatPosition() { setCurrentBinding(getCurrentRepeat().bindRepeatPosition()); editorSession.getValidator().setValidationMarker(currentBinding); } public String getSwapParameter(String action) throws JaxenException { boolean direction = Objects.equals(action, "down") ? MCRSwapTarget.MOVE_DOWN : MCRSwapTarget.MOVE_UP; return MCRSwapTarget.getSwapParameter(getCurrentRepeat(), direction); } public String getInsertParameter() throws JaxenException { return MCRInsertTarget.getInsertParameter(getCurrentRepeat()); } public int nextAnchorID() { return ++anchorID; } public int getAnchorID() { return anchorID; } public int previousAnchorID() { return (anchorID == 0 ? 1 : anchorID - 1); } public void loadResource(String uri, String name) { Element resource = MCRURIResolver.instance().resolve(uri); editorSession.getVariables().put(name, resource); } public void addValidationRule(Node ruleElement) { editorSession.getValidator().addRule(currentBinding.getAbsoluteXPath(), ruleElement); } public boolean hasValidationError() { return editorSession.getValidator().hasError(currentBinding); } public Node getFailedValidationRule() { return editorSession.getValidator().getFailedRule(currentBinding).getRuleElement(); } public NodeSet getFailedValidationRules() { NodeSet nodeSet = new NodeSet(); for (MCRValidator failedRule : editorSession.getValidator().getFailedRules()) { nodeSet.addNode(failedRule.getRuleElement()); } return nodeSet; } public String getSubselectParam(String href) { return currentBinding.getAbsoluteXPath() + ":" + MCRSubselectTarget.encode(href); } public NodeSet getAdditionalParameters() throws ParserConfigurationException { org.w3c.dom.Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); NodeSet nodeSet = new NodeSet(); Map<String, String[]> parameters = editorSession.getRequestParameters(); for (String name : parameters.keySet()) { for (String value : parameters.get(name)) { if ((value != null) && !value.isEmpty()) { nodeSet.addNode(buildAdditionalParameterElement(dom, name, value)); } } } String xPaths2CheckResubmission = editorSession.getSubmission().getXPaths2CheckResubmission(); if (!xPaths2CheckResubmission.isEmpty()) { nodeSet.addNode(buildAdditionalParameterElement(dom, MCREditorSubmission.PREFIX_CHECK_RESUBMISSION, xPaths2CheckResubmission)); } Map<String, String> defaultValues = editorSession.getSubmission().getDefaultValues(); for (String xPath : defaultValues.keySet()) { nodeSet.addNode(buildAdditionalParameterElement(dom, MCREditorSubmission.PREFIX_DEFAULT_VALUE + xPath, defaultValues.get(xPath))); } editorSession.setBreakpoint("After transformation to HTML"); nodeSet.addNode(buildAdditionalParameterElement(dom, MCREditorSessionStore.XEDITOR_SESSION_PARAM, editorSession.getCombinedSessionStepID())); return nodeSet; } private org.w3c.dom.Element buildAdditionalParameterElement(org.w3c.dom.Document doc, String name, String value) { org.w3c.dom.Element element = doc.createElement("param"); element.setAttribute("name", name); element.setTextContent(value); return element; } public void addCleanupRule(String xPath, String relevantIf) { editorSession.getXMLCleaner().addRule(xPath, relevantIf); } public void declareParameter(String name, String defaultValue) { Object currentValue = editorSession.getVariables().get(name); if ((currentValue == null) || Objects.equals(currentValue, "")) { editorSession.getVariables().put(name, defaultValue == null ? "" : defaultValue); } } }
13,931
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREditorSessionStoreUtils.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCREditorSessionStoreUtils.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; /** * @author Frank Lützenkirchen */ public class MCREditorSessionStoreUtils { private static final String XEDITORS_CACHE_KEY = "XEditorsCache"; public static MCREditorSessionStore getSessionStore() { MCRSession session = MCRSessionMgr.getCurrentSession(); MCREditorSessionStore store = (MCREditorSessionStore) (session.get(XEDITORS_CACHE_KEY)); if (store == null) { store = new MCREditorSessionStore(); session.put(XEDITORS_CACHE_KEY, store); } return store; } }
1,388
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCREditorSession.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCREditorSession.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.transform.TransformerException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.Verifier; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRSourceContent; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.frontend.xeditor.tracker.MCRBreakpoint; import org.mycore.frontend.xeditor.tracker.MCRChangeTracker; import org.mycore.frontend.xeditor.validation.MCRXEditorValidator; /** * @author Frank Lützenkirchen */ public class MCREditorSession { private static final Logger LOGGER = LogManager.getLogger(MCREditorSession.class); private static final Pattern PATTERN_URI = Pattern.compile("\\{\\$([^\\}]+)\\}"); private String id; private String url; private Map<String, String[]> requestParameters = new HashMap<>(); private Map<String, Object> variables; private String cancelURL; private Document editedXML; private MCRChangeTracker tracker = new MCRChangeTracker(); private MCREditorSubmission submission = new MCREditorSubmission(this); private MCRXEditorValidator validator = new MCRXEditorValidator(this); private MCRXMLCleaner cleaner = new MCRXMLCleaner(); private MCRXEditorPostProcessor postProcessor = getDefaultPostProcessorImplementation(); private static MCRPostProcessorXSL getDefaultPostProcessorImplementation() { return MCRConfiguration2.getOrThrow("MCR.XEditor.PostProcessor.Default", MCRConfiguration2::instantiateClass); } public MCREditorSession(Map<String, String[]> requestParameters, MCRParameterCollector collector) { // make a copy, the original may be re-used by servlet container this.requestParameters.putAll(requestParameters); this.variables = new HashMap<>(collector.getParameterMap()); removeIllegalVariables(); } public MCREditorSession() { this(Collections.emptyMap(), new MCRParameterCollector()); } public Map<String, Object> getVariables() { return variables; } public void update(MCRParameterCollector collector) { String currentLang = collector.getParameter("CurrentLang", null); if (currentLang != null) { variables.put("CurrentLang", currentLang); } } private void removeIllegalVariables() { for (Iterator<Entry<String, Object>> entries = variables.entrySet().iterator(); entries.hasNext();) { String name = entries.next().getKey(); String result = Verifier.checkXMLName(name); if (result != null) { LOGGER.warn("Illegally named transformation parameter, removing {}", name); entries.remove(); } } } public void setID(String id) { this.id = id; } public String getID() { return id; } public String getCombinedSessionStepID() { return id + "-" + tracker.getChangeCounter(); } public void setPageURL(String pageURL) { if (url == null) { this.url = pageURL.contains("?") ? pageURL.substring(0, pageURL.indexOf("?")) : pageURL; LOGGER.debug("Editor page URL set to {}", this.url); } } public String getPageURL() { return this.url; } public String getRedirectURL(String anchor) { return url + "?" + MCREditorSessionStore.XEDITOR_SESSION_PARAM + "=" + id + (anchor != null ? "#" + anchor : ""); } public Map<String, String[]> getRequestParameters() { return requestParameters; } public String getCancelURL() { return cancelURL; } public void setCancelURL(String cancelURL) { if (this.cancelURL != null) { return; } String cURL = replaceParameters(cancelURL); if (!cURL.contains("{")) { LOGGER.debug("{} set cancel URL to {}", id, cURL); this.cancelURL = cURL; } } public String replaceParameters(String uri) { Matcher m = PATTERN_URI.matcher(uri); StringBuilder sb = new StringBuilder(); while (m.find()) { m.appendReplacement(sb, getReplacement(m.group(1))); } m.appendTail(sb); return sb.toString(); } private String getReplacement(String token) { Object value = variables.get(token); if (value == null) { return "{\\$" + token + "}"; } else { return Matcher.quoteReplacement(value.toString()); } } public Document getEditedXML() { return editedXML; } public void setEditedXML(Document editedXML) { this.editedXML = editedXML; addNamespacesFrom(editedXML.getRootElement()); } private void addNamespacesFrom(Element element) { MCRConstants.registerNamespace(element.getNamespace()); for (Namespace ns : element.getAdditionalNamespaces()) { MCRConstants.registerNamespace(ns); } for (Element child : element.getChildren()) { addNamespacesFrom(child); } } public void setEditedXML(String uri) throws JDOMException, IOException, TransformerException { String uriRe = replaceParameters(uri); if ((editedXML != null) || uriRe.contains("{")) { return; } LOGGER.info("Reading edited XML from {}", uriRe); Document xml = MCRSourceContent.getInstance(uriRe).asXML(); setEditedXML(xml); setBreakpoint("Reading XML from " + uriRe); } public MCRBinding getRootBinding() { MCRBinding binding = new MCRBinding(editedXML, tracker); binding.setVariables(variables); return binding; } public void setBreakpoint(String msg) { if (editedXML != null) { tracker.track(MCRBreakpoint.setBreakpoint(editedXML.getRootElement(), msg)); } } public MCRChangeTracker getChangeTracker() { return tracker; } public MCREditorSubmission getSubmission() { return submission; } public MCRXEditorValidator getValidator() { return validator; } public MCRXMLCleaner getXMLCleaner() { return cleaner; } public MCRXEditorPostProcessor getPostProcessor() { return postProcessor; } protected void setPostProcessor(MCRXEditorPostProcessor postProcessor) { this.postProcessor = postProcessor; } }
7,635
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXEditorPostProcessor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRXEditorPostProcessor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.io.IOException; import java.util.Map; import org.jdom2.Document; import org.jdom2.JDOMException; /** * If you implement this interface then you should have a default constructor if you want it to use with. * @author Sebastian Hofmann (mcrshofm) */ public interface MCRXEditorPostProcessor { /** * Do the post processing. * @param xml the document which has to be post processed * @return the post processed document */ Document process(Document xml) throws IOException, JDOMException; /** * Will be called before {@link #process(Document)}. * @param attributeMap a map which contains the name(key) and value of attributes of the postprocessor element. */ void setAttributes(Map<String, String> attributeMap); }
1,545
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRIncludeHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/MCRIncludeHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.StreamSupport; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.xalan.extensions.ExpressionContext; import org.apache.xpath.NodeSet; import org.apache.xpath.XPathContext; import org.apache.xpath.objects.XNodeSet; import org.apache.xpath.objects.XNodeSetForDOM; import org.jdom2.Element; import org.jdom2.filter.ElementFilter; import org.jdom2.transform.JDOMSource; import org.jdom2.util.IteratorIterable; import org.mycore.common.MCRUsageException; import org.mycore.common.xml.MCRURIResolver; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Handles xed:include, xed:preload and xed:modify|xed:extend to include XEditor components by URI and ID. * * @author Frank L\U00FCtzenkirchen */ public class MCRIncludeHandler { private static final String ATTR_AFTER = "after"; private static final String ATTR_BEFORE = "before"; private static final String ATTR_ID = "id"; private static final String ATTR_REF = "ref"; private static final Logger LOGGER = LogManager.getLogger(MCRIncludeHandler.class); /** Caches preloaded components at application level: resolved only once, used many times (static) */ private static final Map<String, Element> CACHE_AT_APPLICATION_LEVEL = new ConcurrentHashMap<>(); /** Caches preloaded components at transformation level, resolved on every reload of editor form page */ private Map<String, Element> cacheAtTransformationLevel = new HashMap<>(); /** * Preloads editor components from one or more URIs. * * @param uris a list of URIs to preload, separated by whitespace * @param sStatic if true, use static cache on application level, * otherwise reload at each XEditor form transformation */ public void preloadFromURIs(String uris, String sStatic) throws TransformerFactoryConfigurationError { for (String uri : uris.split(",")) { preloadFromURI(uri, sStatic); } } private void preloadFromURI(String uri, String sStatic) throws TransformerFactoryConfigurationError { if (uri.trim().isEmpty()) { return; } LOGGER.debug("preloading " + uri); Element xml; try { xml = resolve(uri.trim(), sStatic); } catch (Exception ex) { LOGGER.warn("Exception preloading " + uri, ex); return; } Map<String, Element> cache = chooseCacheLevel(uri, sStatic); handlePreloadedComponents(xml, cache); } /** * Cache all descendant components that have an @id, handle xed:modify|xed:extend afterwards */ private void handlePreloadedComponents(Element xml, Map<String, Element> cache) { for (Element component : xml.getChildren()) { cacheComponent(cache, component); handlePreloadedComponents(component, cache); handleModify(cache, component); } } private void cacheComponent(Map<String, Element> cache, Element element) { String id = element.getAttributeValue(ATTR_ID); if ((id != null) && !id.isEmpty()) { LOGGER.debug("preloaded component " + id); cache.put(id, element); } } private void handleModify(Map<String, Element> cache, Element element) { if ("modify".equals(element.getName())) { String refID = element.getAttributeValue(ATTR_REF); if (refID == null) { throw new MCRUsageException("<xed:modify /> must have a @ref attribute!"); } Element container = cache.get(refID); if (container == null) { LOGGER.warn("Ignoring xed:modify of " + refID + ", no component with that @id found"); return; } container = container.clone(); String newID = element.getAttributeValue(ATTR_ID); if (newID != null) { container.setAttribute(ATTR_ID, newID); // extend rather that modify LOGGER.debug("extending " + refID + " to " + newID); } else { LOGGER.debug("modifying " + refID); } for (Element command : element.getChildren()) { String commandType = command.getName(); if (Objects.equals(commandType, "remove")) { handleRemove(container, command); } else if (Objects.equals(commandType, "include")) { handleInclude(container, command); } } cacheComponent(cache, container); } } private void handleRemove(Element container, Element removeRule) { String id = removeRule.getAttributeValue(ATTR_REF); LOGGER.debug("removing " + id); findDescendant(container, id).ifPresent(Element::detach); } private Optional<Element> findDescendant(Element container, String id) { IteratorIterable<Element> descendants = container.getDescendants(new ElementFilter()); return StreamSupport.stream(descendants.spliterator(), false) .filter(e -> hasOrIncludesID(e, id)).findFirst(); } private boolean hasOrIncludesID(Element e, String id) { if (id.equals(e.getAttributeValue(ATTR_ID))) { return true; } else { return "include".equals(e.getName()) && id.equals(e.getAttributeValue(ATTR_REF)); } } private void handleInclude(Element container, Element includeRule) { boolean modified = handleBeforeAfter(container, includeRule, ATTR_BEFORE, 0, 0); if (!modified) { includeRule.setAttribute(ATTR_AFTER, includeRule.getAttributeValue(ATTR_AFTER, "*")); handleBeforeAfter(container, includeRule, ATTR_AFTER, 1, container.getChildren().size()); } } private boolean handleBeforeAfter(Element container, Element includeRule, String attributeName, int offset, int defaultPos) { String refID = includeRule.getAttributeValue(attributeName); if (refID != null) { includeRule.removeAttribute(attributeName); Element parent = container; int pos = defaultPos; Optional<Element> neighbor = findDescendant(container, refID); if (neighbor.isPresent()) { Element n = neighbor.get(); parent = n.getParentElement(); List<Element> children = parent.getChildren(); pos = children.indexOf(n) + offset; } LOGGER.debug("including " + Arrays.toString(includeRule.getAttributes().toArray()) + " at pos " + pos); parent.getChildren().add(pos, includeRule.clone()); } return refID != null; } public XNodeSet resolve(ExpressionContext context, String ref) throws TransformerException { LOGGER.debug("including component " + ref); Map<String, Element> cache = chooseCacheLevel(ref, Boolean.FALSE.toString()); Element resolved = cache.get(ref); return (resolved == null ? null : asNodeSet(context, jdom2dom(resolved))); } public XNodeSet resolve(ExpressionContext context, String uri, String sStatic) throws TransformerException { LOGGER.debug("including xml " + uri); Element xml = resolve(uri, sStatic); Node node = jdom2dom(xml); try { return asNodeSet(context, node); } catch (Exception ex) { LOGGER.error(ex); throw ex; } } private Element resolve(String uri, String sStatic) throws TransformerFactoryConfigurationError { Map<String, Element> cache = chooseCacheLevel(uri, sStatic); if (cache.containsKey(uri)) { LOGGER.debug("uri was cached: " + uri); return cache.get(uri); } else { Element xml = MCRURIResolver.instance().resolve(uri); cache.put(uri, xml); return xml; } } private Map<String, Element> chooseCacheLevel(String key, String sStatic) { if (Objects.equals(sStatic, "true") || CACHE_AT_APPLICATION_LEVEL.containsKey(key)) { return CACHE_AT_APPLICATION_LEVEL; } else { return cacheAtTransformationLevel; } } private Node jdom2dom(Element element) throws TransformerException { DOMResult result = new DOMResult(); JDOMSource source = new JDOMSource(element); TransformerFactory.newInstance().newTransformer().transform(source, result); return result.getNode(); } private XNodeSet asNodeSet(ExpressionContext context, Node node) throws TransformerException { NodeSet nodeSet = new NodeSet(); nodeSet.addNode(node); XPathContext xpc = context.getXPathContext(); return new XNodeSetForDOM((NodeList) nodeSet, xpc); } }
10,132
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRemoveElement.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRRemoveElement.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Element; public class MCRRemoveElement implements MCRChange { public static MCRChangeData remove(Element element) { Element parent = element.getParentElement(); MCRChangeData data = new MCRChangeData("removed-element", element, parent.indexOf(element), parent); element.detach(); return data; } public void undo(MCRChangeData data) { data.getContext().addContent(data.getPosition(), data.getElement()); } }
1,256
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSetAttributeValue.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRSetAttributeValue.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Attribute; public class MCRSetAttributeValue implements MCRChange { public static MCRChangeData setValue(Attribute attribute, String value) { MCRChangeData data = new MCRChangeData("set-attribute", attribute); attribute.setValue(value); return data; } public void undo(MCRChangeData data) { Attribute attribute = data.getAttribute(); data.getContext().removeAttribute(attribute.getName(), attribute.getNamespace()); data.getContext().setAttribute(attribute); } }
1,320
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRBreakpoint.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRBreakpoint.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Element; public class MCRBreakpoint implements MCRChange { public static MCRChangeData setBreakpoint(Element context, String label) { return new MCRChangeData("breakpoint", label, context.getContentSize(), context); } public void undo(MCRChangeData data) { // Need implementation } }
1,109
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRChange.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRChange.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; public interface MCRChange { void undo(MCRChangeData data); }
840
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRChangeTracker.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRChangeTracker.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import java.util.Iterator; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.ProcessingInstruction; import org.jdom2.filter.Filters; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; public class MCRChangeTracker implements Cloneable { private static final String CONFIG_PREFIX = "MCR.XEditor.ChangeTracker."; public static final String PREFIX = "xed-tracker-"; private int counter = 0; public void track(MCRChangeData data) { ProcessingInstruction pi = data.getProcessingInstruction(); pi.setTarget(PREFIX + (++counter) + "-" + pi.getTarget()); data.getContext().addContent(data.getPosition(), pi); } public int getChangeCounter() { return counter; } public void undoChanges(Document doc) { undoChanges(doc, 0); } public void undoChanges(Document doc, int stepNumber) { while (counter > stepNumber) { undoLastChange(doc); } } public String undoLastBreakpoint(Document doc) { while (counter > 0) { MCRChangeData change = undoLastChange(doc); if ("breakpoint".equals(change.getType())) { return change.getText(); } } return null; } public MCRChangeData undoLastChange(Document doc) { MCRChangeData data = findLastChange(doc); data.getProcessingInstruction().detach(); counter--; String property = CONFIG_PREFIX + data.getType() + ".Class"; MCRChange change = MCRConfiguration2.<MCRChange>getSingleInstanceOf(property) .orElseThrow(() -> MCRConfiguration2.createConfigurationException(property)); change.undo(data); return data; } public MCRChangeData findLastChange(Document doc) { String typePrefix = PREFIX + counter + "-"; for (ProcessingInstruction instruction : doc.getDescendants(Filters.processinginstruction())) { String target = instruction.getTarget(); if (target.startsWith(typePrefix)) { return new MCRChangeData(instruction, typePrefix); } } throw new MCRException("Lost processing instruction for undo, not found: " + typePrefix); } public static Document removeChangeTracking(Document doc) { Document clone = doc.clone(); removeChangeTracking(clone.getRootElement()); return clone; } public static void removeChangeTracking(Element element) { for (Iterator<ProcessingInstruction> iter = element.getDescendants(Filters.processinginstruction()) .iterator(); iter.hasNext();) { if (iter.next().getTarget().startsWith(PREFIX)) { iter.remove(); } } } @Override public MCRChangeTracker clone() { MCRChangeTracker tracker = new MCRChangeTracker(); tracker.counter = this.counter; return tracker; } }
3,765
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSwapElements.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRSwapElements.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Content; import org.jdom2.Element; public class MCRSwapElements implements MCRChange { public static MCRChangeData swap(Element parent, Element a, Element b) { int posA = parent.indexOf(a); int posB = parent.indexOf(b); return swap(parent, posA, a, posB, b); } public static MCRChangeData swap(Element parent, int posA, int posB) { Content a = parent.getContent().get(posA); Content b = parent.getContent().get(posB); return swap(parent, posA, a, posB, b); } public static MCRChangeData swap(Element parent, int posA, Content a, int posB, Content b) { if (posA > posB) { return swap(parent, posB, b, posA, a); } b.detach(); // x a x x x parent.addContent(posA, b); // x b a x x x a.detach(); // x b x x x parent.addContent(posB, a); // x b x x a x return new MCRChangeData("swapped-elements", posA + " " + posB, posB, parent); } public void undo(MCRChangeData data) { int posA = Integer.parseInt(data.getText().split(" ")[0]); int posB = Integer.parseInt(data.getText().split(" ")[1]); swap(data.getContext(), posA, posB); } }
1,999
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRChangeData.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRChangeData.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import java.io.IOException; import java.io.StringReader; import org.jdom2.Attribute; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.ProcessingInstruction; import org.jdom2.Text; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.MCRException; public class MCRChangeData { protected String type; protected int pos; protected Element context; protected String text; protected ProcessingInstruction pi; private static final XMLOutputter RAW_OUTPUTTER = new XMLOutputter(Format.getRawFormat().setEncoding("UTF-8")); public MCRChangeData(String type, String text, int pos, Element context) { this.type = type; this.text = text; this.pos = pos; this.context = context; } public MCRChangeData(String type, Attribute attribute) { this(type, attribute2text(attribute), 0, attribute.getParent()); } public MCRChangeData(String type, Element data, int pos, Element context) { this(type, element2text(data), pos, context); } public ProcessingInstruction getProcessingInstruction() { if (pi == null) { String data = RAW_OUTPUTTER.outputString(new Text(text)); this.pi = new ProcessingInstruction(type, data); } return pi; } public MCRChangeData(ProcessingInstruction pi, String prefix) { this.pi = pi; this.context = pi.getParentElement(); this.pos = context.indexOf(pi); this.type = pi.getTarget().substring(prefix.length()); String xml = "<x>" + pi.getData() + "</x>"; this.text = text2element(xml).getText(); } public String getType() { return type; } public Element getContext() { return context; } public int getPosition() { return pos; } public String getText() { return text; } public Element getElement() { return text2element(text); } public Attribute getAttribute() { return text2attribute(text); } private static String element2text(Element element) { return RAW_OUTPUTTER.outputString(element); } private Element text2element(String text) { try { return new SAXBuilder().build(new StringReader(text)).detachRootElement(); } catch (JDOMException | IOException ex) { throw new MCRException("Exception in text2element: " + text, ex); } } private static String attribute2text(Attribute attribute) { Element x = new Element("x").setAttribute(attribute.clone()); String text = element2text(x); return text.substring(3, text.length() - 2).trim(); } public Attribute text2attribute(String text) { String xtext = "<x " + text + " />"; return text2element(xtext).getAttributes().get(0).detach(); } }
3,725
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRRemoveAttribute.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRRemoveAttribute.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Attribute; public class MCRRemoveAttribute implements MCRChange { public static MCRChangeData remove(Attribute attribute) { MCRChangeData data = new MCRChangeData("removed-attribute", attribute); attribute.detach(); return data; } public void undo(MCRChangeData data) { data.getContext().setAttribute(data.getAttribute()); } }
1,168
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAddedAttribute.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRAddedAttribute.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Attribute; public class MCRAddedAttribute implements MCRChange { public static MCRChangeData added(Attribute attribute) { return new MCRChangeData("added-attribute", attribute); } public void undo(MCRChangeData data) { Attribute attribute = data.getAttribute(); data.getContext().removeAttribute(attribute.getName(), attribute.getNamespace()); } }
1,181
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAddedElement.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRAddedElement.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import org.jdom2.Element; public class MCRAddedElement implements MCRChange { public static MCRChangeData added(Element element) { return new MCRChangeData("added-this-element", "", 0, element); } public void undo(MCRChangeData data) { data.getContext().detach(); } }
1,076
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSetElementText.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/tracker/MCRSetElementText.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.tracker; import java.util.Iterator; import org.jdom2.Attribute; import org.jdom2.Element; public class MCRSetElementText implements MCRChange { public static MCRChangeData setText(Element element, String text) { Element clone = element.clone(); for (Iterator<Attribute> attributes = clone.getAttributes().iterator(); attributes.hasNext();) { attributes.next(); attributes.remove(); } MCRChangeData data = new MCRChangeData("set-text", clone, 0, element); element.setText(text); return data; } public void undo(MCRChangeData data) { data.getContext().setContent(data.getElement().cloneContent()); } }
1,466
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; import java.util.List; import org.jaxen.JaxenException; import org.mycore.common.xml.MCRXPathBuilder; import org.mycore.common.xml.MCRXPathEvaluator; import org.mycore.frontend.xeditor.MCRBinding; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; public abstract class MCRValidator { private static final String ATTR_RELEVANT_IF = "relevant-if"; private Node ruleElement; protected String xPath; protected String relevantIfXPath; public void init(String baseXPath, Node ruleElement) { Node relativeXPath = ruleElement.getAttributes().getNamedItem("xpath"); this.xPath = relativeXPath != null ? relativeXPath.getNodeValue() : baseXPath; this.ruleElement = ruleElement; if (hasRequiredAttributes()) { relevantIfXPath = getAttributeValue(ATTR_RELEVANT_IF); configure(); } } public abstract boolean hasRequiredAttributes(); /** If validator uses properties to configure its behavior, override this */ public void configure() { // empty } public Node getRuleElement() { return ruleElement; } public String getAttributeValue(String name) { NamedNodeMap attributes = ruleElement.getAttributes(); Node attribute = attributes.getNamedItem(name); return attribute == null ? null : attribute.getNodeValue(); } public boolean hasAttributeValue(String name) { return (getAttributeValue(name) != null); } public boolean validate(MCRValidationResults results, MCRBinding root) throws JaxenException { MCRBinding binding = new MCRBinding(xPath, false, root); boolean isValid = validateBinding(results, binding); binding.detach(); return isValid; } public boolean validateBinding(MCRValidationResults results, MCRBinding binding) { boolean isValid = true; // all nodes must validate List<Object> boundNodes = binding.getBoundNodes(); for (int i = 0; i < boundNodes.size(); i++) { Object node = boundNodes.get(i); String absPath = MCRXPathBuilder.buildXPath(node); if (results.hasError(absPath)) { continue; } MCRBinding nodeBinding = new MCRBinding(i + 1, binding); if (!isRelevant(nodeBinding)) { continue; } String value = MCRBinding.getValue(node); if (value.isEmpty()) { continue; } boolean result = isValid(value); results.mark(absPath, result, this); isValid = isValid && result; } return isValid; } protected boolean isRelevant(MCRBinding binding) { if (null == relevantIfXPath) { return true; } else { MCRXPathEvaluator evaluator = binding.getXPathEvaluator(); boolean isRelevant = evaluator.test(relevantIfXPath); binding.detach(); return isRelevant; } } protected boolean isValid(String value) { return true; } }
3,888
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDateConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRDateConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.mycore.common.MCRException; /** * Helper for date validators to convert string input into a date value. * * @author Frank Lützenkirchen */ public class MCRDateConverter { private static final Date CHECK_DATE = new Date(0L); private List<SimpleDateFormat> formats = new ArrayList<>(); /** * @param patterns a list of allowed SimpleDateFormat patterns separated by ";" */ public MCRDateConverter(String patterns) { for (String pattern : patterns.split(";")) { formats.add(getDateFormat(pattern.trim())); } } protected SimpleDateFormat getDateFormat(String pattern) { SimpleDateFormat df = new SimpleDateFormat(pattern, Locale.ROOT); df.setLenient(false); return df; } /** * * @param input the text string * @return the parsed Date matching one of the allowed date patterns, or null if the text can not be parsed */ public Date string2date(String input) throws MCRException { for (SimpleDateFormat format : formats) { if (format.format(CHECK_DATE).length() != input.length()) { continue; } try { ParsePosition pp = new ParsePosition(0); Date value = format.parse(input, pp); if (pp.getIndex() == input.length()) { return value; } } catch (Exception ignored) { } } return null; } }
2,454
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMinIntegerValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMinIntegerValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; /** * Validates values to be integer numbers not less than a given minimum value. * Example: &lt;xed:validate type="integer" min="100" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMinIntegerValidator extends MCRIntegerValidator { private static final String ATTR_MIN = "min"; private int min; @Override public boolean hasRequiredAttributes() { return super.hasRequiredAttributes() && hasAttributeValue(ATTR_MIN); } @Override public void configure() { min = Integer.parseInt(getAttributeValue(ATTR_MIN)); } @Override protected boolean isValid(String value) { if (!super.isValid(value)) { return false; } else { return min <= Integer.parseInt(value); } } }
1,570
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXPathTestValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRXPathTestValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; import java.util.List; import org.mycore.common.xml.MCRXPathBuilder; import org.mycore.common.xml.MCRXPathEvaluator; import org.mycore.frontend.xeditor.MCRBinding; /** * Validates using an XPath test expression. * * Example: &lt;xed:validate xpath="//max" test="(string-length(.) = 0) or (number(.) &gt;= number(../min))" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRXPathTestValidator extends MCRValidator { private static final String ATTR_TEST = "test"; private String xPathExpression; @Override public boolean hasRequiredAttributes() { return hasAttributeValue(ATTR_TEST); } @Override public void configure() { this.xPathExpression = getAttributeValue(ATTR_TEST); } @Override public boolean validateBinding(MCRValidationResults results, MCRBinding binding) { boolean isValid = true; // all nodes must validate List<Object> boundNodes = binding.getBoundNodes(); for (int i = 0; i < boundNodes.size(); i++) { Object node = boundNodes.get(i); String absPath = MCRXPathBuilder.buildXPath(node); if (results.hasError(absPath)) { continue; } MCRBinding nodeBinding = new MCRBinding(i + 1, binding); if (!isRelevant(nodeBinding)) { continue; } MCRXPathEvaluator evaluator = nodeBinding.getXPathEvaluator(); boolean result = evaluator.test(xPathExpression); nodeBinding.detach(); results.mark(absPath, result, this); isValid = isValid && result; } return isValid; } }
2,455
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMaxIntegerValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMaxIntegerValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; /** * Validates values to be integer numbers not bigger than a given maximum value. * Example: &lt;xed:validate type="integer" max="200" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMaxIntegerValidator extends MCRIntegerValidator { private static final String ATTR_MAX = "max"; private int max; @Override public boolean hasRequiredAttributes() { return super.hasRequiredAttributes() && hasAttributeValue(ATTR_MAX); } @Override public void configure() { max = Integer.parseInt(getAttributeValue(ATTR_MAX)); } @Override protected boolean isValid(String value) { if (!super.isValid(value)) { return false; } else { return Integer.parseInt(value) <= max; } } }
1,572
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMatchesValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMatchesValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; /** * Validates input to match a specified java.util.regex pattern. * Example: &lt;xed:validate xpath="//mods:identifier[@type='doi']" matches="10\.\d+.*" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRMatchesValidator extends MCRValidator { private static final String ATTR_MATCHES = "matches"; private String pattern; @Override public boolean hasRequiredAttributes() { return hasAttributeValue(ATTR_MATCHES); } @Override public void configure() { this.pattern = getAttributeValue(ATTR_MATCHES); } @Override protected boolean isValid(String value) { return value.matches(pattern); } }
1,455
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMinStringValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMinStringValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; /** * Validates text values to be "after" (in java.lang.String#compare order) a given minimum. * Example: &lt;xed:validate type="string" min="AAA" ... /&gt; * * @author Frank Lützenkirchen */ public class MCRMinStringValidator extends MCRValidator { private static final String ATTR_MIN = "min"; private static final String ATTR_TYPE = "type"; private static final String TYPE_STRING = "string"; private String min; @Override public boolean hasRequiredAttributes() { return TYPE_STRING.equals(getAttributeValue(ATTR_TYPE)) && hasAttributeValue(ATTR_MIN); } @Override public void configure() { min = getAttributeValue("min"); } @Override protected boolean isValid(String value) { return min.compareTo(value) <= 0; } }
1,585
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMinDateValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMinDateValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; import java.util.Date; /** * Validates date values against a minimum date. * Date values are specified by one or more SimpleDateFormat patterns separated by ";". * Example: &lt;xed:validate type="date" format="yyyy-MM" min="2017-01" ... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMinDateValidator extends MCRDateValidator { private static final String ATTR_MIN = "min"; private Date minDate; @Override public boolean hasRequiredAttributes() { return super.hasRequiredAttributes() && hasAttributeValue(ATTR_MIN); } @Override public void configure() { super.configure(); String min = getAttributeValue(ATTR_MIN); this.minDate = converter.string2date(min); } @Override protected boolean isValid(String value) { Date date = converter.string2date(value); if (date == null) { return false; } else { return minDate.before(date) || minDate.equals(date); } } }
1,792
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMaxDecimalValidator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-xeditor/src/main/java/org/mycore/frontend/xeditor/validation/MCRMaxDecimalValidator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.xeditor.validation; /** * Validates input to be a decimal number and not bigger than a given value. * The number format is specified by a given locale ID. * Example: &lt;xed:validate type="decimal" locale="de" max="1.999,99"... /&gt; * * * @author Frank Lützenkirchen */ public class MCRMaxDecimalValidator extends MCRDecimalValidator { private static final String ATTR_MAX = "max"; private double max; @Override public boolean hasRequiredAttributes() { return super.hasRequiredAttributes() && hasAttributeValue(ATTR_MAX); } @Override public void configure() { super.configure(); max = converter.string2double(getAttributeValue(ATTR_MAX)); } @Override protected boolean isValid(String value) { Double d = converter.string2double(value); if (d == null) { return false; } else { return d <= max; } } }
1,695
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z