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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRAction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRAction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import org.mycore.parsers.bool.MCRCondition;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* @author Thomas Scheffler (yagee)
*
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "action")
public class MCRAction {
@XmlAttribute
private String action;
@XmlElement(name = "when")
private MCRDecision[] decisions;
public String getURL(MCRWorkflowData workflowData) {
for (MCRDecision decision : decisions) {
@SuppressWarnings("unchecked")
MCRCondition<Object> cond = (MCRCondition<Object>) decision.getCondition();
if (cond.evaluate(workflowData)) {
return decision.getUrl();
}
}
return null;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public MCRDecision[] getDecisions() {
return decisions;
}
public void setDecisions(MCRDecision... decisions) {
this.decisions = decisions;
}
}
| 2,016 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPersistenceServletFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRPersistenceServletFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import java.io.IOException;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRPersistenceServletFilter implements Filter {
private static final Logger LOGGER = LogManager.getLogger(MCRPersistenceServletFilter.class);
/* (non-Javadoc)
* @see jakarta.servlet.Filter#destroy()
*/
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getServletPath().length() > 0) {
String url = getURL(req);
if (url != null) {
prepareRequest(req);
req.getRequestDispatcher(url).forward(req, response);
return;
}
}
chain.doFilter(req, response);
}
private void prepareRequest(HttpServletRequest req) {
Map<String, String[]> parameterMap = req.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
switch (entry.getValue().length) {
case 0:
break;
case 1:
if (!entry.getKey().equals("layout")) {
req.setAttribute(entry.getKey(), entry.getValue()[0]);
}
break;
default:
req.setAttribute(entry.getKey(), entry.getValue());
break;
}
}
}
private String getURL(HttpServletRequest req) {
String servletPath = req.getServletPath();
String[] pathElements = servletPath.split("/");
String operation = pathElements[3];
//get session for DB access
MCRSession session = MCRServlet.getSession(req);
MCRSessionMgr.setCurrentSession(session);
MCRTransactionHelper.beginTransaction();
try {
String url;
String mcrId = MCRServlet.getProperty(req, "id");
if (mcrId == null) {
String collection = getCollection(req);
url = MCRURLRetriever.getURLforCollection(operation, collection, false);
} else {
url = MCRURLRetriever.getURLforID(operation, mcrId, false);
}
LOGGER.info("Matched URL: {}", url);
return url;
} finally {
MCRTransactionHelper.commitTransaction();
MCRSessionMgr.releaseCurrentSession();
}
}
private String getCollection(HttpServletRequest req) {
//layout is collection string
String layout = MCRServlet.getProperty(req, "layout");
if (layout != null) {
return layout;
}
String mcrId = MCRServlet.getProperty(req, "id");
return MCRClassificationUtils.getCollection(mcrId);
}
/* (non-Javadoc)
* @see jakarta.servlet.Filter#init(jakarta.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig config) {
}
}
| 4,399 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCategoryCondition.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRCategoryCondition.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import org.apache.logging.log4j.LogManager;
import org.jdom2.Element;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.parsers.bool.MCRCondition;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRCategoryCondition implements MCRCondition<MCRWorkflowData> {
private MCRCategoryID mcrCategoryID;
private boolean not;
private String fieldName;
private static MCRCategLinkService LINK_SERVICE = MCRCategLinkServiceFactory.getInstance();
public MCRCategoryCondition(String fieldName, MCRCategoryID mcrCategoryID, boolean not) {
this.fieldName = fieldName;
this.mcrCategoryID = mcrCategoryID;
this.not = not;
}
/* (non-Javadoc)
* @see org.mycore.parsers.bool.MCRCondition#evaluate(java.lang.Object)
*/
@Override
public boolean evaluate(MCRWorkflowData workflowData) {
MCRCategLinkReference reference = workflowData.getCategoryReference();
if (reference == null) {
LogManager.getLogger(getClass())
.error("Cannot evaluate '{}', if MCRWorkflowData does not contain an object reference",
toString());
return false;
}
return LINK_SERVICE.isInCategory(reference, mcrCategoryID) ^ not;
}
@Override
public String toString() {
return fieldName + (not ? " != " : " = ") + mcrCategoryID.getId() + " ";
}
/* (non-Javadoc)
* @see org.mycore.parsers.bool.MCRCondition#toXML()
*/
@Override
public Element toXML() {
Element cond = new Element("condition");
cond.setAttribute("field", fieldName);
cond.setAttribute("operator", (not ? "!=" : "="));
cond.setAttribute("value", mcrCategoryID.getId());
return cond;
}
}
| 2,772 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRActionMappingServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRActionMappingServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import java.net.URI;
import java.util.List;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import com.google.common.base.Splitter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Maps collection and action to a redirect URL.
* call /servlets/MCRActionMappingServlet/{collection}/{action}
* @author Thomas Scheffler (yagee)
*
*/
public class MCRActionMappingServlet extends MCRServlet {
private static final long serialVersionUID = 1L;
private static Splitter PATH_SPLITTER = Splitter.on('/').trimResults().omitEmptyStrings().limit(2);
@Override
protected void doGet(MCRServletJob job) throws Exception {
HttpServletRequest request = job.getRequest();
String pathInfo = request.getPathInfo();
HttpServletResponse response = job.getResponse();
if (pathInfo != null) {
List<String> splitted = PATH_SPLITTER.splitToList(pathInfo);
if (splitted.size() == 2) {
String collection = splitted.get(0);
String action = splitted.get(1);
String url = MCRURLRetriever.getURLforCollection(action, collection, true);
if (url != null) {
//MCR-1172 check if we redirect to a valid URI
URI uri = URI.create(url);
response.sendRedirect(response.encodeRedirectURL(uri.toString()));
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return;
}
//misses action
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//should never happen:
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
}
}
| 2,634 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRActionMappings.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRActionMappings.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
/**
* @author Thomas Scheffler (yagee)
*
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "actionmappings")
public class MCRActionMappings {
@XmlElement(name = "collection")
MCRCollection[] collections;
public void setCollections(MCRCollection... collections) {
this.collections = collections;
}
public MCRCollection[] getCollections() {
return collections;
}
}
| 1,390 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRURLRetriever.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRURLRetriever.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
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.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.wfc.MCRConstants;
/**
* @author Thomas Scheffler (yagee)
*/
public final class MCRURLRetriever {
private static final Logger LOGGER = LogManager.getLogger(MCRURLRetriever.class);
private static final MCRCategoryDAO CATEGORY_DAO = MCRCategoryDAOFactory.getInstance();
private static Map<String, MCRCollection> COLLECTION_MAP = initActionsMappings();
private MCRURLRetriever() {
}
private static Map<String, MCRCollection> initActionsMappings() {
try {
MCRActionMappings actionMappings = MCRActionMappingsManager.getActionMappings();
return Arrays
.stream(actionMappings.getCollections())
.collect(Collectors.toMap(MCRCollection::getName, c -> c));
} catch (Exception e) {
throw new MCRException(e);
}
}
public static String getURLforID(String action, String mcrID, boolean absolute) {
final MCRObjectID objID = MCRObjectID.getInstance(mcrID);
String collectionName = MCRClassificationUtils.getCollection(mcrID);
return getURL(action, collectionName, new MCRCategLinkReference(objID), absolute);
}
public static String getURLforCollection(String action, String collection, boolean absolute) {
return getURL(action, collection, null, absolute);
}
private static String getURL(String action, String collectionName, MCRCategLinkReference reference,
boolean absolute) {
MCRCollection defaultCollection = reference != null ? getCollectionWithAction(reference.getType(), action, null)
: null;
MCRCollection collection = getCollectionWithAction(collectionName, action, defaultCollection);
if (collection == null) {
LOGGER.warn("Could not find action ''{}'' in collection: {}", action, collectionName);
return null;
}
return getURL(action, collection, reference, absolute);
}
private static String getURL(String action, MCRCollection collection, MCRCategLinkReference categoryReference,
boolean absolute) {
for (MCRAction act : collection.getActions()) {
if (act.getAction().equals(action)) {
if (LOGGER.isDebugEnabled()) {
String mcrId = categoryReference == null ? null : categoryReference.getObjectID();
LOGGER.debug("Collection: {}, Action: {}, Object: {}", collection.getName(), action, mcrId);
}
String url = act.getURL(new MCRWorkflowData(categoryReference));
if (absolute && url != null && url.startsWith("/")) {
url = MCRFrontendUtil.getBaseURL() + url.substring(1);
}
return url;
}
}
return null;
}
private static MCRCollection getCollectionWithAction(String collection, String action,
MCRCollection defaultCollection) {
MCRCollection mcrCollection = COLLECTION_MAP.get(collection);
if (mcrCollection != null) {
Optional<MCRAction> firstAction = Arrays
.stream(mcrCollection.getActions())
.filter(a -> a.getAction().equals(action))
.findFirst();
if (firstAction.isPresent()) {
return mcrCollection;
}
}
//did not find a collection with that action, checking parent
String parentCollection = getParentCollection(collection);
String defaultCollectionName = defaultCollection == null ? null : defaultCollection.getName();
if (parentCollection == null) {
LOGGER.debug("Using default collection '{}' for action: {}", defaultCollectionName, action);
return defaultCollection;
}
LOGGER.debug("Checking parent collection '{}' for action: {}", parentCollection, action);
MCRCollection collectionWithAction = getCollectionWithAction(parentCollection, action, defaultCollection);
if (collectionWithAction == null) {
LOGGER.debug("Using default collection '{}' for action: {}", defaultCollectionName, action);
return defaultCollection;
}
if (mcrCollection == null) {
mcrCollection = new MCRCollection();
mcrCollection.setName(collection);
mcrCollection.setActions();
}
for (MCRAction act : collectionWithAction.getActions()) {
if (act.getAction().equals(action)) {
int oldLength = mcrCollection.getActions().length;
mcrCollection.setActions(Arrays.copyOf(mcrCollection.getActions(), oldLength + 1));
mcrCollection.getActions()[oldLength] = act;
}
}
//store in cache
COLLECTION_MAP.put(collection, mcrCollection);
return mcrCollection;
}
private static String getParentCollection(String collection) {
MCRCategoryID categoryId = new MCRCategoryID(MCRConstants.COLLECTION_CLASS_ID.getRootID(), collection);
List<MCRCategory> parents = CATEGORY_DAO.getParents(categoryId);
if (parents == null || parents.isEmpty()) {
return null;
}
return parents.iterator().next().getId().getId();
}
}
| 6,697 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRWorkflowRuleAdapter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRWorkflowRuleAdapter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import org.mycore.parsers.bool.MCRBooleanClauseParser;
import org.mycore.parsers.bool.MCRCondition;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
/**
* A JAXB XML Adapter that parses String to MCRCondition an back.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRWorkflowRuleAdapter extends XmlAdapter<String, MCRCondition<?>> {
private MCRBooleanClauseParser parser;
public MCRWorkflowRuleAdapter() {
parser = getClauseParser();
}
/**
* Returns a parser instance that is used in {@link #unmarshal(String)}.
* @return instance of {@link MCRWorkflowRuleParser}
*/
protected MCRBooleanClauseParser getClauseParser() {
return new MCRWorkflowRuleParser();
}
@Override
public MCRCondition<?> unmarshal(final String v) {
return parser.parse(v);
}
@Override
public String marshal(final MCRCondition<?> v) {
return v.toString();
}
}
| 1,716 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRActionMappingsManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRActionMappingsManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.wfc.MCRConstants;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRActionMappingsManager {
public static MCRActionMappings getActionMappings() throws TransformerException, JAXBException {
Source source = MCRURIResolver.instance().resolve("resource:actionmappings.xml", null);
Unmarshaller unmarshaller = MCRConstants.JAXB_CONTEXT.createUnmarshaller();
JAXBElement<MCRActionMappings> jaxbElement = unmarshaller.unmarshal(source, MCRActionMappings.class);
return jaxbElement.getValue();
}
}
| 1,574 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassificationUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-wfc/src/main/java/org/mycore/wfc/actionmapping/MCRClassificationUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.wfc.actionmapping;
import java.util.Collection;
import org.mycore.datamodel.classifications2.MCRCategLinkReference;
import org.mycore.datamodel.classifications2.MCRCategLinkService;
import org.mycore.datamodel.classifications2.MCRCategLinkServiceFactory;
import org.mycore.datamodel.classifications2.MCRCategoryID;
import org.mycore.datamodel.common.MCRLinkTableManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.wfc.MCRConstants;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRClassificationUtils {
private static final MCRCategLinkService LINK_SERVICE = MCRCategLinkServiceFactory.getInstance();
private static final MCRLinkTableManager LINK_TABLE = MCRLinkTableManager.instance();
public static boolean isInCollection(String mcrId, String collection) {
MCRObjectID mcrObjectID = MCRObjectID.getInstance(mcrId);
MCRCategoryID collectionID = new MCRCategoryID(MCRConstants.COLLECTION_CLASS_ID.getRootID(), collection);
MCRCategLinkReference reference = new MCRCategLinkReference(mcrObjectID);
return LINK_SERVICE.isInCategory(reference, collectionID);
}
public static String getCollection(String mcrId) {
MCRObjectID mcrObjectID = MCRObjectID.getInstance(mcrId);
if (mcrObjectID.getTypeId().equals("derivate")) {
return getCollectionFromDerivate(mcrObjectID);
}
return getCollectionFromObject(mcrObjectID);
}
private static String getCollectionFromObject(MCRObjectID mcrObjectID) {
MCRCategLinkReference reference = new MCRCategLinkReference(mcrObjectID);
return LINK_SERVICE.getLinksFromReference(reference)
.stream()
.filter(categID -> categID.getRootID()
.equals(MCRConstants.COLLECTION_CLASS_ID.getRootID()))
.findFirst()
.map(MCRCategoryID::getId)
.orElse(null);
}
private static String getCollectionFromDerivate(MCRObjectID mcrObjectID) {
Collection<String> sourceOf = LINK_TABLE.getSourceOf(mcrObjectID, MCRLinkTableManager.ENTRY_TYPE_DERIVATE);
if (sourceOf.isEmpty()) {
return null;
}
MCRObjectID metaObjectID = MCRObjectID.getInstance(sourceOf.iterator().next());
return getCollectionFromObject(metaObjectID);
}
}
| 3,082 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ViewerTestBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/ViewerTestBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.mycore.common.selenium.MCRSeleniumTestBase;
import org.mycore.iview.tests.controller.ApplicationController;
import org.mycore.iview.tests.controller.ImageViewerController;
import org.mycore.iview.tests.model.TestDerivate;
public abstract class ViewerTestBase extends MCRSeleniumTestBase {
private static final String APPLICATION_CONTROLLER_PROPERTY_NAME = "test.viewer.applicationController";
public static final String BASE_URL = "test.application.url.hostName";
private ImageViewerController viewerController;
private static ApplicationController appController = null;
private ApplicationController applicationController;
@Before
public void setUp() {
initController();
getAppController().setUpDerivate(this.getDriver(), getTestDerivate());
}
@After
public void tearDown() {
this.takeScreenshot();
}
@AfterClass
public static void tearDownClass() {
appController.shutDownDerivate(driver, null);
driver.quit();
}
public String getClassname() {
return getClass().getName();
}
public void initController() {
this.setViewerController(new ImageViewerController(this.getDriver()));
if (appController == null) {
ApplicationController applicationController = getApplicationControllerInstance();
this.setAppController(applicationController);
}
}
private ApplicationController getApplicationControllerInstance() {
if (applicationController == null) {
String applicationControllerClassName = TestProperties.getInstance().getProperty(
APPLICATION_CONTROLLER_PROPERTY_NAME);
applicationController = TestUtil.instantiate(applicationControllerClassName,
ApplicationController.class);
applicationController.init();
}
return applicationController;
}
public abstract TestDerivate getTestDerivate();
public ApplicationController getAppController() {
return appController;
}
private void setAppController(ApplicationController appController) {
ViewerTestBase.appController = appController;
}
public ImageViewerController getViewerController() {
return viewerController;
}
private void setViewerController(ImageViewerController viewerController) {
this.viewerController = viewerController;
}
}
| 3,279 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
TestProperties.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/TestProperties.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests;
import java.io.IOException;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class TestProperties extends Properties {
private static final long serialVersionUID = -1135672087633884258L;
private static final Logger LOGGER = LogManager.getLogger(TestProperties.class);
public static final String TEST_PROPERTIES = "test.properties";
private TestProperties() {
LOGGER.info("Load TestProperties");
try {
load(TestProperties.class.getClassLoader().getResourceAsStream(TEST_PROPERTIES));
} catch (IOException e) {
LOGGER.error("Error while loading test properties!");
}
}
private static TestProperties singleton = null;
public static synchronized TestProperties getInstance() {
if (TestProperties.singleton == null) {
TestProperties.singleton = new TestProperties();
}
return TestProperties.singleton;
}
@Override
public String getProperty(String key, String defaultValue) {
return System.getProperty(key, super.getProperty(key, defaultValue));
}
@Override
public String getProperty(String key) {
return System.getProperty(key, super.getProperty(key));
}
}
| 2,058 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
TestUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/TestUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class TestUtil {
public static <T> T instantiate(final String className, final Class<T> type) {
try {
return type.cast(Class.forName(className).getDeclaredConstructor().newInstance());
} catch (final ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
public static InetAddress getLocalAdress(String remoteHost, int port) throws IOException {
InetSocketAddress socketAddr = new InetSocketAddress(remoteHost, port);
SocketChannel socketChannel = SocketChannel.open(socketAddr);
InetSocketAddress localAddress = (InetSocketAddress) socketChannel.getLocalAddress();
return localAddress.getAddress();
}
}
| 1,620 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
StructureOverviewController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/StructureOverviewController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/**
* @author Sebastian Röher (basti890)
*
*/
public class StructureOverviewController extends SideBarController {
public static final String CHAPTER_OVERVIEW_SELECTOR = "chapterOverview";
private static final Logger LOGGER = LogManager.getLogger(StructureOverviewController.class);
/**
* @param webdriver
*/
public StructureOverviewController(WebDriver webdriver) {
super(webdriver);
}
/**
* builds xpath and calls function {@link SideBarController#clickElementByXpath(String)}
* @param orderLabel
*/
public void selectImageByOrder(String orderLabel) {
String xpath = new MessageFormat("//li/a[../span[@class=\"childLabel\" and contains(text(),\"{0}\")]"
+ "]|//li/a[contains(text(),\"{0}\")]", Locale.ROOT).format(new String[] { orderLabel });
clickElementByXpath(xpath);
}
public boolean isImageSelected(String orderLabel) {
String xPath = new MessageFormat("//li[./span[@class=\"childLabel\" and contains(text(),\"{0}\")]|"
+ "./a[contains(text(),\"{0}\")]]", Locale.ROOT).format(new String[] { orderLabel });
return assertAttributeByXpath(xPath, "data-selected", true);
}
/**
* test all div's with class="childLabel"
*
* @return false if any div with class="childLabel" has "undefined as content else true
*/
public boolean hasUndefinedPageLabels() {
By selector = By.xpath("//span[@class=\"childLabel\"]");
List<WebElement> element = this.getDriver().findElements(selector);
for (WebElement webElement : element) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", element.toString(), selector.toString());
}
String text = webElement.getText();
if ("undefined".equalsIgnoreCase(text)) {
return true;
}
}
return false;
}
}
| 3,010 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ImageViewerController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/ImageViewerController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import org.openqa.selenium.WebDriver;
public class ImageViewerController extends WebDriverController {
private ToolBarController toolBarController;
private SideBarController sideBarController;
private ImageOverviewController imageOverviewController;
private StructureOverviewController structureOverviewController;
public ImageViewerController(WebDriver webdriver) {
super(webdriver);
this.toolBarController = new ToolBarController(webdriver);
this.sideBarController = new SideBarController(webdriver);
this.imageOverviewController = new ImageOverviewController(webdriver);
this.structureOverviewController = new StructureOverviewController(webdriver);
}
@Override
public void setDriver(WebDriver driver) {
super.setDriver(driver);
getToolBarController().setDriver(driver);
getSideBarController().setDriver(driver);
getImageOverviewController().setDriver(driver);
getStructureOverviewController().setDriver(driver);
}
public ToolBarController getToolBarController() {
return toolBarController;
}
public SideBarController getSideBarController() {
return sideBarController;
}
public ImageOverviewController getImageOverviewController() {
return imageOverviewController;
}
public StructureOverviewController getStructureOverviewController() {
return structureOverviewController;
}
}
| 2,242 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
DefaultApplicationController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/DefaultApplicationController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.selenium.MCRSeleniumTestBase;
import org.mycore.iview.tests.model.TestDerivate;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DefaultApplicationController extends ApplicationController {
private static final String webpath = "target/test-classes/testFiles";
private static Map<TestDerivate, String> derivateHTMLMapping;
private static final Logger LOGGER = LogManager.getLogger();
@Override
public void init() {
DefaultApplicationController.derivateHTMLMapping = new HashMap<>();
}
@Override
public void setUpDerivate(WebDriver webdriver, TestDerivate testDerivate) {
Path target = Paths.get(webpath);
if (!Files.exists(target)) {
try (InputStream is = MCRSeleniumTestBase.class.getClassLoader().getResourceAsStream("testFiles.zip");
ZipInputStream zis = new ZipInputStream(is)) {
extractZip(target.getParent().toAbsolutePath().toString(), zis);
} catch (IOException e) {
LOGGER.error("Could not unzip testFiles.zip", e);
}
}
if (!derivateHTMLMapping.containsKey(testDerivate)) {
try {
String name = testDerivate.getName();
if (testDerivate.getStartFile().endsWith(".pdf")) {
buildHTMLFile(name, testDerivate.getStartFile(), "MyCoRePDFViewer");
} else {
buildHTMLFile(name, testDerivate.getStartFile(), "MyCoReImageViewer");
}
DefaultApplicationController.derivateHTMLMapping.put(testDerivate, buildFileName(name));
} catch (IOException e) {
LOGGER.error("Error while open connection to File Location!", e);
}
}
}
protected String buildHTMLFile(String name, String startFile, String page) throws IOException {
try (InputStream viewerHTMLFileStream = DefaultApplicationController.class.getClassLoader()
.getResourceAsStream("testStub/" + page + ".html")) {
String content = IOUtils.toString(viewerHTMLFileStream, StandardCharsets.UTF_8);
String result = content.replace("{$name}", name).replace("{$startFile}", startFile).replace("{$baseUrl}",
MCRSeleniumTestBase.getBaseUrl(System.getProperty("BaseUrlPort")) + "/test-classes/testFiles/");
String fileName = buildFileName(name);
String resultLocation = webpath + "/" + fileName;
File resultFile = new File(resultLocation);
resultFile.getParentFile().mkdirs();
try (FileOutputStream resultStream = new FileOutputStream(resultFile)) {
IOUtils.write(result, resultStream, Charset.defaultCharset());
}
return resultLocation;
}
}
private String buildFileName(String name) {
return name + ".html";
}
@Override
public void shutDownDerivate(WebDriver webdriver, TestDerivate testDerivate) {
}
@Override
public void openViewer(WebDriver webdriver, TestDerivate testDerivate) {
String path = null;
path = MCRSeleniumTestBase.getBaseUrl(System.getProperty("BaseUrlPort")) + "/test-classes/testFiles/"
+ DefaultApplicationController.derivateHTMLMapping.get(testDerivate);
LOGGER.info("Open Viewer with path : {}", path);
webdriver.navigate().to(path);
WebDriverWait wait = new WebDriverWait(webdriver, 5000);
wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By.xpath("/.//ol[contains(@class, 'chapterTreeDesktop')]")));
}
private void extractZip(String dest, ZipInputStream zipInputStream) throws IOException {
ZipEntry nextEntry;
zipInputStream.available();
while ((nextEntry = zipInputStream.getNextEntry()) != null) {
String entryName = nextEntry.getName();
String fileName = dest + "/" + entryName;
File localFile = new File(fileName);
if (nextEntry.isDirectory()) {
localFile.mkdir();
} else {
localFile.createNewFile();
try (FileOutputStream localFileOutputStream = new FileOutputStream(localFile)) {
IOUtils.copyLarge(zipInputStream, localFileOutputStream, 0, nextEntry.getSize());
}
}
zipInputStream.closeEntry();
}
zipInputStream.close();
LOGGER.info("File download complete!");
}
}
| 5,965 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
WebDriverController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/WebDriverController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
/**
* @author Sebastian Röher (basti890)
*
*/
public class WebDriverController {
private WebDriver driver;
private static final Logger LOGGER = LogManager.getLogger(WebDriverController.class);
/**
* @param driver
*/
public WebDriverController(WebDriver driver) {
this.driver = driver;
}
public WebDriver getDriver() {
return driver;
}
public void setDriver(WebDriver driver) {
this.driver = driver;
}
/**
* clicks the first element specified by <b>xPath</b>
*
* @param xpath
*/
public void clickElementByXpath(String xpath) {
By selector = By.xpath(xpath);
WebElement element = getDriver().findElement(selector);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", element.toString(), selector.toString());
}
element.click();
}
/**
* clicks on the first element specified by the <b>xPath</b> and drags it <b>offestX</b> pixels horizontal and <b>offsetY</b> pixels vertical
*
* @param xPath
* @param offsetX
* @param offsetY
*/
public void dragAndDropByXpath(String xPath, int offsetX, int offsetY) {
By selector = By.xpath(xPath);
WebElement element = getDriver().findElement(selector);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", element.toString(), selector.toString());
}
Actions builder = new Actions(getDriver());
builder.dragAndDropBy(element, offsetX, offsetY).perform();
}
/**
* compares the Elements <b>attribute</b>-value to the <b>assertion</b>
*
* @param attribute
* @param assertion
* @param xPath
*
* @return true if the <b>attribute</b> has <b>assertion</b> as value
*/
public boolean assertAttributeByXpath(String xPath, String attribute, boolean assertion) {
return assertAttributeByXpath(xPath, attribute, Boolean.toString(assertion).toLowerCase());
}
/**
* compares the Elements <b>attribute</b>-value to the <b>assertion</b>
*
* @param attribute
* @param assertion
* @param xPath
*
* @return true if the <b>attribute</b> has <b>assertion</b> as value
*/
public boolean assertAttributeByXpath(String xPath, String attribute, String assertion) {
By selector = By.xpath(xPath);
List<WebElement> element = getDriver().findElements(selector);
for (WebElement webElement : element) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", webElement.toString(), selector.toString());
}
if (webElement.getAttribute(attribute) != null) {
return webElement.getAttribute(attribute).contains(assertion);
}
}
LOGGER.error("Element {} or Attribute '{}' not fot found!", xPath, attribute);
return false;
}
/**
* checks if there is any Element in the dom got with the <b>attribute</b> that contains the <b>value</b>
*
* @param attribute
* @param value
* @return true if an element is found
*/
public boolean assertElementByAttributePresent(String attribute, String value) {
By selector = By.xpath(
new MessageFormat("//*[contains(@{0},\"{1}\")]", Locale.ROOT).format(new Object[] { attribute, value }));
List<WebElement> elements = getDriver().findElements(selector);
if (elements.isEmpty()) {
LOGGER.error("No element with attribute '{}' and value '{}' found!", attribute, value);
return false;
}
for (WebElement webElement : elements) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", webElement.toString(), selector.toString());
}
}
return true;
}
}
| 5,077 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ToolBarController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/ToolBarController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
/**
* @author Sebastian Röher (basti890)
*/
public class ToolBarController extends WebDriverController {
public static final String BUTTON_ID_ZOOM_IN = "ZoomInButton";
public static final String BUTTON_ID_ZOOM_OUT = "ZoomOutButton";
public static final String BUTTON_ID_ZOOM_WIDTH = "ZoomWidthButton";
public static final String BUTTON_ID_ZOOM_FIT = "ZoomFitButton";
public static final String BUTTON_ID_PREV_IMG = "PreviousImageButton";
public static final String BUTTON_ID_NEXT_IMG = "NextImageButton";
public static final String BUTTON_ID_SIDEBAR_CONTROLL = "SidebarControllDropdownButton";
private static final String BUTTON_SELECTOR_PATTERN = ".btn[data-id={0}]";
private static final String ELEMENT_SELECTOR_PATTERN = "[data-id={0}]";
private static final String SELECTBOX_SELECTOR = "[data-id=ImageChangeControllGroup] select.dropdown";
private static final Logger LOGGER = LogManager.getLogger(ToolBarController.class);
public ToolBarController(WebDriver webdriver) {
super(webdriver);
}
/**
* clicks the first element with class="btn" and data-id="<b>id</b>"
*
* @param id
*/
public void pressButton(String id) {
By selector = By
.cssSelector(new MessageFormat(BUTTON_SELECTOR_PATTERN, Locale.ROOT).format(new String[] { id }));
WebElement element = this.getDriver().findElement(selector);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", element.toString(), selector.toString());
}
element.click();
}
/**
* clicks the first element with data-id="<b>id</b>"
*
* @param id
*/
public void clickElementById(String id) {
int trys = 10;
By selector = By
.cssSelector(new MessageFormat(ELEMENT_SELECTOR_PATTERN, Locale.ROOT).format(new String[] { id }));
WebElement element = getNotStaleElement(trys, selector);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", element.toString(), selector.toString());
}
List<WebElement> webElements = getDriver().findElements(selector);
if (webElements.size() != 1) {
LOGGER.warn("Multiple Elements found!");
}
element.click();
}
// TODO: do this better!
private WebElement getNotStaleElement(int trys, By selector) {
if (trys <= 0) {
throw new IllegalArgumentException("trys should be more then 0! [" + trys + "]");
}
Exception sere = null;
while (--trys > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
try {
WebElement element = this.getDriver().findElement(selector);
element.isEnabled();
return element;
} catch (StaleElementReferenceException e) {
sere = e;
LOGGER.debug("Stale check failed! [{}]", trys);
}
}
throw new RuntimeException(sere);
}
/**
* selects the first picture with the label <b>orderLabel</b> in the selectbox
*
* @param orderLabel
*/
public void selectPictureWithOrder(String orderLabel) {
By selector = By.cssSelector(SELECTBOX_SELECTOR);
WebElement element = this.getDriver().findElement(selector);
Select select = new Select(element);
select.selectByVisibleText(orderLabel);
}
/**
* checks if the image with the <b>orderLabel</b> is selected
*
* @param oderLabel
* @return true if the if the image with the <b>orderLabel</b> is selected
*/
public boolean isImageSelected(String oderLabel) {
By selector = By.cssSelector(SELECTBOX_SELECTOR);
WebElement element = this.getDriver().findElement(selector);
Select select = new Select(element);
return select != null && select.getFirstSelectedOption() != null
&& select.getFirstSelectedOption().getText().equalsIgnoreCase(oderLabel);
}
}
| 5,296 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ApplicationController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/ApplicationController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import org.mycore.iview.tests.model.TestDerivate;
import org.openqa.selenium.WebDriver;
public abstract class ApplicationController {
public ApplicationController() {
}
public abstract void init();
public abstract void setUpDerivate(WebDriver webdriver, TestDerivate testDerivate);
public abstract void shutDownDerivate(WebDriver webdriver, TestDerivate testDerivate);
public abstract void openViewer(WebDriver webdriver, TestDerivate testDerivate);
}
| 1,252 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ControllerUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/ControllerUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.iview.tests.TestProperties;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class ControllerUtil {
private static final Logger LOGGER = LogManager.getLogger(ControllerUtil.class);
private static final Properties TEST_PROPERTIES = TestProperties.getInstance();
public static final String RESULT_FOLDER = "test.result.folder";
public static final String SCREENSHOT_FOLDER = TEST_PROPERTIES.getProperty(RESULT_FOLDER) + "/screenshots/";
/**
* Waits until the Page is fully loaded
*
* @param driver
*/
public static void waitForPageReady(WebDriver driver) {
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
}
/**
* gets a screenshot from the browsers content
*
* @param driver
* @return screenshot
*/
public static BufferedImage getScreenshot(WebDriver driver, String name) {
if (driver instanceof TakesScreenshot screenshot) {
try {
Thread.sleep(1000);
ByteArrayInputStream input = new ByteArrayInputStream(screenshot.getScreenshotAs(OutputType.BYTES));
byte[] imageBytes = IOUtils.toByteArray(input);
new File(SCREENSHOT_FOLDER).mkdirs();
IOUtils.copy(new ByteArrayInputStream(imageBytes),
new FileOutputStream(new File(SCREENSHOT_FOLDER + name + ".png")));
return ImageIO.read(new ByteArrayInputStream(imageBytes));
} catch (IOException e) {
LOGGER.error("Error while taking screenshot!");
throw new UnsupportedOperationException("Error while taking screenshot!", e);
} catch (InterruptedException e) {
LOGGER.error("Error while taking screenshot!");
throw new RuntimeException("Error while taking screenshot!", e);
}
} else {
throw new UnsupportedOperationException(
"Error while taking screenshot! (driver not instanceof TakesScreenshot)");
}
}
}
| 3,294 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ScrollUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/ScrollUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class ScrollUtil {
public static void scrollByXpath(WebDriver driver, String xPath, int offestX) {
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].scrollTop = arguments[0].scrollTop + arguments[1];",
driver.findElement(By.xpath(xPath)), offestX);
}
}
| 1,222 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
SideBarController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/SideBarController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class SideBarController extends WebDriverController {
public static final String SIDEBAR_CLOSE_SELECTOR = "//button[@class=\"close\"]";
private static final Logger LOGGER = LogManager.getLogger(SideBarController.class);
public SideBarController(WebDriver webdriver) {
super(webdriver);
}
/**
* checks the width of the sidebar
* @param width
* @return
*/
public boolean assertSideBarWidth(int width) {
return getSideBarWidth() == width;
}
/**
* checks the width of the sidebar-div (default is 300px)
* @return true if the width is greater than 2px (2px cause the width of the border will be counted too)
*/
public boolean assertSideBarPresent() {
return getSideBarWidth() > 2;
}
/**
* @return the width of the sidebar
*/
public int getSideBarWidth() {
By selector = By.xpath("//div[contains(@class,\"sidebar\")]");
WebElement element = getDriver().findElement(selector);
if (element == null) {
LOGGER.error("No element with xpath: '{}' found!", selector.toString());
throw new NoSuchElementException();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found ''{}'' with selector :''{}''", element.toString(), selector.toString());
}
return element.getSize().getWidth();
}
/**
* counts the div's, that contain 'thumbnail' in their class-attribute
*
* @return number of thumbnail-div's
*/
public int countThumbnails() {
By selector = By.xpath("//div[contains(@class,\"thumbnail\")]/div[@class='imgSpacer']");
List<WebElement> elements = getDriver().findElements(selector);
return elements.size();
}
/**
* scrolls <b>offestX</b> pixels vertically in the sidebar
*
* @param driver
* @param offestX
*/
public void scrollSidbar(WebDriver driver, int offestX) {
ScrollUtil.scrollByXpath(driver,
"//div[contains(@class,\"sidebar\")]/div[./div[contains(@class,\"thumbnail\")]]", 250);
}
}
| 3,153 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ImageOverviewController.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/controller/ImageOverviewController.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.controller;
import java.util.Locale;
import org.openqa.selenium.WebDriver;
/**
* @author Sebastian Röher (basti890)
*
*/
public class ImageOverviewController extends SideBarController {
public static final String IMAGE_OVERVIEW_SELECTOR = "imageOverview";
/**
* @param webdriver
*/
public ImageOverviewController(WebDriver webdriver) {
super(webdriver);
}
/**
* builds xpath for and calls function {@link SideBarController#clickElementByXpath(String)}
* @param orderLabel
*/
public void clickImageByOrder(String orderLabel) {
clickElementByXpath(
String.format(Locale.ROOT, "//div[@class=\"caption\" and contains(text(),\"%s\")]", orderLabel));
}
/**
* checks if the Image is selected
*
* @param orderLabel
* @return true if the div of the Image has the class "selected"
*/
public boolean isImageSelected(String orderLabel) {
String xPath = String.format(Locale.ROOT, "//div[./div[@class=\"caption\" and contains(text(),\"%s\")]]",
orderLabel);
return assertAttributeByXpath(xPath, "class", "selected");
}
}
| 1,924 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
FilterSelection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/FilterSelection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
import java.util.ArrayList;
import java.util.List;
public class FilterSelection extends Selection {
public FilterSelection(Selection fs, PixelFilter filter) {
this.source = fs;
this.filter = filter;
}
private Selection source;
private PixelFilter filter;
@Override
public List<Pixel> getPixel() {
List<Pixel> pixels = this.source.getPixel();
List<Pixel> filteredPixels = new ArrayList<>();
for (Pixel pixel : pixels) {
if (filter.filter(pixel)) {
filteredPixels.add(pixel);
}
}
return filteredPixels;
}
}
| 1,405 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
DebugBufferedImageWindow.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/DebugBufferedImageWindow.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class DebugBufferedImageWindow extends JFrame {
private static final long serialVersionUID = 1L;
private BufferedImage imageToShow;
public DebugBufferedImageWindow(BufferedImage imageToShow) {
super("Debug-Window");
this.imageToShow = imageToShow;
setSize(imageToShow.getWidth(), imageToShow.getHeight());
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(imageToShow, 0, 0, null);
}
}
| 1,480 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Position.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/Position.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
public class Position {
public Position(int x, int y) {
this.x = x;
this.y = y;
}
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
| 1,131 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Selection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/Selection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public abstract class Selection {
private static final Logger LOGGER = LogManager.getLogger(Selection.class);
/**
* @return a List of all Pixel wich contains this selection
*/
public abstract List<Pixel> getPixel();
/**
* @return returns a hashmap wich contains the position as key and the pixel as value
*/
public Map<Position, Pixel> getPositionPixelMap() {
HashMap<Position, Pixel> positionPixelHashMap = new HashMap<>();
List<Pixel> pixels = this.getPixel();
for (Pixel p : pixels) {
positionPixelHashMap.put(p.getPosition(), p);
}
return positionPixelHashMap;
}
/**
* Creates a selection of all Pixel of a Buffered image
*
* @param bufferedImage the buffered image from wich the selection should be created
* @return the selection
*/
public static Selection fromBufferedImage(BufferedImage bufferedImage) {
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
final ArrayList<Pixel> p = new ArrayList<>();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
p.add(new Pixel(new Color(bufferedImage.getRGB(x, y)), new Position(x, y)));
}
}
return new Selection() {
@Override
public List<Pixel> getPixel() {
return p;
}
};
}
public Position getUpperLeft() {
Map<Position, Pixel> positionPixelMap = this.getPositionPixelMap();
Set<Position> positionSet = positionPixelMap.keySet();
LOGGER.debug("getUpperLeft: ");
int upper = 100000;
int left = 100000;
LOGGER.debug(String.format("(Positions : %d )", positionSet.size()));
for (Position position : positionSet) {
if (position.getX() < left) {
left = position.getX();
}
if (position.getY() < upper) {
upper = position.getY();
}
}
LOGGER.debug("upper: {}", upper);
LOGGER.debug("left: {}", left);
return new Position(left, upper);
}
public Position getLowerRight() {
Map<Position, Pixel> positionPixelMap = this.getPositionPixelMap();
Set<Position> positionSet = positionPixelMap.keySet();
LOGGER.debug("getLowerRight: ");
int lower = 0;
int right = 0;
LOGGER.debug(String.format("(Positions : %d )", positionSet.size()));
for (Position position : positionSet) {
if (position.getX() > right) {
right = position.getX();
}
if (position.getY() > lower) {
lower = position.getY();
}
}
LOGGER.debug("lower: {}", lower);
LOGGER.debug("right: {}", right);
return new Position(right, lower);
}
public BufferedImage toBufferedImage() {
Position upperLeft = this.getUpperLeft();
Position lowerRight = this.getLowerRight();
BufferedImage result = new BufferedImage(lowerRight.getX() - upperLeft.getX() + 1,
lowerRight.getY() - upperLeft.getY() + 1, BufferedImage.TYPE_INT_RGB);
Map<Position, Pixel> positionPixelMap = this.getPositionPixelMap();
Set<Position> positionSet = positionPixelMap.keySet();
LOGGER.debug("start-Set-RGB()");
for (Position position : positionSet) {
result.setRGB(position.getX() - upperLeft.getX(), position.getY() - upperLeft.getY(),
positionPixelMap.get(position).getColor().getRGB());
}
LOGGER.debug("end-Set-RGB()");
return result;
}
}
| 4,770 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
PixelFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/PixelFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
public interface PixelFilter {
/**
* Filters a Pixel
* @param pixel the pixel to check
* @return true if the pixel should be appear in new Selection
*/
boolean filter(Pixel pixel);
}
| 981 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ColorFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/ColorFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
import java.awt.Color;
public class ColorFilter implements PixelFilter {
public ColorFilter(Color colorToFilter, boolean throwOut, int tolerance) {
this.colorToFilter = colorToFilter;
this.throwOut = throwOut;
this.tolerance = tolerance;
}
private final Color colorToFilter;
private final boolean throwOut;
private final int tolerance;
@Override
public boolean filter(Pixel pixel) {
Color color = pixel.getColor();
if (color.equals(colorToFilter)) {
return throwOut;
} else {
int red = color.getRed();
int blue = color.getBlue();
int green = color.getGreen();
int redDiff = Math.abs(red - colorToFilter.getRed());
int blueDiff = Math.abs(green - colorToFilter.getGreen());
int greenDiff = Math.abs(blue - colorToFilter.getBlue());
return (redDiff + blueDiff + greenDiff > tolerance) ^ !(throwOut);
}
}
}
| 1,766 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Pixel.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/image/api/Pixel.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.image.api;
import java.awt.Color;
public class Pixel {
public Pixel(Color color, Position position) {
this.color = color;
this.position = position;
}
private Color color;
private Position position;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
}
| 1,287 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
StructureOverviewIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/StructureOverviewIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.ViewerTestBase;
import org.mycore.iview.tests.controller.ControllerUtil;
import org.mycore.iview.tests.controller.ImageViewerController;
import org.mycore.iview.tests.controller.StructureOverviewController;
import org.mycore.iview.tests.controller.ToolBarController;
import org.mycore.iview.tests.image.api.ColorFilter;
import org.mycore.iview.tests.image.api.FilterSelection;
import org.mycore.iview.tests.image.api.Selection;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class StructureOverviewIT extends ViewerTestBase {
private static final String RGB_LABEL = "rgb.tiff";
private static final String RED_LABEL = "r.png";
private static final String GREEN_LABEL = "g.png";
private static final String BLUE_LABEL = "b.png";
private static final int TOLERANCE = 20;
private static final Logger LOGGER = LogManager.getLogger(StructureOverviewIT.class);
@Test
/**
* Checks if the structure Overview loaded from mets.xml works!
* @throws IOException
* @throws InterruptedException
*/
public void testStructureOverview() throws InterruptedException {
this.setTestName(getClassname() + "-testStructureOverview");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
StructureOverviewController soController = controller.getStructureOverviewController();
tbController.pressButton(ToolBarController.BUTTON_ID_SIDEBAR_CONTROLL);
Thread.sleep(1000);
tbController.clickElementById(StructureOverviewController.CHAPTER_OVERVIEW_SELECTOR);
int greenPixelCount = selectImgAndCountColor(soController, getGreenLabel(), Color.GREEN);
int redPixelCount = selectImgAndCountColor(soController, getRedLabel(), Color.RED);
int bluePixelCount = selectImgAndCountColor(soController, getBlueLabel(), Color.BLUE);
int redPixelCountRGB = selectImgAndCountColor(soController, getRgbLabel(), Color.RED);
int greenPixelCountRGB = selectImgAndCountColor(soController, getRgbLabel(), Color.GREEN);
int bluePixelCountRGB = selectImgAndCountColor(soController, getRgbLabel(), Color.BLUE);
String messagePattern = "There should be less red pixels in the rgb screenshot than in the red ({0} > {1})";
assertLess(redPixelCount, redPixelCountRGB, messagePattern);
messagePattern = "There should be less green pixels in the rgb screenshot than in the red ({0} > {1})";
assertLess(greenPixelCount, greenPixelCountRGB, messagePattern);
messagePattern = "There should be less blue pixels in the rgb screenshot than in the red ({0} > {1})";
assertLess(bluePixelCount, bluePixelCountRGB, messagePattern);
Assert.assertFalse("There should´nt be any 'undefined' page labels.", soController.hasUndefinedPageLabels());
}
/**
* selects an image with {@link StructureOverviewController#selectImageByOrder(String)} and counts Pixels of the color
*
* @param soController
* @param label
* @param color
* @return
* @throws InterruptedException
*/
private int selectImgAndCountColor(StructureOverviewController soController, String label, Color color)
throws InterruptedException {
soController.selectImageByOrder(label);
Thread.sleep(500);
String message = color + " schould be selected (class-attribut 'selected' should be set)!";
Assert.assertTrue(message, soController.isImageSelected(label));
String fileName = String.format("%s-%s-%s", this.getClassname(), label, color);
BufferedImage bImage = ControllerUtil.getScreenshot(getDriver(), fileName);
return getColorCount(bImage, color);
}
/**
* Gets the count of pixel with a specific color
* @param image
* @param color
* @return
*/
private int getColorCount(BufferedImage image, Color color) {
return new FilterSelection(Selection.fromBufferedImage(image), new ColorFilter(color, false, TOLERANCE))
.getPixel().size();
}
private void assertLess(int moreValue, int lessValue, String messagePattern) {
String message = new MessageFormat(messagePattern, Locale.ROOT).format(new Object[] { lessValue, moreValue });
LOGGER.debug(message);
Assert.assertTrue(message, lessValue < moreValue);
}
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.RGB_TEST_DERIVATE;
}
/**
* @return the greenLabel
*/
public String getGreenLabel() {
return GREEN_LABEL;
}
/**
* @return the redLabel
*/
public String getRedLabel() {
return RED_LABEL;
}
/**
* @return the blueLabel
*/
public String getBlueLabel() {
return BLUE_LABEL;
}
/**
* @return the rgbLabel
*/
public String getRgbLabel() {
return RGB_LABEL;
}
}
| 6,345 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
PDFStructureIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/PDFStructureIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class PDFStructureIT extends StructureOverviewIT {
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.PDF_TEST_DERIVATE;
}
@Override
public String getGreenLabel() {
return "g.png";
}
@Override
public String getRedLabel() {
return "r.png";
}
@Override
public String getBlueLabel() {
return "b.png";
}
@Override
public String getRgbLabel() {
return "rgb.png";
}
}
| 1,479 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
PDFImageOverviewIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/PDFImageOverviewIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class PDFImageOverviewIT extends ImageOverviewIT {
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.PDF_TEST_DERIVATE;
}
@Override
public String getGreenLabel() {
return "2";
}
@Override
public String getRedLabel() {
return "1";
}
@Override
public String getBlueLabel() {
return "3";
}
@Override
public String getRgbLabel() {
return "4";
}
}
| 1,461 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ImageOverviewIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/ImageOverviewIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.ViewerTestBase;
import org.mycore.iview.tests.controller.ControllerUtil;
import org.mycore.iview.tests.controller.ImageOverviewController;
import org.mycore.iview.tests.controller.ImageViewerController;
import org.mycore.iview.tests.controller.ToolBarController;
import org.mycore.iview.tests.image.api.ColorFilter;
import org.mycore.iview.tests.image.api.FilterSelection;
import org.mycore.iview.tests.image.api.Selection;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class ImageOverviewIT extends ViewerTestBase {
private static final String RGB_LABEL = "rgb.tiff";
private static final String RED_LABEL = "r.png";
private static final String GREEN_LABEL = "g.png";
private static final String BLUE_LABEL = "b.png";
private static final int TOLERANCE = 20;
private static final Logger LOGGER = LogManager.getLogger(ImageOverviewIT.class);
@Test
/**
* Checks if the image overview works
* @throws IOException
* @throws InterruptedException
*/
public void testImageOverview() throws InterruptedException {
this.setTestName(getClassname() + "-testImageOverview");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
ImageOverviewController ioController = controller.getImageOverviewController();
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_IN);
tbController.pressButton(ToolBarController.BUTTON_ID_SIDEBAR_CONTROLL);
tbController.clickElementById(ImageOverviewController.IMAGE_OVERVIEW_SELECTOR);
Thread.sleep(500);
int greenPixelCount = clickImgAndCountColor(ioController, getGreenLabel(), Color.GREEN);
int redPixelCount = clickImgAndCountColor(ioController, getRedLabel(), Color.RED);
ioController.scrollSidbar(getDriver(), 250);
int bluePixelCount = clickImgAndCountColor(ioController, getBlueLabel(), Color.BLUE);
ioController.scrollSidbar(getDriver(), 250);
int redPixelCountRGB = clickImgAndCountColor(ioController, getRgbLabel(), Color.RED);
int greenPixelCountRGB = clickImgAndCountColor(ioController, getRgbLabel(), Color.GREEN);
int bluePixelCountRGB = clickImgAndCountColor(ioController, getRgbLabel(), Color.BLUE);
String messagePattern = "There should be less red pixels in the rgb screenshot than in the red ({0} > {1})";
assertLess(redPixelCount, redPixelCountRGB, messagePattern);
messagePattern = "There should be less green pixels in the rgb screenshot than in the green ({0} > {1})";
assertLess(greenPixelCount, greenPixelCountRGB, messagePattern);
messagePattern = "There should be less blue pixels in the rgb screenshot than in the blue ({0} > {1})";
assertLess(bluePixelCount, bluePixelCountRGB, messagePattern);
}
/**
* clicks an image via {@link ImageOverviewController#clickImageByOrder(String)} and counts the pixels of the color
*
* @param ioController
* @param label
* @param color
* @return
* @throws InterruptedException
*/
private int clickImgAndCountColor(ImageOverviewController ioController, String label, Color color)
throws InterruptedException {
ioController.clickImageByOrder(label);
Thread.sleep(500);
String message = label + " should be selected (class-attribut 'selected' should be set)!";
Assert.assertTrue(message, ioController.isImageSelected(label));
String fileName = String.format("%s-%s-%s-%s-%s", this.getClassname(), label, color.getRed(), color.getBlue(),
color.getGreen());
BufferedImage bImage = ControllerUtil.getScreenshot(getDriver(), fileName);
return getColorCount(bImage, color);
}
/**
* Gets the count of pixel with a specific color
* @param image
* @param color
* @return
*/
private int getColorCount(BufferedImage image, Color color) {
return new FilterSelection(Selection.fromBufferedImage(image), new ColorFilter(color, false, TOLERANCE))
.getPixel().size();
}
private void assertLess(int moreValue, int lessValue, String messagePattern) {
String message = new MessageFormat(messagePattern, Locale.ROOT).format(new Object[] { lessValue, moreValue });
LOGGER.debug(message);
Assert.assertTrue(message, lessValue < moreValue);
}
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.RGB_TEST_DERIVATE;
}
/**
* @return the greenLabel
*/
public String getGreenLabel() {
return GREEN_LABEL;
}
/**
* @return the redLabel
*/
public String getRedLabel() {
return RED_LABEL;
}
/**
* @return the blueLabel
*/
public String getBlueLabel() {
return BLUE_LABEL;
}
/**
* @return the rgbLabel
*/
public String getRgbLabel() {
return RGB_LABEL;
}
}
| 6,396 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
PDFImageSectionIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/PDFImageSectionIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class PDFImageSectionIT extends ImageSectionIT {
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.PDF_TEST_DERIVATE;
}
@Override
public String getStartImage() {
return "[4]";
}
}
| 1,235 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
SideBarIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/SideBarIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import java.text.MessageFormat;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.ViewerTestBase;
import org.mycore.iview.tests.controller.ImageOverviewController;
import org.mycore.iview.tests.controller.ImageViewerController;
import org.mycore.iview.tests.controller.SideBarController;
import org.mycore.iview.tests.controller.ToolBarController;
import org.mycore.iview.tests.model.TestDerivate;
import org.openqa.selenium.UnsupportedCommandException;
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class SideBarIT extends ViewerTestBase {
private static final Logger LOGGER = LogManager.getLogger(SideBarIT.class);
@Test
public void testSideBarPresent() {
this.setTestName(getClassname() + "-testSideBarPresent");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
SideBarController sbController = controller.getSideBarController();
tbController.pressButton(ToolBarController.BUTTON_ID_SIDEBAR_CONTROLL);
tbController.clickElementById(ImageOverviewController.IMAGE_OVERVIEW_SELECTOR);
Assert.assertTrue("SideBar should be present!", sbController.assertSideBarPresent());
tbController.clickElementByXpath(SideBarController.SIDEBAR_CLOSE_SELECTOR);
Assert.assertFalse("SideBar should not be present!", sbController.assertSideBarPresent());
}
@Test
/**
* Ignored because https://github.com/mozilla/geckodriver/issues/233
*/
public void testSideBarResize() {
this.setTestName(getClassname() + "-testSideBarResize");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
SideBarController sbController = controller.getSideBarController();
tbController.pressButton(ToolBarController.BUTTON_ID_SIDEBAR_CONTROLL);
tbController.clickElementById(ImageOverviewController.IMAGE_OVERVIEW_SELECTOR);
int sbWidthStart = sbController.getSideBarWidth();
try { // Firefox does not support actions so we just let the test pass.
sbController.dragAndDropByXpath("//div[contains(@class,\"sidebar\")]/span[@class=\"resizer\"]", 50, 0);
} catch (UnsupportedCommandException e) {
LOGGER.warn("Driver does not support Actions", e);
return;
}
int sbWidthEnd = sbController.getSideBarWidth();
assertLess(sbWidthEnd, sbWidthStart, "Sidebar width schould be increased!");
}
@Test
public void testOverviewLayout() throws InterruptedException {
this.setTestName(getClassname() + "-testOvervieLayout");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
SideBarController sbController = controller.getSideBarController();
tbController.pressButton(ToolBarController.BUTTON_ID_SIDEBAR_CONTROLL);
tbController.clickElementById(ImageOverviewController.IMAGE_OVERVIEW_SELECTOR);
int before = sbController.countThumbnails();
try {
sbController.dragAndDropByXpath("//div[contains(@class,'sidebar')]/span[@class='resizer']", 300, 0);
} catch (UnsupportedCommandException e) {
LOGGER.warn("Driver does not support Actions", e);
return;
}
Thread.sleep(1000);
int after = sbController.countThumbnails();
// this test does not really work, because there are only 4 thumbnails left
Assert.assertEquals(before, after);
}
private void assertLess(int moreValue, int lessValue, String messagePattern) {
String message = new MessageFormat(messagePattern, Locale.ROOT).format(new Object[] { lessValue, moreValue });
LOGGER.debug(message);
Assert.assertTrue(message, lessValue < moreValue);
}
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.RGB_TEST_DERIVATE;
}
}
| 5,360 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
PDFSideBarIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/PDFSideBarIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class PDFSideBarIT extends SideBarIT {
@Override
public void testOverviewLayout() {
}
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.PDF_TEST_DERIVATE;
}
}
| 1,206 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
PDFNavbarIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/PDFNavbarIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.model.TestDerivate;
/**
* @author Sebastian Röher (basti890)
*
*/
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class PDFNavbarIT extends NavbarIT {
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.PDF_TEST_DERIVATE;
}
@Override
public String getGreenLabel() {
return "[2]";
}
@Override
public String getRedLabel() {
return "[1]";
}
@Override
public String getBlueLabel() {
return "[3]";
}
@Override
public String getRgbLabel() {
return "[4]";
}
}
| 1,455 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
NavbarIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/NavbarIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.text.MessageFormat;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.ViewerTestBase;
import org.mycore.iview.tests.controller.ControllerUtil;
import org.mycore.iview.tests.controller.ImageViewerController;
import org.mycore.iview.tests.controller.StructureOverviewController;
import org.mycore.iview.tests.controller.ToolBarController;
import org.mycore.iview.tests.image.api.ColorFilter;
import org.mycore.iview.tests.image.api.FilterSelection;
import org.mycore.iview.tests.image.api.Selection;
import org.mycore.iview.tests.model.TestDerivate;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class NavbarIT extends ViewerTestBase {
private static final String RGB_LABEL = "[4] - rgb.tiff";
private static final String RED_LABEL = "[1] - r.png";
private static final String GREEN_LABEL = "[2] - g.png";
private static final String BLUE_LABEL = "[3] - b.png";
private static final int TOLERANCE = 20;
private static final Logger LOGGER = LogManager.getLogger(NavbarIT.class);
@Test
public void testBasicElementsPresent() {
this.setTestName(getClassname() + "-testBasicElementsPresent");
this.getAppController().openViewer(this.getDriver(), this.getTestDerivate());
WebDriver driver = this.getDriver();
Assert.assertTrue("Sidebar button should be present",
driver.findElement(By.xpath("//*[@data-id='SidebarControllGroup']")).isDisplayed());
}
@Test
public void testActionGroup() {
this.setTestName(getClassname() + "-testActionElementsPresent");
this.getAppController().openViewer(this.getDriver(), this.getTestDerivate());
WebDriver driver = this.getDriver();
Assert.assertTrue("Share button should be present", driver.findElement(By.xpath("//*[@data-id='ShareButton']"))
.isDisplayed());
}
@Test
public void testModificationGroup() {
this.setTestName(getClassname() + "-testModifactionElementsPresent");
this.getAppController().openViewer(this.getDriver(), this.getTestDerivate());
WebDriver driver = this.getDriver();
Assert.assertTrue("RotateButton should be present", driver
.findElement(By.xpath("//*[@data-id='RotateButton']")).isDisplayed());
}
@Test
public void testImageChangeGroup() {
this.setTestName(getClassname() + "-testImageChangePresent");
this.getAppController().openViewer(this.getDriver(), this.getTestDerivate());
WebDriver driver = this.getDriver();
Assert.assertTrue("PreviousImageButton should be present",
driver.findElement(By.xpath("//*[@data-id='PreviousImageButton']")).isDisplayed());
Assert.assertTrue("NextImageButton should be present",
driver.findElement(By.xpath("//*[@data-id='NextImageButton']")).isDisplayed());
}
@Test
public void testZoomGroup() {
this.setTestName(getClassname() + "-testZoomElementsPresent");
this.getAppController().openViewer(this.getDriver(), this.getTestDerivate());
WebDriver driver = this.getDriver();
Assert.assertTrue("ZoomIn button should be present",
driver.findElement(By.xpath("//*[@data-id='ZoomInButton']")).isDisplayed());
Assert.assertTrue("ZoomOut button should be present",
driver.findElement(By.xpath("//*[@data-id='ZoomOutButton']")).isDisplayed());
Assert.assertTrue("ZoomWidth button should be present",
driver.findElement(By.xpath("//*[@data-id='ZoomWidthButton']")).isDisplayed());
Assert.assertTrue("ZoomFit button should be present",
driver.findElement(By.xpath("//*[@data-id='ZoomFitButton']")).isDisplayed());
}
@Test
public void testNavigationPrev() throws InterruptedException {
this.setTestName(getClassname() + "-testStructureOverview");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
int redPixelCountRGB = selectImgAndCountColor(tbController, getRgbLabel(), Color.RED);
int greenPixelCountRGB = selectImgAndCountColor(tbController, getRgbLabel(), Color.GREEN);
int bluePixelCountRGB = selectImgAndCountColor(tbController, getRgbLabel(), Color.BLUE);
int bluePixelCount = selectPrevImgAndCountColor(tbController, getBlueLabel(), Color.BLUE);
int greenPixelCount = selectPrevImgAndCountColor(tbController, getGreenLabel(), Color.GREEN);
int redPixelCount = selectPrevImgAndCountColor(tbController, getRedLabel(), Color.RED);
String messagePattern = "There should be less red pixels in the rgb screenshot than in the red ({0} > {1})";
assertLess(redPixelCount, redPixelCountRGB, messagePattern);
messagePattern = "There should be less green pixels in the rgb screenshot than in the green ({0} > {1})";
assertLess(greenPixelCount, greenPixelCountRGB, messagePattern);
messagePattern = "There should be less blue pixels in the rgb screenshot than in the blue ({0} > {1})";
assertLess(bluePixelCount, bluePixelCountRGB, messagePattern);
}
@Test
public void testNavigationNext() throws InterruptedException {
this.setTestName(getClassname() + "-testStructureOverview");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
int redPixelCountRGB = selectImgAndCountColor(tbController, getRgbLabel(), Color.RED);
int greenPixelCountRGB = countColor(tbController, getRgbLabel(), Color.GREEN);
int bluePixelCountRGB = countColor(tbController, getRgbLabel(), Color.BLUE);
int redPixelCount = selectImgAndCountColor(tbController, getRedLabel(), Color.RED);
String messagePattern = "There should be less red pixels in the rgb screenshot than in the red ({0} > {1})";
assertLess(redPixelCount, redPixelCountRGB, messagePattern);
int greenPixelCount = selectNextImgAndCountColor(tbController, getGreenLabel(), Color.GREEN);
messagePattern = "There should be less green pixels in the rgb screenshot than in the green ({0} > {1})";
assertLess(greenPixelCount, greenPixelCountRGB, messagePattern);
int bluePixelCount = selectNextImgAndCountColor(tbController, getBlueLabel(), Color.BLUE);
messagePattern = "There should be less blue pixels in the rgb screenshot than in the blue ({0} > {1})";
assertLess(bluePixelCount, bluePixelCountRGB, messagePattern);
}
private int selectPrevImgAndCountColor(ToolBarController tbController, String label, Color color)
throws InterruptedException {
tbController.pressButton(ToolBarController.BUTTON_ID_PREV_IMG);
Thread.sleep(500);
return countColor(tbController, label, color);
}
private int selectNextImgAndCountColor(ToolBarController tbController, String label, Color color)
throws InterruptedException {
tbController.pressButton(ToolBarController.BUTTON_ID_NEXT_IMG);
Thread.sleep(500);
return countColor(tbController, label, color);
}
private int countColor(ToolBarController tbController, String label, Color color) {
String message = color + " schould be selected (class-attribut 'selected' should be set)!";
Assert.assertTrue(message, tbController.isImageSelected(label));
String fileName = String.format("%s-%s-%s-%s-%s", this.getClassname(), label, color.getRed(), color.getBlue(),
color.getGreen());
BufferedImage bImage = ControllerUtil.getScreenshot(getDriver(), fileName);
return new FilterSelection(Selection.fromBufferedImage(bImage), new ColorFilter(color, false, TOLERANCE))
.getPixel().size();
}
/**
* selects an image with {@link StructureOverviewController#selectImageByOrder(String)} and counts Pixels of the color
*
* @param tbController
* @param label
* @param color
* @return
* @throws InterruptedException
*/
private int selectImgAndCountColor(ToolBarController tbController, String label, Color color)
throws InterruptedException {
tbController.selectPictureWithOrder(label);
Thread.sleep(500);
return countColor(tbController, label, color);
}
private void assertLess(int moreValue, int lessValue, String messagePattern) {
String message = new MessageFormat(messagePattern, Locale.ROOT).format(new Object[] { lessValue, moreValue });
LOGGER.debug(message);
Assert.assertTrue(message, lessValue < moreValue);
}
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.RGB_TEST_DERIVATE;
}
/**
* @return the rgbLabel
*/
public String getRgbLabel() {
return RGB_LABEL;
}
/**
* @return the blueLabel
*/
public String getBlueLabel() {
return BLUE_LABEL;
}
/**
* @return the greenLabel
*/
public String getGreenLabel() {
return GREEN_LABEL;
}
/**
* @return the redLabel
*/
public String getRedLabel() {
return RED_LABEL;
}
}
| 10,569 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ImageSectionIT.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/ImageSectionIT.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mycore.iview.tests.ViewerTestBase;
import org.mycore.iview.tests.controller.ControllerUtil;
import org.mycore.iview.tests.controller.ImageViewerController;
import org.mycore.iview.tests.controller.ToolBarController;
import org.mycore.iview.tests.image.api.ColorFilter;
import org.mycore.iview.tests.image.api.FilterSelection;
import org.mycore.iview.tests.image.api.Selection;
import org.mycore.iview.tests.model.TestDerivate;
@Category(org.mycore.iview.tests.groups.ImageViewerTests.class)
public class ImageSectionIT extends ViewerTestBase {
private static final String START_IMAGE = "[4] - rgb.tiff";
private static final int TOLERANCE = 20;
private static final Logger LOGGER = LogManager.getLogger(ImageSectionIT.class);
private static final int DELAY_TIME = 3000;
@Test
/**
* Checks if the zoom button works!
* @throws IOException
* @throws InterruptedException
*/
public void testImageZoom() throws InterruptedException {
this.setTestName(getClassname() + "-testImageZoom");
this.getDriver();
this.getAppController().openViewer(this.getDriver(), getTestDerivate());
ImageViewerController controller = this.getViewerController();
ToolBarController tbController = controller.getToolBarController();
tbController.selectPictureWithOrder(getStartImage());
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_WIDTH);
Thread.sleep(DELAY_TIME);
BufferedImage notZoomed = ControllerUtil.getScreenshot(getDriver(), this.getClassname() + "-notZoomed");
int redPixelCountNotZoomed = getColorCount(notZoomed, Color.RED);
int greenPixelCountNotZoomed = getColorCount(notZoomed, Color.GREEN);
//-
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_IN);
Thread.sleep(DELAY_TIME);
BufferedImage zoomed = ControllerUtil.getScreenshot(getDriver(), this.getClassname() + "-zoomed");
int redPixelCountZoomed = getColorCount(zoomed, Color.RED);
int greenPixelCountZoomed = getColorCount(zoomed, Color.GREEN);
int bluePixelCountZoomed = getColorCount(zoomed, Color.BLUE);
String message1Pattern
= "There should be less red pixels in the zoomed screenshot than in the not zoomed ({0} > {1})";
assertLess(redPixelCountNotZoomed, redPixelCountZoomed, message1Pattern);
String message2Pattern
= "There should be less green pixels in the not zoomed screenshot than in the zoomed ({0} < {1})";
assertLess(greenPixelCountZoomed, greenPixelCountNotZoomed, message2Pattern);
//-
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_IN);
Thread.sleep(DELAY_TIME);
BufferedImage zoomed2 = ControllerUtil.getScreenshot(getDriver(), this.getClassname() + "-zoomed2");
int greenPixelCountZoomed2 = getColorCount(zoomed2, Color.GREEN);
int bluePixelCountZoomed2 = getColorCount(zoomed2, Color.BLUE);
String message3Pattern
= "There should be less blue pixels in the zoomed screenshot than in the zoomed2 ({0} > {1})";
assertLess(bluePixelCountZoomed2, bluePixelCountZoomed, message3Pattern);
String message4Pattern
= "There should be less green pixels in the zoomed2 screenshot than in the zoomed ({0} > {1})";
assertLess(greenPixelCountZoomed, greenPixelCountZoomed2, message4Pattern);
//-
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_OUT);
Thread.sleep(DELAY_TIME);
BufferedImage zoomed3 = ControllerUtil.getScreenshot(getDriver(), this.getClassname() + "zoomed3");
int greenPixelCountZoomed3 = getColorCount(zoomed3, Color.GREEN);
int bluePixelCountZoomed3 = getColorCount(zoomed3, Color.BLUE);
int redPixelCountZoomed3 = getColorCount(zoomed3, Color.RED);
String message5Pattern
= "There should be less green pixels in the zoomed2 screenshot than in the zoomed3 ({0} > {1})";
assertLess(greenPixelCountZoomed3, greenPixelCountZoomed2, message5Pattern);
String message6Pattern
= "There should be less blue pixels in the zoomed3 screenshot than in the zoomed2 ({0} > {1})";
assertLess(bluePixelCountZoomed2, bluePixelCountZoomed3, message6Pattern);
//-
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_OUT);
Thread.sleep(DELAY_TIME);
BufferedImage zoomed4 = ControllerUtil.getScreenshot(getDriver(), this.getClassname() + "zoomed4");
int greenPixelCountZoomed4 = getColorCount(zoomed4, Color.GREEN);
int bluePixelCountZoomed4 = getColorCount(zoomed4, Color.BLUE);
int redPixelCountZoomed4 = getColorCount(zoomed4, Color.RED);
tbController.pressButton(ToolBarController.BUTTON_ID_ZOOM_OUT);
Thread.sleep(DELAY_TIME);
String message7Pattern
= "There should be less blue pixels in the zoomed4 screenshot than in the zoomed3 ({0} > {1})";
assertLess(bluePixelCountZoomed3, bluePixelCountZoomed4, message7Pattern);
String message8Pattern
= "There should be less green pixels in the zoomed4 screenshot than in the zoomed3 ({0} > {1})";
assertLess(greenPixelCountZoomed3, greenPixelCountZoomed4, message8Pattern);
String message9Pattern
= "There should be less red pixels in the zoomed3 screenshot than in the zoomed4 ({0} > {1})";
assertLess(redPixelCountZoomed4, redPixelCountZoomed3, message9Pattern);
}
/**
* Gets the count of pixel with a specific color
* @param image
* @param color
* @return
*/
private int getColorCount(BufferedImage image, Color color) {
return new FilterSelection(Selection.fromBufferedImage(image), new ColorFilter(color, false, TOLERANCE))
.getPixel().size();
}
private void assertLess(int moreValue, int lessValue, String messagePattern) {
String message = new MessageFormat(messagePattern, Locale.ROOT).format(new Object[] { lessValue, moreValue });
LOGGER.debug(message);
Assert.assertTrue(message, lessValue < moreValue);
}
@Override
public TestDerivate getTestDerivate() {
return BaseTestConstants.RGB_TEST_DERIVATE;
}
/**
* @return the startImage
*/
public String getStartImage() {
return START_IMAGE;
}
}
| 7,554 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
BaseTestConstants.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/base/BaseTestConstants.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.base;
import org.mycore.iview.tests.model.TestDerivate;
public class BaseTestConstants {
public static final int TIME_OUT_IN_SECONDS = 30;
protected static final TestDerivate RGB_TEST_DERIVATE = new TestDerivate() {
@Override
public String getStartFile() {
return "r.png";
}
@Override
public String getName() {
return "derivate_0000005";
}
};
protected static final TestDerivate PDF_TEST_DERIVATE = new TestDerivate() {
@Override
public String getStartFile() {
return "PDF-Test.pdf";
}
@Override
public String getName() {
return "derivate_0000004";
}
};
}
| 1,489 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ImageViewerTests.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/groups/ImageViewerTests.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.groups;
public interface ImageViewerTests {
}
| 805 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
TestDerivate.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/test/java/org/mycore/iview/tests/model/TestDerivate.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iview.tests.model;
/**
* Abstract Class to resolve the Testfiles for a specific Test.
* @author Sebastian Hofmann
*/
public abstract class TestDerivate {
/**
* @return gets the file wich should be show first
*/
public abstract String getStartFile();
/**
* Used to identify the TestDerivate for debugging
* @return a simple name
*/
public abstract String getName();
}
| 1,162 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerConfigurationBuilder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerConfigurationBuilder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import java.util.Map;
import org.mycore.viewer.configuration.MCRViewerConfiguration.ResourceType;
import com.google.common.collect.Multimap;
import jakarta.servlet.http.HttpServletRequest;
/**
* Use this class to build your {@link MCRViewerConfiguration}.
* You can use {@link #mets(HttpServletRequest)} or {@link #pdf(HttpServletRequest)}
* as entry point and use {@link #mixin(MCRViewerConfiguration)} to append
* additional configuration.
*
* @author Matthias Eichner
*/
public class MCRViewerConfigurationBuilder {
private MCRViewerConfiguration internalConfig;
private HttpServletRequest request;
private MCRViewerConfigurationBuilder(HttpServletRequest request) {
this.request = request;
this.internalConfig = new MCRViewerConfiguration();
}
/**
* Mix in the configuration into the builder. This overwrites properties and
* resources with the same name.
*
* @param configuration the configuration to mix in.
* @return same instance
*/
public MCRViewerConfigurationBuilder mixin(MCRViewerConfiguration configuration) {
configuration.setup(request);
mixin(internalConfig, configuration);
return this;
}
/**
* Gets the configuration.
*/
public MCRViewerConfiguration get() {
return internalConfig;
}
/**
* Mix in the second configuration into the first.
*/
public static void mixin(MCRViewerConfiguration conf1, MCRViewerConfiguration conf2) {
Map<String, Object> conf2Props = conf2.getProperties();
for (Map.Entry<String, Object> property : conf2Props.entrySet()) {
conf1.setProperty(property.getKey(), property.getValue());
}
Multimap<ResourceType, String> resources = conf2.getResources();
for (Map.Entry<ResourceType, String> resource : resources.entries()) {
if (ResourceType.script.equals(resource.getKey())) {
conf1.addScript(resource.getValue());
} else if (ResourceType.css.equals(resource.getKey())) {
conf1.addCSS(resource.getValue());
}
}
}
/**
* Creates a new configuration builder.
*
* @param request the servlet request
* @return a new configuration builder instance.
*/
public static MCRViewerConfigurationBuilder build(HttpServletRequest request) {
return new MCRViewerConfigurationBuilder(request);
}
/**
* Builds the default mets configuration without any plugins.
*/
public static MCRViewerConfigurationBuilder mets(HttpServletRequest request) {
MCRViewerMetsConfiguration metsConfig = new MCRViewerMetsConfiguration();
return MCRViewerConfigurationBuilder.build(request)
.mixin(metsConfig)
.mixin(new MCRViewerAltoEditorConfiguration().setup(request));
}
/**
* Builds the default mets configuration without any plugins.
*/
public static MCRViewerConfigurationBuilder iiif(HttpServletRequest request) {
MCRViewerIIIFConfiguration iiifConfig = new MCRViewerIIIFConfiguration();
return MCRViewerConfigurationBuilder.build(request)
.mixin(iiifConfig)
.mixin(new MCRViewerAltoEditorConfiguration().setup(request));
}
/**
* Builds the mets configuration with the metadata, piwik and logo plugin.
*/
public static MCRViewerConfigurationBuilder metsAndPlugins(HttpServletRequest request) {
return mets(request).mixin(plugins(request).get());
}
/**
* Builds the default pdf configuration without any plugins.
*/
public static MCRViewerConfigurationBuilder pdf(HttpServletRequest request) {
MCRViewerPDFConfiguration pdfConfig = new MCRViewerPDFConfiguration();
return MCRViewerConfigurationBuilder.build(request).mixin(pdfConfig);
}
/**
* Builds the default pdf configuration without any plugins.
*/
public static MCRViewerConfigurationBuilder epub(HttpServletRequest request) {
MCRViewerEPUBConfiguration epubConfig = new MCRViewerEPUBConfiguration();
return MCRViewerConfigurationBuilder.build(request).mixin(epubConfig);
}
/**
* Builds just the plugins (metadata, piwik, logo).
*/
public static MCRViewerConfigurationBuilder plugins(HttpServletRequest request) {
return MCRViewerConfigurationBuilder.build(request).mixin(new MCRViewerLogoConfiguration())
.mixin(new MCRViewerMetadataConfiguration()).mixin(new MCRViewerPiwikConfiguration());
}
}
| 5,356 | 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-viewer/src/main/java/org/mycore/viewer/configuration/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/>.
*/
/**
* iview configuration
*/
package org.mycore.viewer.configuration;
| 799 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerAltoEditorConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerAltoEditorConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.viewer.alto.MCRALTOUtil;
import org.mycore.viewer.alto.model.MCRStoredChangeSet;
import org.mycore.viewer.alto.service.MCRAltoChangeSetStore;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerAltoEditorConfiguration extends MCRViewerConfiguration {
private MCRAltoChangeSetStore changeSetStore = MCRConfiguration2
.<MCRAltoChangeSetStore>getInstanceOf("MCR.Viewer.AltoChangeSetStore.Class").orElseThrow();
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
String derivate = getDerivate(request);
if (MCRAccessManager.checkPermission(derivate, MCRALTOUtil.EDIT_ALTO_PERMISSION)) {
this.setProperty("altoEditorPostURL", MCRFrontendUtil.getBaseURL(request) + "rsc/viewer/alto");
boolean isReviewer = MCRAccessManager.checkPermission(derivate, MCRALTOUtil.REVIEW_ALTO_PERMISSION);
if (isReviewer) {
this.setProperty("altoReviewer", true);
}
String[] altoChangeIDS = request.getParameterMap().getOrDefault("altoChangeID", new String[0]);
if (altoChangeIDS.length > 0) {
String altoChangeID = altoChangeIDS[0];
MCRStoredChangeSet mcrStoredChangeSet = changeSetStore.get(altoChangeID);
if (isReviewer || mcrStoredChangeSet.getSessionID().equals(MCRSessionMgr.getCurrentSessionID())) {
this.setProperty("altoChangePID", altoChangeID);
this.setProperty("altoChanges", mcrStoredChangeSet.getChangeSet());
this.setProperty("leftShowOnStart", "altoEditor");
}
}
}
return this;
}
}
| 2,699 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerIIIFConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerIIIFConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerIIIFConfiguration extends MCRViewerBaseConfiguration {
@Override
public MCRViewerIIIFConfiguration setup(HttpServletRequest request) {
super.setup(request);
// properties
final String derivate = getDerivate(request);
setProperty("manifestURL", MCRFrontendUtil.getBaseURL()
+ MCRConfiguration2.getStringOrThrow("MCR.Viewer.IIIF.URL.Presentation")
+ derivate + "/manifest");
setProperty("imageAPIURL", MCRFrontendUtil.getBaseURL()
+ MCRConfiguration2.getStringOrThrow("MCR.Viewer.IIIF.URL.Image"));
setProperty("filePath", getDerivate(request) + getFilePath(request));
// script
final boolean debugParameterSet = isDebugMode(request);
addLocalScript("iview-client-iiif.js", true, debugParameterSet);
addLocalScript("lib/manifesto/manifesto.js", true, debugParameterSet);
return this;
}
@Override
public String getDocType(HttpServletRequest request) {
return "manifest";
}
}
| 1,971 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerMetadataConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerMetadataConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.services.i18n.MCRTranslation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
public class MCRViewerMetadataConfiguration extends MCRViewerConfiguration {
private static final int EXPIRE_METADATA_CACHE_TIME = 10; // in seconds
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
String derivate = getDerivate(request);
MCRObjectID derivateID = MCRObjectID.getInstance(derivate);
final MCRObjectID objectID = MCRMetadataManager.getObjectId(derivateID, EXPIRE_METADATA_CACHE_TIME,
TimeUnit.SECONDS);
if (objectID == null) {
String errorMessage = MCRTranslation.translate("component.viewer.MCRIViewClientServlet.object.not.found");
// TODO: we should not throw an webapplication exc. here -> instead throw something líke ConfigException
throw new WebApplicationException(Response.status(Status.NOT_FOUND).entity(errorMessage).build());
}
// properties
setProperty("objId", objectID.toString());
String urlFormat = "%sreceive/%s?XSL.Transformer=%s";
String transformer = MCRConfiguration2.getString("MCR.Viewer.metadata.transformer").orElse(null);
if (transformer != null) {
setProperty(
"metadataURL",
String.format(Locale.ROOT, urlFormat, MCRFrontendUtil.getBaseURL(), objectID, transformer));
}
// script
addLocalScript("iview-client-metadata.js", true, isDebugMode(request));
return this;
}
}
| 2,755 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerConfigurationStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerConfigurationStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import jakarta.servlet.http.HttpServletRequest;
/**
* Strategy which decides which image viewer configuration should be loaded by the
* given request.
*
* @author Matthias Eichner
*/
public interface MCRViewerConfigurationStrategy {
/**
* Gets the image view configuration.
*/
MCRViewerConfiguration get(HttpServletRequest request);
}
| 1,131 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerLogoConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerLogoConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerLogoConfiguration extends MCRViewerConfiguration {
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
String logoURL = MCRConfiguration2.getString("MCR.Viewer.logo.URL").orElse(null);
if (logoURL != null) {
String framedParameter = request.getParameter("frame");
if (!Boolean.parseBoolean(framedParameter)) {
this.addLocalScript("iview-client-logo.js", true, isDebugMode(request));
this.setProperty("logoURL", MCRFrontendUtil.getBaseURL() + logoURL);
String logoCssProperty = MCRConfiguration2.getString("MCR.Viewer.logo.css").orElse(null);
if (logoCssProperty != null) {
this.addCSS(MCRFrontendUtil.getBaseURL() + logoCssProperty);
}
}
}
return this;
}
}
| 1,831 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRJAXBContent;
import org.mycore.common.content.MCRXMLContent;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.MCRFrontendUtil;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementWrapper;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlTransient;
import jakarta.xml.bind.annotation.XmlValue;
/**
* Base class for the iview client configuration. You can add properties, javascript files and css files.
* To retrieve the configuration in xml call {@link #toXML()}. To get it in json call {@link #toJSON()}.
*
* @author Matthias Eichner
*/
public class MCRViewerConfiguration {
private static Logger LOGGER = LogManager.getLogger(MCRViewerConfiguration.class);
public enum ResourceType {
script, css
}
private Multimap<ResourceType, String> resources;
private Map<String, Object> properties;
private static boolean DEBUG_MODE;
private static Pattern REQUEST_PATH_PATTERN;
static {
DEBUG_MODE = Boolean.parseBoolean(MCRConfiguration2.getString("MCR.Viewer.DeveloperMode").orElse("false"));
REQUEST_PATH_PATTERN = Pattern.compile("/(\\w+_derivate_\\d+)(/.*)?");
}
public MCRViewerConfiguration() {
resources = LinkedListMultimap.create();
properties = new HashMap<>();
}
/**
* Returns the properties of this configuration.
*
* @return map of all properties set in this configuration
*/
public Map<String, Object> getProperties() {
return properties;
}
/**
* Returns a multimap containing all resources (javascript and css url's).
*
* @return map of resources
*/
public Multimap<ResourceType, String> getResources() {
return resources;
}
/**
* Setup's the configuration with the request.
*
* @param request the request which should be parsed to build this configuration.
* @return itself
*/
public MCRViewerConfiguration setup(HttpServletRequest request) {
return this;
}
/**
* Returns true if the debug/developer mode is active.
*
* <ul>
* <li>URL parameter iview2.debug = true</li>
* <li>MCR.Viewer.DeveloperMode property = true</li>
* </ul>
*
* @param request the request to check the iview2.debug parameter
* @return true if the debug mode is active, otherwise false
*/
public static boolean isDebugMode(HttpServletRequest request) {
return DEBUG_MODE ||
Boolean.TRUE.toString().toLowerCase(Locale.ROOT).equals(request.getParameter("iview2.debug"));
}
/**
* Helper method to get the derivate id of the given request. Returns null
* if no derivate identifier could be found in the request object.
*
* @param request http request
* @return the derivate id embedded in the path of the request
*/
public static String getDerivate(HttpServletRequest request) {
try {
return getFromPath(request.getPathInfo(), 1);
} catch (Exception exc) {
LOGGER.warn("Unable to get the derivate id of request {}", request.getRequestURI());
return null;
}
}
/**
* Helper method to get the path to the start file. The path is
* URI decoded and starts with a slash.
*
* @param request http request
* @return path to the file or null if the path couldn't be retrieved
*/
public static String getFilePath(HttpServletRequest request) {
try {
String fromPath = getFromPath(request.getPathInfo(), 2);
if (fromPath == null || fromPath.isEmpty() || fromPath.equals("/")) {
String derivate = getDerivate(request);
MCRDerivate deriv = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivate));
String nameOfMainFile = deriv.getDerivate().getInternals().getMainDoc();
return "/" + nameOfMainFile;
}
return fromPath;
} catch (Exception exc) {
LOGGER.warn("Unable to get the file path of request {}", request.getRequestURI());
return null;
}
}
/**
* Gets the group from the {@link #REQUEST_PATH_PATTERN}.
*
* @param path uri decoded path
* @param groupNumber the group number which should be returnd
* @return the value of the regular expression group
*/
private static String getFromPath(String path, int groupNumber) {
Matcher matcher = REQUEST_PATH_PATTERN.matcher(path);
if (matcher.find()) {
return matcher.group(groupNumber);
}
return null;
}
/**
* Adds a new javascript file which should be included by the image viewer.
*/
public void addScript(final String url) {
this.resources.put(ResourceType.script, url);
}
/**
* Shorthand MCRViewerConfiguration#addLocalScript(String, true, false)
*
* @param file the local javascript file to include
*/
public void addLocalScript(final String file) {
this.addLocalScript(file, true, false);
}
/**
* Shorthand MCRViewerConfiguration#addLocalScript(file, hasMinified, false)
*
* @param file the local javascript file to include
* @param hasMinified is a minified version available
*/
public void addLocalScript(final String file, boolean hasMinified) {
this.addLocalScript(file, hasMinified, false);
}
/**
* Adds a local (based in modules/iview2/js/) javascript file which should be included
* by the image viewer. You should always call this method with the base file version.
* E.g. addLocalScript("iview-client-mobile.js");.
*
* <p>This method uses the minified (adds a .min) version only if hasMinified is true and debugMode is false.</p>.
*
* @param file the local javascript file to include
* @param hasMinified is a minified version available
* @param debugMode if the debug mode is active or not
*/
public void addLocalScript(final String file, final boolean hasMinified, final boolean debugMode) {
String baseURL = MCRFrontendUtil.getBaseURL();
StringBuilder scriptURL = new StringBuilder(baseURL);
scriptURL.append("modules/iview2/js/");
if (hasMinified && !debugMode) {
scriptURL.append(file, 0, file.lastIndexOf("."));
scriptURL.append(".min.js");
} else {
scriptURL.append(file);
}
addScript(scriptURL.toString());
}
/**
* Adds a new css file which should be included by the image viewer.
*
* @param url the url to add e.g. baseURL + "modules/iview2/css/my.css"
*/
public void addCSS(final String url) {
this.resources.put(ResourceType.css, url);
}
/**
* Adds a local (based in modules/iview2/css/) css file.
*
* @param file to include
*/
public void addLocalCSS(final String file) {
String baseURL = MCRFrontendUtil.getBaseURL();
addCSS(baseURL + "modules/iview2/css/" + file);
}
/**
* Sets a new property.
*
* @param name name of the property
* @param value value of the property
*/
public void setProperty(String name, Object value) {
this.properties.put(name, value);
}
/**
* Removes a property by name.
*
* @param name name of the property which should be removed
* @return the removed value or null when nothing is done
*/
public Object removeProperty(String name) {
return this.properties.remove(name);
}
/**
* Returns the configuration in json format.
*
* @return json the configuration as json string
*/
public String toJSON() {
final Gson gson = new GsonBuilder().registerTypeAdapter(Multimap.class, new MultimapSerializer()).create();
return gson.toJson(this);
}
/**
* Returns the configuration in xml content format.
*
* @return the configuration as xml content
*/
public MCRXMLContent toXML() throws JAXBException {
MCRIViewClientXMLConfiguration xmlConfig = new MCRIViewClientXMLConfiguration(resources, properties);
return new MCRJAXBContent<>(
JAXBContext.newInstance(xmlConfig.getClass()), xmlConfig);
}
@XmlRootElement(name = "xml")
private static class MCRIViewClientXMLConfiguration {
private Multimap<ResourceType, String> resources;
private Map<String, Object> properties;
@SuppressWarnings("unused")
MCRIViewClientXMLConfiguration() {
}
MCRIViewClientXMLConfiguration(Multimap<ResourceType, String> resources,
Map<String, Object> properties) {
this.resources = resources;
this.properties = properties;
}
@XmlElements({ @XmlElement(name = "resource") })
@XmlElementWrapper(name = "resources")
public final List<MCRIViewClientResource> getResources() {
return resources.entries()
.stream()
.map(entry -> new MCRIViewClientResource(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
@XmlElements({ @XmlElement(name = "property") })
@XmlElementWrapper(name = "properties")
public final List<MCRIViewClientProperty> getProperties() {
return properties.entrySet()
.stream()
.map(entry -> new MCRIViewClientProperty(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
}
@XmlRootElement(name = "resource")
private static class MCRIViewClientResource {
@XmlAttribute(name = "type", required = true)
public ResourceType type;
@XmlValue
public String url;
@SuppressWarnings("unused")
MCRIViewClientResource() {
}
MCRIViewClientResource(ResourceType type, String url) {
this.type = type;
this.url = url;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MCRIViewClientResource rhs)) {
return false;
}
if (obj == this) {
return true;
}
return new EqualsBuilder().append(type, rhs.type).append(url, rhs.url).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31).append(type.ordinal()).append(url).toHashCode();
}
}
@XmlRootElement(name = "property")
private static class MCRIViewClientProperty {
@XmlAttribute(name = "name", required = true)
public String name;
@XmlTransient
public Object value;
@XmlValue
public String getXMLValue() {
return (value == null) ? "" : value.toString();
}
@SuppressWarnings("unused")
MCRIViewClientProperty() {
}
MCRIViewClientProperty(String name, Object value) {
this.name = name;
this.value = value;
}
}
private static final class MultimapSerializer implements JsonSerializer<Multimap<ResourceType, String>> {
@SuppressWarnings("serial")
private static final Type T = new TypeToken<Map<ResourceType, Collection<String>>>() {
}.getType();
@Override
public JsonElement serialize(Multimap<ResourceType, String> arg0, Type arg1, JsonSerializationContext arg2) {
return arg2.serialize(arg0.asMap(), T);
}
}
}
| 13,713 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerBaseConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerBaseConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import java.util.Locale;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpServletRequest;
/**
* Base configuration for the mycore image viewer. Sets the following parameter:
* <dl>
* <dt>webApplicationBaseURL</dt><dd>base URL of the mycore system</dd>
* <dt>derivate</dt><dd>name of the derivate which should be displayed.</dd>
* <dt>filePath</dt><dd>path of the file which should be displayed (in the derivate)</dd>
* <dt>doctype</dt><dd>the type of the structure e.g. (mets/pdf) </dd>
* <dt>mobile</dt><dd>should the mobile or the desktop client started.</dd>
* <dt>i18nURL</dt><dd>URL to the i18n.json</dd>
* <dt>lang</dt><dd>current selected language</dd>
* </dl>
* @author Matthias Eichner
*/
public abstract class MCRViewerBaseConfiguration extends MCRViewerConfiguration {
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
// property
setProperty("webApplicationBaseURL", MCRFrontendUtil.getBaseURL());
setProperty("derivate", getDerivate(request));
setProperty("filePath", getFilePath(request));
setProperty("doctype", getDocType(request));
boolean mobile = isMobile(request);
setProperty("mobile", mobile);
setProperty("i18nURL",
MCRFrontendUtil.getBaseURL(request) + "rsc/locale/translate/{lang}/component.mets.*,component.viewer.*");
setProperty("derivateURL", MCRServlet.getServletBaseURL() + "MCRFileNodeServlet/" + getDerivate(request) + "/");
setProperty("lang", MCRSessionMgr.getCurrentSession().getCurrentLanguage());
setProperty("adminMail", MCRConfiguration2.getString("MCR.Mail.Recipients").orElse(""));
final String canvasOverviewEnabled = MCRConfiguration2.getString("MCR.Viewer.canvas.overview.enabled")
.orElse("true");
setProperty("canvas.overview.enabled", Boolean.valueOf(canvasOverviewEnabled));
final String canvasOverviewCanvasOverviewMinVisibleSize = MCRConfiguration2
.getString("MCR.Viewer.canvas.overview.minVisibleSize").orElse(null);
if (canvasOverviewCanvasOverviewMinVisibleSize != null) {
setProperty("canvas.overview.minVisibleSize", canvasOverviewCanvasOverviewMinVisibleSize);
}
final String canvasStartupFitWidth = MCRConfiguration2.getString("MCR.Viewer.canvas.startup.fitWidth")
.orElse(null);
if (canvasStartupFitWidth != null && canvasStartupFitWidth.toLowerCase(Locale.ROOT).equals("true")) {
setProperty("canvas.startup.fitWidth", true);
}
String leftShowOnStart = MCRConfiguration2.getString("MCR.Viewer.leftShowOnStart").orElse(null);
if (leftShowOnStart != null) {
setProperty("leftShowOnStart", leftShowOnStart);
}
// script & css
boolean developerMode = isDebugMode(request);
addLocalScript("iview-client-base.js", true, developerMode);
final boolean framed = this.isFramed(request);
if (mobile && !framed && !"js".equals(request.getParameter("XSL.Style"))) {
addLocalScript("iview-client-mobile.js", true, developerMode);
addLocalCSS("mobile.css");
} else {
if (framed) {
addLocalScript("iview-client-frame.js", true, developerMode);
} else if (this.getEmbeddedParameter(request) != null) {
addLocalScript("iview-client-frame.js", true, developerMode);
setProperty("embedded", "true");
setProperty("permalink.updateHistory", false);
setProperty("chapter.showOnStart", false);
} else {
addLocalScript("iview-client-desktop.js", true, developerMode);
}
addLocalCSS("default.css");
}
String maximalScale = MCRConfiguration2.getString("MCR.Viewer.Canvas.Startup.MaximalPageScale").orElse("");
if (!maximalScale.isEmpty()) {
setProperty("maximalPageScale", maximalScale);
}
return this;
}
private String getEmbeddedParameter(HttpServletRequest request) {
return request.getParameter("embedded");
}
protected boolean isMobile(HttpServletRequest req) {
String mobileParameter = req.getParameter("mobile");
if (mobileParameter != null) {
return Boolean.parseBoolean(mobileParameter);
} else {
return req.getHeader("User-Agent").contains("Mobile");
}
}
protected boolean isFramed(HttpServletRequest req) {
String frameParameter = req.getParameter("frame");
return Boolean.parseBoolean(frameParameter);
}
public abstract String getDocType(HttpServletRequest request);
}
| 5,696 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerMetsConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerMetsConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import java.nio.file.Files;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerMetsConfiguration extends MCRViewerBaseConfiguration {
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
// properties
final String derivate = getDerivate(request);
setProperty("metsURL", MCRServlet.getServletBaseURL() + "MCRMETSServlet/" + derivate);
// Parameter can be used to provide multiple urls
String imageXmlPath = MCRConfiguration2.getString("MCR.Viewer.BaseURL").orElse(null);
if (imageXmlPath == null || imageXmlPath.isEmpty()) {
imageXmlPath = MCRServlet.getServletBaseURL() + "MCRTileServlet/";
}
setProperty("tileProviderPath", imageXmlPath);
if (imageXmlPath.contains(",")) {
imageXmlPath = imageXmlPath.split(",")[0];
}
setProperty("imageXmlPath", imageXmlPath);
setProperty("pdfCreatorStyle", MCRConfiguration2.getString("MCR.Viewer.PDFCreatorStyle").orElse(null));
setProperty("pdfCreatorURI", MCRConfiguration2.getString("MCR.Viewer.PDFCreatorURI").orElse(null));
setProperty("text.enabled", MCRConfiguration2.getString("MCR.Viewer.text.enabled").orElse("false"));
setProperty("pdfCreatorFormatString",
MCRConfiguration2.getString("MCR.Viewer.PDFCreatorFormatString").orElse(null));
setProperty("pdfCreatorRestrictionFormatString",
MCRConfiguration2.getString("MCR.Viewer.PDFCreatorRestrictionFormatString").orElse(null));
// script
final boolean debugParameterSet = isDebugMode(request);
addLocalScript("iview-client-mets.js", true, debugParameterSet);
final MCRPath teiDirectoryPath = MCRPath.getPath(derivate, "/tei");
if (Files.exists(teiDirectoryPath) && Files.isDirectory(teiDirectoryPath)) {
addLocalScript("iview-client-tei.js", true, debugParameterSet);
addLocalCSS("tei.css");
MCRConfiguration2.getString("MCR.Viewer.TeiStyle")
.ifPresent((style) -> setProperty("teiStylesheet", style));
}
return this;
}
@Override
public String getDocType(HttpServletRequest request) {
return "mets";
}
}
| 3,214 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerEPUBConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerEPUBConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.frontend.MCRFrontendUtil;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerEPUBConfiguration extends MCRViewerBaseConfiguration {
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
final boolean debugMode = isDebugMode(request);
addLocalScript("lib/epubjs/epub.js", true, debugMode);
addLocalScript("lib/jszip/jszip.js", true, debugMode);
addLocalScript("iview-client-epub.js", true, debugMode);
addLocalScript("lib/es6-promise/es6-promise.auto.js", true, debugMode);
final String derivate = getDerivate(request);
final String filePath = getFilePath(request);
// put / at the end to let epubjs know its extracted
setProperty("epubPath", MCRFrontendUtil.getBaseURL(request) + "rsc/epub/" + derivate + filePath + "/");
return this;
}
@Override
public String getDocType(HttpServletRequest request) {
return "epub";
}
}
| 1,799 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerPiwikConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerPiwikConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.common.config.MCRConfiguration2;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerPiwikConfiguration extends MCRViewerConfiguration {
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
if (MCRConfiguration2.getBoolean("MCR.Piwik.enable").orElse(false)) {
this.addLocalScript("iview-client-piwik.js", true, isDebugMode(request));
this.setProperty("MCR.Piwik.baseurl", MCRConfiguration2.getStringOrThrow("MCR.Piwik.baseurl"));
this.setProperty("MCR.Piwik.id", MCRConfiguration2.getStringOrThrow("MCR.Piwik.id"));
}
return this;
}
}
| 1,469 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerPDFConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerPDFConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpServletRequest;
public class MCRViewerPDFConfiguration extends MCRViewerBaseConfiguration {
@Override
public MCRViewerConfiguration setup(HttpServletRequest request) {
super.setup(request);
String pdfProviderURL = MCRConfiguration2.getString("MCR.Viewer.pdfProviderURL")
.orElse(MCRServlet.getServletBaseURL() + "MCRFileNodeServlet/{derivate}/{filePath}");
String pdfWorkerLocation = MCRFrontendUtil.getBaseURL() + "modules/iview2/js/lib/pdf.worker.min.js";
setProperty("pdfProviderURL", pdfProviderURL);
setProperty("pdfWorkerURL", pdfWorkerLocation);
// script
addLocalScript("lib/pdf.js", false);
addLocalScript("iview-client-pdf.js", true, isDebugMode(request));
return this;
}
@Override
public String getDocType(HttpServletRequest request) {
return "pdf";
}
}
| 1,833 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerDefaultConfigurationStrategy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRViewerDefaultConfigurationStrategy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import java.util.Locale;
import jakarta.servlet.http.HttpServletRequest;
/**
* Default image viewer configuration. Decides if the mets or the pdf configuration is used.
* Returns the appropriate configuration with all plugins (piwik, metadata, logo).
*
* @author Matthias Eichner
*/
public class MCRViewerDefaultConfigurationStrategy implements MCRViewerConfigurationStrategy {
@Override
public MCRViewerConfiguration get(HttpServletRequest request) {
if (isPDF(request)) {
return getPDF(request);
} else if (isEpub(request)) {
return getEpub(request);
} else if (isIIIF(request)) {
return getIIIF(request);
} else {
return getMETS(request);
}
}
private boolean isEpub(HttpServletRequest request) {
String filePath = MCRViewerConfiguration.getFilePath(request);
return filePath != null && filePath.toLowerCase(Locale.ROOT).endsWith(".epub");
}
protected boolean isPDF(HttpServletRequest request) {
// well, this is the best test to check the type, for sure!
String filePath = MCRViewerConfiguration.getFilePath(request);
return filePath != null && filePath.toLowerCase(Locale.ROOT).endsWith(".pdf");
}
private boolean isIIIF(HttpServletRequest request) {
return request.getPathInfo().contains("/iiif/");
}
protected MCRViewerConfiguration getPDF(HttpServletRequest request) {
return MCRViewerConfigurationBuilder.pdf(request).mixin(MCRViewerConfigurationBuilder.plugins(request).get())
.get();
}
protected MCRViewerConfiguration getEpub(HttpServletRequest request) {
return MCRViewerConfigurationBuilder.epub(request).mixin(MCRViewerConfigurationBuilder.plugins(request).get())
.get();
}
protected MCRViewerConfiguration getMETS(HttpServletRequest request) {
return MCRViewerConfigurationBuilder.metsAndPlugins(request).get();
}
protected MCRViewerConfiguration getIIIF(HttpServletRequest request) {
return MCRViewerConfigurationBuilder.iiif(request).mixin(MCRViewerConfigurationBuilder.plugins(request).get())
.get();
}
}
| 2,982 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIviewDefaultACLProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRIviewDefaultACLProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.access.MCRAccessManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.servlet.http.HttpSession;
public class MCRIviewDefaultACLProvider implements MCRIviewACLProvider {
@Override
public boolean checkAccess(HttpSession session, MCRObjectID derivateID) {
return MCRAccessManager.checkPermission(derivateID, MCRAccessManager.PERMISSION_VIEW) ||
MCRAccessManager.checkPermission(derivateID, MCRAccessManager.PERMISSION_READ);
}
}
| 1,269 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIviewACLProvider.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/configuration/MCRIviewACLProvider.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.configuration;
import org.mycore.datamodel.metadata.MCRObjectID;
import jakarta.servlet.http.HttpSession;
public interface MCRIviewACLProvider {
boolean checkAccess(HttpSession session, MCRObjectID derivateID);
}
| 973 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRViewerResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/resources/MCRViewerResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.resources;
import static org.mycore.common.xml.MCRLayoutService.getContentTransformer;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.xsl.MCRParameterCollector;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.services.i18n.MCRTranslation;
import org.mycore.viewer.configuration.MCRIviewACLProvider;
import org.mycore.viewer.configuration.MCRIviewDefaultACLProvider;
import org.mycore.viewer.configuration.MCRViewerConfiguration;
import org.mycore.viewer.configuration.MCRViewerConfigurationStrategy;
import org.mycore.viewer.configuration.MCRViewerDefaultConfigurationStrategy;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.CacheControl;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.EntityTag;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.xml.bind.JAXBException;
/**
* Base resource for the mycore image viewer.
*
* @author Matthias Eichner
* @author Sebastian Hofmann
*/
@Path("/viewer")
public class MCRViewerResource {
private static final MCRIviewACLProvider IVIEW_ACL_PROVDER = MCRConfiguration2
.<MCRIviewACLProvider>getInstanceOf("MCR.Viewer.MCRIviewACLProvider")
.orElseGet(MCRIviewDefaultACLProvider::new);
private static final String JSON_CONFIG_ELEMENT_NAME = "json";
@GET
@Path("{derivate}{path: (/[^?#]*)?}")
public Response show(@Context HttpServletRequest request, @Context Request jaxReq,
@Context ServletContext context, @Context ServletConfig config) throws Exception {
return showViewer(request, jaxReq);
}
@GET
@Path("iiif/{derivate}{path: (/[^?#]*)?}")
public Response showIIIF(@Context HttpServletRequest request, @Context Request jaxReq,
@Context ServletContext context, @Context ServletConfig config) throws Exception {
return showViewer(request, jaxReq);
}
private Response showViewer(HttpServletRequest request, Request jaxReq) throws Exception {
MCRContent content = getContent(request);
String contentETag = content.getETag();
Response.ResponseBuilder responseBuilder = null;
EntityTag eTag = contentETag == null ? null : new EntityTag(contentETag);
if (eTag != null) {
responseBuilder = jaxReq.evaluatePreconditions(eTag);
}
if (responseBuilder == null) {
responseBuilder = Response.ok(content.asByteArray(), MediaType.valueOf(content.getMimeType()));
}
if (eTag != null) {
responseBuilder.tag(eTag);
}
if (content.isUsingSession()) {
CacheControl cc = new CacheControl();
cc.setPrivate(true);
cc.setMaxAge(0);
cc.setMustRevalidate(true);
responseBuilder.cacheControl(cc);
}
return responseBuilder.build();
}
/**
* Builds the jdom configuration response document.
*
* @param config the mycore configuration object
* @return jdom configuration object
*/
private static Document buildResponseDocument(MCRViewerConfiguration config)
throws JDOMException, IOException, JAXBException {
String configJson = config.toJSON();
Element startIviewClientElement = new Element("IViewConfig");
Element configElement = new Element(JSON_CONFIG_ELEMENT_NAME);
startIviewClientElement.addContent(configElement);
startIviewClientElement.addContent(config.toXML().asXML().getRootElement().detach());
configElement.addContent(configJson);
return new Document(startIviewClientElement);
}
protected MCRContent getContent(final HttpServletRequest req)
throws Exception {
// get derivate id from request object
String derivate = MCRViewerConfiguration.getDerivate(req);
if (derivate == null) {
MCRJerseyUtil.throwException(Status.BAD_REQUEST, "Could not locate derivate identifer in path.");
}
// get mycore object id
final MCRObjectID derivateID = MCRObjectID.getInstance(derivate);
if (!MCRMetadataManager.exists(derivateID)) {
String errorMessage = MCRTranslation.translate("component.viewer.MCRIViewClientServlet.object.not.found",
derivateID);
MCRJerseyUtil.throwException(Status.NOT_FOUND, errorMessage);
}
// check permission
if (IVIEW_ACL_PROVDER != null && !IVIEW_ACL_PROVDER.checkAccess(req.getSession(), derivateID)) {
String errorMessage = MCRTranslation.translate("component.viewer.MCRIViewClientServlet.noRights",
derivateID);
MCRJerseyUtil.throwException(Status.UNAUTHORIZED, errorMessage);
}
// build configuration object
MCRViewerConfigurationStrategy configurationStrategy = MCRConfiguration2
.<MCRViewerDefaultConfigurationStrategy>getInstanceOf(
"MCR.Viewer.configuration.strategy")
.orElseGet(MCRViewerDefaultConfigurationStrategy::new);
MCRJDOMContent source = new MCRJDOMContent(buildResponseDocument(configurationStrategy.get(req)));
MCRParameterCollector parameter = new MCRParameterCollector(req);
MCRContentTransformer transformer = getContentTransformer(source.getDocType(), parameter);
return transformer.transform(source);
}
}
| 6,740 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRALTOEditorResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/resources/MCRALTOEditorResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.resources;
import java.util.Date;
import java.util.List;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.MCRJerseyUtil;
import org.mycore.viewer.alto.MCRALTOUtil;
import org.mycore.viewer.alto.model.MCRAltoChangePID;
import org.mycore.viewer.alto.model.MCRAltoChangeSet;
import org.mycore.viewer.alto.model.MCRStoredChangeSet;
import org.mycore.viewer.alto.service.MCRAltoChangeApplier;
import org.mycore.viewer.alto.service.MCRAltoChangeSetStore;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/viewer/alto")
public class MCRALTOEditorResource {
private MCRAltoChangeSetStore changeSetStore = MCRConfiguration2
.<MCRAltoChangeSetStore>getInstanceOf("MCR.Viewer.AltoChangeSetStore.Class").orElseThrow();
private MCRAltoChangeApplier changeApplier = MCRConfiguration2
.<MCRAltoChangeApplier>getInstanceOf("MCR.Viewer.AltoChangeApplier.Class").orElseThrow();
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/store")
public MCRAltoChangePID storeChangeSet(MCRAltoChangeSet changeSet) {
MCRJerseyUtil.checkPermission(changeSet.getDerivateID(), MCRALTOUtil.EDIT_ALTO_PERMISSION);
MCRStoredChangeSet storedChangeSet = changeSetStore.storeChangeSet(changeSet);
return new MCRAltoChangePID(storedChangeSet.getPid());
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/update/{pid}")
public MCRAltoChangePID updateChangeSet(MCRAltoChangeSet changeSet, @PathParam("pid") String pid) {
String currentSessionID = MCRSessionMgr.getCurrentSessionID();
if (currentSessionID != null && !currentSessionID.equals(changeSetStore.get(pid).getSessionID())) {
MCRJerseyUtil.checkPermission(changeSet.getDerivateID(), MCRALTOUtil.REVIEW_ALTO_PERMISSION);
}
MCRStoredChangeSet storedChangeSet = changeSetStore.updateChangeSet(pid, changeSet);
if (storedChangeSet == null) {
return storeChangeSet(changeSet);
} else {
return new MCRAltoChangePID(storedChangeSet.getPid());
}
}
@POST
@Path("/apply/{pid}")
public Response applyChangeSet(@PathParam("pid") String pid) {
MCRStoredChangeSet storedChangeSet = changeSetStore.get(pid);
MCRJerseyUtil.checkPermission(storedChangeSet.getDerivateID(), MCRALTOUtil.REVIEW_ALTO_PERMISSION);
changeApplier.applyChange(storedChangeSet.getChangeSet());
storedChangeSet.setApplied(new Date());
return Response.ok().build();
}
@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes()
@Path("/delete/{pid}")
public String deleteChangeSet(@PathParam("pid") String pid) {
String currentSessionID = MCRSessionMgr.getCurrentSessionID();
MCRStoredChangeSet storedChangeSet = changeSetStore.get(pid);
if (currentSessionID != null && !currentSessionID.equals(storedChangeSet.getSessionID())) {
MCRJerseyUtil.checkPermission(storedChangeSet.getDerivateID(), MCRALTOUtil.REVIEW_ALTO_PERMISSION);
}
changeSetStore.delete(pid);
return pid;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/list")
public List<MCRStoredChangeSet> listChangeSets(
@DefaultValue("0") @QueryParam("start") long start,
@DefaultValue("10") @QueryParam("count") long count,
@QueryParam("derivate") String derivate,
@QueryParam("session") String session) {
String currentSessionID = MCRSessionMgr.getCurrentSessionID();
if (currentSessionID == null || !currentSessionID.equals(session)) {
MCRJerseyUtil.checkPermission(MCRALTOUtil.REVIEW_ALTO_PERMISSION);
}
List<MCRStoredChangeSet> list;
if (derivate == null && session == null) {
list = changeSetStore.list(start, count);
} else if (derivate != null) {
list = changeSetStore.listByDerivate(start, count, derivate);
} else {
list = changeSetStore.listBySessionID(start, count, session);
}
return list;
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/list/count")
public long count() {
return changeSetStore.count();
}
}
| 5,371 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREpubZipResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/resources/MCREpubZipResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.resources;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.StreamSupport;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.jersey.MCRStaticContent;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
@Path("/epub")
@MCRStaticContent // prevents session creation
public class MCREpubZipResource {
public static final String EPUB_SPLIT = ".epub/";
@Context
HttpServletRequest request;
@Context
private HttpServletResponse response;
private static void suppressedClose(Closeable... closeus) {
for (Closeable closeme : closeus) {
if (closeme != null) {
try {
closeme.close();
} catch (IOException ignored) {
}
}
}
}
@GET
@Path("/{derivateID}/{epubFilePathAndPathInEpub:.+}")
public Response extract(
@PathParam("derivateID") String derivateID,
@PathParam("epubFilePathAndPathInEpub") String epubFileAndSubpath) {
java.nio.file.Path epubPath = null;
final String[] split = epubFileAndSubpath.split(EPUB_SPLIT, 2);
if (split.length != 2) {
throw new WebApplicationException("The path seems to be wrong: " + epubFileAndSubpath,
Response.Status.BAD_REQUEST);
}
final String epubFile = split[0] + EPUB_SPLIT.substring(0, EPUB_SPLIT.length() - 1);
final String pathInEpub = split[1];
MCRSession session = null;
try { // creates a quick session to get the physical path to the epub from db and check rights
MCRSessionMgr.unlock();
session = MCRServlet.getSession(request);
MCRSessionMgr.setCurrentSession(session);
MCRFrontendUtil.configureSession(session, request, response);
if (!MCRAccessManager.checkPermission(derivateID, MCRAccessManager.PERMISSION_READ)) {
throw new WebApplicationException("No rights to read " + derivateID, Response.Status.FORBIDDEN);
}
epubPath = MCRPath.getPath(derivateID, epubFile).toPhysicalPath();
} catch (IOException e) {
throw new WebApplicationException("Error while resolving physical path of " + derivateID + ":" + epubFile,
e);
} finally { // releases the session reliable
try {
if (session != null && MCRTransactionHelper.isTransactionActive()) {
if (MCRTransactionHelper.transactionRequiresRollback()) {
MCRTransactionHelper.rollbackTransaction();
} else {
MCRTransactionHelper.commitTransaction();
}
}
} finally {
MCRSessionMgr.releaseCurrentSession();
MCRSessionMgr.lock();
}
}
if (!Files.exists(epubPath)) {
throw new WebApplicationException("The file " + derivateID + ":" + epubFile + " is not present!",
Response.Status.NOT_FOUND);
}
// try with closeable can not be used in this case.
// The streams/files would be closed after we leave this method
// StreamingOutput is called after this method is left
// StreamingOutput would try to call write/read on the closed stream
// this method is responsible for the streams and the zip file until the point responsible is set to false
// after that the StreamingOutput is responsible
SeekableByteChannel epubStream = null;
InputStream zipFileStream = null;
ZipFile zipFile = null;
boolean responsible = true;
try {
epubStream = Files.newByteChannel(epubPath, StandardOpenOption.READ);
zipFile = new ZipFile.Builder().setSeekableByteChannel(epubStream).get();
final Optional<ZipArchiveEntry> entryOfFileInEpub = StreamSupport
.stream(Spliterators.spliteratorUnknownSize(zipFile.getEntries().asIterator(), Spliterator.ORDERED),
false)
.filter(entry -> !entry.isDirectory())
.filter(entry -> Optional.ofNullable(entry.getName()).filter(pathInEpub::equals).isPresent())
.findFirst();
final ZipArchiveEntry zipArchiveEntry = entryOfFileInEpub
.orElseThrow(() -> new WebApplicationException("EPUB does not contain: " + pathInEpub,
Response.Status.NOT_FOUND));
zipFileStream = zipFile.getInputStream(zipArchiveEntry);
final InputStream finalZipFileStream = zipFileStream;
final Closeable finalZipFile = zipFile;
final Closeable finalEpubStream = epubStream;
StreamingOutput out = output -> {
try {
IOUtils.copy(finalZipFileStream, output);
} catch (IOException e) {
// suppress spamming the console with broken pipe on request abort
} finally {
suppressedClose(finalZipFileStream, finalZipFile, finalEpubStream);
}
};
responsible = false;
return Response.ok(out).build();
} catch (IOException e) {
throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
} finally {
if (responsible) {
// if responsible is true then this method is responsible for closing
suppressedClose(zipFileStream, zipFile, epubStream);
}
}
}
}
| 7,310 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRALTOUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/MCRALTOUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto;
public class MCRALTOUtil {
public static final String EDIT_ALTO_PERMISSION = "edit-alto";
public static final String REVIEW_ALTO_PERMISSION = "review-alto";
}
| 928 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoChangeSetStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/MCRAltoChangeSetStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service;
import java.util.List;
import org.mycore.viewer.alto.model.MCRAltoChangeSet;
import org.mycore.viewer.alto.model.MCRStoredChangeSet;
public interface MCRAltoChangeSetStore {
MCRStoredChangeSet get(String pid);
MCRStoredChangeSet storeChangeSet(MCRAltoChangeSet changeSet);
MCRStoredChangeSet updateChangeSet(String pid, MCRAltoChangeSet changeSet);
List<MCRStoredChangeSet> list();
List<MCRStoredChangeSet> listBySessionID(String sessionID);
List<MCRStoredChangeSet> listByDerivate(String derivateID);
List<MCRStoredChangeSet> list(long start, long count);
List<MCRStoredChangeSet> listBySessionID(long start, long count, String sessionID);
List<MCRStoredChangeSet> listByDerivate(long start, long count, String derivateID);
long count();
void delete(String pid);
}
| 1,591 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDerivateTitleResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/MCRDerivateTitleResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service;
public interface MCRDerivateTitleResolver {
String resolveTitle(String derivateID);
}
| 858 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoChangeApplier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/MCRAltoChangeApplier.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service;
import org.mycore.viewer.alto.model.MCRAltoChangeSet;
public interface MCRAltoChangeApplier {
void applyChange(MCRAltoChangeSet changeSet);
}
| 915 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultAltoChangeApplier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/impl/MCRDefaultAltoChangeApplier.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.viewer.alto.model.MCRAltoChangeSet;
import org.mycore.viewer.alto.model.MCRAltoWordChange;
import org.mycore.viewer.alto.service.MCRAltoChangeApplier;
public class MCRDefaultAltoChangeApplier implements MCRAltoChangeApplier {
private static final Logger LOGGER = LogManager.getLogger();
private Map<String, List<MCRAltoWordChange>> fileChangeMap = new ConcurrentHashMap<>();
@Override
public void applyChange(MCRAltoChangeSet changeSet) {
String derivateID = changeSet.getDerivateID();
changeSet.getWordChanges().stream().forEach(change -> {
List<MCRAltoWordChange> list = fileChangeMap.computeIfAbsent(change.getFile(), (k) -> new ArrayList<>());
list.add(change);
});
fileChangeMap.keySet().forEach(file -> {
LOGGER.info("Open file {} to apply changes!", file);
MCRPath altoFilePath = MCRPath.getPath(derivateID, file);
if (!Files.exists(altoFilePath)) {
LOGGER.warn("Could not find file {} which was referenced by alto change!", altoFilePath);
throw new MCRException(new IOException("Alto-File " + altoFilePath + " does not exist"));
}
Document altoDocument = readALTO(altoFilePath);
List<MCRAltoWordChange> wordChangesInThisFile = fileChangeMap.get(file);
wordChangesInThisFile.stream().forEach(wordChange -> {
String xpath = String
.format(Locale.ROOT, "//alto:String[number(@HPOS)=number('%d') and number(@VPOS)=number('%d')]",
wordChange.getHpos(), wordChange.getVpos());
List<Element> wordToChange = XPathFactory.instance()
.compile(xpath, Filters.element(), null, MCRConstants.ALTO_NAMESPACE).evaluate(altoDocument);
if (wordToChange.size() != 1) {
LOGGER.warn("Found {} words to change.", wordToChange.size());
}
wordToChange.forEach(word -> {
word.setAttribute("CONTENT", wordChange.getTo());
word.setAttribute("WC", "1");
});
});
storeALTO(altoFilePath, altoDocument);
});
}
private void storeALTO(MCRPath altoFilePath, Document altoDocument) {
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
try (OutputStream outputStream = Files
.newOutputStream(altoFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.WRITE)) {
xmlOutputter.output(altoDocument, outputStream);
} catch (IOException e) {
throw new MCRException(e);
}
}
private Document readALTO(MCRPath altoFilePath) {
try (InputStream inputStream = Files.newInputStream(altoFilePath, StandardOpenOption.READ)) {
return new SAXBuilder().build(inputStream);
} catch (JDOMException | IOException e) {
throw new MCRException(e);
}
}
}
| 4,622 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJPAAltoChangeSetStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/impl/MCRJPAAltoChangeSetStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service.impl;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.viewer.alto.model.MCRAltoChangeSet;
import org.mycore.viewer.alto.model.MCRDBStoredChangeSet;
import org.mycore.viewer.alto.model.MCRStoredChangeSet;
import org.mycore.viewer.alto.service.MCRAltoChangeSetStore;
import org.mycore.viewer.alto.service.MCRDerivateTitleResolver;
public class MCRJPAAltoChangeSetStore implements MCRAltoChangeSetStore {
private MCRDerivateTitleResolver titleResolver = MCRConfiguration2
.<MCRDerivateTitleResolver>getInstanceOf("MCR.Viewer.DerivateTitleResolver.Class").orElseThrow();
@Override
public MCRStoredChangeSet get(String pid) {
return MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.ByPID", MCRDBStoredChangeSet.class)
.setParameter("pid", pid)
.getSingleResult();
}
@Override
public MCRStoredChangeSet storeChangeSet(MCRAltoChangeSet changeSet) {
String objectTitle = titleResolver.resolveTitle(changeSet.getDerivateID());
String userID = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
MCRDBStoredChangeSet storedChangeSet = new MCRDBStoredChangeSet(MCRSessionMgr.getCurrentSessionID(),
changeSet.getDerivateID(), objectTitle, new Date(), null,
userID, changeSet);
MCREntityManagerProvider.getCurrentEntityManager().persist(storedChangeSet);
return storedChangeSet;
}
@Override
public MCRStoredChangeSet updateChangeSet(String pid, MCRAltoChangeSet changeSet) {
MCRStoredChangeSet storedChangeSet = get(pid);
storedChangeSet.setChangeSet(changeSet);
return storedChangeSet;
}
@Override
public List<MCRStoredChangeSet> list() {
return castList(MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.Unapplied", MCRDBStoredChangeSet.class)
.getResultList());
}
@Override
public List<MCRStoredChangeSet> listBySessionID(String sessionID) {
return castList(MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.Unapplied.bySID", MCRDBStoredChangeSet.class)
.setParameter("sid", sessionID)
.getResultList());
}
@Override
public List<MCRStoredChangeSet> listByDerivate(String derivateID) {
return castList(MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.Unapplied.byDerivate", MCRDBStoredChangeSet.class)
.setParameter("derivateID", derivateID)
.getResultList());
}
@Override
public List<MCRStoredChangeSet> list(long start, long count) {
return castList(MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.Unapplied", MCRDBStoredChangeSet.class)
.setFirstResult(Math.toIntExact(start))
.setMaxResults(Math.toIntExact(count))
.getResultList());
}
@Override
public List<MCRStoredChangeSet> listBySessionID(long start, long count, String sessionID) {
return castList(MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.Unapplied.bySID", MCRDBStoredChangeSet.class)
.setParameter("sid", sessionID)
.setFirstResult(Math.toIntExact(start))
.setMaxResults(Math.toIntExact(count))
.getResultList());
}
@Override
public List<MCRStoredChangeSet> listByDerivate(long start, long count, String derivateID) {
return castList(MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Get.ALTOCS.Unapplied.byDerivate", MCRDBStoredChangeSet.class)
.setParameter("derivateID", derivateID)
.setFirstResult(Math.toIntExact(start))
.setMaxResults(Math.toIntExact(count))
.getResultList());
}
@Override
public long count() {
return MCREntityManagerProvider
.getCurrentEntityManager()
.createNamedQuery("Count.ALTOCS.Unapplied", Number.class)
.getSingleResult()
.longValue();
}
@Override
public void delete(String pid) {
MCREntityManagerProvider.getCurrentEntityManager()
.createNamedQuery("Delete.ALTOCS.byPID")
.setParameter("pid", pid)
.executeUpdate();
}
private List<MCRStoredChangeSet> castList(List<MCRDBStoredChangeSet> storedChangeSet) {
return storedChangeSet.stream().map(MCRStoredChangeSet.class::cast).collect(Collectors.toList());
}
}
| 5,704 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultDerivateTitleResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/impl/MCRDefaultDerivateTitleResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service.impl;
import java.util.concurrent.TimeUnit;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.viewer.alto.service.MCRDerivateTitleResolver;
public class MCRDefaultDerivateTitleResolver implements MCRDerivateTitleResolver {
private static final int EXPIRE_METADATA_CACHE_TIME = 10; // in seconds
@Override
public String resolveTitle(String derivateIDString) {
MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDString);
final MCRObjectID objectID = MCRMetadataManager.getObjectId(derivateID, EXPIRE_METADATA_CACHE_TIME,
TimeUnit.SECONDS);
MCRObject object = MCRMetadataManager.retrieveMCRObject(objectID);
return object.getStructure().getDerivateLink(derivateID).getXLinkTitle();
}
}
| 1,645 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMemoryChangeSetStore.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/service/impl/MCRMemoryChangeSetStore.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.service.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.viewer.alto.model.MCRAltoChangeSet;
import org.mycore.viewer.alto.model.MCRStoredChangeSet;
import org.mycore.viewer.alto.service.MCRAltoChangeSetStore;
import org.mycore.viewer.alto.service.MCRDerivateTitleResolver;
public class MCRMemoryChangeSetStore implements MCRAltoChangeSetStore {
private MCRDerivateTitleResolver titleResolver = MCRConfiguration2
.<MCRDerivateTitleResolver>getInstanceOf("MCR.Viewer.DerivateTitleResolver.Class").orElseThrow();
private Map<String, List<MCRStoredChangeSet>> derivateChangeSet = new HashMap<>();
private Map<String, List<MCRStoredChangeSet>> sessionIDChangeSet = new HashMap<>();
private Map<String, MCRStoredChangeSet> idChangeSet = new HashMap<>();
public MCRMemoryChangeSetStore() {
}
@Override
public MCRStoredChangeSet get(String pid) {
return this.idChangeSet.get(pid);
}
@Override
public MCRStoredChangeSet storeChangeSet(MCRAltoChangeSet changeSet) {
MCRStoredChangeSet mcrStoredChangeSet = new MCRStoredChangeSet();
String derivateID = changeSet.getDerivateID();
String objectTitle = titleResolver.resolveTitle(derivateID);
mcrStoredChangeSet.setUser(MCRSessionMgr.getCurrentSession().getUserInformation().getUserID());
mcrStoredChangeSet.setObjectTitle(objectTitle);
mcrStoredChangeSet.setCreated(new Date());
mcrStoredChangeSet.setChangeSet(changeSet);
mcrStoredChangeSet.setSessionID(MCRSessionMgr.getCurrentSessionID());
mcrStoredChangeSet.setDerivateID(derivateID);
return storeChangeSet(mcrStoredChangeSet);
}
public MCRStoredChangeSet storeChangeSet(MCRStoredChangeSet storedChangeSet) {
addTo(derivateChangeSet, storedChangeSet.getDerivateID(), storedChangeSet);
addTo(sessionIDChangeSet, storedChangeSet.getSessionID(), storedChangeSet);
idChangeSet.put(storedChangeSet.getPid(), storedChangeSet);
return storedChangeSet;
}
@Override
public MCRStoredChangeSet updateChangeSet(String pid, MCRAltoChangeSet changeSet) {
MCRStoredChangeSet storedChangeSet = this.get(pid);
this.delete(pid);
return this.storeChangeSet(storedChangeSet);
}
@Override
public List<MCRStoredChangeSet> list() {
return new ArrayList<>(idChangeSet.values());
}
@Override
public List<MCRStoredChangeSet> listBySessionID(String sessionID) {
List<MCRStoredChangeSet> changeSets = sessionIDChangeSet.get(sessionID);
if (changeSets != null) {
return changeSets.stream().filter(change -> change.getApplied() == null).collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public List<MCRStoredChangeSet> listByDerivate(String derivateID) {
List<MCRStoredChangeSet> changeSets = derivateChangeSet.get(derivateID);
if (changeSets != null) {
return changeSets.stream().filter(change -> change.getApplied() == null).collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public List<MCRStoredChangeSet> list(long start, long count) {
return idChangeSet
.values()
.stream()
.filter(change -> change.getApplied() == null)
.skip(start)
.limit(count)
.collect(Collectors.toList());
}
@Override
public List<MCRStoredChangeSet> listBySessionID(long start, long count, String sessionID) {
List<MCRStoredChangeSet> changeSets = sessionIDChangeSet
.get(sessionID);
if (changeSets != null) {
return changeSets
.stream()
.filter(change -> change.getApplied() == null)
.skip(start)
.limit(count)
.collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public List<MCRStoredChangeSet> listByDerivate(long start, long count, String derivateID) {
List<MCRStoredChangeSet> changeSets = derivateChangeSet
.get(derivateID);
if (changeSets != null) {
return changeSets
.stream()
.filter(change -> change.getApplied() == null)
.skip(start)
.limit(count)
.collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public long count() {
return idChangeSet.size();
}
@Override
public void delete(String pid) {
MCRStoredChangeSet mcrStoredChangeSet = idChangeSet.get(pid);
derivateChangeSet.get(mcrStoredChangeSet.getDerivateID()).remove(mcrStoredChangeSet);
sessionIDChangeSet.get(mcrStoredChangeSet.getSessionID()).remove(mcrStoredChangeSet);
this.idChangeSet.remove(pid);
}
private void addTo(Map<String, List<MCRStoredChangeSet>> setMap, String key, MCRStoredChangeSet set) {
List<MCRStoredChangeSet> list;
if (setMap.containsKey(key)) {
list = setMap.get(key);
} else {
list = new ArrayList<>();
setMap.put(key, list);
}
list.add(set);
}
}
| 6,307 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDBStoredChangeSet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRDBStoredChangeSet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
import java.io.IOException;
import java.util.Date;
import org.mycore.common.MCRException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Lob;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
@Entity(name = MCRDBStoredChangeSet.ENTITY_NAME)
@Table(name = MCRDBStoredChangeSet.ENTITY_NAME)
@NamedQueries({
@NamedQuery(name = "Count.ALTOCS.Unapplied",
query = "select count(u) from " + MCRDBStoredChangeSet.ENTITY_NAME + " u "
+ "where u.applied IS NULL"),
@NamedQuery(name = "Get.ALTOCS.ByPID",
query = "select u from " + MCRDBStoredChangeSet.ENTITY_NAME + " u "
+ "where u.pid = :pid "
+ "and u.applied IS NULL"),
@NamedQuery(name = "Get.ALTOCS.Unapplied",
query = "select u from " + MCRDBStoredChangeSet.ENTITY_NAME + " u where u.applied IS NULL"),
@NamedQuery(name = "Get.ALTOCS.Unapplied.bySID",
query = "select u from " + MCRDBStoredChangeSet.ENTITY_NAME
+ " u where u.sessionID = :sid and u.applied IS NULL"),
@NamedQuery(name = "Get.ALTOCS.Unapplied.byDerivate",
query = "select u from " + MCRDBStoredChangeSet.ENTITY_NAME
+ " u where u.derivateID = :derivateID and u.applied IS NULL"),
@NamedQuery(name = "Delete.ALTOCS.byPID",
query = "delete from " + MCRDBStoredChangeSet.ENTITY_NAME + " u where u.pid = :pid") })
public class MCRDBStoredChangeSet extends MCRStoredChangeSet {
protected static final String ENTITY_NAME = "MCRAltoChangeStore";
protected static final int MB = 1024 * 1024 * 1024;
@Column(nullable = false, length = MB)
@Lob
@Basic(fetch = FetchType.LAZY)
private String altoChangeSet;
public MCRDBStoredChangeSet() {
}
public MCRDBStoredChangeSet(String sessionID, String derivateID, String objectTitle, Date created,
Date applied, String user, MCRAltoChangeSet altoChangeSet) {
super(sessionID, derivateID, objectTitle, created, applied, user);
setChangeSet(altoChangeSet);
}
public String getAltoChangeSet() {
return altoChangeSet;
}
public void setAltoChangeSet(String altoChangeSet) {
super.setChangeSet(stringToChangeSet(altoChangeSet));
this.altoChangeSet = altoChangeSet;
}
@Override
public MCRAltoChangeSet getChangeSet() {
return stringToChangeSet(this.altoChangeSet);
}
@Override
public void setChangeSet(MCRAltoChangeSet changeSet) {
super.setChangeSet(changeSet);
setAltoChangeSet(changeSetToString(changeSet));
}
private MCRAltoChangeSet stringToChangeSet(String changeSet) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(changeSet, MCRAltoChangeSet.class);
} catch (IOException e) {
throw new MCRException("Could not create changeSet from json string", e);
}
}
private String changeSetToString(MCRAltoChangeSet changeSet) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(changeSet);
} catch (JsonProcessingException e) {
throw new MCRException("Could not create json from changeSet object", e);
}
}
}
| 4,289 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoredChangeSet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRStoredChangeSet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.Transient;
@MappedSuperclass
public class MCRStoredChangeSet extends MCRStoredAltoChangeSetMetadata {
public MCRStoredChangeSet() {
}
public MCRStoredChangeSet(String sessionID, String derivateID, String objectTitle, Date created,
Date applied, String user) {
super(sessionID, derivateID, objectTitle, created, applied, user);
}
@Transient
@JsonInclude()
private MCRAltoChangeSet changeSet;
public MCRAltoChangeSet getChangeSet() {
return changeSet;
}
public void setChangeSet(MCRAltoChangeSet changeSet) {
this.changeSet = changeSet;
}
}
| 1,537 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoChange.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRAltoChange.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
public class MCRAltoChange {
public MCRAltoChange(String file, String type) {
this.file = file;
this.type = type;
}
public MCRAltoChange() {
}
private String file;
private String type;
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 1,256 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStoredAltoChangeSetMetadata.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRStoredAltoChangeSetMetadata.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
import java.util.Date;
import java.util.UUID;
import jakarta.persistence.Column;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
@MappedSuperclass
public class MCRStoredAltoChangeSetMetadata {
public MCRStoredAltoChangeSetMetadata() {
this.pid = UUID.randomUUID().toString();
}
public MCRStoredAltoChangeSetMetadata(String sessionID, String derivateID, String objectTitle, Date created,
Date applied, String user) {
this();
this.sessionID = sessionID;
this.derivateID = derivateID;
this.objectTitle = objectTitle;
this.created = created;
this.applied = applied;
this.user = user;
}
@Column(nullable = false)
private String sessionID;
@Column(nullable = false)
private String derivateID;
@Column(nullable = false)
private String objectTitle;
@Column(nullable = false)
private Date created;
private Date applied;
@Id
private String pid;
@Column(nullable = false, name = "username")
private String user;
public String getSessionID() {
return sessionID;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getDerivateID() {
return derivateID;
}
public void setDerivateID(String derivateID) {
this.derivateID = derivateID;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getObjectTitle() {
return objectTitle;
}
public void setObjectTitle(String objectTitle) {
this.objectTitle = objectTitle;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Date getApplied() {
return applied;
}
public void setApplied(Date applied) {
this.applied = applied;
}
}
| 2,888 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoChangeSet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRAltoChangeSet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
import java.util.ArrayList;
import java.util.List;
public class MCRAltoChangeSet {
private List<MCRAltoWordChange> wordChanges;
private String derivateID;
public MCRAltoChangeSet(String derivateID, List<MCRAltoWordChange> wordChanges) {
this.derivateID = derivateID;
this.wordChanges = wordChanges;
}
public MCRAltoChangeSet() {
this.wordChanges = new ArrayList<>();
}
public List<MCRAltoWordChange> getWordChanges() {
return wordChanges;
}
public String getDerivateID() {
return derivateID;
}
public void setDerivateID(String derivateID) {
this.derivateID = derivateID;
}
}
| 1,445 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoChangePID.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRAltoChangePID.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
public class MCRAltoChangePID {
public MCRAltoChangePID(String pid) {
this.pid = pid;
}
public MCRAltoChangePID() {
}
private String pid;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
}
| 1,061 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAltoWordChange.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-viewer/src/main/java/org/mycore/viewer/alto/model/MCRAltoWordChange.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.viewer.alto.model;
public class MCRAltoWordChange extends MCRAltoChange {
public MCRAltoWordChange(String file, String type, int hpos, int vpos, int width, int height, String from,
String to) {
super(file, type);
this.hpos = hpos;
this.vpos = vpos;
this.width = width;
this.height = height;
this.from = from;
this.to = to;
}
public MCRAltoWordChange() {
}
private int hpos;
private int vpos;
private int width;
private int height;
private String from;
private String to;
public int getHpos() {
return hpos;
}
public int getVpos() {
return vpos;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
}
| 1,670 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTEIValidatorTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-tei/src/test/java/org/mycore/coma/model/validation/MCRTEIValidatorTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.coma.model.validation;
import java.io.IOException;
import java.net.URL;
import javax.xml.transform.stream.StreamSource;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.tei.MCRTEIValidator;
import org.xml.sax.SAXException;
public class MCRTEIValidatorTest {
@Test
public void validate() throws IOException, SAXException {
MCRTEIValidator teiValidator = getTeiValidator("xml/validTei.xml");
teiValidator.validate();
Assert.assertTrue(teiValidator.getErrors().size() + teiValidator.getFatals().size() == 0);
}
@Test
public void validateFail() throws IOException, SAXException {
MCRTEIValidator teiValidator = getTeiValidator("xml/invalidTei.xml");
teiValidator.validate();
Assert.assertTrue(teiValidator.getErrors().size() + teiValidator.getFatals().size() > 0);
}
private MCRTEIValidator getTeiValidator(String path) throws IOException {
URL resource = MCRTEIValidatorTest.class.getClassLoader().getResource(path);
return new MCRTEIValidator(new StreamSource(resource.openStream()));
}
}
| 1,856 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTEIValidator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-tei/src/main/java/org/mycore/tei/MCRTEIValidator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.tei;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* SAX Error handler for validating TEI XML
*/
public class MCRTEIValidator implements ErrorHandler {
/**
* XML Schema file for transcriptions
*/
public static final String MCR_TRANSCRIPTION_SCHEMA = "xsd/mcrtranscr.xsd";
/**
* Exception map key: fatalError
*/
public static final String FATAL_ERROR = "fatalError";
/**
* Exception map key: error
*/
public static final String ERROR = "error";
/**
* Exception map key: warning
*/
public static final String WARNING = "warning";
private Hashtable<String, List<SAXParseException>> exceptionMap;
private Source teiSource;
/**
* initialize TEI validator
* @param teiSource - the TEI XML source
*/
public MCRTEIValidator(Source teiSource) {
this.teiSource = teiSource;
this.exceptionMap = new Hashtable<>();
this.exceptionMap.put(WARNING, new ArrayList<>());
this.exceptionMap.put(ERROR, new ArrayList<>());
this.exceptionMap.put(FATAL_ERROR, new ArrayList<>());
}
private Schema getSchema(String path) throws SAXException {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", false);
schemaFactory.setErrorHandler(this);
return schemaFactory.newSchema(MCRTEIValidator.class.getClassLoader().getResource(
path));
}
/**
* run the TEI validator
* @throws IOException - if the input cannot be read
* @throws SAXException - if the XML parsing fails
*/
public void validate() throws IOException, SAXException {
Validator validator = this.getSchema(MCR_TRANSCRIPTION_SCHEMA).newValidator();
validator.setErrorHandler(this);
validator.validate(this.teiSource);
}
@Override
public void warning(SAXParseException exception) {
this.exceptionMap.get(WARNING).add(exception);
}
@Override
public void error(SAXParseException exception) {
this.exceptionMap.get(ERROR).add(exception);
}
@Override
public void fatalError(SAXParseException exception) {
this.exceptionMap.get(FATAL_ERROR).add(exception);
}
/**
* @return the list of warnings
*/
public List<SAXParseException> getWarnings() {
return this.exceptionMap.get(WARNING);
}
/**
* @return the list of errors
*/
public List<SAXParseException> getErrors() {
return this.exceptionMap.get(ERROR);
}
/**
* @return the list of fatal errors
*/
public List<SAXParseException> getFatals() {
return this.exceptionMap.get(FATAL_ERROR);
}
}
| 3,929 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMigrationCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-migration/src/main/java/org/mycore/migration/cli/MCRMigrationCommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.migration.cli;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.Filters;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.mycore.access.MCRAccessException;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.backend.jpa.links.MCRLINKHREF;
import org.mycore.backend.jpa.links.MCRLINKHREFPK_;
import org.mycore.backend.jpa.links.MCRLINKHREF_;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRException;
import org.mycore.common.MCRPersistenceException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.common.content.transformer.MCRXSLTransformer;
import org.mycore.common.xml.MCRXMLFunctions;
import org.mycore.datamodel.common.MCRAbstractMetadataVersion;
import org.mycore.datamodel.common.MCRLinkTableManager;
import org.mycore.datamodel.common.MCRXMLMetadataManager;
import org.mycore.datamodel.metadata.MCRBase;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRMetaDerivateLink;
import org.mycore.datamodel.metadata.MCRMetaEnrichedLinkID;
import org.mycore.datamodel.metadata.MCRMetaLangText;
import org.mycore.datamodel.metadata.MCRMetaLinkID;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.datamodel.metadata.MCRObjectService;
import org.mycore.datamodel.metadata.MCRObjectStructure;
import org.mycore.datamodel.niofs.MCRPath;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import org.mycore.iview2.services.MCRTileJob;
import org.xml.sax.SAXException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
/**
* @author Thomas Scheffler (yagee)
*/
@MCRCommandGroup(name = "MyCoRe migration")
public class MCRMigrationCommands {
private static final Logger LOGGER = LogManager.getLogger();
@MCRCommand(syntax = "migrate author servflags",
help = "Create missing servflags for createdby and modifiedby. (MCR-786)",
order = 20)
public static List<String> addServFlags() {
TreeSet<String> ids = new TreeSet<>(MCRXMLMetadataManager.instance().listIDs());
ArrayList<String> cmds = new ArrayList<>(ids.size());
for (String id : ids) {
cmds.add("migrate author servflags for " + id);
}
return cmds;
}
@MCRCommand(syntax = "migrate author servflags for {0}",
help = "Create missing servflags for createdby and modifiedby for object {0}. (MCR-786)",
order = 10)
public static void addServFlags(String id)
throws IOException, MCRPersistenceException, MCRAccessException {
MCRObjectID objectID = MCRObjectID.getInstance(id);
MCRBase obj = MCRMetadataManager.retrieve(objectID);
MCRObjectService service = obj.getService();
if (!service.isFlagTypeSet(MCRObjectService.FLAG_TYPE_CREATEDBY)) { //the egg
List<? extends MCRAbstractMetadataVersion<?>> versions = MCRXMLMetadataManager.instance()
.listRevisions(objectID);
String createUser = null, modifyUser = null;
if (versions == null) {
LOGGER.warn(
"Cannot restore author servflags as there are no versions available. Setting to current user.");
createUser = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
modifyUser = createUser;
} else {
MCRAbstractMetadataVersion<?> firstVersion = versions.get(0);
for (MCRAbstractMetadataVersion<?> version : versions) {
if (version.getType() == 'A') {
firstVersion = version; // get last 'added'
}
}
MCRAbstractMetadataVersion<?> lastVersion = versions.get(versions.size() - 1);
createUser = firstVersion.getUser();
modifyUser = lastVersion.getUser();
}
service.addFlag(MCRObjectService.FLAG_TYPE_CREATEDBY, createUser);
LOGGER.info("{}, created by: {}", objectID, createUser);
if (!service.isFlagTypeSet(MCRObjectService.FLAG_TYPE_MODIFIEDBY)) { //the chicken
//have to restore also modifiedby from version history.
LOGGER.info("{}, modified by: {}", objectID, modifyUser);
service.addFlag(MCRObjectService.FLAG_TYPE_MODIFIEDBY, modifyUser);
}
obj.setImportMode(true);
MCRMetadataManager.update(obj);
}
}
@MCRCommand(syntax = "fix MCR-1717", help = "Fixes wrong entries in tile job table (see MCR-1717 comments)")
public static void fixMCR1717() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
List<MCRTileJob> tiles = allTileJobQuery.getResultList();
tiles.stream()
.filter(tj -> !tj.getPath().startsWith("/"))
.peek(tj -> LOGGER.info("Fixing TileJob {}:{}", tj.getDerivate(), tj.getPath()))
.forEach(tj -> {
String newPath = "/" + tj.getPath();
tj.setPath(newPath);
});
}
@MCRCommand(syntax = "fix invalid derivate links {0} for {1}",
help = "Fixes the paths of all derivate links "
+ "({0} -> xpath -> e.g. /mycoreobject/metadata/derivateLinks/derivateLink) for object {1}. (MCR-1267)",
order = 15)
public static void fixDerivateLinks(String xpath, String id) throws IOException, JDOMException, SAXException {
// get mcr object
MCRObjectID objectID = MCRObjectID.getInstance(id);
// find derivate links
Document xml = MCRXMLMetadataManager.instance().retrieveXML(objectID);
Element mcrObjectXML = xml.getRootElement();
XPathExpression<Element> expression = XPathFactory.instance().compile(xpath, Filters.element());
List<Element> derivateLinkElements = expression.evaluate(mcrObjectXML);
// check them
boolean changedObject = false;
for (Element derivateLinkElement : derivateLinkElements) {
String href = derivateLinkElement.getAttributeValue("href", MCRConstants.XLINK_NAMESPACE);
MCRMetaDerivateLink link = new MCRMetaDerivateLink();
link.setReference(href, null, null);
String owner = link.getOwner();
try {
String path = link.getPath();
MCRPath mcrPath = MCRPath.getPath(owner, path);
if (!Files.exists(mcrPath)) {
// path is correct URI encoded but not found.
// this could have two reasons
// 1. the file does not exist on the file system
// 2. maybe the path isn't correct URI decoded
// -> e.g. a?c.tif -> path (a), query (c.tif) which is obvious wrong
if (tryRawPath(objectID, derivateLinkElement, href, link, owner)) {
changedObject = true;
} else {
LOGGER.warn("{} of {}cannot be found on file system. This is most likly a dead link.", href,
objectID);
}
}
} catch (URISyntaxException uriExc) {
// path could not be decoded, so maybe its already decoded
// check if the file with href exists, if so, the path is
// not encoded properly
if (tryRawPath(objectID, derivateLinkElement, href, link, owner)) {
changedObject = true;
} else {
LOGGER.warn(
"{} of {} isn't URI encoded and cannot be found on file system."
+ " This is most likly a dead link.",
href, objectID);
}
}
}
// store the mcr object if its changed
if (changedObject) {
// we use MCRXMLMetadataMananger because we don't want to validate the old mcr object
MCRXMLMetadataManager.instance().update(objectID, xml, new Date());
// manually fire update event
MCRObject newObject = MCRMetadataManager.retrieveMCRObject(objectID);
newObject.setImportMode(true);
MCRMetadataManager.fireUpdateEvent(newObject);
}
}
private static boolean tryRawPath(MCRObjectID objectID, Element derivateLinkElement, String href,
MCRMetaDerivateLink link, String owner) {
String rawPath = link.getRawPath();
MCRPath mcrPath = MCRPath.getPath(owner, rawPath);
if (Files.exists(mcrPath)) {
// path exists -> do URI encoding for href
try {
String encodedHref = MCRXMLFunctions.encodeURIPath(rawPath);
derivateLinkElement.setAttribute("href", owner + encodedHref, MCRConstants.XLINK_NAMESPACE);
return true;
} catch (URISyntaxException uriEncodeException) {
LOGGER.error("Unable to encode {} for object {}", rawPath, objectID, uriEncodeException);
return false;
}
}
return false;
}
@MCRCommand(syntax = "add missing children to {0}",
help = "Adds missing children to structure of parent {0}. (MCR-1480)",
order = 15)
public static void fixMissingChildren(String id) {
MCRObjectID parentId = MCRObjectID.getInstance(id);
Collection<String> children = MCRLinkTableManager.instance().getSourceOf(parentId,
MCRLinkTableManager.ENTRY_TYPE_PARENT);
if (children.isEmpty()) {
return;
}
MCRObject parent = MCRMetadataManager.retrieveMCRObject(parentId);
MCRObjectStructure parentStructure = parent.getStructure();
int sizeBefore = parentStructure.getChildren().size();
children.stream().map(MCRObjectID::getInstance)
.filter(cid -> !parentStructure.getChildren().stream()
.anyMatch(candidate -> candidate.getXLinkHrefID().equals(cid)))
.sorted().map(MCRMigrationCommands::toLinkId).sequential()
.peek(lid -> LOGGER.info("Adding {} to {}", lid, parentId)).forEach(parentStructure::addChild);
if (parentStructure.getChildren().size() != sizeBefore) {
MCRMetadataManager.fireUpdateEvent(parent);
}
}
private static MCRMetaLinkID toLinkId(MCRObjectID mcrObjectID) {
return new MCRMetaLinkID("child", mcrObjectID, null, null);
}
@MCRCommand(syntax = "add missing children",
help = "Adds missing children to structure of parent objects using MCRLinkTableManager. (MCR-1480)",
order = 20)
public static List<String> fixMissingChildren() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> query = cb.createQuery(String.class);
Root<MCRLINKHREF> ac = query.from(MCRLINKHREF.class);
return em
.createQuery(query
.select(cb.concat(cb.literal("add missing children to "),
ac.get(MCRLINKHREF_.key).get(MCRLINKHREFPK_.mcrto)))
.where(cb.equal(ac.get(MCRLINKHREF_.key).get(MCRLINKHREFPK_.mcrtype),
MCRLinkTableManager.ENTRY_TYPE_PARENT))
.distinct(true).orderBy(cb.asc(cb.literal(1))))
.getResultList();
}
// 2017-> 2018
@MCRCommand(syntax = "migrate tei entries in mets file of derivate {0}")
public static void migrateTEIEntrysOfMetsFileOfDerivate(String derivateIdStr)
throws IOException, JDOMException {
final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIdStr);
if (!MCRMetadataManager.exists(derivateID)) {
LOGGER.info("Derivate " + derivateIdStr + " does not exist!");
return;
}
final MCRPath metsPath = MCRPath.getPath(derivateIdStr, "mets.xml");
if (!Files.exists(metsPath)) {
LOGGER.info("Derivate " + derivateIdStr + " has not mets.xml!");
return;
}
final MCRXSLTransformer transformer = MCRXSLTransformer.getInstance("xsl/mets-translation-migration.xsl");
final Document xml;
try (InputStream is = Files.newInputStream(metsPath)) {
final MCRContent content = transformer.transform(new MCRStreamContent(is));
xml = content.asXML();
}
try (OutputStream os = Files.newOutputStream(metsPath, StandardOpenOption.TRUNCATE_EXISTING)) {
final XMLOutputter writer = new XMLOutputter(Format.getPrettyFormat());
writer.output(xml, os);
}
LOGGER.info("Migrated mets of " + derivateIdStr);
}
// 2018 -> 2019
@MCRCommand(syntax = "migrate all derivates",
help = "Migrates the order and label of all derivates (MCR-2003, MCR-2099)")
public static List<String> migrateAllDerivates() {
List<String> objectTypes = MCRObjectID.listTypes();
objectTypes.remove("derivate");
objectTypes.remove("class");
ArrayList<String> commands = new ArrayList<>();
for (String t : objectTypes) {
for (String objID : MCRXMLMetadataManager.instance().listIDsOfType(t)) {
commands.add("migrate derivatelinks for object " + objID);
}
}
return commands;
}
@MCRCommand(syntax = "migrate derivatelinks for object {0}",
help = "Migrates the Order of derivates from object {0} to derivate "
+ "(MCR-2003, MCR-2099)")
public static List<String> migrateDerivateLink(String objectIDStr) {
final MCRObjectID objectID = MCRObjectID.getInstance(objectIDStr);
if (!MCRMetadataManager.exists(objectID)) {
throw new MCRException("The object " + objectIDStr + "does not exist!");
}
final MCRObject mcrObject = MCRMetadataManager.retrieveMCRObject(objectID);
final List<MCRMetaEnrichedLinkID> derivates = mcrObject.getStructure().getDerivates();
return derivates.stream().map(
(der) -> "migrate derivate " + der.getXLinkHrefID() + " using order " + (derivates.indexOf(der) + 1))
.collect(Collectors.toList());
}
@MCRCommand(syntax = "migrate derivate {0} using order {1}",
help = "Sets the order of derivate {0} to the number {1}")
public static void setOrderOfDerivate(String derivateIDStr, String orderStr) throws MCRAccessException {
final int order = Integer.parseInt(orderStr);
final MCRObjectID derivateID = MCRObjectID.getInstance(derivateIDStr);
if (!MCRMetadataManager.exists(derivateID)) {
throw new MCRException("The object " + derivateIDStr + "does not exist!");
}
final MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(derivateID);
derivate.setOrder(order);
//migrate title:
//in professorenkatalog we used a service flag to store the title -> should be moved to titles/tile
if (derivate.getService().getFlags("title").size() > 0) {
String title = derivate.getService().getFlags("title").get(0);
derivate.getDerivate().getTitles().add(new MCRMetaLangText("title", "de", null, 0, "main", title));
derivate.getService().removeFlags("title");
}
//update derivate
MCRMetadataManager.update(derivate);
}
}
| 17,314 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
ProfileProtocolConst.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/xposed/src/main/java/moe/fuqiuluo/shamrock/remote/service/data/profile/ProfileProtocolConst.java | package moe.fuqiuluo.shamrock.remote.service.data.profile;
public interface ProfileProtocolConst {
public static final String CMD_GET_PROFILE_DETAIL = "OidbSvc.0x480_9_IMCore";
public static final String CMD_SET_PROFILE_DETAIL = "OidbSvc.0x4ff_9_IMCore";
public static final String KET_INTERESTS = "interests";
public static final String KEY_AGE = "age";
public static final String KEY_BIRTHDAY = "birthday";
public static final String KEY_COLLEGE = "college";
public static final String KEY_COMPANY = "company";
public static final String KEY_CONSTELLATION = "key_constellation";
public static final String KEY_EMAIL = "email";
public static final String KEY_HOMETOWN = "hometown";
public static final String KEY_HOMETOWN_DESC = "hometown_desc";
public static final String KEY_LOCATION = "location";
public static final String KEY_LOCATION_DESC = "location_desc";
public static final String KEY_LOCATION_NAME = "location_name";
public static final String KEY_NICK = "nick";
public static final String KEY_PARSE_PROFILE_LOCATION = "parse_profile_location";
public static final String KEY_PERSONAL_NOTE = "personalNote";
public static final String KEY_PROFESSION = "profession";
public static final String KEY_SEX = "sex";
public static final String PARAM_ADD_FRIEND_SOURCE = "addFriendSource";
public static final String PARAM_COME_FROM_TYPE = "comeFromType";
public static final String PARAM_GET_CONTROL = "getControl";
public static final String PARAM_IS_FRIEND = "isFriend";
public static final String PARAM_LOGIN_SIG = "loginSig";
public static final String PARAM_QZONE_FEED_TIMESTAMP = "qZoneFeedTimeStamp";
public static final String PARAM_QZONE_SEED = "qZoneSeed";
public static final String PARAM_REQ_0X5EB = "req0x5ebList";
public static final String PARAM_REQ_EXTEND = "reqExtendFriend";
public static final String PARAM_REQ_MEDAL = "reqMedalWall";
public static final String PARAM_REQ_SERVICES = "reqServiceList";
public static final String PARAM_REQ_TEMPLATE = "reqTemplate";
public static final String PARAM_SEARCH_NAME = "searchName";
public static final String PARAM_SECURE_SIG = "secureSig";
public static final String PARAM_SELF_UIN = "selfUin";
public static final String PARAM_TARGET_UIN = "targetUin";
public static final String PARAM_TROOP_CODE = "troopCode";
public static final String PARAM_TROOP_UIN = "troopUin";
}
| 2,489 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
msg_comm.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/msf/msgcomm/msg_comm.java | package msf.msgcomm;
import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBoolField;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.mobileqq.pb.PBStringField;
import com.tencent.mobileqq.pb.PBUInt32Field;
import com.tencent.mobileqq.pb.PBUInt64Field;
import tencent.im.msg.im_msg_body;
public class msg_comm {
public static class Msg extends MessageMicro<Msg> {
public MsgHead msg_head = new MsgHead();
public ContentHead content_head = new ContentHead();
public im_msg_body.MsgBody msg_body = new im_msg_body.MsgBody();
//public msg_comm$AppShareInfo appshare_info = new msg_comm$AppShareInfo();
}
public static class ContentHead extends MessageMicro<ContentHead> {
public final PBUInt32Field pkg_num = PBField.initUInt32(0);
public final PBUInt32Field pkg_index = PBField.initUInt32(0);
public final PBUInt32Field div_seq = PBField.initUInt32(0);
public final PBUInt32Field auto_reply = PBField.initUInt32(0);
}
public static class MutilTransHead extends MessageMicro<MutilTransHead> {
public final PBUInt32Field status = PBField.initUInt32(0);
public final PBUInt32Field msgId = PBField.initUInt32(0);
public final PBUInt32Field friend_flag = PBField.initUInt32(0);
public final PBStringField from_anno_id = PBField.initString("");
public final PBStringField from_face_url = PBField.initString("");
}
public static class MsgHead extends MessageMicro<MsgHead> {
public final PBUInt64Field from_uin = PBField.initUInt64(0);
public final PBUInt64Field to_uin = PBField.initUInt64(0);
public final PBUInt32Field msg_type = PBField.initUInt32(0);
public final PBUInt32Field c2c_cmd = PBField.initUInt32(0);
public final PBUInt32Field msg_seq = PBField.initUInt32(0);
public final PBUInt32Field msg_time = PBField.initUInt32(0);
public final PBUInt64Field msg_uid = PBField.initUInt64(0);
//public msg_comm$C2CTmpMsgHead c2c_tmp_msg_head = new msg_comm$C2CTmpMsgHead();
public GroupInfo group_info = new GroupInfo();
public final PBUInt32Field from_appid = PBField.initUInt32(0);
public final PBUInt32Field from_instid = PBField.initUInt32(0);
public final PBUInt32Field user_active = PBField.initUInt32(0);
//public msg_comm$DiscussInfo discuss_info = new msg_comm$DiscussInfo();
public final PBStringField from_nick = PBField.initString("");
public final PBUInt64Field auth_uin = PBField.initUInt64(0);
public final PBStringField auth_nick = PBField.initString("");
public final PBUInt32Field msg_flag = PBField.initUInt32(0);
public final PBStringField auth_remark = PBField.initString("");
public final PBStringField group_name = PBField.initString("");
public MutilTransHead mutiltrans_head = new MutilTransHead();
//public im_msg_head$InstCtrl msg_inst_ctrl = new im_msg_head$InstCtrl();
public final PBUInt32Field public_account_group_send_flag = PBField.initUInt32(0);
public final PBUInt32Field wseq_in_c2c_msghead = PBField.initUInt32(0);
public final PBUInt64Field cpid = PBField.initUInt64(0);
//public msg_comm$ExtGroupKeyInfo ext_group_key_info = new msg_comm$ExtGroupKeyInfo();
public final PBStringField multi_compatible_text = PBField.initString("");
public final PBUInt32Field auth_sex = PBField.initUInt32(0);
public final PBBoolField is_src_msg = PBField.initBool(false);
}
public static class GroupInfo extends MessageMicro<GroupInfo> {
public final PBBytesField group_card;
public final PBUInt32Field group_card_type;
public final PBUInt32Field group_level;
public final PBBytesField group_name;
public final PBBytesField group_rank;
public final PBUInt64Field group_code = PBField.initUInt64(0);
public final PBUInt32Field group_type = PBField.initUInt32(0);
public final PBUInt64Field group_info_seq = PBField.initUInt64(0);
public GroupInfo() {
ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY;
this.group_card = PBField.initBytes(byteStringMicro);
this.group_rank = PBField.initBytes(byteStringMicro);
this.group_level = PBField.initUInt32(0);
this.group_card_type = PBField.initUInt32(0);
this.group_name = PBField.initBytes(byteStringMicro);
}
}
}
| 4,639 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
msg_transmit.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/msf/msgsvc/msgtransmit/msg_transmit.java | package msf.msgsvc.msgtransmit;
import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.mobileqq.pb.PBRepeatMessageField;
import com.tencent.mobileqq.pb.PBStringField;
import msf.msgcomm.msg_comm;
public class msg_transmit {
public static class PbMultiMsgTransmit extends MessageMicro<PbMultiMsgTransmit> {
public final PBRepeatMessageField<msg_comm.Msg> msg = PBField.initRepeatMessage(msg_comm.Msg.class);
public final PBRepeatMessageField<msg_transmit.PbMultiMsgItem> pbItemList = PBField.initRepeatMessage(msg_transmit.PbMultiMsgItem.class);
}
public static class PbMultiMsgItem extends MessageMicro<PbMultiMsgItem> {
public final PBStringField fileName = PBField.initString("");
public final PBBytesField buffer = PBField.initBytes(ByteStringMicro.EMPTY);
}
public static class PbMultiMsgNew extends MessageMicro<PbMultiMsgNew> {
public final PBRepeatMessageField<msg_comm.Msg> msg = PBField.initRepeatMessage(msg_comm.Msg.class);
}
}
| 1,151 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
stUinInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/friendlist/stUinInfo.java | package friendlist;
import com.qq.jce.JceStruct;
public final class stUinInfo extends JceStruct {
public byte cGender;
public long dwFlag;
public long dwuin;
public String sEmail;
public String sName;
public String sPhone;
public String sRemark;
public stUinInfo() {
this.dwuin = 0L;
this.dwFlag = 0L;
this.sName = "";
this.cGender = (byte) 0;
this.sPhone = "";
this.sEmail = "";
this.sRemark = "";
}
public stUinInfo(long j2, long j3, String str, byte b2, String str2, String str3, String str4) {
this.dwuin = 0L;
this.dwFlag = 0L;
this.sName = "";
this.cGender = (byte) 0;
this.sPhone = "";
this.sEmail = "";
this.sRemark = "";
this.dwuin = j2;
this.dwFlag = j3;
this.sName = str;
this.cGender = b2;
this.sPhone = str2;
this.sEmail = str3;
this.sRemark = str4;
}
}
| 981 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
TicketManager.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/manager/TicketManager.java | package mqq.manager;
import android.content.Context;
import oicq.wlogin_sdk.request.Ticket;
public interface TicketManager extends Manager {
String getA2(String uin);
byte[] getDA2(String uin);
Ticket getLocalTicket(String uin, int id);
String getOpenSdkKey(String uin, int i2);
String getPskey(String uin, String domain);
String getPt4Token(String uin, String domain);
String getSkey(String uin); // 假的Skey
String getRealSkey(String uin);
//Ticket getPskey(String uin, long j2, String[] strArr, WtTicketPromise wtTicketPromise);
//Ticket getPskeyForOpen(String uin, long j2, String[] strArr, byte[] bArr, WtTicketPromise wtTicketPromise);
//void getPskeyIgnoreCache(String uin, long j2, String[] strArr, WtTicketPromise wtTicketPromise);
//Ticket getSkey(String str, long j2, WtTicketPromise wtTicketPromise);
byte[] getSt(String uin, int appid);
byte[] getStkey(String uin, int appid);
String getStweb(String uin);
String getSuperkey(String str);
//Ticket getTicket(String str, long j2, int i2, WtTicketPromise wtTicketPromise, Bundle bundle);
String getVkey(String str);
//void registTicketManagerListener(TicketManagerListener ticketManagerListener);
void reloadCache(Context context);
int sendRPCData(long j2, String str, String str2, byte[] bArr, int i2);
//void setAlterTicket(HashMap<String, String> hashMap);
//void setPskeyManager(IPskeyManager iPskeyManager);
//void unregistTicketManagerListener(TicketManagerListener ticketManagerListener);
}
| 1,582 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
MSFServlet.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/MSFServlet.java | package mqq.app;
import android.content.Intent;
import com.tencent.qphone.base.remote.FromServiceMsg;
import com.tencent.qphone.base.remote.ToServiceMsg;
public abstract class MSFServlet extends Servlet {
public <T> T decodePacket(byte[] bArr, String str, T t) {
return null;
}
public String[] getPreferSSOCommands() {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
public Intent onReceive(FromServiceMsg fromServiceMsg) {
return null;
}
public abstract void onReceive(Intent intent, FromServiceMsg fromServiceMsg);
public abstract void onSend(Intent intent, Packet packet);
Intent removeRequest(int i2) {
return null;
}
public void sendToMSF(Intent intent, ToServiceMsg toServiceMsg) {
}
@Override // mqq.app.Servlet
public void service(Intent intent) {
}
}
| 907 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
Servlet.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/Servlet.java | package mqq.app;
import android.content.Intent;
public abstract class Servlet {
private ServletContainer container;
private AppRuntime mAppRuntime;
public AppRuntime getAppRuntime() {
return this.mAppRuntime;
}
ServletContainer getServletContainer() {
return this.container;
}
public abstract void service(Intent intent);
public void onCreate() {
}
public void onDestroy() {
}
public void init(AppRuntime appRuntime, ServletContainer servletContainer) {
this.mAppRuntime = appRuntime;
this.container = servletContainer;
}
}
| 616 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
AppRuntime.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/AppRuntime.java | package mqq.app;
import android.os.Bundle;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.tencent.qphone.base.remote.ToServiceMsg;
import mqq.app.api.IRuntimeService;
public abstract class AppRuntime {
public static final int ACCOUNT_MANAGER = 0;
public static final int WTLOGIN_MANAGER = 1;
public static final int TICKET_MANAGER = 2;
public static final int SERVER_CONFIG_MANAGER = 3;
public static final int END_UN_LOGIN_MANAGER = 4;
public enum Status {
online(11),
offline(21),
away(31),
invisiable(41),
busy(50),
qme(60),
dnd(70),
receiveofflinemsg(95);
private final int value;
Status(int i2) {
this.value = i2;
}
public static Status build(int i2) {
if (i2 != 11) {
if (i2 != 21) {
if (i2 != 31) {
if (i2 != 41) {
if (i2 != 50) {
if (i2 != 60) {
if (i2 != 70) {
if (i2 != 95) {
return null;
}
return receiveofflinemsg;
}
return dnd;
}
return qme;
}
return busy;
}
return invisiable;
}
return away;
}
return offline;
}
return online;
}
public int getValue() {
return this.value;
}
}
public <T extends IRuntimeService> T getRuntimeService(Class<T> cls, String namespace) {
throw new UnsupportedOperationException();
}
public <T extends IRuntimeService> T getRuntimeServiceIPCSync(@NonNull Class<T> cls, String str) {
throw new UnsupportedOperationException();
}
public String getAccount() {
return "";
}
public abstract String getCurrentAccountUin();
public String getCurrentUin() {
return !"0".equals(getCurrentAccountUin()) ? getCurrentAccountUin() : "";
}
public long getLongAccountUin() {
return 0;
}
public boolean isLogin() {
return false;
}
public ServletContainer getServletContainer() {
return null;
}
public void onCreate(Bundle bundle) {
}
}
| 2,672 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
Packet.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/Packet.java | package mqq.app;
import android.text.TextUtils;
import com.qq.jce.JceStruct;
import com.qq.jce.wup.UniPacket;
import com.tencent.qphone.base.remote.ToServiceMsg;
import java.util.HashMap;
public class Packet {
private String account;
public boolean autoResend;
private UniPacket client;
private boolean noResponse;
private byte[] sendData;
private String ssoCommand;
private String traceInfo;
private HashMap<String, String> transInfo;
private long timeout = 30000;
public boolean quickSendEnable = false;
public int quickSendStrategy = 0;
private HashMap<String, Object> attributes = new HashMap<>();
/* JADX INFO: Access modifiers changed from: package-private */
public Packet(String str) {
this.account = "0";
UniPacket uniPacket = new UniPacket(true);
this.client = uniPacket;
uniPacket.setEncodeName("UTF-8");
if (str != null) {
this.account = str;
}
}
public static <T> T decodePacket(byte[] bArr, String str, T t) {
UniPacket uniPacket = new UniPacket(true);
uniPacket.setEncodeName("utf-8");
uniPacket.decode(bArr);
return (T) uniPacket.getByClass(str, t);
}
public Object addAttribute(String str, Object obj) {
return this.attributes.put(str, obj);
}
public void addRequestPacket(String str, JceStruct jceStruct) {
this.client.put(str, jceStruct);
}
public HashMap<String, Object> getAttributes() {
return this.attributes;
}
public String getFuncName() {
return this.client.getServantName();
}
public String getServantName() {
return this.client.getServantName();
}
public void putSendData(byte[] bArr) {
this.sendData = bArr;
}
public void setAccount(String str) {
this.account = str;
}
public void setAttributes(HashMap<String, Object> hashMap) {
this.attributes = hashMap;
}
public void setFuncName(String str) {
this.client.setFuncName(str);
}
public void setNoResponse() {
this.noResponse = true;
}
public void setQuickSend(boolean z, int i2) {
this.quickSendEnable = z;
this.quickSendStrategy = i2;
}
public void setSSOCommand(String str) {
this.ssoCommand = str;
}
public void setServantName(String str) {
this.client.setServantName(str);
}
public void setTimeout(long j2) {
this.timeout = j2;
}
public void setTraceInfo(String str) {
this.traceInfo = str;
}
public void setTransInfo(HashMap<String, String> hashMap) {
this.transInfo = hashMap;
}
public ToServiceMsg toMsg() {
return null;
}
}
| 2,774 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
ServletContainer.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/ServletContainer.java | package mqq.app;
public class ServletContainer {
public void registerServletCommand(String str, Servlet servlet) {
}
Servlet getServlet(String str) {
return null;
}
}
| 194 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
MobileQQ.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/MobileQQ.java | package mqq.app;
import com.tencent.qphone.base.remote.SimpleAccount;
import com.tencent.qphone.base.util.BaseApplication;
import java.util.List;
public abstract class MobileQQ extends BaseApplication {
public static MobileQQ getMobileQQ() {
throw new UnsupportedOperationException("only view.");
}
public String getQQProcessName() {
throw new UnsupportedOperationException("only view.");
}
public AppRuntime peekAppRuntime() {
throw new RuntimeException();
}
public AppRuntime waitAppRuntime(BaseActivity baseActivity) {
return null;
}
public AppRuntime waitAppRuntime() {
return waitAppRuntime(null);
}
public List<SimpleAccount> getAllAccounts() {
return null;
}
public int getMsfConnectedNetType() {
return 0;
}
}
| 839 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
IRuntimeService.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/mqq/app/api/IRuntimeService.java | package mqq.app.api;
import mqq.app.AppRuntime;
public interface IRuntimeService {
void onCreate(AppRuntime appRuntime);
void onDestroy();
} | 151 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
TTimInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/TTimInfo.java | package SummaryCard;
public class TTimInfo {
public int iIsOnline;
}
| 74 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
VoiceInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/VoiceInfo.java | package SummaryCard;
public class VoiceInfo {
public byte bRead;
public short shDuration;
public String strUrl;
public byte[] vVoiceId;
}
| 155 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
TCampusSchoolInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/TCampusSchoolInfo.java | package SummaryCard;
import com.qq.jce.JceStruct;
public final class TCampusSchoolInfo extends JceStruct {
public int iIsValidForCertified;
public long uSchoolId;
public long uTimestamp;
} | 202 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
QCallInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/QCallInfo.java | package SummaryCard;
public class QCallInfo {
public int bStatus;
public String strNick;
public long uQCallId;
}
| 126 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
TEIMInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/TEIMInfo.java | package SummaryCard;
public class TEIMInfo {
public int iBindCompanyEmailStatus;
public String sBindCompanyEmail;
}
| 125 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
GiftInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/GiftInfo.java | package SummaryCard;
public class GiftInfo {
public long uOpenFlag;
public byte[] vGiftInfo;
}
| 104 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
TCampusCircleInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/TCampusCircleInfo.java | package SummaryCard;
import com.qq.jce.JceStruct;
public final class TCampusCircleInfo extends JceStruct {
public int eStatus;
public int iIsSigned;
public TCampusSchoolInfo stSchoolInfo;
public String strAcademy;
public String strName;
} | 260 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
AlbumInfo.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/AlbumInfo.java | package SummaryCard;
import com.qq.jce.JceStruct;
import java.util.ArrayList;
public final class AlbumInfo extends JceStruct {
static ArrayList<PhotoInfo> cache_vPhotos;
public ArrayList<PhotoInfo> vPhotos;
} | 219 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
DateCard.java | /FileExtraction/Java_unseen/djkcyl_Shamrock/qqinterface/src/main/java/SummaryCard/DateCard.java | package SummaryCard;
public final class DateCard {
public byte bConstellation;
public byte bMarriage;
public long lTinyId;
public String strCompany;
public String strDistance;
public String strElapse;
public String strSchool;
public long uHomeCity;
public long uHomeCountry;
public long uHomeProvince;
public long uHomeZone;
public long uProfession;
public long uSchoolId;
public byte[] vActivityList;
public byte[] vDateInfo;
public byte[] vFaces;
public byte[] vGroupList;
public byte[] vNearbyInfo;
} | 576 | Java | .java | djkcyl/Shamrock | 106 | 66 | 1 | 2023-10-20T10:43:47Z | 2023-10-24T04:30:56Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.