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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRSessionResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRSessionResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;
/**
* This Class will be stored in the a {@link jakarta.servlet.http.HttpSession} and can be used to resolve the
* {@link MCRSession}. We can not store {@link MCRSession} directly in the {@link jakarta.servlet.http.HttpSession}
* because values need to be {@link java.io.Serializable}.
*/
public final class MCRSessionResolver implements Serializable, HttpSessionBindingListener {
private static final Logger LOGGER = LogManager.getLogger();
private final String sessionID;
private MCRSessionResolver(final String sessionID) {
this.sessionID = sessionID;
}
public MCRSessionResolver(final MCRSession session) {
this(session.getID());
}
public String getSessionID() {
return sessionID;
}
/**
* Tries to resolve the {@link MCRSession} throught the {@link MCRSessionMgr}
*
* @return if is already closed it will return a {@link Optional#empty()}
*/
public Optional<MCRSession> resolveSession() {
return Optional.ofNullable(MCRSessionMgr.getSession(sessionID));
}
@Override
public void valueBound(HttpSessionBindingEvent hsbe) {
Object obj = hsbe.getValue();
if (LOGGER.isDebugEnabled() && obj instanceof MCRSessionResolver sessionResolver) {
LOGGER.debug("Bound MCRSession {} to HttpSession {}", sessionResolver.getSessionID(),
hsbe.getSession().getId());
}
}
@Override
public void valueUnbound(HttpSessionBindingEvent hsbe) {
// hsbe.getValue() does not work right with tomcat
Optional<MCRSessionResolver> newSessionResolver = Optional
.ofNullable(hsbe.getSession().getAttribute(MCRServlet.ATTR_MYCORE_SESSION))
.filter(o -> o instanceof MCRSessionResolver)
.map(MCRSessionResolver.class::cast);
MCRSessionResolver oldResolver = this;
if (newSessionResolver.isPresent() && !oldResolver.equals(newSessionResolver.get())) {
LOGGER.warn("Attribute {} is beeing unbound from session {} and replaced by {}!", hsbe.getName(),
oldResolver.getSessionID(), newSessionResolver.get());
oldResolver.resolveSession().ifPresent(MCRSession::close);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MCRSessionResolver that = (MCRSessionResolver) o;
return Objects.equals(getSessionID(), that.getSessionID());
}
@Override
public int hashCode() {
return Objects.hash(getSessionID());
}
@Override
public String toString() {
return "Resolver to " + getSessionID();
}
}
| 3,850 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCrypt.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCrypt.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
/**
* Java-based implementation of the unix crypt(3) command
*
* Based upon C source code written by Eric Young, eay@psych.uq.oz.au Java
* conversion by John F. Dumas, jdumas@zgs.com
*
* Found at
* <a href="http://locutus.kingwoodcable.com/jfd/crypt.html">http://locutus.kingwoodcable.com/jfd/crypt.html</a>
* Minor optimizations by Wes Biggs, wes@cacas.org Adaption and extension for the MyCoRe Open Source
* System by Detlev Degenhardt, Detlev.Degenhardt@rz.uni-freiburg.de
*
* Eric's original code is licensed under the BSD license. As this is
* derivative, the same license applies.
*
* @author Detlev Degenhardt
*/
public class MCRCrypt {
private static final int ITERATIONS = 16;
private static final boolean[] SHIFTS_2 = { false, false, true, true, true, true, true, true, false, true, true,
true, true, true, true,
false };
private static final int[][] SKB = {
{
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x00000010, 0x20000000, 0x20000010, 0x00010000, 0x00010010, 0x20010000, 0x20010010, 0x00000800,
0x00000810,
0x20000800, 0x20000810, 0x00010800, 0x00010810, 0x20010800, 0x20010810, 0x00000020, 0x00000030, 0x20000020,
0x20000030,
0x00010020, 0x00010030, 0x20010020, 0x20010030, 0x00000820, 0x00000830, 0x20000820, 0x20000830, 0x00010820,
0x00010830,
0x20010820, 0x20010830, 0x00080000, 0x00080010, 0x20080000, 0x20080010, 0x00090000, 0x00090010, 0x20090000,
0x20090010,
0x00080800, 0x00080810, 0x20080800, 0x20080810, 0x00090800, 0x00090810, 0x20090800, 0x20090810, 0x00080020,
0x00080030,
0x20080020, 0x20080030, 0x00090020, 0x00090030, 0x20090020, 0x20090030, 0x00080820, 0x00080830, 0x20080820,
0x20080830,
0x00090820, 0x00090830, 0x20090820, 0x20090830, },
{
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
0x00000000, 0x02000000, 0x00002000, 0x02002000, 0x00200000, 0x02200000, 0x00202000, 0x02202000, 0x00000004,
0x02000004,
0x00002004, 0x02002004, 0x00200004, 0x02200004, 0x00202004, 0x02202004, 0x00000400, 0x02000400, 0x00002400,
0x02002400,
0x00200400, 0x02200400, 0x00202400, 0x02202400, 0x00000404, 0x02000404, 0x00002404, 0x02002404, 0x00200404,
0x02200404,
0x00202404, 0x02202404, 0x10000000, 0x12000000, 0x10002000, 0x12002000, 0x10200000, 0x12200000, 0x10202000,
0x12202000,
0x10000004, 0x12000004, 0x10002004, 0x12002004, 0x10200004, 0x12200004, 0x10202004, 0x12202004, 0x10000400,
0x12000400,
0x10002400, 0x12002400, 0x10200400, 0x12200400, 0x10202400, 0x12202400, 0x10000404, 0x12000404, 0x10002404,
0x12002404,
0x10200404, 0x12200404, 0x10202404, 0x12202404, },
{
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
0x00000000, 0x00000001, 0x00040000, 0x00040001, 0x01000000, 0x01000001, 0x01040000, 0x01040001, 0x00000002,
0x00000003,
0x00040002, 0x00040003, 0x01000002, 0x01000003, 0x01040002, 0x01040003, 0x00000200, 0x00000201, 0x00040200,
0x00040201,
0x01000200, 0x01000201, 0x01040200, 0x01040201, 0x00000202, 0x00000203, 0x00040202, 0x00040203, 0x01000202,
0x01000203,
0x01040202, 0x01040203, 0x08000000, 0x08000001, 0x08040000, 0x08040001, 0x09000000, 0x09000001, 0x09040000,
0x09040001,
0x08000002, 0x08000003, 0x08040002, 0x08040003, 0x09000002, 0x09000003, 0x09040002, 0x09040003, 0x08000200,
0x08000201,
0x08040200, 0x08040201, 0x09000200, 0x09000201, 0x09040200, 0x09040201, 0x08000202, 0x08000203, 0x08040202,
0x08040203,
0x09000202, 0x09000203, 0x09040202, 0x09040203, },
{
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
0x00000000, 0x00100000, 0x00000100, 0x00100100, 0x00000008, 0x00100008, 0x00000108, 0x00100108, 0x00001000,
0x00101000,
0x00001100, 0x00101100, 0x00001008, 0x00101008, 0x00001108, 0x00101108, 0x04000000, 0x04100000, 0x04000100,
0x04100100,
0x04000008, 0x04100008, 0x04000108, 0x04100108, 0x04001000, 0x04101000, 0x04001100, 0x04101100, 0x04001008,
0x04101008,
0x04001108, 0x04101108, 0x00020000, 0x00120000, 0x00020100, 0x00120100, 0x00020008, 0x00120008, 0x00020108,
0x00120108,
0x00021000, 0x00121000, 0x00021100, 0x00121100, 0x00021008, 0x00121008, 0x00021108, 0x00121108, 0x04020000,
0x04120000,
0x04020100, 0x04120100, 0x04020008, 0x04120008, 0x04020108, 0x04120108, 0x04021000, 0x04121000, 0x04021100,
0x04121100,
0x04021008, 0x04121008, 0x04021108, 0x04121108, },
{
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x10000000, 0x00010000, 0x10010000, 0x00000004, 0x10000004, 0x00010004, 0x10010004, 0x20000000,
0x30000000,
0x20010000, 0x30010000, 0x20000004, 0x30000004, 0x20010004, 0x30010004, 0x00100000, 0x10100000, 0x00110000,
0x10110000,
0x00100004, 0x10100004, 0x00110004, 0x10110004, 0x20100000, 0x30100000, 0x20110000, 0x30110000, 0x20100004,
0x30100004,
0x20110004, 0x30110004, 0x00001000, 0x10001000, 0x00011000, 0x10011000, 0x00001004, 0x10001004, 0x00011004,
0x10011004,
0x20001000, 0x30001000, 0x20011000, 0x30011000, 0x20001004, 0x30001004, 0x20011004, 0x30011004, 0x00101000,
0x10101000,
0x00111000, 0x10111000, 0x00101004, 0x10101004, 0x00111004, 0x10111004, 0x20101000, 0x30101000, 0x20111000,
0x30111000,
0x20101004, 0x30101004, 0x20111004, 0x30111004, },
{
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
0x00000000, 0x08000000, 0x00000008, 0x08000008, 0x00000400, 0x08000400, 0x00000408, 0x08000408, 0x00020000,
0x08020000,
0x00020008, 0x08020008, 0x00020400, 0x08020400, 0x00020408, 0x08020408, 0x00000001, 0x08000001, 0x00000009,
0x08000009,
0x00000401, 0x08000401, 0x00000409, 0x08000409, 0x00020001, 0x08020001, 0x00020009, 0x08020009, 0x00020401,
0x08020401,
0x00020409, 0x08020409, 0x02000000, 0x0A000000, 0x02000008, 0x0A000008, 0x02000400, 0x0A000400, 0x02000408,
0x0A000408,
0x02020000, 0x0A020000, 0x02020008, 0x0A020008, 0x02020400, 0x0A020400, 0x02020408, 0x0A020408, 0x02000001,
0x0A000001,
0x02000009, 0x0A000009, 0x02000401, 0x0A000401, 0x02000409, 0x0A000409, 0x02020001, 0x0A020001, 0x02020009,
0x0A020009,
0x02020401, 0x0A020401, 0x02020409, 0x0A020409, },
{
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
0x00000000, 0x00000100, 0x00080000, 0x00080100, 0x01000000, 0x01000100, 0x01080000, 0x01080100, 0x00000010,
0x00000110,
0x00080010, 0x00080110, 0x01000010, 0x01000110, 0x01080010, 0x01080110, 0x00200000, 0x00200100, 0x00280000,
0x00280100,
0x01200000, 0x01200100, 0x01280000, 0x01280100, 0x00200010, 0x00200110, 0x00280010, 0x00280110, 0x01200010,
0x01200110,
0x01280010, 0x01280110, 0x00000200, 0x00000300, 0x00080200, 0x00080300, 0x01000200, 0x01000300, 0x01080200,
0x01080300,
0x00000210, 0x00000310, 0x00080210, 0x00080310, 0x01000210, 0x01000310, 0x01080210, 0x01080310, 0x00200200,
0x00200300,
0x00280200, 0x00280300, 0x01200200, 0x01200300, 0x01280200, 0x01280300, 0x00200210, 0x00200310, 0x00280210,
0x00280310,
0x01200210, 0x01200310, 0x01280210, 0x01280310, },
{
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
0x00000000, 0x04000000, 0x00040000, 0x04040000, 0x00000002, 0x04000002, 0x00040002, 0x04040002, 0x00002000,
0x04002000,
0x00042000, 0x04042000, 0x00002002, 0x04002002, 0x00042002, 0x04042002, 0x00000020, 0x04000020, 0x00040020,
0x04040020,
0x00000022, 0x04000022, 0x00040022, 0x04040022, 0x00002020, 0x04002020, 0x00042020, 0x04042020, 0x00002022,
0x04002022,
0x00042022, 0x04042022, 0x00000800, 0x04000800, 0x00040800, 0x04040800, 0x00000802, 0x04000802, 0x00040802,
0x04040802,
0x00002800, 0x04002800, 0x00042800, 0x04042800, 0x00002802, 0x04002802, 0x00042802, 0x04042802, 0x00000820,
0x04000820,
0x00040820, 0x04040820, 0x00000822, 0x04000822, 0x00040822, 0x04040822, 0x00002820, 0x04002820, 0x00042820,
0x04042820,
0x00002822, 0x04002822, 0x00042822, 0x04042822, }, };
private static final int[][] SPTRANS = {
{
/* nibble 0 */
0x00820200, 0x00020000, 0x80800000, 0x80820200, 0x00800000, 0x80020200, 0x80020000, 0x80800000, 0x80020200,
0x00820200,
0x00820000, 0x80000200, 0x80800200, 0x00800000, 0x00000000, 0x80020000, 0x00020000, 0x80000000, 0x00800200,
0x00020200,
0x80820200, 0x00820000, 0x80000200, 0x00800200, 0x80000000, 0x00000200, 0x00020200, 0x80820000, 0x00000200,
0x80800200,
0x80820000, 0x00000000, 0x00000000, 0x80820200, 0x00800200, 0x80020000, 0x00820200, 0x00020000, 0x80000200,
0x00800200,
0x80820000, 0x00000200, 0x00020200, 0x80800000, 0x80020200, 0x80000000, 0x80800000, 0x00820000, 0x80820200,
0x00020200,
0x00820000, 0x80800200, 0x00800000, 0x80000200, 0x80020000, 0x00000000, 0x00020000, 0x00800000, 0x80800200,
0x00820200,
0x80000000, 0x80820000, 0x00000200, 0x80020200, },
{
/* nibble 1 */
0x10042004, 0x00000000, 0x00042000, 0x10040000, 0x10000004, 0x00002004, 0x10002000, 0x00042000, 0x00002000,
0x10040004,
0x00000004, 0x10002000, 0x00040004, 0x10042000, 0x10040000, 0x00000004, 0x00040000, 0x10002004, 0x10040004,
0x00002000,
0x00042004, 0x10000000, 0x00000000, 0x00040004, 0x10002004, 0x00042004, 0x10042000, 0x10000004, 0x10000000,
0x00040000,
0x00002004, 0x10042004, 0x00040004, 0x10042000, 0x10002000, 0x00042004, 0x10042004, 0x00040004, 0x10000004,
0x00000000,
0x10000000, 0x00002004, 0x00040000, 0x10040004, 0x00002000, 0x10000000, 0x00042004, 0x10002004, 0x10042000,
0x00002000,
0x00000000, 0x10000004, 0x00000004, 0x10042004, 0x00042000, 0x10040000, 0x10040004, 0x00040000, 0x00002004,
0x10002000,
0x10002004, 0x00000004, 0x10040000, 0x00042000, },
{
/* nibble 2 */
0x41000000, 0x01010040, 0x00000040, 0x41000040, 0x40010000, 0x01000000, 0x41000040, 0x00010040, 0x01000040,
0x00010000,
0x01010000, 0x40000000, 0x41010040, 0x40000040, 0x40000000, 0x41010000, 0x00000000, 0x40010000, 0x01010040,
0x00000040,
0x40000040, 0x41010040, 0x00010000, 0x41000000, 0x41010000, 0x01000040, 0x40010040, 0x01010000, 0x00010040,
0x00000000,
0x01000000, 0x40010040, 0x01010040, 0x00000040, 0x40000000, 0x00010000, 0x40000040, 0x40010000, 0x01010000,
0x41000040,
0x00000000, 0x01010040, 0x00010040, 0x41010000, 0x40010000, 0x01000000, 0x41010040, 0x40000000, 0x40010040,
0x41000000,
0x01000000, 0x41010040, 0x00010000, 0x01000040, 0x41000040, 0x00010040, 0x01000040, 0x00000000, 0x41010000,
0x40000040,
0x41000000, 0x40010040, 0x00000040, 0x01010000, },
{
/* nibble 3 */
0x00100402, 0x04000400, 0x00000002, 0x04100402, 0x00000000, 0x04100000, 0x04000402, 0x00100002, 0x04100400,
0x04000002,
0x04000000, 0x00000402, 0x04000002, 0x00100402, 0x00100000, 0x04000000, 0x04100002, 0x00100400, 0x00000400,
0x00000002,
0x00100400, 0x04000402, 0x04100000, 0x00000400, 0x00000402, 0x00000000, 0x00100002, 0x04100400, 0x04000400,
0x04100002,
0x04100402, 0x00100000, 0x04100002, 0x00000402, 0x00100000, 0x04000002, 0x00100400, 0x04000400, 0x00000002,
0x04100000,
0x04000402, 0x00000000, 0x00000400, 0x00100002, 0x00000000, 0x04100002, 0x04100400, 0x00000400, 0x04000000,
0x04100402,
0x00100402, 0x00100000, 0x04100402, 0x00000002, 0x04000400, 0x00100402, 0x00100002, 0x00100400, 0x04100000,
0x04000402,
0x00000402, 0x04000000, 0x04000002, 0x04100400, },
{
/* nibble 4 */
0x02000000, 0x00004000, 0x00000100, 0x02004108, 0x02004008, 0x02000100, 0x00004108, 0x02004000, 0x00004000,
0x00000008,
0x02000008, 0x00004100, 0x02000108, 0x02004008, 0x02004100, 0x00000000, 0x00004100, 0x02000000, 0x00004008,
0x00000108,
0x02000100, 0x00004108, 0x00000000, 0x02000008, 0x00000008, 0x02000108, 0x02004108, 0x00004008, 0x02004000,
0x00000100,
0x00000108, 0x02004100, 0x02004100, 0x02000108, 0x00004008, 0x02004000, 0x00004000, 0x00000008, 0x02000008,
0x02000100,
0x02000000, 0x00004100, 0x02004108, 0x00000000, 0x00004108, 0x02000000, 0x00000100, 0x00004008, 0x02000108,
0x00000100,
0x00000000, 0x02004108, 0x02004008, 0x02004100, 0x00000108, 0x00004000, 0x00004100, 0x02004008, 0x02000100,
0x00000108,
0x00000008, 0x00004108, 0x02004000, 0x02000008, },
{
/* nibble 5 */
0x20000010, 0x00080010, 0x00000000, 0x20080800, 0x00080010, 0x00000800, 0x20000810, 0x00080000, 0x00000810,
0x20080810,
0x00080800, 0x20000000, 0x20000800, 0x20000010, 0x20080000, 0x00080810, 0x00080000, 0x20000810, 0x20080010,
0x00000000,
0x00000800, 0x00000010, 0x20080800, 0x20080010, 0x20080810, 0x20080000, 0x20000000, 0x00000810, 0x00000010,
0x00080800,
0x00080810, 0x20000800, 0x00000810, 0x20000000, 0x20000800, 0x00080810, 0x20080800, 0x00080010, 0x00000000,
0x20000800,
0x20000000, 0x00000800, 0x20080010, 0x00080000, 0x00080010, 0x20080810, 0x00080800, 0x00000010, 0x20080810,
0x00080800,
0x00080000, 0x20000810, 0x20000010, 0x20080000, 0x00080810, 0x00000000, 0x00000800, 0x20000010, 0x20000810,
0x20080800,
0x20080000, 0x00000810, 0x00000010, 0x20080010, },
{
/* nibble 6 */
0x00001000, 0x00000080, 0x00400080, 0x00400001, 0x00401081, 0x00001001, 0x00001080, 0x00000000, 0x00400000,
0x00400081,
0x00000081, 0x00401000, 0x00000001, 0x00401080, 0x00401000, 0x00000081, 0x00400081, 0x00001000, 0x00001001,
0x00401081,
0x00000000, 0x00400080, 0x00400001, 0x00001080, 0x00401001, 0x00001081, 0x00401080, 0x00000001, 0x00001081,
0x00401001,
0x00000080, 0x00400000, 0x00001081, 0x00401000, 0x00401001, 0x00000081, 0x00001000, 0x00000080, 0x00400000,
0x00401001,
0x00400081, 0x00001081, 0x00001080, 0x00000000, 0x00000080, 0x00400001, 0x00000001, 0x00400080, 0x00000000,
0x00400081,
0x00400080, 0x00001080, 0x00000081, 0x00001000, 0x00401081, 0x00400000, 0x00401080, 0x00000001, 0x00001001,
0x00401081,
0x00400001, 0x00401080, 0x00401000, 0x00001001, },
{
/* nibble 7 */
0x08200020, 0x08208000, 0x00008020, 0x00000000, 0x08008000, 0x00200020, 0x08200000, 0x08208020, 0x00000020,
0x08000000,
0x00208000, 0x00008020, 0x00208020, 0x08008020, 0x08000020, 0x08200000, 0x00008000, 0x00208020, 0x00200020,
0x08008000,
0x08208020, 0x08000020, 0x00000000, 0x00208000, 0x08000000, 0x00200000, 0x08008020, 0x08200020, 0x00200000,
0x00008000,
0x08208000, 0x00000020, 0x00200000, 0x00008000, 0x08000020, 0x08208020, 0x00008020, 0x08000000, 0x00000000,
0x00208000,
0x08200020, 0x08008020, 0x08008000, 0x00200020, 0x08208000, 0x00000020, 0x00200020, 0x08008000, 0x08208020,
0x00200000,
0x08200000, 0x08000020, 0x00208000, 0x00008020, 0x08008020, 0x08200000, 0x00000020, 0x08208000, 0x00208020,
0x00000000,
0x08000000, 0x08200020, 0x00008000, 0x00208020, }, };
private MCRCrypt() {
} // defined so class can't be instantiated.
private static int byteToUnsigned(byte b) {
return b >= 0 ? (int) b : b + 256;
}
private static int fourBytesToInt(byte[] b, int offset) {
return byteToUnsigned(b[offset++]) | byteToUnsigned(b[offset++]) << 8 | byteToUnsigned(b[offset++]) << 16
| byteToUnsigned(b[offset]) << 24;
}
private static void intToFourBytes(int iValue, byte[] b, int offset) {
b[offset++] = (byte) (iValue & 0xff);
b[offset++] = (byte) (iValue >>> 8 & 0xff);
b[offset++] = (byte) (iValue >>> 16 & 0xff);
b[offset] = (byte) (iValue >>> 24 & 0xff);
}
private static void permOp(int a, int b, int n, int m, int[] results) {
int t;
t = (a >>> n ^ b) & m;
a ^= t << n;
b ^= t;
results[0] = a;
results[1] = b;
}
private static int hpermOp(int a, int n, int m) {
int t;
t = (a << 16 - n ^ a) & m;
a = a ^ t ^ t >>> 16 - n;
return a;
}
private static int[] desSetKey(byte[] key) {
int[] schedule = new int[ITERATIONS * 2];
int c = fourBytesToInt(key, 0);
int d = fourBytesToInt(key, 4);
int[] results = new int[2];
permOp(d, c, 4, 0x0f0f0f0f, results);
d = results[0];
c = results[1];
c = hpermOp(c, -2, 0xcccc0000);
d = hpermOp(d, -2, 0xcccc0000);
permOp(d, c, 1, 0x55555555, results);
d = results[0];
c = results[1];
permOp(c, d, 8, 0x00ff00ff, results);
c = results[0];
d = results[1];
permOp(d, c, 1, 0x55555555, results);
d = results[0];
c = results[1];
d = (d & 0x000000ff) << 16 | d & 0x0000ff00 | (d & 0x00ff0000) >>> 16 | (c & 0xf0000000) >>> 4;
c &= 0x0fffffff;
int s;
int t;
int j = 0;
for (int i = 0; i < ITERATIONS; i++) {
if (SHIFTS_2[i]) {
c = c >>> 2 | c << 26;
d = d >>> 2 | d << 26;
} else {
c = c >>> 1 | c << 27;
d = d >>> 1 | d << 27;
}
c &= 0x0fffffff;
d &= 0x0fffffff;
s = SKB[0][c & 0x3f] | SKB[1][c >>> 6 & 0x03 | c >>> 7 & 0x3c] | SKB[2][c >>> 13 & 0x0f | c >>> 14 & 0x30]
| SKB[3][c >>> 20 & 0x01 | c >>> 21 & 0x06 | c >>> 22 & 0x38];
t = SKB[4][d & 0x3f] | SKB[5][d >>> 7 & 0x03 | d >>> 8 & 0x3c] | SKB[6][d >>> 15 & 0x3f]
| SKB[7][d >>> 21 & 0x0f | d >>> 22 & 0x30];
schedule[j++] = (t << 16 | s & 0x0000ffff) & 0xffffffff;
s = s >>> 16 | t & 0xffff0000;
s = s << 4 | s >>> 28;
schedule[j++] = s & 0xffffffff;
}
return schedule;
}
private static int dEncrypt(int l, int r, int s, int e0, int e1, int[] ss) {
int t;
int u;
int v;
v = r ^ r >>> 16;
u = v & e0;
v = v & e1;
u = u ^ u << 16 ^ r ^ ss[s];
t = v ^ v << 16 ^ r ^ ss[s + 1];
t = t >>> 4 | t << 28;
l ^= SPTRANS[1][t & 0x3f] | SPTRANS[3][t >>> 8 & 0x3f] | SPTRANS[5][t >>> 16 & 0x3f]
| SPTRANS[7][t >>> 24 & 0x3f]
| SPTRANS[0][u & 0x3f] | SPTRANS[2][u >>> 8 & 0x3f] | SPTRANS[4][u >>> 16 & 0x3f]
| SPTRANS[6][u >>> 24 & 0x3f];
return l;
}
private static int[] body(int[] schedule, int eswap0, int eswap1) {
int left = 0;
int right = 0;
int t;
for (int j = 0; j < 25; j++) {
for (int i = 0; i < ITERATIONS * 2; i += 4) {
left = dEncrypt(left, right, i, eswap0, eswap1, schedule);
right = dEncrypt(right, left, i + 2, eswap0, eswap1, schedule);
}
t = left;
left = right;
right = t;
}
t = right;
right = left >>> 1 | left << 31;
left = t >>> 1 | t << 31;
left &= 0xffffffff;
right &= 0xffffffff;
int[] results = new int[2];
permOp(right, left, 1, 0x55555555, results);
right = results[0];
left = results[1];
permOp(left, right, 8, 0x00ff00ff, results);
left = results[0];
right = results[1];
permOp(right, left, 2, 0x33333333, results);
right = results[0];
left = results[1];
permOp(left, right, 16, 0x0000ffff, results);
left = results[0];
right = results[1];
permOp(right, left, 4, 0x0f0f0f0f, results);
right = results[0];
left = results[1];
int[] out = new int[2];
out[0] = left;
out[1] = right;
return out;
}
public static final String ALPHABET = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final char[] CHARS = ALPHABET.toCharArray();
/**
* This method encrypts a string given a cleartext string and a "salt".
*
* @param salt
* A two-character string representing the salt used to iterate
* the encryption engine.
* @param original
* The string to be encrypted.
* @return A string consisting of the 2-character salt followed by the
* encrypted string.
*/
public static String crypt(String salt, String original) {
// wwb -- Should do some sanity checks: salt needs to be 2 chars, in
// alpha.
while (salt.length() < 2) {
salt += "A";
}
char[] buffer = new char[13];
char charZero = salt.charAt(0);
char charOne = salt.charAt(1);
buffer[0] = charZero;
buffer[1] = charOne;
int eswap0 = ALPHABET.indexOf(charZero);
int eswap1 = ALPHABET.indexOf(charOne) << 4;
byte[] key = new byte[8];
for (int i = 0; i < key.length; i++) {
key[i] = (byte) 0;
}
for (int i = 0; i < key.length && i < original.length(); i++) {
key[i] = (byte) (original.charAt(i) << 1);
}
int[] schedule = desSetKey(key);
int[] out = body(schedule, eswap0, eswap1);
byte[] b = new byte[9];
intToFourBytes(out[0], b, 0);
intToFourBytes(out[1], b, 4);
b[8] = 0;
for (int i = 2, y = 0, u = 0x80; i < 13; i++) {
for (int j = 0, c = 0; j < 6; j++) {
c <<= 1;
if ((b[y] & u) != 0) {
c |= 1;
}
u >>>= 1;
if (u == 0) {
y++;
u = 0x80;
}
buffer[i] = ALPHABET.charAt(c);
}
}
return new String(buffer);
}
/**
* This method encrypts a string given the cleartext string. A random salt
* is generated using java.util.Random.
*
* @param original
* The string to be encrypted.
* @return A string consisting of the 2-character salt followed by the
* encrypted string.
*/
public static String crypt(String original) {
java.util.Random randomGenerator = new java.util.Random();
int numSaltChars = CHARS.length;
String salt;
salt = String.valueOf(CHARS[Math.abs(randomGenerator.nextInt()) % numSaltChars])
+ CHARS[Math.abs(randomGenerator.nextInt()) % numSaltChars];
return crypt(salt, original);
}
}
| 25,059 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPropertiesResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRPropertiesResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
/**
* The <code>MCRPropertiesResolver</code> supports substitution of any %reference%
* in a <code>String</code> or <code>Property</code> instance.
* <p>
* // possible use case<br>
* Properties p = MCRConfiguration.instance().getProperties();<br>
* MCRPropertiesResolver r = new MCRPropertiesResolver(p);<br>
* Properties resolvedProperties = r.resolveAll(p);<br>
* </p>
*
* @author Matthias Eichner
*/
public class MCRPropertiesResolver extends MCRTextResolver {
public MCRPropertiesResolver() {
super();
}
public MCRPropertiesResolver(Map<String, String> propertiesMap) {
super(propertiesMap);
}
public MCRPropertiesResolver(Properties properties) {
super(properties);
}
@Override
public String addVariable(String name, String value) {
return super.addVariable(name, removeSelfReference(name, value));
}
private String removeSelfReference(String name, String value) {
int pos1 = value.indexOf("%");
if (pos1 != -1) {
int pos2 = value.indexOf("%", pos1 + 1);
if (pos2 != -1) {
String ref = value.substring(pos1 + 1, pos2);
if (name.equals(ref)) {
return value.replaceAll("\\s*%" + name + "%\\s*,?", "");
}
}
}
return value;
}
@Override
protected void registerDefaultTerms() throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException, InstantiationException {
registerTerm(Property.class);
}
/**
* Substitute all %references% of the given <code>Properties</code> and
* return a new <code>Properties</code> object.
*
* @param toResolve properties to resolve
* @return resolved properties
*/
public Properties resolveAll(Properties toResolve) {
Properties resolvedProperties = new Properties();
for (Entry<Object, Object> entrySet : toResolve.entrySet()) {
String key = entrySet.getKey().toString();
String value = removeSelfReference(key, entrySet.getValue().toString());
String resolvedValue = this.resolve(value);
resolvedProperties.put(key, resolvedValue);
}
return resolvedProperties;
}
/**
* Substitute all %references% of the given <code>Map</code> and
* return a new <code>Map</code> object.
*
* @param toResolve properties to resolve
* @return resolved properties
*/
public Map<String, String> resolveAll(Map<String, String> toResolve) {
Map<String, String> resolvedMap = new HashMap<>();
for (Entry<String, String> entrySet : toResolve.entrySet()) {
String key = entrySet.getKey();
String value = removeSelfReference(key, entrySet.getValue());
resolvedMap.put(key, this.resolve(value));
}
return resolvedMap;
}
public static class Property extends Variable {
public Property(MCRTextResolver textResolver) {
super(textResolver);
}
@Override
public String getStartEnclosingString() {
return "%";
}
@Override
public String getEndEnclosingString() {
return "%";
}
}
}
| 4,210 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJSONTypeAdapter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRJSONTypeAdapter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonSerializer;
public abstract class MCRJSONTypeAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> {
public Type bindTo() {
ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
return superclass.getActualTypeArguments()[0];
}
}
| 1,192 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLanguageDetector.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRLanguageDetector.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.lang.Character.UnicodeScript;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Detects the language of a given text string by
* looking for typical words and word endings and used characters for each language.
* German, english, french, arabic, chinese, japanese, greek and hebrew are currently supported.
*
* @author Frank Lützenkirchen
*/
public class MCRLanguageDetector {
private static Logger LOGGER = LogManager.getLogger(MCRLanguageDetector.class);
private static Properties words = new Properties();
private static Properties endings = new Properties();
private static Map<UnicodeScript, String> code2languageCodes = new HashMap<>();
static {
code2languageCodes.put(UnicodeScript.ARABIC, "ar");
code2languageCodes.put(UnicodeScript.GREEK, "el");
code2languageCodes.put(UnicodeScript.HAN, "zh");
code2languageCodes.put(UnicodeScript.HEBREW, "he");
code2languageCodes.put(UnicodeScript.HIRAGANA, "ja");
code2languageCodes.put(UnicodeScript.KATAKANA, "ja");
words.put("de", "als am auch auf aus bei bis das dem den der deren derer des dessen"
+ " die dies diese dieser dieses ein eine einer eines einem für"
+ " hat im ist mit sich sie über und vom von vor wie zu zum zur");
words.put("en",
"a and are as at do for from has have how its like new of on or the their through to with you your");
words.put("fr", "la le les un une des, à aux de pour par sur comme aussi jusqu'à"
+ " jusqu'aux quel quels quelles laquelle lequel lesquelles"
+ " lesquelles auxquels auxquelles avec sans ont sont duquel desquels desquelles quand");
endings.put("en", "ar ble cal ce ced ed ent ic ies ing ive ness our ous ons ral th ure y");
endings.put("de", "ag chen gen ger iche icht ig ige isch ische ischen kar ker"
+ " keit ler mus nen ner rie rer ter ten trie tz ung yse");
endings.put("fr", "é, és, ée, ées, euse, euses, ème, euil, asme, isme, aux");
}
private static int buildScore(String text, String lang, String wordList, String endings) {
text = text.toLowerCase(Locale.ROOT).trim();
text = text.replace(',', ' ').replace('-', ' ').replace('/', ' ');
text = " " + text + " ";
int score = 0;
StringTokenizer st = new StringTokenizer(wordList, " ");
while (st.hasMoreTokens()) {
String word = st.nextToken();
int pos = 0;
while ((pos = text.indexOf(" " + word + " ", pos)) >= 0) {
score += 2;
pos = Math.min(pos + word.length() + 1, text.length());
}
}
st = new StringTokenizer(endings, " ");
while (st.hasMoreTokens()) {
String ending = st.nextToken();
if (text.contains(ending + " ")) {
score += 1;
}
int pos = 0;
while ((pos = text.indexOf(ending + " ", pos)) >= 0) {
score += 1;
pos = Math.min(pos + ending.length() + 1, text.length());
}
}
LOGGER.debug("Score {} = {}", lang, score);
return score;
}
public static String detectLanguageByCharacter(String text) {
if (text == null || text.isEmpty()) {
LOGGER.warn("The text for language detection is null or empty");
return null;
}
LOGGER.debug("Detecting language of [{}]", text);
Map<UnicodeScript, AtomicInteger> scores = new HashMap<>();
buildScores(text, scores);
UnicodeScript code = getCodeWithMaxScore(scores);
return code2languageCodes.getOrDefault(code, null);
}
private static void buildScores(String text, Map<UnicodeScript, AtomicInteger> scores) {
try {
char[] chararray = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
UnicodeScript code = UnicodeScript.of(Character.codePointAt(chararray, i));
increaseScoreFor(scores, code);
}
} catch (Exception ignored) {
}
}
private static void increaseScoreFor(Map<UnicodeScript, AtomicInteger> scores, UnicodeScript code) {
scores.computeIfAbsent(code, k -> new AtomicInteger()).incrementAndGet();
}
private static UnicodeScript getCodeWithMaxScore(Map<UnicodeScript, AtomicInteger> scores) {
UnicodeScript maxCode = null;
int maxScore = 0;
for (UnicodeScript code : scores.keySet()) {
int score = scores.get(code).get();
if (score > maxScore) {
maxScore = score;
maxCode = code;
}
}
return maxCode;
}
/**
* Detects the language of a given text string.
*
* @param text the text string
* @return the language code: de, en, fr, ar ,el, zh, he, jp or null
*/
public static String detectLanguage(String text) {
LOGGER.debug("Detecting language of [{}]", text);
String bestLanguage = detectLanguageByCharacter(text);
if (bestLanguage == null) {
int bestScore = 0;
Enumeration<Object> languages = words.keys();
while (languages.hasMoreElements()) {
String language = (String) languages.nextElement();
String wordList = words.getProperty(language);
String endingList = endings.getProperty(language);
int score = buildScore(text, language, wordList, endingList);
if (score > bestScore) {
bestLanguage = language;
bestScore = score;
}
}
}
LOGGER.debug("Detected language = {}", bestLanguage);
return bestLanguage;
}
}
| 6,877 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSession.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRSession.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import static org.mycore.common.events.MCRSessionEvent.Type.activated;
import static org.mycore.common.events.MCRSessionEvent.Type.passivated;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRSessionEvent;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.events.MCRShutdownHandler.Closeable;
import org.mycore.util.concurrent.MCRTransactionableRunnable;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
/**
* Instances of this class collect information kept during a session like the currently active user, the preferred
* language etc.
*
* @author Detlev Degenhardt
* @author Jens Kupferschmidt
* @author Frank Lützenkirchen
*/
public class MCRSession implements Cloneable {
private static final URI DEFAULT_URI = URI.create("");
/** A map storing arbitrary session data * */
private Map<Object, Object> map = new Hashtable<>();
@SuppressWarnings("unchecked")
private Map.Entry<Object, Object>[] emptyEntryArray = new Map.Entry[0];
private List<Map.Entry<Object, Object>> mapEntries;
private boolean mapChanged = true;
AtomicInteger accessCount;
AtomicInteger concurrentAccess;
ThreadLocal<AtomicInteger> currentThreadCount = ThreadLocal.withInitial(AtomicInteger::new);
/** the logger */
static Logger LOGGER = LogManager.getLogger(MCRSession.class.getName());
/** The user ID of the session */
private MCRUserInformation userInformation;
/** The language for this session as upper case character */
private String language = null;
private Locale locale = null;
/** The unique ID of this session */
private String sessionID;
private String ip;
private long loginTime, lastAccessTime, thisAccessTime, createTime;
private StackTraceElement[] constructingStackTrace;
private Optional<URI> firstURI = Optional.empty();
private ThreadLocal<Throwable> lastActivatedStackTrace = new ThreadLocal<>();
private ThreadLocal<Queue<Runnable>> onCommitTasks = ThreadLocal.withInitial(ArrayDeque::new);
private static ExecutorService COMMIT_SERVICE;
private static MCRUserInformation guestUserInformation = MCRSystemUserInformation.getGuestInstance();
static {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("MCRSession-OnCommitService-#%d")
.build();
COMMIT_SERVICE = Executors.newFixedThreadPool(4, threadFactory);
MCRShutdownHandler.getInstance().addCloseable(new Closeable() {
@Override
public void prepareClose() {
COMMIT_SERVICE.shutdown();
}
@Override
public int getPriority() {
return Integer.MIN_VALUE + 8;
}
@Override
public void close() {
if (!COMMIT_SERVICE.isTerminated()) {
try {
COMMIT_SERVICE.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
LOGGER.warn("Error while waiting for shutdown.", e);
}
}
}
});
}
/**
* The constructor of a MCRSession. As default the user ID is set to the value of the property variable named
* 'MCR.Users.Guestuser.UserName'.
*/
MCRSession() {
userInformation = guestUserInformation;
setCurrentLanguage(MCRConfiguration2.getString("MCR.Metadata.DefaultLang").orElse(MCRConstants.DEFAULT_LANG));
accessCount = new AtomicInteger();
concurrentAccess = new AtomicInteger();
ip = "";
sessionID = buildSessionID();
MCRSessionMgr.addSession(this);
LOGGER.debug("MCRSession created {}", sessionID);
setLoginTime();
createTime = loginTime;
Throwable t = new Throwable();
t.fillInStackTrace();
constructingStackTrace = t.getStackTrace();
}
protected final void setLoginTime() {
loginTime = System.currentTimeMillis();
lastAccessTime = loginTime;
thisAccessTime = loginTime;
}
/**
* Constructs a unique session ID for this session, based on current time and IP address of host where the code
* runs.
*/
private static String buildSessionID() {
return UUID.randomUUID().toString();
}
/**
* Returns the unique ID of this session
*/
public String getID() {
return sessionID;
}
/**
* Returns a list of all stored object keys within MCRSession. This method is not thread safe. I you need thread
* safe access to all stored objects use {@link MCRSession#getMapEntries()} instead.
*
* @return Returns a list of all stored object keys within MCRSession as java.util.Ierator
*/
public Iterator<Object> getObjectsKeyList() {
return Collections.unmodifiableSet(map.keySet()).iterator();
}
/**
* Returns an unmodifiable list of all entries in this MCRSession This method is thread safe.
*/
public List<Map.Entry<Object, Object>> getMapEntries() {
if (mapChanged) {
mapChanged = false;
final Set<Entry<Object, Object>> entrySet = Collections.unmodifiableMap(map).entrySet();
final Map.Entry<Object, Object>[] entryArray = entrySet.toArray(emptyEntryArray);
mapEntries = List.of(entryArray);
}
return mapEntries;
}
/** returns the current language */
public final String getCurrentLanguage() {
return language;
}
/** sets the current language */
public final void setCurrentLanguage(String language) {
Locale newLocale = Locale.forLanguageTag(language);
this.language = language;
this.locale = newLocale;
}
public Locale getLocale() {
return locale;
}
/** Write data to the logger for debugging purposes */
public final void debug() {
LOGGER.debug("SessionID = {}", sessionID);
LOGGER.debug("UserID = {}", getUserInformation().getUserID());
LOGGER.debug("IP = {}", ip);
LOGGER.debug("language = {}", language);
}
/** Stores an object under the given key within the session * */
public Object put(Object key, Object value) {
mapChanged = true;
return map.put(key, value);
}
/** Returns the object that was stored in the session under the given key * */
public Object get(Object key) {
return map.get(key);
}
public void deleteObject(Object key) {
mapChanged = true;
map.remove(key);
}
/** Get the current ip value */
public String getCurrentIP() {
return ip;
}
/** Set the ip to the given IP */
public final void setCurrentIP(String newip) {
//a necessary condition for an IP address is to start with an hexadecimal value or ':'
if (Character.digit(newip.charAt(0), 16) == -1 && newip.charAt(0) != ':') {
LOGGER.error("Is not a valid IP address: {}", newip);
return;
}
try {
InetAddress inetAddress = InetAddress.getByName(newip);
ip = inetAddress.getHostAddress();
} catch (UnknownHostException e) {
LOGGER.error("Exception while parsing new ip {} using old value.", newip, e);
}
}
public final long getLoginTime() {
return loginTime;
}
public void close() {
// remove from session list
LOGGER.debug("Remove myself from MCRSession list");
MCRSessionMgr.removeSession(this);
// clear bound objects
LOGGER.debug("Clearing local map.");
map.clear();
mapEntries = null;
sessionID = null;
}
@Override
public String toString() {
return "MCRSession[" + getID() + ",user:'" + getUserInformation().getUserID() + "',ip:" + getCurrentIP()
+ "]";
}
public long getLastAccessedTime() {
return lastAccessTime;
}
public void setFirstURI(Supplier<URI> uri) {
if (firstURI.isEmpty()) {
firstURI = Optional.of(uri.get());
}
}
/**
* Activate this session. For internal use mainly by MCRSessionMgr.
*
* @see MCRSessionMgr#setCurrentSession(MCRSession)
*/
void activate() {
lastAccessTime = thisAccessTime;
thisAccessTime = System.currentTimeMillis();
accessCount.incrementAndGet();
if (currentThreadCount.get().getAndIncrement() == 0) {
lastActivatedStackTrace.set(new RuntimeException("This is for debugging purposes only"));
fireSessionEvent(activated, concurrentAccess.incrementAndGet());
} else {
MCRException e = new MCRException(
"Cannot activate a Session more than once per thread: " + currentThreadCount.get().get());
LOGGER.warn("Too many activate() calls stacktrace:", e);
LOGGER.warn("First activate() call stacktrace:", lastActivatedStackTrace.get());
}
}
/**
* Passivate this session. For internal use mainly by MCRSessionMgr.
*
* @see MCRSessionMgr#releaseCurrentSession()
*/
void passivate() {
if (currentThreadCount.get().getAndDecrement() == 1) {
lastActivatedStackTrace.set(null);
fireSessionEvent(passivated, concurrentAccess.decrementAndGet());
} else {
LOGGER.debug("deactivate currentThreadCount: {}", currentThreadCount.get().get());
}
if (firstURI.isEmpty()) {
firstURI = Optional.of(DEFAULT_URI);
}
onCommitTasks.remove();
}
/**
* Fire MCRSessionEvents. This is a common method that fires all types of MCRSessionEvent. Mainly for internal use
* of MCRSession and MCRSessionMgr.
*
* @param type
* type of event
* @param concurrentAccessors
* number of concurrentThreads (passivateEvent gets 0 for singleThread)
*/
void fireSessionEvent(MCRSessionEvent.Type type, int concurrentAccessors) {
MCRSessionEvent event = new MCRSessionEvent(this, type, concurrentAccessors);
LOGGER.debug(event);
MCRSessionMgr.getListeners().forEach(l -> l.sessionEvent(event));
}
public long getThisAccessTime() {
return thisAccessTime;
}
public long getCreateTime() {
return createTime;
}
/**
* starts a new database transaction.
*/
@Deprecated
public void beginTransaction() {
MCRTransactionHelper.beginTransaction();
}
/**
* Determine whether the current resource transaction has been marked for rollback.
* @return boolean indicating whether the transaction has been marked for rollback
*/
@Deprecated
public boolean transactionRequiresRollback() {
return MCRTransactionHelper.transactionRequiresRollback();
}
/**
* commits the database transaction. Commit is only done if {@link #isTransactionActive()} returns true.
*/
@Deprecated
public void commitTransaction() {
MCRTransactionHelper.commitTransaction();
}
/**
* forces the database transaction to roll back. Roll back is only performed if {@link #isTransactionActive()}
* returns true.
*/
@Deprecated
public void rollbackTransaction() {
MCRTransactionHelper.rollbackTransaction();
}
/**
* Is the transaction still alive?
*
* @return true if the transaction is still alive
*/
@Deprecated
public boolean isTransactionActive() {
return MCRTransactionHelper.isTransactionActive();
}
public StackTraceElement[] getConstructingStackTrace() {
return constructingStackTrace;
}
public Optional<URI> getFirstURI() {
return firstURI;
}
/**
* @return the userInformation
*/
public MCRUserInformation getUserInformation() {
return userInformation;
}
/**
* @param userSystemAdapter
* the userInformation to set
* @throws IllegalArgumentException if transition to new user information is forbidden (privilege escalation)
*/
public void setUserInformation(MCRUserInformation userSystemAdapter) {
//check for MCR-1400
if (!isTransitionAllowed(userSystemAdapter)) {
throw new IllegalArgumentException("User transition from "
+ getUserInformation().getUserID()
+ " to " + userSystemAdapter.getUserID()
+ " is not permitted within the same session.");
}
this.userInformation = userSystemAdapter;
setLoginTime();
}
/**
* Add a task which will be executed after {@link #commitTransaction()} was called.
*
* @param task thread witch will be executed after an commit
*/
public void onCommit(Runnable task) {
this.onCommitTasks.get().offer(Objects.requireNonNull(task));
}
protected void submitOnCommitTasks() {
Queue<Runnable> runnables = onCommitTasks.get();
onCommitTasks.remove();
CompletableFuture.allOf(runnables.stream()
.map(r -> new MCRTransactionableRunnable(r, this))
.map(MCRSession::toCompletableFuture)
.toArray(CompletableFuture[]::new))
.join();
}
private static CompletableFuture<?> toCompletableFuture(MCRTransactionableRunnable r) {
try {
return CompletableFuture.runAsync(r, COMMIT_SERVICE);
} catch (RuntimeException e) {
LOGGER.error("Could not submit onCommit task. Running it locally.", e);
try {
r.run();
} catch (RuntimeException e2) {
LOGGER.fatal("Argh! Could not run task either. This task is lost 😰", e2);
}
return CompletableFuture.completedFuture(null);
}
}
private boolean isTransitionAllowed(MCRUserInformation userSystemAdapter) {
//allow if current user super user or system user or not logged in
if (MCRSystemUserInformation.getSuperUserInstance().getUserID().equals(userInformation.getUserID())
|| MCRSystemUserInformation.getGuestInstance().getUserID().equals(userInformation.getUserID())
|| MCRSystemUserInformation.getSystemUserInstance().getUserID().equals(userInformation.getUserID())) {
return true;
}
//allow if new user information has default rights of guest user
//or userID equals old userID
return MCRSystemUserInformation.getGuestInstance().getUserID().equals(userSystemAdapter.getUserID())
|| MCRSystemUserInformation.getSystemUserInstance().getUserID().equals(userSystemAdapter.getUserID())
|| userInformation.getUserID().equals(userSystemAdapter.getUserID());
}
}
| 16,509 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCoreVersion.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCoreVersion.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import org.mycore.common.config.MCRConfigurationDir;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRCoreVersion {
private static Properties prop = loadVersionProperties();
public static final String VERSION = prop.getProperty("git.build.version");
public static final String BRANCH = prop.getProperty("git.branch");
public static final String REVISION = prop.getProperty("git.commit.id.full");
public static final String DESCRIBE = prop.getProperty("git.commit.id.describe");
public static final String ABBREV = prop.getProperty("git.commit.id.abbrev");
public static final String COMPLETE = VERSION + " " + BRANCH + ":" + DESCRIBE;
public static String getVersion() {
return VERSION;
}
private static Properties loadVersionProperties() {
Properties props = new Properties();
URL gitPropURL = MCRCoreVersion.class.getResource("/org/mycore/git.properties");
try (InputStream gitPropStream = getInputStream(gitPropURL)) {
props.load(gitPropStream);
} catch (IOException e) {
throw new MCRException("Error while initializing MCRCoreVersion.", e);
}
return props;
}
private static InputStream getInputStream(URL gitPropURL) throws IOException {
if (gitPropURL == null) {
return new InputStream() {
@Override
public int read() {
return -1;
}
};
}
return gitPropURL.openStream();
}
public static String getBranch() {
return BRANCH;
}
public static String getRevision() {
return REVISION;
}
public static String getGitDescribe() {
return DESCRIBE;
}
public static String getCompleteVersion() {
return COMPLETE;
}
public static String getAbbrev() {
return ABBREV;
}
public static Map<String, String> getVersionProperties() {
return prop.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
}
public static void main(String[] arg) throws IOException {
System.out.printf(Locale.ROOT, "MyCoRe\tver: %s\tbranch: %s\tcommit: %s%n", VERSION, BRANCH, DESCRIBE);
System.out.printf(Locale.ROOT, "Config directory: %s%n", MCRConfigurationDir.getConfigurationDirectory());
prop.store(System.out, "Values of '/org/mycore/version.properties' resource");
}
}
| 3,469 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSystemUserInformation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRSystemUserInformation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import org.mycore.common.config.MCRConfiguration2;
/**
* A {@link MCRUserInformation} implementation with no roles attached.
* @author Thomas Scheffler (yagee)
*
*/
public class MCRSystemUserInformation implements MCRUserInformation {
private static MCRSystemUserInformation janitorInstance = new MCRSystemUserInformation(
new UserIdResolver("MCRJANITOR", null), true);
private static MCRSystemUserInformation systemInstance = new MCRSystemUserInformation(new UserIdResolver("SYSTEM",
null), false);
private static MCRSystemUserInformation guestInstance = new MCRSystemUserInformation(new UserIdResolver("guest",
"MCR.Users.Guestuser.UserName"), false);
private static MCRSystemUserInformation superUserInstance = new MCRSystemUserInformation(new UserIdResolver(
"administrator", "MCR.Users.Superuser.UserName"), true);
private boolean roleReturn;
private UserIdResolver userID;
private MCRSystemUserInformation(UserIdResolver userID, boolean roleReturn) {
this.userID = userID;
this.roleReturn = roleReturn;
}
/**
* Always returns "SYSTEM"
*/
@Override
public String getUserID() {
return userID.getUserId();
}
/**
* Always returns <em>false</em>
*/
@Override
public boolean isUserInRole(String role) {
return roleReturn;
}
/**
* @return the systemInstance
*/
public static MCRSystemUserInformation getSystemUserInstance() {
return systemInstance;
}
@Override
public String getUserAttribute(String attribute) {
return null;
}
/**
* @return the guestInstance
*/
public static MCRSystemUserInformation getGuestInstance() {
return guestInstance;
}
/**
* @return the superUserInstance
*/
public static MCRSystemUserInformation getSuperUserInstance() {
return superUserInstance;
}
/**
* @return the janitor Instance
*/
public static MCRSystemUserInformation getJanitorInstance() {
return janitorInstance;
}
private static class UserIdResolver {
private String userId;
private String property;
UserIdResolver(String userId, String property) {
this.userId = userId;
this.property = property;
}
public String getUserId() {
if (property == null) {
return userId;
}
return MCRConfiguration2.getString(property).orElse(userId);
}
}
}
| 3,323 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionMgr.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRSessionMgr.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import static org.mycore.common.events.MCRSessionEvent.Type.created;
import static org.mycore.common.events.MCRSessionEvent.Type.destroyed;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.events.MCRSessionListener;
import org.mycore.util.concurrent.MCRReadWriteGuard;
/**
* Manages sessions for a MyCoRe system. This class is backed by a ThreadLocal variable, so every Thread is guaranteed
* to get a unique instance of MCRSession. Care must be taken when using an environment utilizing a Thread pool, such as
* many Servlet engines. In this case it is possible for the session object to stay attached to a thread where it should
* not be. Use the {@link #releaseCurrentSession()}method to reset the session object for a Thread to its default
* values. The basic idea for the implementation of this class is taken from an apache project, namely the class
* org.apache.common.latka.LatkaProperties.java written by Morgan Delagrange.
*
* @author Detlev Degenhardt
* @author Thomas Scheffler (yagee)
*/
public class MCRSessionMgr {
private static Map<String, MCRSession> sessions = Collections.synchronizedMap(new HashMap<>());
private static List<MCRSessionListener> listeners = new ArrayList<>();
private static MCRReadWriteGuard listenersGuard = new MCRReadWriteGuard();
private static final Logger LOGGER = LogManager.getLogger();
/**
* This ThreadLocal is automatically instantiated per thread with a MyCoRe session object containing the default
* session parameters which are set in the constructor of MCRSession.
*
* @see ThreadLocal
*/
private static ThreadLocal<MCRSession> theThreadLocalSession = ThreadLocal.withInitial(MCRSession::new);
private static ThreadLocal<Boolean> isSessionAttached = ThreadLocal.withInitial(() -> Boolean.FALSE);
private static ThreadLocal<Boolean> isSessionCreationLocked = ThreadLocal.withInitial(() -> Boolean.TRUE);
/**
* This method returns the unique MyCoRe session object for the current Thread. The session object is initialized
* with the default MyCoRe session data.
*
* @return MyCoRe MCRSession object
* @throws MCRException if the current Thread {@link #isLocked()}
*/
public static MCRSession getCurrentSession() {
if (isSessionCreationLocked.get()) {
throw new MCRException("Session creation is locked!");
}
isSessionAttached.set(Boolean.TRUE);
return theThreadLocalSession.get();
}
private static void checkSessionLock() {
if (isSessionCreationLocked.get()) {
throw new MCRException("Session creation is locked!");
}
}
/**
* This method sets a MyCoRe session object for the current Thread. This method fires a "activated" event, when
* called the first time for this session and thread.
* Calling this method also unlocks the current Thread for MCRSession handling.
*
* @see org.mycore.common.events.MCRSessionEvent.Type#activated
*/
public static void setCurrentSession(MCRSession theSession) {
if (hasCurrentSession()) {
MCRSession currentSession = getCurrentSession();
if (currentSession != theSession && currentSession.getID() != null) {
LOGGER.error("Current session will be released: " + currentSession,
new MCRException("Current thread already has a session attached!"));
releaseCurrentSession();
}
}
unlock();
theSession.activate();
theThreadLocalSession.set(theSession);
isSessionAttached.set(Boolean.TRUE);
}
/**
* Releases the MyCoRe session from its current thread. Subsequent calls of getCurrentSession() will return a
* different MCRSession object than before for the current Thread. One use for this method is to reset the session
* inside a Thread-pooling environment like Servlet engines. This method fires a "passivated" event, when called the
* last time for this session and thread.
*
* @see org.mycore.common.events.MCRSessionEvent.Type#passivated
*/
public static void releaseCurrentSession() {
//theThreadLocalSession maybe null if called after close()
if (theThreadLocalSession != null && hasCurrentSession()) {
MCRSession session = theThreadLocalSession.get();
session.passivate();
MCRSession.LOGGER.debug("MCRSession released {}", session.getID());
theThreadLocalSession.remove();
isSessionAttached.remove();
lock();
}
}
/**
* Returns a boolean indicating if a {@link MCRSession} is bound to the current thread.
*
* @return true if a session is bound to the current thread
*/
public static boolean hasCurrentSession() {
return isSessionAttached.get();
}
/**
* Returns the current session ID. This method does not spawn a new session as {@link #getCurrentSession()} would
* do.
*
* @return current session ID or <code>null</code> if current thread has no session attached.
*/
public static String getCurrentSessionID() {
if (hasCurrentSession()) {
return getCurrentSession().getID();
}
return null;
}
/**
* Locks the MCRSessionMgr and no {@link MCRSession}s can be attached to the current Thread.
*/
public static void lock() {
isSessionCreationLocked.set(true);
}
/**
* Unlocks the MCRSessionMgr to allow management of {@link MCRSession}s on the current Thread.
*/
public static void unlock() {
isSessionCreationLocked.set(false);
}
/**
* @return the lock status of MCRSessionMgr, defaults to <code>true</code> on new Threads
*/
public static boolean isLocked() {
return isSessionCreationLocked.get();
}
/**
* Returns the MCRSession for the given sessionID.
*/
public static MCRSession getSession(String sessionID) {
MCRSession s = sessions.get(sessionID);
if (s == null) {
MCRSession.LOGGER.warn("MCRSession with ID {} not cached any more", sessionID);
}
return s;
}
/**
* Add MCRSession to a static Map that manages all sessions. This method fires a "created" event and is invoked by
* MCRSession constructor.
*
* @see MCRSession#MCRSession()
* @see org.mycore.common.events.MCRSessionEvent.Type#created
*/
static void addSession(MCRSession session) {
sessions.put(session.getID(), session);
session.fireSessionEvent(created, session.concurrentAccess.get());
}
/**
* Remove MCRSession from a static Map that manages all sessions. This method fires a "destroyed" event and is
* invoked by MCRSession.close().
*
* @see MCRSession#close()
* @see org.mycore.common.events.MCRSessionEvent.Type#destroyed
*/
static void removeSession(MCRSession session) {
sessions.remove(session.getID());
session.fireSessionEvent(destroyed, session.concurrentAccess.get());
}
/**
* Add a MCRSessionListener, that gets infomed about MCRSessionEvents.
*
* @see #removeSessionListener(MCRSessionListener)
*/
public static void addSessionListener(MCRSessionListener listener) {
listenersGuard.write(() -> listeners.add(listener));
}
/**
* Removes a MCRSessionListener from the list.
*
* @see #addSessionListener(MCRSessionListener)
*/
public static void removeSessionListener(MCRSessionListener listener) {
listenersGuard.write(() -> listeners.remove(listener));
}
/**
* Allows access to all MCRSessionListener instances. Mainly for internal use of MCRSession.
*/
static List<MCRSessionListener> getListeners() {
return listenersGuard.read(() -> listeners.stream().collect(Collectors.toList()));
}
public static void close() {
listenersGuard.write(() -> {
Collection<MCRSession> var = sessions.values();
for (MCRSession session : var.toArray(MCRSession[]::new)) {
session.close();
}
LogManager.getLogger(MCRSessionMgr.class).info("Removing thread locals...");
isSessionAttached = null;
theThreadLocalSession = null;
listeners.clear();
LogManager.getLogger(MCRSessionMgr.class).info("...done.");
});
listenersGuard = null;
}
public static Map<String, MCRSession> getAllSessions() {
return sessions;
}
}
| 9,671 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCacheManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCacheManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
/**
*
* @author Thomas Scheffler (yagee)
*
* Need to insert some things here
* jmx.mbean
*/
public class MCRCacheManager implements MCRCacheManagerMBean {
@SuppressWarnings("rawtypes")
private final MCRCache cache;
public MCRCacheManager(@SuppressWarnings("rawtypes") final MCRCache cache) {
this.cache = cache;
}
public long getCapacity() {
return cache.getCapacity();
}
public double getFillRate() {
return cache.getFillRate();
}
public double getHitRate() {
return cache.getHitRate();
}
public long getHits() {
return cache.backingCache.stats().hitCount();
}
public long getRequests() {
return cache.backingCache.stats().requestCount();
}
public long getEvictions() {
return cache.backingCache.stats().evictionCount();
}
public long getSize() {
return cache.getCurrentSize();
}
/**
* jmx.managed-operation
*/
public void setCapacity(long capacity) {
cache.setCapacity(capacity);
}
public void clear() {
cache.clear();
}
}
| 1,882 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRGeoUtilities.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRGeoUtilities.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Objects;
/**
* @author shermann
*
*/
public class MCRGeoUtilities {
/**
* Converts coordinates to decimal degree (as used by google maps).
*
*/
public static double toDecimalDegrees(int degree, int minutes, double seconds) {
return (((seconds / 60) + minutes) / 60) + degree;
}
/**
* Converts coordinates in pica format to decimal degree (as used by google maps).
*
* @return the decimal degree representation of the coordinates
*/
public static double toDecimalDegrees(String picaValue) {
if (picaValue == null || picaValue.length() == 0 || (!isValid(picaValue))) {
return 0d;
}
String[] strings = picaValue.split(" ");
if (strings.length < 3) {
return 0d;
}
int degree = Integer.parseInt(strings[1]);
int minutes = Integer.parseInt(strings[2]);
double seconds = 0d;
if (strings.length >= 4) {
seconds = Double.parseDouble(strings[3]);
}
int factor = Objects.equals(strings[0], "W") || Objects.equals(strings[0], "S") ? -1 : 1;
return ((((seconds / 60) + minutes) / 60) + degree) * factor;
}
/**
* Converts decimal degree to ordinary coordinates.
*
*/
public static String toDegreeMinuteSecond(double inDecimalDegree) {
int degree = (int) inDecimalDegree;
int minutes = (int) ((inDecimalDegree - degree) * 60);
double seconds = ((inDecimalDegree - degree) * 60 - minutes) * 60;
return new MessageFormat("{0}° {1}'' {2}", Locale.ROOT).format(
new Object[] { degree, minutes, Math.round(seconds * 100d / 100d) });
}
/**
* @param picaValue the value as stored in opac/pica
* @return a human readable form like 38° 22′ S
*
* @see #toDegreeMinuteSecond(double)
*/
public static String toDegreeMinuteSecond(String picaValue) {
if (picaValue == null || picaValue.length() == 0 || (!isValid(picaValue))) {
return null;
}
String[] strings = picaValue.split(" ");
if (strings.length < 3) {
return null;
}
double seconds = 0d;
if (strings.length >= 4) {
seconds = Double.parseDouble(strings[3]);
}
return new MessageFormat("{0}° {1}'' {2} {3}", Locale.ROOT).format(
new Object[] { Integer.valueOf(strings[1]), Integer.valueOf(strings[2]), Math.round(seconds * 100d / 100d),
strings[0] });
}
private static boolean isValid(String picaValue) {
String regex = "[EWSN]{1}\\s[0-9]{3}\\s[0-9]{2}(\\s[0-9]*)*";
return picaValue.matches(regex);
}
}
| 3,550 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJSONManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRJSONManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class MCRJSONManager {
private GsonBuilder gsonBuilder;
private static MCRJSONManager instance;
private MCRJSONManager() {
gsonBuilder = new GsonBuilder();
}
public void registerAdapter(MCRJSONTypeAdapter<?> typeAdapter) {
gsonBuilder.registerTypeAdapter(typeAdapter.bindTo(), typeAdapter);
}
public static MCRJSONManager instance() {
if (instance == null) {
instance = new MCRJSONManager();
}
return instance;
}
public GsonBuilder getGsonBuilder() {
return gsonBuilder;
}
public Gson createGson() {
return gsonBuilder.create();
}
}
| 1,483 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRExceptionCauseFinder.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRExceptionCauseFinder.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import javax.xml.transform.TransformerException;
import org.apache.xml.utils.WrappedRuntimeException;
/**
* Tries to find the cause of an exception by diving down
* those exceptions that wrap other exceptions, recursively.
* The exception at the bottom of the stack is returned.
*
* @author Frank Lützenkirchen
*/
public class MCRExceptionCauseFinder {
public static Exception getCause(TransformerException ex) {
Throwable cause = ex.getException();
return (cause == null ? ex : getCause(cause));
}
public static Exception getCause(Throwable ex) {
Throwable cause = ex.getCause();
return (cause == null ? (Exception) ex : getCause(cause));
}
public static Exception getCause(WrappedRuntimeException ex) {
return getCause(ex.getException());
}
}
| 1,577 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileTime;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.streams.MCRDevNull;
import org.mycore.common.content.streams.MCRMD5InputStream;
import org.mycore.common.function.MCRThrowableTask;
import org.mycore.datamodel.niofs.MCRPathUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import jakarta.xml.bind.DatatypeConverter;
/**
* This class represent a general set of external methods to support the programming API.
*
* @author Jens Kupferschmidt
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public class MCRUtils {
// public constant data
private static final Logger LOGGER = LogManager.getLogger();
// The file slash
private static String SLASH = System.getProperty("file.separator");
/**
* Reads exactly <code>len</code> bytes from the input stream into the byte array. This method reads repeatedly from
* the underlying stream until all the bytes are read. InputStream.read is often documented to block like this, but
* in actuality it does not always do so, and returns early with just a few bytes. readBlockiyng blocks until all
* the bytes are read, the end of the stream is detected, or an exception is thrown. You will always get as many
* bytes as you asked for unless you get an eof or other exception. Unlike readFully, you find out how many bytes
* you did get.
*
* @param b
* the buffer into which the data is read.
* @param off
* the start offset of the data.
* @param len
* the number of bytes to read.
* @return number of bytes actually read.
* @exception IOException
* if an I/O error occurs.
*/
public static int readBlocking(InputStream in, byte[] b, int off, int len) throws IOException {
int totalBytesRead = 0;
while (totalBytesRead < len) {
int bytesRead = in.read(b, off + totalBytesRead, len - totalBytesRead);
if (bytesRead < 0) {
break;
}
totalBytesRead += bytesRead;
}
return totalBytesRead;
} // end readBlocking
/**
* Reads exactly <code>len</code> bytes from the input stream into the byte array. This method reads repeatedly from
* the underlying stream until all the bytes are read. Reader.read is often documented to block like this, but in
* actuality it does not always do so, and returns early with just a few bytes. readBlockiyng blocks until all the
* bytes are read, the end of the stream is detected, or an exception is thrown. You will always get as many bytes
* as you asked for unless you get an eof or other exception. Unlike readFully, you find out how many bytes you did
* get.
*
* @param c
* the buffer into which the data is read.
* @param off
* the start offset of the data.
* @param len
* the number of bytes to read.
* @return number of bytes actually read.
* @exception IOException
* if an I/O error occurs.
*/
public static int readBlocking(Reader in, char[] c, int off, int len) throws IOException {
int totalCharsRead = 0;
while (totalCharsRead < len) {
int charsRead = in.read(c, off + totalCharsRead, len - totalCharsRead);
if (charsRead < 0) {
break;
}
totalCharsRead += charsRead;
}
return totalCharsRead;
} // end readBlocking
/**
* Writes plain text to a file.
*
* @param textToWrite
* the text to write into the file
* @param fileName
* the name of the file to write to, given as absolute path
* @return a handle to the written file
*/
public static Path writeTextToFile(String textToWrite, String fileName, Charset cs) throws IOException {
Path file = Paths.get(fileName);
Files.write(file, Collections.singletonList(textToWrite), cs, StandardOpenOption.CREATE);
return file;
}
/**
* The method return a list of all file names under the given directory and subdirectories of itself.
*
* @param basedir
* the File instance of the basic directory
* @return an ArrayList with file names as pathes
*/
public static ArrayList<String> getAllFileNames(File basedir) {
ArrayList<String> out = new ArrayList<>();
File[] stage = basedir.listFiles();
for (File element : stage) {
if (element.isFile()) {
out.add(element.getName());
}
if (element.isDirectory()) {
out.addAll(getAllFileNames(element, element.getName() + SLASH));
}
}
return out;
}
/**
* The method return a list of all file names under the given directory and subdirectories of itself.
*
* @param basedir
* the File instance of the basic directory
* @param path
* the part of directory path
* @return an ArrayList with file names as pathes
*/
public static ArrayList<String> getAllFileNames(File basedir, String path) {
ArrayList<String> out = new ArrayList<>();
File[] stage = basedir.listFiles();
for (File element : stage) {
if (element.isFile()) {
out.add(path + element.getName());
}
if (element.isDirectory()) {
out.addAll(getAllFileNames(element, path + element.getName() + SLASH));
}
}
return out;
}
/**
* The method return a list of all directory names under the given directory and subdirectories of itself.
*
* @param basedir
* the File instance of the basic directory
* @return an ArrayList with directory names as pathes
*/
public static ArrayList<String> getAllDirectoryNames(File basedir) {
ArrayList<String> out = new ArrayList<>();
File[] stage = basedir.listFiles();
for (File element : stage) {
if (element.isDirectory()) {
out.add(element.getName());
out.addAll(getAllDirectoryNames(element, element.getName() + SLASH));
}
}
return out;
}
/**
* The method return a list of all directory names under the given directory and subdirectories of itself.
*
* @param basedir
* the File instance of the basic directory
* @param path
* the part of directory path
* @return an ArrayList with directory names as pathes
*/
public static ArrayList<String> getAllDirectoryNames(File basedir, String path) {
ArrayList<String> out = new ArrayList<>();
File[] stage = basedir.listFiles();
for (File element : stage) {
if (element.isDirectory()) {
out.add(path + element.getName());
out.addAll(getAllDirectoryNames(element, path + element.getName() + SLASH));
}
}
return out;
}
public static String parseDocumentType(InputStream in) {
SAXParser parser = null;
try {
parser = SAXParserFactory.newInstance().newSAXParser();
} catch (Exception ex) {
String msg = "Could not build a SAX Parser for processing XML input";
throw new MCRConfigurationException(msg, ex);
}
final Properties detected = new Properties();
final String forcedInterrupt = "mcr.forced.interrupt";
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
LOGGER.debug("MCRLayoutService detected root element = {}", qName);
detected.setProperty("docType", qName);
throw new MCRException(forcedInterrupt);
}
};
try {
parser.parse(new InputSource(in), handler);
} catch (Exception ex) {
if (!forcedInterrupt.equals(ex.getMessage())) {
String msg = "Error while detecting XML document type from input source";
throw new MCRException(msg, ex);
}
}
String docType = detected.getProperty("docType");
int pos = docType.indexOf(':') + 1;
if (pos > 0) {
//filter namespace prefix
docType = docType.substring(pos);
}
return docType;
}
public static String asSHA1String(int iterations, byte[] salt, String text) throws NoSuchAlgorithmException {
return getHash(iterations, salt, text, "SHA-1");
}
public static String asSHA256String(int iterations, byte[] salt, String text) throws NoSuchAlgorithmException {
return getHash(iterations, salt, text, "SHA-256");
}
public static String asMD5String(int iterations, byte[] salt, String text) throws NoSuchAlgorithmException {
return getHash(iterations, salt, text, "MD5");
}
public static String asCryptString(String salt, String text) {
return MCRCrypt.crypt(salt, text);
}
/**
* Hashes string specified by alogrithm.
*
* @param text input
* @param algorithm hash algorithm
* @param salt salt
* @param iterations hash iterations, 1 is default
* @return hashed string as hex string
* @throws MCRException is hashing failed
*/
public static String hashString(String text, String algorithm, byte[] salt, int iterations) {
try {
return getHash(iterations, salt, text, algorithm);
} catch (NoSuchAlgorithmException e) {
throw new MCRException("Unable to hash string", e);
}
}
private static String getHash(int iterations, byte[] salt, String text, String algorithm)
throws NoSuchAlgorithmException {
MessageDigest digest;
if (--iterations < 0) {
iterations = 0;
}
byte[] data;
digest = MessageDigest.getInstance(algorithm);
text = Normalizer.normalize(text, Form.NFC);
if (salt != null) {
digest.update(salt);
}
data = digest.digest(text.getBytes(StandardCharsets.UTF_8));
for (int i = 0; i < iterations; i++) {
data = digest.digest(data);
}
return toHexString(data);
}
public static String toHexString(byte[] data) {
return DatatypeConverter.printHexBinary(data).toLowerCase(Locale.ROOT);
}
/**
* Calculates md5 sum of InputStream. InputStream is consumed after calling this method and automatically closed.
*/
public static String getMD5Sum(InputStream inputStream) throws IOException {
try (MCRMD5InputStream md5InputStream = new MCRMD5InputStream(inputStream)) {
IOUtils.copy(md5InputStream, new MCRDevNull());
return md5InputStream.getMD5String();
}
}
/**
* Extracts files in a tar archive. Currently works only on uncompressed tar files.
*
* @param source
* the uncompressed tar to extract
* @param expandToDirectory
* the directory to extract the tar file to
* @throws IOException
* if the source file does not exists
*/
public static void untar(Path source, Path expandToDirectory) throws IOException {
try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) {
TarArchiveEntry tarEntry;
FileSystem targetFS = expandToDirectory.getFileSystem();
HashMap<Path, FileTime> directoryTimes = new HashMap<>();
while ((tarEntry = tain.getNextEntry()) != null) {
Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName());
Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath();
if (tarEntry.isDirectory()) {
Files.createDirectories(expandToDirectory.resolve(absoluteTarget));
directoryTimes.put(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
} else {
if (Files.notExists(absoluteTarget.getParent())) {
Files.createDirectories(absoluteTarget.getParent());
}
Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING);
Files.setLastModifiedTime(absoluteTarget,
FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
}
}
//restore directory dates
Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Path absolutePath = dir.normalize().toAbsolutePath();
FileTime lastModifiedTime = directoryTimes.get(absolutePath);
if (lastModifiedTime != null) {
Files.setLastModifiedTime(absolutePath, lastModifiedTime);
} else {
LOGGER.warn("Could not restore last modified time for {} from TAR file {}.", absolutePath,
source);
}
return super.postVisitDirectory(dir, exc);
}
});
}
}
@SafeVarargs
public static Exception unwrapExCeption(Exception e, Class<? extends Exception>... classes) {
if (classes.length == 0) {
return e;
}
Class<? extends Exception> mainExceptionClass = classes[0];
Throwable check = e;
for (Class<? extends Exception> instChk : classes) {
if (instChk.isInstance(check)) {
return (Exception) check;
}
check = check.getCause();
if (check == null) {
break;
}
}
@SuppressWarnings("unchecked")
Constructor<? extends Exception>[] constructors = (Constructor<? extends Exception>[]) mainExceptionClass
.getConstructors();
for (Constructor<? extends Exception> c : constructors) {
Class<?>[] parameterTypes = c.getParameterTypes();
try {
if (parameterTypes.length == 0) {
Exception exception = c.newInstance((Object[]) null);
exception.initCause(e);
return exception;
}
if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(mainExceptionClass)) {
return c.newInstance(e);
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException ex) {
LOGGER.warn("Exception while initializing exception {}", mainExceptionClass.getCanonicalName(), ex);
return e;
}
}
LOGGER.warn("Could not instanciate Exception {}", mainExceptionClass.getCanonicalName());
return e;
}
/**
* Takes a file size in bytes and formats it as a string for output. For values < 5 KB the output format is for
* example "320 Byte". For values > 5 KB the output format is for example "6,8 KB". For values > 1 MB the
* output format is for example "3,45 MB".
*/
public static String getSizeFormatted(long bytes) {
String sizeUnit;
String sizeText;
double sizeValue;
if (bytes >= 1024 * 1024) {
// >= 1 MB
sizeUnit = "MB";
sizeValue = (double) Math.round(bytes / 10485.76) / 100;
} else if (bytes >= 5 * 1024) {
// >= 5 KB
sizeUnit = "KB";
sizeValue = (double) Math.round(bytes / 102.4) / 10;
} else {
// < 5 KB
sizeUnit = "Byte";
sizeValue = bytes;
}
sizeText = String.valueOf(sizeValue).replace('.', ',');
if (sizeText.endsWith(",0")) {
sizeText = sizeText.substring(0, sizeText.length() - 2);
}
return sizeText + " " + sizeUnit;
}
/**
* Helps to implement {@link Comparable#compareTo(Object)}
*
* For every <code>part</code> a check is performed in the specified order.
* The first check that does not return <code>0</code> the result is returned
* by this method. So when this method returns <code>0</code> <code>first</code>
* and <code>other</code> should be the same.
*
* @param first first Object that should be compared
* @param other Object that first should be compared against, e.g. <code>first.compareTo(other)</code>
* @param part different <code>compareTo()</code> steps
* @param <T> object that wants to implement compareTo()
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*
* @throws NullPointerException if either <code>first</code> or <code>other</code> is null
*
* deprecated in June 2023, because it was only used to compare MCRObjectID objects
* which is no handled differently
*
*/
@Deprecated
@SafeVarargs
@SuppressWarnings("unchecked")
public static <T> int compareParts(T first, T other, Function<T, Comparable>... part) {
return Stream.of(part)
.mapToInt(f -> f.apply(first).compareTo(f.apply(other)))
.filter(i -> i != 0)
.findFirst()
.orElse(0);
}
/**
* @param t contains the printStackTrace
* @return the stacktrace as string
*/
public static String getStackTraceAsString(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw)); // closing string writer has no effect
return sw.toString();
}
/**
* Checks is trimmed <code>value</code> is not empty.
* @param value String to test
* @return <em>empty</em> if value is <code>null</code> or empty after trimming.
*/
public static Optional<String> filterTrimmedNotEmpty(String value) {
return Optional.ofNullable(value)
.map(String::trim)
.filter(s -> !s.isEmpty());
}
/**
* Measures the time of a method call.
* timeHandler is guaranteed to be called even if exception is thrown.
* @param unit time unit for timeHandler
* @param timeHandler gets the duration in <code>unit</code>
* @param task method reference
* @throws T if task.run() throws Exception
*/
public static <T extends Throwable> void measure(TimeUnit unit, Consumer<Long> timeHandler,
MCRThrowableTask<T> task) throws T {
long time = System.nanoTime();
try {
task.run();
} finally {
time = System.nanoTime() - time;
timeHandler.accept(unit.convert(time, TimeUnit.NANOSECONDS));
}
}
/**
* Measures and logs the time of a method call
* @param task method reference
* @throws T if task.run() throws Exception
*/
public static <T extends Throwable> Duration measure(MCRThrowableTask<T> task) throws T {
long time = System.nanoTime();
task.run();
time = System.nanoTime() - time;
return Duration.of(time, TimeUnit.NANOSECONDS.toChronoUnit());
}
public static Path safeResolve(Path basePath, Path resolve) {
Path absoluteBasePath = Objects.requireNonNull(basePath)
.toAbsolutePath();
final Path resolved = absoluteBasePath
.resolve(Objects.requireNonNull(resolve))
.normalize();
if (resolved.startsWith(absoluteBasePath)) {
return resolved;
}
throw new MCRException("Bad path: " + resolve);
}
public static Path safeResolve(Path basePath, String... resolve) {
if (resolve.length == 0) {
return basePath;
}
String[] more = Stream.of(resolve).skip(1).toArray(String[]::new);
final Path resolvePath = basePath.getFileSystem().getPath(resolve[0], more);
return safeResolve(basePath, resolvePath);
}
}
| 22,844 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJSONUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRJSONUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.mycore.services.i18n.MCRTranslation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonPrimitive;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRJSONUtils {
public static Gson createGSON() {
return new GsonBuilder()
.setPrettyPrinting()
.create();
}
public static JsonArray getJsonArray(Collection<String> list) {
JsonArray ja = new JsonArray();
for (String s : list) {
ja.add(new JsonPrimitive(s));
}
return ja;
}
public static String getTranslations(String prefixes, String lang) {
Map<String, String> transMap = new HashMap<>();
Arrays.stream(prefixes.split(","))
.map(currentPrefix -> MCRTranslation.translatePrefixToLocale(
currentPrefix.substring(0, currentPrefix.length() - 1), MCRTranslation.getLocale(lang)))
.forEach(transMap::putAll);
Gson gson = createGSON();
return gson.toJson(transMap);
}
}
| 1,947 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCalendar.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCalendar.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.BuddhistCalendar;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.CopticCalendar;
import com.ibm.icu.util.EthiopicCalendar;
import com.ibm.icu.util.GregorianCalendar;
import com.ibm.icu.util.HebrewCalendar;
import com.ibm.icu.util.IslamicCalendar;
import com.ibm.icu.util.JapaneseCalendar;
import com.ibm.icu.util.ULocale;
/**
* This class implements all methods for handling calendars in MyCoRe objects
* and data models. It is licensed by <a href="http://source.icu-project.org/repos/icu/icu/trunk/license.html">ICU License</a>.
*
* @author Jens Kupferschmidt
* @author Thomas Junge
* @see <a href="http://site.icu-project.org/home">http://site.icu-project.org/home</a>
*/
public class MCRCalendar {
/**
* Logger
*/
private static final Logger LOGGER = LogManager.getLogger(MCRCalendar.class.getName());
/**
* Tag for Buddhistic calendar
*/
public static final String TAG_BUDDHIST = "buddhist";
/**
* Tag for Chinese calendar
*/
public static final String TAG_CHINESE = "chinese";
/**
* Tag for Coptic calendar
*/
public static final String TAG_COPTIC = "coptic";
/**
* Tag for Ethiopic calendar
*/
public static final String TAG_ETHIOPIC = "ethiopic";
/**
* Tag for Gregorian calendar
*/
public static final String TAG_GREGORIAN = "gregorian";
/**
* Tag for Hebrew calendar
*/
public static final String TAG_HEBREW = "hebrew";
/**
* Tag for Islamic calendar
*/
public static final String TAG_ISLAMIC = "islamic";
/**
* Tag for Japanese calendar
*/
public static final String TAG_JAPANESE = "japanese";
/**
* Tag for Julian calendar
*/
public static final String TAG_JULIAN = "julian";
/**
* Tag for Persic calendar
*/
public static final String TAG_PERSIC = "persic";
/**
* Tag for Armenian calendar
*/
public static final String TAG_ARMENIAN = "armenian";
/**
* Tag for Egyptian calendar
*/
public static final String TAG_EGYPTIAN = "egyptian";
/**
* Minimum Julian Day number is 0 = 01.01.4713 BC
*/
public static final int MIN_JULIAN_DAY_NUMBER = 0;
/**
* Maximum Julian Day number is 3182057 = 28.01.4000
*/
public static final int MAX_JULIAN_DAY_NUMBER = 3182057;
/**
* a list of calendar tags they are supported in this class
*/
public static final List<String> CALENDARS_LIST = List.of(
TAG_GREGORIAN, TAG_JULIAN, TAG_ISLAMIC, TAG_BUDDHIST, TAG_COPTIC, TAG_ETHIOPIC, TAG_PERSIC, TAG_JAPANESE,
TAG_ARMENIAN, TAG_EGYPTIAN, TAG_HEBREW);
/**
* the Julian day of the first day in the armenian calendar, 1.1.1 arm = 13.7.552 greg
*/
public static final int FIRST_ARMENIAN_DAY;
/**
* the Julian day of the first day in the egyptian calendar, 1.1.1 eg = 18.2.747 BC greg
*/
public static final int FIRST_EGYPTIAN_DAY;
static {
final Calendar firstArmenian = GregorianCalendar.getInstance();
firstArmenian.set(552, GregorianCalendar.JULY, 13);
FIRST_ARMENIAN_DAY = firstArmenian.get(Calendar.JULIAN_DAY);
final Calendar firstEgypt = GregorianCalendar.getInstance();
firstEgypt.set(747, GregorianCalendar.FEBRUARY, 18);
firstEgypt.set(Calendar.ERA, GregorianCalendar.BC);
FIRST_EGYPTIAN_DAY = firstEgypt.get(Calendar.JULIAN_DAY);
}
private static final String MSG_CALENDAR_UNSUPPORTED = "Calendar %s is not supported!";
/**
* @see #getHistoryDateAsCalendar(String, boolean, String)
*/
public static Calendar getHistoryDateAsCalendar(String input, boolean last, CalendarType calendarType) {
LOGGER.debug("Input of getHistoryDateAsCalendar: {} {} {}", input, calendarType, Boolean.toString(last));
final String dateString = StringUtils.trim(input);
// check dateString
if (StringUtils.isBlank(dateString)) {
throw new MCRException("The ancient date string is null or empty");
}
final Calendar out;
if (dateString.equals("4713-01-01 BC")) {
LOGGER.debug("Date string contains MIN_JULIAN_DAY_NUMBER");
out = new GregorianCalendar();
out.set(Calendar.JULIAN_DAY, MCRCalendar.MIN_JULIAN_DAY_NUMBER);
return out;
}
if (dateString.equals("4000-01-28 AD")) {
LOGGER.debug("Date string contains MAX_JULIAN_DAY_NUMBER");
out = new GregorianCalendar();
out.set(Calendar.JULIAN_DAY, MCRCalendar.MAX_JULIAN_DAY_NUMBER);
return out;
}
out = switch (calendarType) {
case Armenian -> getCalendarFromArmenianDate(dateString, last);
case Buddhist -> getCalendarFromBuddhistDate(dateString, last);
case Coptic -> getCalendarFromCopticDate(dateString, last);
case Egyptian -> getCalendarFromEgyptianDate(dateString, last);
case Ethiopic -> getCalendarFromEthiopicDate(dateString, last);
case Gregorian -> getCalendarFromGregorianDate(dateString, last);
case Hebrew -> getCalendarFromHebrewDate(dateString, last);
case Islamic -> getCalendarFromIslamicDate(dateString, last);
case Japanese -> getCalendarFromJapaneseDate(dateString, last);
case Julian -> getCalendarFromJulianDate(dateString, last);
case Persic -> getCalendarFromPersicDate(dateString, last);
default -> throw new MCRException("Calendar type " + calendarType + " not supported!");
};
LOGGER.debug("Output of getHistoryDateAsCalendar: {}", getCalendarDateToFormattedString(out));
return out;
}
/**
* This method check an ancient date string for the given calendar. For
* syntax of the date string see javadocs of calendar methods.
*
* @param dateString the date as string.
* @param last the value is true if the date should be filled with the
* highest value of month or day like 12 or 31 else it fill the
* date with the lowest value 1 for month and day.
* @param calendarString the calendar name as String, kind of the calendars are
* ('gregorian', 'julian', 'islamic', 'buddhist', 'coptic',
* 'ethiopic', 'persic', 'japanese', 'armenian' or 'egyptian' )
* @return the ICU Calendar instance of the concrete calendar type or null if an error was occurred.
* @throws MCRException if parsing has an error
*/
public static Calendar getHistoryDateAsCalendar(String dateString, boolean last, String calendarString)
throws MCRException {
return getHistoryDateAsCalendar(dateString, last, CalendarType.of(calendarString));
}
/**
* Check the date string for julian or gregorian calendar
*
* @param dateString the date string
* @param last the flag for first / last day
* @return an integer array with [0] = year; [1] = month; [2] = day; [3] = era : -1 = BC : +1 = AC
*/
private static int[] checkDateStringForJulianCalendar(String dateString, boolean last, CalendarType calendarType) {
// look for BC
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(dateString, Locale.ROOT));
final boolean bc = beforeZero(dateTrimmed, calendarType);
final String cleanDate = cleanDate(dateTrimmed, calendarType);
final int[] fields = parseDateString(cleanDate, last, calendarType);
final int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
final int era = bc ? -1 : 1;
// test of the monthly
if (mon > GregorianCalendar.DECEMBER || mon < GregorianCalendar.JANUARY) {
throw new MCRException("The month of the date is inadmissible.");
}
// Test of the daily
if (day > 31) {
throw new MCRException("The day of the date is inadmissible.");
} else if ((day > 30) && (mon == GregorianCalendar.APRIL || mon == GregorianCalendar.JUNE ||
mon == GregorianCalendar.SEPTEMBER || mon == GregorianCalendar.NOVEMBER)) {
throw new MCRException("The day of the date is inadmissible.");
} else if ((day > 29) && (mon == GregorianCalendar.FEBRUARY)) {
throw new MCRException("The day of the date is inadmissible.");
} else if ((day > 28) && (mon == GregorianCalendar.FEBRUARY) && !isLeapYear(year, calendarType)) {
throw new MCRException("The day of the date is inadmissible.");
}
return new int[] { year, mon, day, era };
}
/**
* This method convert a ancient date to a general Calendar value. The
* syntax for the gregorian input is: <br>
* <ul>
* <li> [[[t]t.][m]m.][yyy]y [v. Chr.]</li>
* <li> [[[t]t.][m]m.][yyy]y [AD|BC]</li>
* <li> [-|AD|BC] [[[t]t.][m]m.][yyy]y</li>
* <li> [[[t]t/][m]m/][yyy]y [AD|BC]</li>
* <li> [-|AD|BC] [[[t]t/][m]m/][yyy]y</li>
* <li> y[yyy][-m[m][-t[t]]] [v. Chr.]</li>
* <li> y[yyy][-m[m][-t[t]]] [AD|BC]</li>
* <li> [-|AD|BC] y[yyy][-m[m][-t[t]]]</li>
* </ul>
*
* @param dateString
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 12 or 31 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the GregorianCalendar date value or null if an error was
* occurred.
* @exception MCRException if parsing has an error
*/
protected static GregorianCalendar getCalendarFromGregorianDate(String dateString, boolean last)
throws MCRException {
try {
int[] fields = checkDateStringForJulianCalendar(dateString, last, CalendarType.Gregorian);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(fields[0], fields[1], fields[2]);
if (fields[3] == -1) {
calendar.set(Calendar.ERA, GregorianCalendar.BC);
} else {
calendar.set(Calendar.ERA, GregorianCalendar.AD);
}
return calendar;
} catch (Exception e) {
throw new MCRException("The ancient gregorian date is false.", e);
}
}
/**
* This method convert a JulianCalendar date to a general Calendar value.
* The syntax for the julian input is: <br>
* <ul>
* <li> [[[t]t.][m]m.][yyy]y [v. Chr.|n. Chr.]</li>
* <li> [[[t]t.][m]m.][yyy]y [AD|BC]</li>
* <li> [-|AD|BC] [[[t]t.][m]m.][yyy]y</li>
* <li> [[[t]t/][m]m/][yyy]y [AD|BC]</li>
* <li> [-|AD|BC] [[[t]t/][m]m/][yyy]y</li>
* <li> y[yyy][-m[m][-t[t]]] [v. Chr.|n. Chr.]</li>
* <li> y[yyy][-m[m][-t[t]]] [AD|BC]</li>
* <li> [-|AD|BC] y[yyy][-m[m][-t[t]]]</li>
* </ul>
*
* @param dateString
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 12 or 31 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the GregorianCalendar date value or null if an error was
* occurred.
* @exception MCRException if parsing has an error
*/
protected static Calendar getCalendarFromJulianDate(String dateString, boolean last) throws MCRException {
try {
int[] fields = checkDateStringForJulianCalendar(dateString, last, CalendarType.Julian);
final Calendar calendar = Calendar.getInstance(CalendarType.Julian.getLocale());
((GregorianCalendar) calendar).setGregorianChange(new Date(Long.MAX_VALUE));
calendar.set(fields[0], fields[1], fields[2]);
if (fields[3] == -1) {
calendar.set(Calendar.ERA, GregorianCalendar.BC);
} else {
calendar.set(Calendar.ERA, GregorianCalendar.AD);
}
return calendar;
} catch (Exception e) {
throw new MCRException("The ancient julian date is false.", e);
}
}
/**
* This method converts an islamic calendar date to a IslamicCalendar value civil mode.
* The syntax for the islamic input is: <br>
* <ul>
* <li> [[[t]t.][m]m.][yyy]y [H.|h.]</li>
* <li> [.\u0647 | .\u0647 .\u0642] [[[t]t.][m]m.][yyy]y</li>
* <li> y[yyy][-m[m][-t[t]]] H.|h.</li>
* </ul>
*
* @param dateString
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 12 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the IslamicCalendar date value or null if an error was occurred.
* @exception MCRException if parsing has an error
*/
protected static IslamicCalendar getCalendarFromIslamicDate(String dateString, boolean last) {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(dateString, Locale.ROOT));
final boolean before = beforeZero(dateTrimmed, CalendarType.Islamic);
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Islamic);
final int[] fields = parseDateString(cleanDate, last, CalendarType.Islamic);
int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
if (before) {
year = -year + 1;
}
// test of the monthly
if (mon > 11 || mon < 0) {
throw new MCRException("The month of the date is inadmissible.");
}
// Test of the daily
if (day > 30 || mon % 2 == 1 && mon < 11 && day > 29 || day < 1) {
throw new MCRException("The day of the date is inadmissible.");
}
IslamicCalendar calendar = new IslamicCalendar();
calendar.setCivil(true);
calendar.set(year, mon, day);
return calendar;
}
/**
* This method convert a HebrewCalendar date to a HebrewCalendar value. The
* syntax for the hebrew input is [[t]t.][m]m.][yyy]y] or
* [[yyy]y-[[m]m]-[[t]t].
*
* @param datestr
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 13 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the HebrewCalendar date value or null if an error was occurred.
* @exception MCRException if parsing has an error
*/
protected static HebrewCalendar getCalendarFromHebrewDate(String datestr, boolean last) {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(datestr, Locale.ROOT));
final boolean before = beforeZero(dateTrimmed, CalendarType.Hebrew);
if (before) {
throw new MCRException("Dates before 1 not supported in Hebrew calendar!");
}
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Hebrew);
final int[] fields = parseDateString(cleanDate, last, CalendarType.Hebrew);
final int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
HebrewCalendar hcal = new HebrewCalendar();
hcal.set(year, mon, day);
return hcal;
}
/**
* Check the date string for ethiopic or coptic calendar
*
* @param dateString the date string
* @param last the flag for first / last day
* @return an integer array with [0] = year; [1] = month; [2] = day; [3] = era : -1 = B.M.: +1 = A.M.
*/
private static int[] checkDateStringForCopticCalendar(String dateString, boolean last, CalendarType calendarType) {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(dateString, Locale.ROOT));
final boolean bm = beforeZero(dateTrimmed, calendarType);
final String cleanDate = cleanDate(dateTrimmed, calendarType);
final int[] fields = parseDateString(cleanDate, last, calendarType);
int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
final int era = bm ? -1 : 1;
if (bm) {
year = -year + 1;
}
// test of the monthly
if (mon > 12 || mon < 0) {
throw new MCRException("The month of the date is inadmissible.");
}
// Test of the daily
if (day > 30 || day < 1 || day > 6 && mon == 12) {
throw new MCRException("The day of the date is inadmissible.");
}
return new int[] { year, mon, day, era };
}
/**
* This method convert a CopticCalendar date to a CopticCalendar value. The
* syntax for the coptic input is: <br>
* <ul>
* <li> [[[t]t.][m]m.][yyy]y [[A.|a.]M.]</li>
* <li> y[yyy][-m[m][-t[t]]] [A.|a.]M.]</li>
* </ul>
*
* @param dateString
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 12 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the CopticCalendar date value or null if an error was occurred.
* @exception MCRException if parsing has an error
*/
protected static CopticCalendar getCalendarFromCopticDate(String dateString, boolean last) {
try {
final int[] fields = checkDateStringForCopticCalendar(dateString, last, CalendarType.Coptic);
CopticCalendar calendar = new CopticCalendar();
calendar.set(fields[0], fields[1], fields[2]);
return calendar;
} catch (Exception e) {
throw new MCRException("The ancient coptic calendar date is false.", e);
}
}
/**
* This method convert a EthiopicCalendar date to a EthiopicCalendar value.
* The syntax for the ethiopic input is: <br>
* <ul>
* <li> [[[t]t.][m]m.][yyy]y [E.E.]</li>
* <li> y[yyy][-m[m][-t[t]]] [E.E.]</li>
* </ul>
*
* @param dateString
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 13 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the EthiopicCalendar date value or null if an error was occurred.
* @exception MCRException if parsing has an error
*/
protected static EthiopicCalendar getCalendarFromEthiopicDate(String dateString, boolean last) {
try {
final int[] fields = checkDateStringForCopticCalendar(dateString, last, CalendarType.Ethiopic);
EthiopicCalendar calendar = new EthiopicCalendar();
calendar.set(fields[0], fields[1], fields[2]);
return calendar;
} catch (Exception e) {
throw new MCRException("The ancient ethiopic calendar date is false.", e);
}
}
/**
* This method convert a JapaneseCalendar date to a JapaneseCalendar value.
* The syntax for the japanese input is: <br>
* <ul>
* <li> [[[t]t.][m]m.][H|M|S|T|R][yyy]y <br>
* H: Heisei; M: Meiji, S: Showa, T: Taiso, R: Reiwa
* </li>
* <li> [H|M|S|T|R]y[yyy][-m[m][-t[t]]]</li>
* </ul>
*
* @param datestr
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 12 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the JapaneseCalendar date value or null if an error was occurred.
* @exception MCRException if parsing has an error
*/
protected static JapaneseCalendar getCalendarFromJapaneseDate(String datestr, boolean last) {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(datestr, Locale.ROOT));
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Japanese);
// japanese dates contain the era statement directly in the year e.g. 1.1.H2
// before parsing we have to remove this
final String eraToken;
final int era;
if (StringUtils.contains(cleanDate, "M")) {
eraToken = "M";
era = JapaneseCalendar.MEIJI;
} else if (StringUtils.contains(cleanDate, "T")) {
eraToken = "T";
era = JapaneseCalendar.TAISHO;
} else if (StringUtils.contains(cleanDate, "S")) {
eraToken = "S";
era = JapaneseCalendar.SHOWA;
} else if (StringUtils.contains(cleanDate, "H")) {
eraToken = "H";
era = JapaneseCalendar.HEISEI;
} else if (StringUtils.contains(cleanDate, "R")) {
eraToken = "R";
era = JapaneseCalendar.REIWA;
} else {
throw new MCRException("Japanese date " + datestr + " does not contain era statement!");
}
final String firstPart = StringUtils.substringBefore(cleanDate, eraToken);
final String secondPart = StringUtils.substringAfter(cleanDate, eraToken);
final int[] fields = parseDateString(firstPart + secondPart, last, CalendarType.Japanese);
final int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
JapaneseCalendar jcal = new JapaneseCalendar();
jcal.set(year, mon, day);
jcal.set(Calendar.ERA, era);
return jcal;
}
/**
* This method convert a BuddhistCalendar date to a IslamicCalendar value.
* The syntax for the buddhist input is: <br>
* <ul>
* <li> [-][[[t]t.][m]m.][yyy]y [B.E.]</li>
* <li> [-] [[[t]t.][m]m.][yyy]y</li>
* <li> [-] y[yyy][-m[m][-t[t]]] [B.E.]</li>
* <li> [-] y[yyy][-m[m][-t[t]]]</li>
* </ul>
*
* @param datestr
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 12 or 31 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the BuddhistCalendar date value or null if an error was occurred.
* @exception MCRException if parsing has an error
*/
protected static BuddhistCalendar getCalendarFromBuddhistDate(String datestr, boolean last) {
// test before Buddhas
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(datestr, Locale.ROOT));
final boolean bb = beforeZero(dateTrimmed, CalendarType.Buddhist);
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Buddhist);
final int[] fields = parseDateString(cleanDate, last, CalendarType.Buddhist);
int year = fields[0];
int mon = fields[1];
int day = fields[2];
if (bb) {
year = -year + 1; // if before Buddha
}
if (year == 2125 && mon == 9 && day >= 5 && day < 15) {
day = 15;
}
BuddhistCalendar budcal = new BuddhistCalendar();
budcal.set(year, mon, day);
return budcal;
}
/**
* This method convert a PersicCalendar date to a GregorianCalendar value.
* The syntax for the persian input is: <br>
* <ul>
* <li> [-] [[[t]t.][m]m.][yyy]y</li>
* <li> [-] y[yyy][-m[m][-t[t]]]</li>
* </ul>
*
* @param datestr
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 13 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the GregorianCalendar date value or null if an error was
* occurred.
* @exception MCRException if parsing has an error
*/
protected static GregorianCalendar getCalendarFromPersicDate(String datestr, boolean last) {
try {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(datestr, Locale.ROOT));
final boolean bb = beforeZero(dateTrimmed, CalendarType.Persic);
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Persic);
final int[] fields = parseDateString(cleanDate, last, CalendarType.Persic);
final int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
final int njahr;
if (bb) {
njahr = -year + 1 + 621;
} else {
njahr = year + 621;
}
GregorianCalendar newdate = new GregorianCalendar();
newdate.clear();
newdate.set(njahr, Calendar.MARCH, 20); // yearly beginning to 20.3.
// beginning of the month (day to year)
int begday = 0;
if (mon == 1) {
begday = 31;
}
if (mon == 2) {
begday = 62;
}
if (mon == 3) {
begday = 93;
}
if (mon == 4) {
begday = 124;
}
if (mon == 5) {
begday = 155;
}
if (mon == 6) {
begday = 186;
}
if (mon == 7) {
begday = 216;
}
if (mon == 8) {
begday = 246;
}
if (mon == 9) {
begday = 276;
}
if (mon == 10) {
begday = 306;
}
if (mon == 11) {
begday = 336;
}
begday += day - 1;
int jh = njahr / 100; // century
int b = jh % 4;
int c = njahr % 100; // year of the century
int d = c / 4; // count leap year of the century
final int min = b * 360 + 350 * c - d * 1440 + 720;
if (njahr >= 0) {
newdate.add(Calendar.MINUTE, min); // minute of day
newdate.add(Calendar.DATE, begday); // day of the year
} else {
newdate.add(Calendar.DATE, begday + 2); // day of the year
newdate.add(Calendar.MINUTE, min); // minute of day
}
return newdate;
} catch (Exception e) {
throw new MCRException("The ancient persian date is false.", e);
}
}
/**
* This method convert a ArmenianCalendar date to a GregorianCalendar value.
* The syntax for the Armenian input is [-][[t]t.][m]m.][yyy]y] or
* [-][[yyy]y-[[m]m]-[[t]t].
*
* <ul>
* <li> [-] [[[t]t.][m]m.][yyy]y</li>
* <li> [-] y[yyy][-m[m][-t[t]]]</li>
* </ul>
*
* @param datestr
* the date as string.
* @param last
* the value is true if the date should be filled with the
* highest value of month or day like 13 or 30 else it fill the
* date with the lowest value 1 for month and day.
*
* @return the GregorianCalendar date value or null if an error was
* occurred.
* @exception MCRException if parsing has an error
*/
protected static GregorianCalendar getCalendarFromArmenianDate(String datestr, boolean last) {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(datestr, Locale.ROOT));
final boolean before = beforeZero(dateTrimmed, CalendarType.Armenian);
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Armenian);
final int[] fields = parseDateString(cleanDate, last, CalendarType.Armenian);
int year = fields[0];
int mon = fields[1];
int day = fields[2];
if (before) {
year = -year + 1;
}
// Armenian calendar has every year an invariant of 365 days - these are added to the beginning of the
// calendar defined in FIRST_ARMENIAN_DAY (13.7.552)
int addedDays = (year - 1) * 365;
if (mon == 12) {
addedDays += 12 * 30;
} else {
addedDays += mon * 30;
}
addedDays += day - 1;
final GregorianCalendar result = new GregorianCalendar();
result.set(Calendar.JULIAN_DAY, (FIRST_ARMENIAN_DAY + addedDays));
return result;
}
/**
* This method convert a EgyptianCalendar date to a GregorianCalendar value.
* The syntax for the egyptian (Nabonassar) input is: <br>
* <ul>
* <li> [-][[[t]t.][m]m.][yyy]y [A.N.]</li>
* <li> [-] [[[t]t.][m]m.][yyy]y</li>
* <li> [-] y[yyy][-m[m][-t[t]]] [A.N.]</li>
* <li> [-] y[yyy][-m[m][-t[t]]]</li>
* </ul>
* <p>
* For calculating the resulting Gregorian date, February, 18 747 BC is used as initial date for Egyptian calendar.
*
* @param datestr the date as string.
* @param last the value is true if the date should be filled with the
* highest value of month or day like 13 or 30 else it fill the
* date with the lowest value 1 for month and day.
* @return the GregorianCalendar date value or null if an error was
* occurred.
*/
protected static GregorianCalendar getCalendarFromEgyptianDate(String datestr, boolean last) {
final String dateTrimmed = StringUtils.trim(StringUtils.upperCase(datestr, Locale.ROOT));
final boolean ba = beforeZero(dateTrimmed, CalendarType.Egyptian);
final String cleanDate = cleanDate(dateTrimmed, CalendarType.Egyptian);
final int[] fields = parseDateString(cleanDate, last, CalendarType.Egyptian);
int year = fields[0];
final int mon = fields[1];
final int day = fields[2];
if (ba) {
year = -year + 1;
}
int addedDays = (year - 1) * 365;
if (mon == 12) {
addedDays += 12 * 30;
} else {
addedDays += mon * 30;
}
addedDays += day - 1;
final GregorianCalendar result = new GregorianCalendar();
result.set(Calendar.JULIAN_DAY, (FIRST_EGYPTIAN_DAY + addedDays));
return result;
}
/**
* This method return the Julian Day number for a given Calendar instance.
*
* @return the Julian Day number as Integer
*/
public static int getJulianDayNumber(Calendar calendar) {
return calendar.get(Calendar.JULIAN_DAY);
}
/**
* This method return the Julian Day number for a given Calendar instance.
*
* @return the Julian Day number as String
*/
public static String getJulianDayNumberAsString(Calendar calendar) {
return Integer.toString(calendar.get(Calendar.JULIAN_DAY));
}
/**
* This method get the Gregorian calendar form a given calendar
*
* @param calendar
* an instance of a Calendar
* @return a Gregorian calendar
*/
public static GregorianCalendar getGregorianCalendarOfACalendar(Calendar calendar) {
int julianDay = getJulianDayNumber(calendar);
GregorianCalendar ret = new GregorianCalendar();
ret.set(Calendar.JULIAN_DAY, julianDay);
return ret;
}
/**
* This method returns the date as string in format 'yy-MM-dd G'.
*
* @return the date string
*/
public static String getCalendarDateToFormattedString(Calendar calendar) {
if (calendar instanceof IslamicCalendar) {
return getCalendarDateToFormattedString(calendar, "dd.MM.yyyy");
} else if (calendar instanceof GregorianCalendar) {
return getCalendarDateToFormattedString(calendar, "yyyy-MM-dd G");
}
return getCalendarDateToFormattedString(calendar, "yyyy-MM-dd G");
}
/**
* This method returns the date as string.
*
* @param calendar
* the Calendar date
* @param format
* the format of the date as String
*
* @return the date string in the format. If the format is wrong dd.MM.yyyy
* G is set. If the date is wrong an empty string will be returned.
* The output is depending on calendar type. For Calendar it will use
* the Julian Calendar to 05.10.1582. Then it use the Gregorian Calendar.
*/
public static String getCalendarDateToFormattedString(Calendar calendar, String format) {
if (calendar == null || format == null || format.trim().length() == 0) {
return "";
}
SimpleDateFormat formatter = null;
try {
if (calendar instanceof IslamicCalendar) {
formatter = new SimpleDateFormat(format, Locale.ENGLISH);
} else if (calendar instanceof GregorianCalendar) {
formatter = new SimpleDateFormat(format, Locale.ENGLISH);
} else {
formatter = new SimpleDateFormat(format, Locale.ENGLISH);
}
} catch (Exception e) {
formatter = new SimpleDateFormat("dd.MM.yyyy G", Locale.ENGLISH);
}
try {
formatter.setCalendar(calendar);
if (calendar instanceof IslamicCalendar) {
return formatter.format(calendar.getTime()) + " h.";
} else if (calendar instanceof CopticCalendar) {
return formatter.format(calendar.getTime()) + " A.M.";
} else if (calendar instanceof EthiopicCalendar) {
return formatter.format(calendar.getTime()) + " E.E.";
} else {
return formatter.format(calendar.getTime());
}
} catch (Exception e) {
return "";
}
}
/**
* The method get a date String in format yyyy-MM-ddThh:mm:ssZ for ancient date values.
*
* @param date the date string
* @param useLastValue as boolean
* - true if incomplete dates should be filled up with last month or last day
* @param calendarName the name if the calendar defined in MCRCalendar
* @return the date in format yyyy-MM-ddThh:mm:ssZ
*/
public static String getISODateToFormattedString(String date, boolean useLastValue, String calendarName) {
String formattedDate = null;
try {
Calendar calendar = MCRCalendar.getHistoryDateAsCalendar(date, useLastValue, calendarName);
GregorianCalendar gregorianCalendar = MCRCalendar.getGregorianCalendarOfACalendar(calendar);
formattedDate = MCRCalendar.getCalendarDateToFormattedString(gregorianCalendar, "yyyy-MM-dd")
+ "T00:00:00.000Z";
if (gregorianCalendar.get(Calendar.ERA) == GregorianCalendar.BC) {
formattedDate = "-" + formattedDate;
}
} catch (Exception e) {
String errorMsg = "Error while converting date string : " + date + " - " + useLastValue +
" - " + calendarName;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(errorMsg, e);
}
LOGGER.warn(errorMsg);
return "";
}
return formattedDate;
}
/**
* This method returns the calendar type as string.
*
* @param calendar the Calendar date
* @return The calendar type as string. If Calendar is empty an empty string will be returned.
*/
public static String getCalendarTypeString(Calendar calendar) {
if (calendar == null) {
return "";
}
if (calendar instanceof IslamicCalendar) {
return TAG_ISLAMIC;
} else if (calendar instanceof BuddhistCalendar) {
return TAG_BUDDHIST;
} else if (calendar instanceof CopticCalendar) {
return TAG_COPTIC;
} else if (calendar instanceof EthiopicCalendar) {
return TAG_ETHIOPIC;
} else if (calendar instanceof HebrewCalendar) {
return TAG_HEBREW;
} else if (calendar instanceof JapaneseCalendar) {
return TAG_JAPANESE;
} else if (calendar instanceof GregorianCalendar) {
return TAG_GREGORIAN;
} else {
return TAG_JULIAN;
}
}
/**
* Parses a clean date string in German (d.m.y), English (d/m/y) or ISO (y-m-d) form and returns the year, month
* and day as an array.
*
* @param dateString the date to parse
* @param last flag to determine if the last month or day of a month is to be used when no month
* or day is given
* @param calendarType the calendar type to parse the date string for
* @return a field containing year, month and day statements
*/
public static int[] parseDateString(String dateString, boolean last, CalendarType calendarType) {
// German, English or ISO?
final boolean iso = isoFormat(dateString);
final String delimiter = delimiter(dateString);
// check for positions of year and month delimiters
final int firstdot = StringUtils.indexOf(dateString, delimiter, 1);
final int secdot = StringUtils.indexOf(dateString, delimiter, firstdot + 1);
final int day;
final int mon;
final int year;
if (secdot != -1) {
// we have a date in the form of d.m.yy or y/m/d
final int firstPart = Integer.parseInt(StringUtils.substring(dateString, 0, firstdot));
final int secondPart = Integer.parseInt(StringUtils.substring(dateString, firstdot + 1, secdot));
final int thirdPart = Integer.parseInt(StringUtils.substring(dateString, secdot + 1));
if (iso) {
year = firstPart;
mon = secondPart - 1;
day = thirdPart;
} else {
day = firstPart;
mon = secondPart - 1;
year = thirdPart;
}
} else {
if (firstdot != -1) {
// we have a date in form of m.y or y/m
final int firstPart = Integer.parseInt(StringUtils.substring(dateString, 0, firstdot));
final int secondPart = Integer.parseInt(StringUtils.substring(dateString, firstdot + 1));
if (iso) {
year = firstPart;
mon = secondPart - 1;
} else {
mon = firstPart - 1;
year = secondPart;
}
if (last) {
day = getLastDayOfMonth(mon, year, calendarType);
} else {
day = 1;
}
} else {
// we have just a year statement
year = Integer.parseInt(dateString);
if (last) {
mon = getLastMonth(year, calendarType);
day = getLastDayOfMonth(mon, year, calendarType);
} else {
mon = getFirstMonth(calendarType);
day = 1;
}
}
}
return new int[] { year, mon, day };
}
/**
* Returns true if the given input date is in ISO format (xx-xx-xx), otherwise false.
*
* @param input the input date to check
* @return true if the given input date is in ISO format (xx-xx-xx), otherwise false
*/
public static boolean isoFormat(String input) {
return -1 != StringUtils.indexOf(input, "-", 1);
}
/**
* Cleans a given date by removing era statements like -, AD, B.E. etc.
*
* @param input the date to clean
* @param calendarType the calendar type of the given date
* @return the cleaned date containing only day, month and year statements
*/
public static String cleanDate(String input, CalendarType calendarType) {
final String date = StringUtils.trim(StringUtils.upperCase(input, Locale.ROOT));
final int start;
final int end;
final int length = StringUtils.length(date);
if (StringUtils.startsWith(date, "-")) {
start = 1;
end = length;
} else {
final int[] borders = switch (calendarType) {
case Armenian -> calculateArmenianDateBorders(date);
case Buddhist -> calculateBuddhistDateBorders(date);
case Coptic, Ethiopic -> calculateCopticDateBorders(date);
case Egyptian -> calculateEgyptianDateBorders(date);
case Gregorian, Julian -> calculateGregorianDateBorders(date);
case Hebrew -> calculateHebrewDateBorders(date);
case Islamic -> calculateIslamicDateBorders(date);
case Japanese -> calculateJapaneseDateBorders(date);
case Persic -> calculatePersianDateBorders(date);
default -> throw new MCRException(String.format(Locale.ROOT, MSG_CALENDAR_UNSUPPORTED, calendarType));
};
start = borders[0];
end = borders[1];
}
return StringUtils.trim(StringUtils.substring(date, start, end));
}
/**
* Calculates the borders of an egyptian date.
*
* @param datestr the egyptian date contain era statements like -, A.N.
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculateEgyptianDateBorders(String datestr) {
final int start;
final int ende;
final int length = StringUtils.length(datestr);
if (StringUtils.startsWith(datestr, "-")) {
start = 1;
} else {
start = 0;
}
if (StringUtils.contains(datestr, "A.N.")) {
ende = StringUtils.indexOf(datestr, "A.N.");
} else {
ende = length;
}
return new int[] { start, ende };
}
/**
* Calculates the borders of an armenian date.
*
* @param input the armenian date contain era statements like -
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculateArmenianDateBorders(String input) {
final int start;
if (StringUtils.startsWith(input, "-")) {
start = 1;
} else {
start = 0;
}
return new int[] { start, StringUtils.length(input) };
}
/**
* Calculates the borders of a japanese date.
*
* @param input the japanese date contain era statements like -
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculateJapaneseDateBorders(String input) {
final int start;
if (StringUtils.startsWith(input, "-")) {
start = 1;
} else {
start = 0;
}
return new int[] { start, StringUtils.length(input) };
}
/**
* Calculates the borders of a persian date.
*
* @param dateStr the persina date contain era statements like -
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculatePersianDateBorders(String dateStr) {
final int start;
if (StringUtils.startsWith(dateStr, "-")) {
start = 1;
} else {
start = 0;
}
return new int[] { start, StringUtils.length(dateStr) };
}
/**
* Calculates the borders of a coptic/ethiopian date.
*
* @param input the coptic/ethiopian date contain era statements like -, A.M, A.E.
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculateCopticDateBorders(String input) {
final int start;
final int end;
final int length = StringUtils.length(input);
if (StringUtils.startsWith(input, "-")) {
start = 1;
end = length;
} else {
start = 0;
if (StringUtils.contains(input, "A.M")) {
end = StringUtils.indexOf(input, "A.M.");
} else if (StringUtils.contains(input, "E.E.")) {
end = StringUtils.indexOf(input, "E.E.");
} else {
end = length;
}
}
return new int[] { start, end };
}
/**
* Calculates the borders of a hebrew date.
*
* @param input the hebrew date contain era statements like -
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculateHebrewDateBorders(String input) {
return new int[] { 0, StringUtils.length(input) };
}
/**
* Calculates the borders of an islamic date.
*
* @param dateString the islamic date contain era statements like -
* @return the indexes of the date string containing the date without era statements
*/
public static int[] calculateIslamicDateBorders(String dateString) {
int start = 0;
int ende = dateString.length();
int i = dateString.indexOf("H.");
if (i != -1) {
ende = i;
}
if (dateString.length() > 10) {
i = dateString.indexOf(".\u0647.\u0642");
if (i != -1) {
start = 3;
} else {
i = dateString.indexOf(".\u0647");
if (i != -1) {
start = 2;
}
}
}
return new int[] { start, ende };
}
/**
* Calculates the date borders for a Gregorian date in the form d.m.y [N. CHR|V.CHR|AD|BC]
*
* @param dateString the date string to parse
* @return a field containing the start position of the date string in index 0 and the end position in index 1
*/
public static int[] calculateGregorianDateBorders(String dateString) {
final int start;
final int end;
final int length = StringUtils.length(dateString);
if (StringUtils.contains(dateString, "N. CHR") || StringUtils.contains(dateString, "V. CHR")) {
final int positionNChr = StringUtils.indexOf(dateString, "N. CHR");
final int positionVChr = StringUtils.indexOf(dateString, "V. CHR");
if (positionNChr != -1) {
if (positionNChr == 0) {
start = 7;
end = length;
} else {
start = 0;
end = positionNChr - 1;
}
} else if (positionVChr != -1) {
if (positionVChr == 0) {
start = 7;
end = length;
} else {
start = 0;
end = positionVChr - 1;
}
} else {
start = 0;
end = length;
}
} else if (StringUtils.contains(dateString, "AD") || StringUtils.contains(dateString, "BC")) {
final int positionAD = StringUtils.indexOf(dateString, "AD");
final int positionBC = StringUtils.indexOf(dateString, "BC");
if (positionAD != -1) {
if (positionAD == 0) {
start = 2;
end = length;
} else {
start = 0;
end = positionAD - 1;
}
} else if (positionBC != -1) {
if (positionBC == 0) {
start = 2;
end = length;
} else {
start = 0;
end = positionBC - 1;
}
} else {
start = 0;
end = length;
}
} else {
start = 0;
end = length;
}
return new int[] { start, end };
}
/**
* Calculates the date borders for a Buddhist date in the form d.m.y [B.E.]
*
* @param datestr the date string to parse
* @return a field containing the start position of the date string in index 0 and the end position in index 1
*/
public static int[] calculateBuddhistDateBorders(String datestr) {
final int start;
final int end;
final int length = StringUtils.length(datestr);
if (StringUtils.startsWith(datestr, "-")) {
start = 1;
end = length;
} else {
start = 0;
if (StringUtils.contains(datestr, "B.E.")) {
end = StringUtils.indexOf(datestr, "B.E.");
} else {
end = length;
}
}
return new int[] { start, end };
}
/**
* Returns the delimiter for the given date input: ., - or /.
*
* @param input the date input to check
* @return the delimiter for the given date input
*/
public static String delimiter(String input) {
if (-1 != StringUtils.indexOf(input, "-", 1)) {
return "-";
} else if (-1 != StringUtils.indexOf(input, "/", 1)) {
return "/";
} else {
return ".";
}
}
/**
* Returns true if the given date input is before the year zero of the given calendar type.
* <p>
* Examples:
* <ul>
* <li>1 BC is before zero for gregorian/julian calendars</li>
* <li>-1 is before zero for all calendar types</li>
* <li>1 AD is after zero for gregorian/julian calendars</li>
* <li>1 is after zero for all calendar types</li>
* </ul>
*
* @param input the input date to check
* @param calendarType the calendar type
* @return true if the given input date is for the calendars zero date
*/
public static boolean beforeZero(String input, CalendarType calendarType) {
if (StringUtils.startsWith(input, "-")) {
return true;
}
return switch (calendarType) {
case Buddhist -> StringUtils.contains(input, "B.E.");
case Gregorian, Julian -> StringUtils.contains(input, "BC") || StringUtils.contains(input, "V. CHR");
// these calendars do not allow for an era statement other than -
case Coptic, Hebrew, Ethiopic, Persic, Chinese, Islamic, Armenian, Egyptian, Japanese -> false;
default -> throw new MCRException(String.format(Locale.ROOT, MSG_CALENDAR_UNSUPPORTED, calendarType));
};
}
/**
* Returns the last day number for the given month, e.g. {@link GregorianCalendar#FEBRUARY} has 28 in normal years
* and 29 days in leap years.
*
* @param month the month number
* @param year the year
* @param calendarType the calendar type to evaluate the last day for
* @return the last day number for the given month
*/
public static int getLastDayOfMonth(int month, int year, CalendarType calendarType) {
final Calendar cal = Calendar.getInstance(calendarType.getLocale());
if (calendarType == CalendarType.Julian) {
((GregorianCalendar) cal).setGregorianChange(new Date(Long.MAX_VALUE));
}
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* Returns the first month of a year for the given calendar type, e.g. January for gregorian calendars.
*
* @param calendarType the calendar type to evaluate the first month for
* @return the first month of a year for the given calendar type
*/
public static int getFirstMonth(CalendarType calendarType) {
return switch (calendarType) {
case Buddhist, Gregorian, Julian -> GregorianCalendar.JANUARY;
case Coptic, Egyptian -> CopticCalendar.TOUT;
case Ethiopic -> EthiopicCalendar.MESKEREM;
case Hebrew -> HebrewCalendar.TISHRI;
case Islamic -> IslamicCalendar.MUHARRAM;
case Armenian, Persic -> 0;
default -> throw new MCRException(String.format(Locale.ROOT, MSG_CALENDAR_UNSUPPORTED, calendarType));
};
}
/**
* Returns the last month number of the given year for the given calendar type.
*
* @param year the year to calculate last month number for
* @param calendarType the calendar type
* @return the last month number of the given year for the given calendar type
*/
public static int getLastMonth(int year, CalendarType calendarType) {
final Calendar cal = Calendar.getInstance(calendarType.getLocale());
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.MONTH);
}
/**
* Returns true, if the given year is a leap year in the given calendar type.
*
* @param year the year to analyse
* @param calendarType the calendar type
* @return true, if the given year is a leap year in the given calendar type; otherwise false
*/
public static boolean isLeapYear(int year, CalendarType calendarType) {
return switch (calendarType) {
case Gregorian -> new GregorianCalendar().isLeapYear(year);
case Julian -> year % 4 == 0;
default -> throw new MCRException(String.format(Locale.ROOT, MSG_CALENDAR_UNSUPPORTED, calendarType));
};
}
public enum CalendarType {
Buddhist(TAG_BUDDHIST, new ULocale("@calendar=buddhist")),
Chinese(TAG_CHINESE, new ULocale("@calendar=chinese")),
Coptic(TAG_COPTIC, new ULocale("@calendar=coptic")),
Ethiopic(TAG_ETHIOPIC, new ULocale("@calendar=ethiopic")),
Gregorian(TAG_GREGORIAN, new ULocale("@calendar=gregorian")),
Hebrew(TAG_HEBREW, new ULocale("@calendar=hebrew")),
Islamic(TAG_ISLAMIC, new ULocale("@calendar=islamic-civil")),
Japanese(TAG_JAPANESE, new ULocale("@calendar=japanese")),
Julian(TAG_JULIAN, new ULocale("@calendar=gregorian")),
Persic(TAG_PERSIC, new ULocale("@calendar=persian")),
// Armenian calendar uses coptic calendar as a base, since both have 12 months + 5 days
Armenian(TAG_ARMENIAN, new ULocale("@calendar=coptic")),
// Egyptian calendar uses coptic calendar as a base, since both have 12 months + 5 days
Egyptian(TAG_EGYPTIAN, new ULocale("@calendar=coptic"));
private final String type;
private final ULocale locale;
CalendarType(String type, ULocale locale) {
this.type = type;
this.locale = locale;
}
public ULocale getLocale() {
return locale;
}
public String getType() {
return type;
}
public static CalendarType of(String type) {
return Arrays.stream(CalendarType.values())
.filter(current -> StringUtils.equals(current.getType(), type))
.findFirst().orElseThrow();
}
}
}
| 56,531 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTextResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRTextResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* <p>
* This class parses and resolve strings which contains variables.
* To add a variable call <code>addVariable</code>.
* </p><p>
* The algorithm is optimized that each character is touched only once.
* </p><p>
* To resolve a string a valid syntax is required:
* </p><p>
* <b>{}:</b> Use curly brackets for variables or properties. For example "{var1}"
* or "{MCR.basedir}"
* </p><p>
* <b>[]:</b> Use squared brackets to define a condition. All data within
* squared brackets is only used if the internal variables are
* not null and not empty. For example "[hello {lastName}]" is only resolved
* if the value of "lastName" is not null and not empty. Otherwise the whole
* content in the squared brackets are ignored.
* </p><p>
* <b>\:</b> Use the escape character to use all predefined characters.
* </p>
* <p>
* Sample:<br>
* "Lastname: {lastName}[, Firstname: {firstName}]"<br>
* </p>
*
* @author Matthias Eichner
*/
public class MCRTextResolver {
private static final Logger LOGGER = LogManager.getLogger(MCRTextResolver.class);
protected TermContainer termContainer;
/**
* This map contains all variables that can be resolved.
*/
protected Map<String, String> variablesMap;
/**
* Retains the text if a variable couldn't be resolved.
* Example if {Variable} could not be resolved:
* true: "Hello {Variable}" -> "Hello {Variable}"
* false: "Hello "
* <p>By default retainText is true</p>
*/
protected boolean retainText;
/**
* Defines how deep the text is resolved.
* <dl>
* <dt>Deep</dt><dd>everything is resolved</dd>
* <dt>NoVariables</dt><dd>the value of variables is not being resolved</dd>
* </dl>
*/
protected ResolveDepth resolveDepth;
protected CircularDependencyTracker tracker;
/**
* Creates the term list for the text resolver and adds
* the default terms.
*/
protected void registerDefaultTerms() throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException, InstantiationException {
registerTerm(Variable.class);
registerTerm(Condition.class);
registerTerm(EscapeCharacter.class);
}
/**
* Register a new term. The resolver invokes the term via reflection.
*
* @param termClass the term class to register.
*/
public void registerTerm(Class<? extends Term> termClass) throws NoSuchMethodException, InvocationTargetException,
IllegalAccessException, InstantiationException {
this.termContainer.add(termClass);
}
/**
* Unregister a term.
*
* @param termClass this class is unregistered
*/
public void unregisterTerm(Class<? extends Term> termClass) throws NoSuchMethodException,
InvocationTargetException, InstantiationException, IllegalAccessException {
this.termContainer.remove(termClass);
}
/**
* Defines how deep the text is resolved.
* <dl>
* <dt>Deep</dt><dd>everything is resolved</dd>
* <dt>NoVariables</dt><dd>the value of variables is not being resolved</dd>
* </dl>
*/
public enum ResolveDepth {
Deep, NoVariables
}
/**
* Creates a new text resolver with a map of variables.
*/
public MCRTextResolver() {
this.variablesMap = new HashMap<>();
this.setResolveDepth(ResolveDepth.Deep);
this.setRetainText(true);
this.tracker = new CircularDependencyTracker(this);
try {
this.termContainer = new TermContainer(this);
this.registerDefaultTerms();
} catch (Exception exc) {
throw new MCRException("Unable to register default terms", exc);
}
}
/**
* Creates a new text resolver. To add variables call
* <code>addVariable</code>, otherwise only MyCoRe property
* resolving is possible.
*/
public MCRTextResolver(Map<String, String> variablesMap) {
this();
mixin(variablesMap);
}
public MCRTextResolver(Properties properties) {
this();
mixin(properties);
}
protected TermContainer getTermContainer() {
return this.termContainer;
}
protected CircularDependencyTracker getTracker() {
return this.tracker;
}
public void mixin(Map<String, String> variables) {
for (Entry<String, String> entrySet : variables.entrySet()) {
String key = entrySet.getKey();
String value = entrySet.getValue();
this.addVariable(key, value);
}
}
public void mixin(Properties properties) {
for (Entry<Object, Object> entrySet : properties.entrySet()) {
String key = entrySet.getKey().toString();
String value = entrySet.getValue().toString();
this.addVariable(key, value);
}
}
/**
* Sets if the text should be retained if a variable couldn't be resolved.
* <p>
* Example:<br>
* true: "Hello {Variable}" -> "Hello {Variable}"<br>
* false: "Hello "
* </p>
* <p>By default retainText is true</p>
*/
public void setRetainText(boolean retainText) {
this.retainText = retainText;
}
/**
* Checks if the text should be retained if a variable couldn't be resolved.
* <p>By default retainText is true</p>
*/
public boolean isRetainText() {
return this.retainText;
}
/**
* Adds a new variable to the resolver. This overwrites a
* existing variable with the same name.
*
* @param name name of the variable
* @param value value of the variable
* @return the previous value of the specified name, or null
* if it did not have one
*/
public String addVariable(String name, String value) {
return variablesMap.put(name, value);
}
/**
* Removes a variable from the resolver. This method does
* nothing if no variable with the name exists.
*
* @return the value of the removed variable, or null if
* no variable with the name exists
*/
public String removeVariable(String name) {
return variablesMap.remove(name);
}
/**
* Checks if a variable with the specified name exists.
*
* @return true if a variable exists, otherwise false
*/
public boolean containsVariable(String name) {
return variablesMap.containsKey(name);
}
/**
* Sets the resolve depth.
*
* @param resolveDepth defines how deep the text is resolved.
*/
public void setResolveDepth(ResolveDepth resolveDepth) {
this.resolveDepth = resolveDepth;
}
/**
* Returns the current resolve depth.
*
* @return resolve depth enumeration
*/
public ResolveDepth getResolveDepth() {
return this.resolveDepth;
}
/**
* This method resolves all variables in the text.
* The syntax is described at the head of the class.
*
* @param text the string where the variables have to be
* resolved
* @return the resolved string
*/
public String resolve(String text) {
this.getTracker().clear();
Text textResolver = new Text(this);
textResolver.resolve(text, 0);
return textResolver.getValue();
}
/**
* Returns the value of a variable.
*
* @param varName the name of the variable
* @return the value
*/
public String getValue(String varName) {
return variablesMap.get(varName);
}
/**
* Returns a <code>Map</code> of all variables.
*
* @return a <code>Map</code> of all variables.
*/
public Map<String, String> getVariables() {
return variablesMap;
}
/**
* A term is a defined part in a text. In general, a term is defined by brackets,
* but this is not required. Here are some example terms:
* <ul>
* <li>Variable: {term1}</li>
* <li>Condition: [term2]</li>
* <li>EscapeChar: \[</li>
* </ul>
*
* You can write your own terms and add them to the text resolver. A sample is
* shown in the <code>MCRTextResolverTest</code> class.
*
* @author Matthias Eichner
*/
protected abstract static class Term {
/**
* The string buffer within the term. For example: {<b>var</b>}.
*/
protected StringBuffer termBuffer;
/**
* If the term is successfully resolved. By default this
* is true.
*/
protected boolean resolved;
/**
* The current character position in the term.
*/
protected int position;
protected MCRTextResolver textResolver;
public Term(MCRTextResolver textResolver) {
this.textResolver = textResolver;
this.termBuffer = new StringBuffer();
this.resolved = true;
this.position = 0;
}
/**
* Resolves the text from the startPosition to the end of the text
* or if a term specific end character is found.
*
* @param text the term to resolve
* @param startPosition the current character position
* @return the value of the term after resolving
*/
public String resolve(String text, int startPosition) {
for (position = startPosition; position < text.length(); position++) {
Term internalTerm = getTerm(text, position);
if (internalTerm != null) {
position += internalTerm.getStartEnclosingString().length();
internalTerm.resolve(text, position);
if (!internalTerm.resolved) {
resolved = false;
}
position = internalTerm.position;
termBuffer.append(internalTerm.getValue());
} else {
boolean complete = resolveInternal(text, position);
if (complete) {
int endEnclosingSize = getEndEnclosingString().length();
if (endEnclosingSize > 1) {
position += endEnclosingSize - 1;
}
break;
}
}
}
return getValue();
}
/**
* Returns a new term in dependence of the current character (position of the text).
* If no term is defined null is returned.
*
* @return a term or null if no one found
*/
private Term getTerm(String text, int pos) {
TermContainer termContainer = this.getTextResolver().getTermContainer();
for (Entry<String, Class<? extends Term>> termEntry : termContainer.getTermSet()) {
String startEnclosingStringOfTerm = termEntry.getKey();
if (text.startsWith(startEnclosingStringOfTerm, pos)
&& !startEnclosingStringOfTerm.equals(this.getEndEnclosingString())) {
try {
return termContainer.instantiate(termEntry.getValue());
} catch (Exception exc) {
LOGGER.error(exc);
}
}
}
return null;
}
/**
* Does term specific resolving for the current character.
*
* @return true if the end string is reached, otherwise false
*/
protected abstract boolean resolveInternal(String text, int pos);
/**
* Returns the value of the term. Overwrite this if you
* don't want to get the default termBuffer content as value.
*
* @return the value of the term
*/
public String getValue() {
return termBuffer.toString();
}
/**
* Implement this to define the start enclosing string for
* your term. The resolver searches in the text for this
* string, if found, the text is processed by your term.
*
* @return the start enclosing string
*/
public abstract String getStartEnclosingString();
/**
* Implement this to define the end enclosing string for
* your term. You have to check manual in the
* <code>resolveInternal</code> method if the end of
* your term is reached.
*
* @return the end enclosing string
*/
public abstract String getEndEnclosingString();
public MCRTextResolver getTextResolver() {
return textResolver;
}
}
/**
* A variable is surrounded by curly brackets. It supports recursive
* resolving for the content of the variable. The name of the variable
* is set by the termBuffer and the value is equal the content of the
* valueBuffer.
*/
protected static class Variable extends Term {
/**
* A variable doesn't return the termBuffer, but
* this valueBuffer.
*/
private StringBuffer valueBuffer;
private boolean complete;
public Variable(MCRTextResolver textResolver) {
super(textResolver);
valueBuffer = new StringBuffer();
complete = false;
}
@Override
public boolean resolveInternal(String text, int pos) {
if (text.startsWith(getEndEnclosingString(), pos)) {
this.track();
// get the value from the variables table
String value = getTextResolver().getValue(termBuffer.toString());
if (value == null) {
resolved = false;
if (getTextResolver().isRetainText()) {
this.valueBuffer.append(getStartEnclosingString()).append(termBuffer)
.append(getEndEnclosingString());
}
this.untrack();
complete = true;
return true;
}
// resolve the content of the variable recursive
// to resolve all other internal variables, condition etc.
if (getTextResolver().getResolveDepth() != ResolveDepth.NoVariables) {
Text recursiveResolvedText = resolveText(value);
resolved = recursiveResolvedText.resolved;
value = recursiveResolvedText.getValue();
}
// set the value of the variable
valueBuffer.append(value);
this.untrack();
complete = true;
return true;
}
termBuffer.append(text.charAt(pos));
return false;
}
@Override
public String getValue() {
if (!complete) {
// assume that the variable is not complete
return getStartEnclosingString() + termBuffer;
}
return valueBuffer.toString();
}
@Override
public String getStartEnclosingString() {
return "{";
}
@Override
public String getEndEnclosingString() {
return "}";
}
/**
* Tracks the variable to check for circular dependency.
*/
protected void track() {
this.getTextResolver().getTracker().track("var", getTrackID());
}
protected void untrack() {
this.getTextResolver().getTracker().untrack("var", getTrackID());
}
protected String getTrackID() {
return getStartEnclosingString() + termBuffer + getEndEnclosingString();
}
/**
* This method resolves all variables in the text.
* The syntax is described at the head of the class.
*
* @param text the string where the variables have to be
* resolved
* @return the resolved string
*/
public Text resolveText(String text) {
Text textResolver = new Text(getTextResolver());
textResolver.resolve(text, 0);
return textResolver;
}
}
/**
* A condition is defined by squared brackets. All data which
* is set in these brackets is only used if the internal variables are
* not null and not empty. For example "[hello {lastName}]" is only resolved
* if the value of "lastName" is not null and not empty. Otherwise the whole
* content in the squared brackets are ignored.
*/
protected static class Condition extends Term {
public Condition(MCRTextResolver textResolver) {
super(textResolver);
}
@Override
protected boolean resolveInternal(String text, int pos) {
if (text.startsWith(getEndEnclosingString(), pos)) {
return true;
}
termBuffer.append(text.charAt(pos));
return false;
}
@Override
public String getValue() {
if (resolved) {
return super.getValue();
}
return "";
}
@Override
public String getStartEnclosingString() {
return "[";
}
@Override
public String getEndEnclosingString() {
return "]";
}
}
/**
* As escape character the backslashed is used. Only the
* first character after the escape char is add to the term.
*/
protected static class EscapeCharacter extends Term {
public EscapeCharacter(MCRTextResolver textResolver) {
super(textResolver);
}
@Override
public boolean resolveInternal(String text, int pos) {
return true;
}
@Override
public String resolve(String text, int startPos) {
position = startPos;
char c = text.charAt(position);
termBuffer.append(c);
return termBuffer.toString();
}
@Override
public String getStartEnclosingString() {
return "\\";
}
@Override
public String getEndEnclosingString() {
return "";
}
}
/**
* A simple text, every character is added to the term (except its
* a special one).
*/
protected static class Text extends Term {
public Text(MCRTextResolver textResolver) {
super(textResolver);
}
@Override
public boolean resolveInternal(String text, int pos) {
termBuffer.append(text.charAt(pos));
return false;
}
@Override
public String getStartEnclosingString() {
return "";
}
@Override
public String getEndEnclosingString() {
return "";
}
}
/**
* Simple class to hold terms and instantiate them.
*/
protected static class TermContainer {
protected Map<String, Class<? extends Term>> termMap = new HashMap<>();
protected MCRTextResolver textResolver;
public TermContainer(MCRTextResolver textResolver) {
this.textResolver = textResolver;
}
public Term instantiate(Class<? extends Term> termClass) throws InvocationTargetException,
NoSuchMethodException, InstantiationException, IllegalAccessException {
Constructor<? extends Term> c = termClass.getConstructor(MCRTextResolver.class);
return c.newInstance(this.textResolver);
}
public void add(Class<? extends Term> termClass) throws InvocationTargetException, NoSuchMethodException,
InstantiationException, IllegalAccessException {
Term term = instantiate(termClass);
this.termMap.put(term.getStartEnclosingString(), termClass);
}
public void remove(Class<? extends Term> termClass) throws InvocationTargetException, NoSuchMethodException,
InstantiationException, IllegalAccessException {
Term term = instantiate(termClass);
this.termMap.remove(term.getStartEnclosingString());
}
public Set<Entry<String, Class<? extends Term>>> getTermSet() {
return this.termMap.entrySet();
}
}
protected static class CircularDependencyTracker {
protected MCRTextResolver textResolver;
protected Map<String, List<String>> trackMap;
public CircularDependencyTracker(MCRTextResolver textResolver) {
this.textResolver = textResolver;
this.trackMap = new HashMap<>();
}
public void track(String type, String id) throws CircularDependencyExecption {
List<String> idList = trackMap.computeIfAbsent(type, k -> new ArrayList<>());
if (idList.contains(id)) {
throw new CircularDependencyExecption(idList, id);
}
idList.add(id);
}
public void untrack(String type, String id) {
List<String> idList = trackMap.get(type);
if (idList == null) {
LOGGER.error("text resolver circular dependency tracking error: cannot get type {} of {}", type, id);
return;
}
idList.remove(id);
}
public void clear() {
this.trackMap.clear();
}
}
protected static class CircularDependencyExecption extends RuntimeException {
private static final long serialVersionUID = -2448797538275144448L;
private List<String> dependencyList;
private String id;
public CircularDependencyExecption(List<String> dependencyList, String id) {
this.dependencyList = dependencyList;
this.id = id;
}
@Override
public String getMessage() {
StringBuilder msg = new StringBuilder("A circular dependency exception occurred");
msg.append("\n").append("circular path: ");
for (String dep : dependencyList) {
msg.append(dep).append(" > ");
}
msg.append(id);
return msg.toString();
}
public String getId() {
return id;
}
public List<String> getDependencyList() {
return dependencyList;
}
}
}
| 23,628 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMailer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRMailer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
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.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.MCRMailer.EMail.MessagePart;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRJAXBContent;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.content.transformer.MCRXSL2XMLTransformer;
import org.mycore.common.xsl.MCRParameterCollector;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
import jakarta.activation.URLDataSource;
import jakarta.mail.Authenticator;
import jakarta.mail.Message;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlEnum;
import jakarta.xml.bind.annotation.XmlEnumValue;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.XmlValue;
/**
* This class provides methods to send emails from within a MyCoRe application.
*
* @author Marc Schluepmann
* @author Frank Lützenkirchen
* @author Werner Greßhoff
* @author René Adler (eagle)
*
*/
public class MCRMailer extends MCRServlet {
private static final Logger LOGGER = LogManager.getLogger(MCRMailer.class);
private static final String DELIMITER = "\n--------------------------------------\n";
private static Session mailSession;
protected static final String ENCODING;
/** How often should MCRMailer try to send mail? */
protected static int numTries;
private static final long serialVersionUID = 1L;
@Override
protected void doGetPost(MCRServletJob job) throws Exception {
String goTo = job.getRequest().getParameter("goto");
String xsl = job.getRequest().getParameter("xsl");
Document input = (Document) (job.getRequest().getAttribute("MCRXEditorSubmission"));
MCRMailer.sendMail(input, xsl);
job.getResponse().sendRedirect(goTo);
}
static {
ENCODING = MCRConfiguration2.getStringOrThrow("MCR.Mail.Encoding");
Properties mailProperties = new Properties();
try {
Authenticator auth = null;
numTries = MCRConfiguration2.getOrThrow("MCR.Mail.NumTries", Integer::parseInt);
if (MCRConfiguration2.getString("MCR.Mail.User").isPresent()
&& MCRConfiguration2.getString("MCR.Mail.Password").isPresent()) {
auth = new SMTPAuthenticator();
mailProperties.setProperty("mail.smtp.auth", "true");
}
String starttsl = MCRConfiguration2.getString("MCR.Mail.STARTTLS").orElse("disabled");
if (Objects.equals(starttsl, "enabled")) {
mailProperties.setProperty("mail.smtp.starttls.enabled", "true");
} else if (Objects.equals(starttsl, "required")) {
mailProperties.setProperty("mail.smtp.starttls.enabled", "true");
mailProperties.setProperty("mail.smtp.starttls.required", "true");
}
mailProperties.setProperty("mail.smtp.host", MCRConfiguration2.getStringOrThrow("MCR.Mail.Server"));
mailProperties.setProperty("mail.transport.protocol",
MCRConfiguration2.getStringOrThrow("MCR.Mail.Protocol"));
mailProperties.setProperty("mail.smtp.port", MCRConfiguration2.getString("MCR.Mail.Port").orElse("25"));
mailSession = Session.getDefaultInstance(mailProperties, auth);
mailSession.setDebug(MCRConfiguration2.getOrThrow("MCR.Mail.Debug", Boolean::parseBoolean));
} catch (MCRConfigurationException mcrx) {
String msg = "Missing e-mail configuration data.";
LOGGER.fatal(msg, mcrx);
}
}
/**
* This method sends a simple plaintext email with the given parameters.
*
* @param sender
* the sender of the email
* @param recipient
* the recipient of the email
* @param subject
* the subject of the email
* @param body
* the textbody of the email
*/
public static void send(String sender, String recipient, String subject, String body) {
LOGGER.debug("Called plaintext send method with single recipient.");
ArrayList<String> recipients = new ArrayList<>();
recipients.add(recipient);
send(sender, null, recipients, null, subject, body, null);
}
/**
* This method sends a simple plaintext email to more than one recipient. If
* flag BCC is true, the sender will also get the email as BCC recipient.
*
* @param sender
* the sender of the email
* @param recipients
* the recipients of the email as a List of Strings
* @param subject
* the subject of the email
* @param body
* the textbody of the email
* @param bcc
* if true, sender will also get a copy as cc recipient
*/
public static void send(String sender, List<String> recipients, String subject, String body, boolean bcc) {
LOGGER.debug("Called plaintext send method with multiple recipients.");
List<String> bccList = null;
if (bcc) {
bccList = new ArrayList<>();
bccList.add(sender);
}
send(sender, null, recipients, bccList, subject, body, null);
}
/**
* This method sends a multipart email with the given parameters.
*
* @param sender
* the sender of the email
* @param recipient
* the recipient of the email
* @param subject
* the subject of the email
* @param parts
* a List of URL strings which should be added as parts
* @param body
* the textbody of the email
*/
public static void send(String sender, String recipient, String subject, String body, List<String> parts) {
LOGGER.debug("Called multipart send method with single recipient.");
ArrayList<String> recipients = new ArrayList<>();
recipients.add(recipient);
send(sender, null, recipients, null, subject, body, parts);
}
/**
* This method sends a multipart email to more than one recipient. If flag
* BCC is true, the sender will also get the email as BCC recipient.
*
* @param sender
* the sender of the email
* @param recipients
* the recipients of the email as a List of Strings
* @param subject
* the subject of the email
* @param body
* the textbody of the email
* @param parts
* a List of URL strings which should be added as parts
* @param bcc
* if true, sender will also get a copy as bcc recipient
*/
public static void send(String sender, List<String> recipients, String subject, String body, List<String> parts,
boolean bcc) {
LOGGER.debug("Called multipart send method with multiple recipients.");
List<String> bccList = null;
if (bcc) {
bccList = new ArrayList<>();
bccList.add(sender);
}
send(sender, null, recipients, bccList, subject, body, parts);
}
/**
* Send email from a given XML document. See the sample mail below:
* <pre>
* <email>
* <from>bingo@bongo.com</from>
* <to>jim.knopf@lummerland.de</to>
* <bcc>frau.waas@lummerland.de</bcc>
* <subject>Grüße aus der Stadt der Drachen</subject>
* <body>Es ist recht bewölkt. Alles Gute, Jim.</body>
* <body type="html">Es ist recht bewölkt. Alles Gute, Jim.</body>
* <part>http://upload.wikimedia.org/wikipedia/de/f/f7/JimKnopf.jpg</part>
* </email>
* </pre>
* @param email the email as JDOM element.
*/
public static void send(Element email) {
try {
send(email, false);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
* Send email from a given XML document. See the sample mail below:
* <pre>
* <email>
* <from>bingo@bongo.com</from>
* <to>jim.knopf@lummerland.de</to>
* <bcc>frau.waas@lummerland.de</bcc>
* <subject>Grüße aus der Stadt der Drachen</subject>
* <body>Es ist recht bewölkt. Alles Gute, Jim.</body>
* <body type="html">Es ist recht bewölkt. Alles Gute, Jim.</body>
* <part>http://upload.wikimedia.org/wikipedia/de/f/f7/JimKnopf.jpg</part>
* </email>
* </pre>
* @param email the email as JDOM element.
* @param allowException allow to throw exceptions if set to <code>true</code>
*/
public static void send(Element email, Boolean allowException) throws Exception {
EMail mail = EMail.parseXML(email);
if (allowException) {
if (mail.to == null || mail.to.isEmpty()) {
throw new MCRException("No receiver defined for mail\n" + mail + '\n');
}
trySending(mail);
} else {
send(mail);
}
}
/**
* Sends email. When sending email fails (for example, outgoing mail server
* is not responding), sending will be retried after five minutes. This is
* done up to 10 times.
*
*
* @param from
* the sender of the email
* @param replyTo
* the reply-to addresses as a List of Strings, may be null
* @param to
* the recipients of the email as a List of Strings
* @param bcc
* the bcc recipients of the email as a List of Strings, may be
* null
* @param subject
* the subject of the email
* @param body
* the text of the email
* @param parts
* a List of URL strings which should be added as parts, may be
* null
*/
public static void send(final String from, final List<String> replyTo, final List<String> to,
final List<String> bcc, final String subject, final String body, final List<String> parts) {
EMail mail = new EMail();
mail.from = from;
mail.replyTo = replyTo;
mail.to = to;
mail.bcc = bcc;
mail.subject = subject;
mail.msgParts = new ArrayList<>();
mail.msgParts.add(new MessagePart(body));
mail.parts = parts;
send(mail);
}
/**
* Sends email. When sending email fails (for example, outgoing mail server
* is not responding), sending will be retried after five minutes. This is
* done up to 10 times.
*
* @param mail the email
*/
public static void send(EMail mail) {
if (mail.to == null || mail.to.isEmpty()) {
throw new MCRException("No receiver defined for mail\n" + mail + '\n');
}
try {
if (numTries > 0) {
trySending(mail);
}
} catch (Exception ex) {
LOGGER.info("Sending e-mail failed: ", ex);
if (numTries < 2) {
return;
}
Thread t = new Thread(() -> {
for (int i = numTries - 1; i > 0; i--) {
LOGGER.info("Retrying in 5 minutes...");
try {
Thread.sleep(300000); // wait 5 minutes
} catch (InterruptedException ignored) {
}
try {
trySending(mail);
LOGGER.info("Successfully resended e-mail.");
break;
} catch (Exception ex1) {
LOGGER.info("Sending e-mail failed: ", ex1);
}
}
});
t.start(); // Try to resend mail in separate thread
}
}
private static void trySending(EMail mail) throws Exception {
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(EMail.buildAddress(mail.from));
Optional<List<InternetAddress>> toList = EMail.buildAddressList(mail.to);
if (toList.isPresent()) {
msg.addRecipients(Message.RecipientType.TO, toList.get().toArray(InternetAddress[]::new));
}
Optional<List<InternetAddress>> replyToList = EMail.buildAddressList(mail.replyTo);
if (replyToList.isPresent()) {
msg.setReplyTo((replyToList.get().toArray(InternetAddress[]::new)));
}
Optional<List<InternetAddress>> bccList = EMail.buildAddressList(mail.bcc);
if (bccList.isPresent()) {
msg.addRecipients(Message.RecipientType.BCC,
bccList.get().toArray(InternetAddress[]::new));
}
msg.setSentDate(new Date());
msg.setSubject(mail.subject, ENCODING);
if (mail.parts != null && !mail.parts.isEmpty() || mail.msgParts != null && mail.msgParts.size() > 1) {
Multipart multipart = new MimeMultipart();
// Create the message part
MimeBodyPart messagePart = new MimeBodyPart();
if (mail.msgParts.size() > 1) {
multipart = new MimeMultipart("mixed");
MimeMultipart alternative = new MimeMultipart("alternative");
for (MessagePart m : mail.msgParts) {
messagePart = new MimeBodyPart();
messagePart.setText(m.message, ENCODING, m.type.value());
alternative.addBodyPart(messagePart);
}
messagePart = new MimeBodyPart();
messagePart.setContent(alternative);
multipart.addBodyPart(messagePart);
} else {
Optional<MessagePart> plainMsg = mail.getTextMessage();
if (plainMsg.isPresent()) {
messagePart.setText(plainMsg.get().message, ENCODING);
multipart.addBodyPart(messagePart);
}
}
if (mail.parts != null && !mail.parts.isEmpty()) {
for (String part : mail.parts) {
messagePart = new MimeBodyPart();
URL url = new URI(part).toURL();
DataSource source = new URLDataSource(url);
messagePart.setDataHandler(new DataHandler(source));
String fileName = url.getPath();
if (fileName.contains("\\")) {
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
} else if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
}
messagePart.setFileName(fileName);
multipart.addBodyPart(messagePart);
}
}
msg.setContent(multipart);
} else {
Optional<MessagePart> plainMsg = mail.getTextMessage();
if (plainMsg.isPresent()) {
msg.setText(plainMsg.get().message, ENCODING);
}
}
LOGGER.info("Sending e-mail to {}", mail.to);
Transport.send(msg);
}
/**
* Generates e-mail from the given input document by transforming it with an xsl stylesheet,
* and sends the e-mail afterwards.
*
* @param input the xml input document
* @param stylesheet the xsl stylesheet that will generate the e-mail, without the ending ".xsl"
* @param parameters the optionally empty table of xsl parameters
* @return the generated e-mail
*
* @see org.mycore.common.MCRMailer
*/
public static Element sendMail(Document input, String stylesheet, Map<String, String> parameters) throws Exception {
LOGGER.info("Generating e-mail from {} using {}.xsl", input.getRootElement().getName(), stylesheet);
if (LOGGER.isDebugEnabled()) {
debug(input.getRootElement());
}
Element eMail = transform(input, stylesheet, parameters).getRootElement();
if (LOGGER.isDebugEnabled()) {
debug(eMail);
}
if (eMail.getChildren("to").isEmpty()) {
LOGGER.warn("Will not send e-mail, no 'to' address specified");
} else {
LOGGER.info("Sending e-mail to {}: {}", eMail.getChildText("to"), eMail.getChildText("subject"));
MCRMailer.send(eMail);
}
return eMail;
}
/**
* Generates e-mail from the given input document by transforming it with an xsl stylesheet,
* and sends the e-mail afterwards.
*
* @param input the xml input document
* @param stylesheet the xsl stylesheet that will generate the e-mail, without the ending ".xsl"
* @return the generated e-mail
*
* @see org.mycore.common.MCRMailer
*/
public static Element sendMail(Document input, String stylesheet) throws Exception {
return sendMail(input, stylesheet, Collections.emptyMap());
}
/**
* Transforms the given input element using xsl stylesheet.
*
* @param input the input document to transform.
* @param stylesheet the name of the xsl stylesheet to use, without the ".xsl" ending.
* @param parameters the optionally empty table of xsl parameters
* @return the output document generated by the transformation process
*/
private static Document transform(Document input, String stylesheet, Map<String, String> parameters)
throws Exception {
MCRJDOMContent source = new MCRJDOMContent(input);
final String xslFolder = MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder");
MCRXSL2XMLTransformer transformer = MCRXSL2XMLTransformer.getInstance(xslFolder + "/" + stylesheet + ".xsl");
MCRParameterCollector parameterCollector = MCRParameterCollector.getInstanceFromUserSession();
parameterCollector.setParameters(parameters);
MCRContent result = transformer.transform(source, parameterCollector);
return result.asXML();
}
/** Outputs xml to the LOGGER for debugging */
private static void debug(Element xml) {
XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
LOGGER.debug(DELIMITER + "{}" + DELIMITER, xout.outputString(xml));
}
@XmlRootElement(name = "email")
public static class EMail {
private static final JAXBContext JAXB_CONTEXT = initContext();
@XmlElement
public String from;
@XmlElement
public List<String> replyTo;
@XmlElement
public List<String> to;
@XmlElement
public List<String> bcc;
@XmlElement
public String subject;
@XmlElement(name = "body")
public List<MessagePart> msgParts;
@XmlElement(name = "part")
public List<String> parts;
private static JAXBContext initContext() {
try {
return JAXBContext.newInstance(EMail.class.getPackage().getName(), EMail.class.getClassLoader());
} catch (final JAXBException e) {
throw new MCRException("Could not instantiate JAXBContext.", e);
}
}
/**
* Parse a email from given {@link Element}.
*
* @param xml the email
* @return the {@link EMail} object
*/
public static EMail parseXML(final Element xml) {
try {
final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
return (EMail) unmarshaller.unmarshal(new JDOMSource(xml));
} catch (final JAXBException e) {
throw new MCRException("Exception while transforming Element to EMail.", e);
}
}
/**
* Builds email address from a string. The string may be a single email
* address or a combination of a personal name and address, like "John Doe"
* <john@doe.com>
*
* @param s the email address string
* @return a {@link InternetAddress}
* @throws Exception throws AddressException or UnsupportedEncodingException
*/
private static InternetAddress buildAddress(String s) throws Exception {
if (!s.endsWith(">")) {
return new InternetAddress(s.trim());
}
String name = s.substring(0, s.lastIndexOf("<")).trim();
String addr = s.substring(s.lastIndexOf("<") + 1, s.length() - 1).trim();
if (name.startsWith("\"") && name.endsWith("\"")) {
name = name.substring(1, name.length() - 1);
}
return new InternetAddress(addr, name);
}
/**
* Builds a list of email addresses from a string list.
*
* @param addresses the list with email addresses
* @return a list of {@link InternetAddress}s
* @see MCRMailer.EMail#buildAddress(String)
*/
private static Optional<List<InternetAddress>> buildAddressList(final List<String> addresses) {
return addresses != null ? Optional.of(addresses.stream().map(address -> {
try {
return buildAddress(address);
} catch (Exception ex) {
return null;
}
}).collect(Collectors.toList())) : Optional.empty();
}
/**
* Returns the text message part.
*
* @return the text message part
*/
public Optional<MessagePart> getTextMessage() {
return msgParts != null ? Optional.of(msgParts).get().stream()
.filter(m -> m.type.equals(MessageType.TEXT)).findFirst() : Optional.empty();
}
/**
* Returns the HTML message part.
*
* @return the HTML message part
*/
public Optional<MessagePart> getHTMLMessage() {
return msgParts != null ? Optional.of(msgParts).get().stream()
.filter(m -> m.type.equals(MessageType.HTML)).findFirst() : Optional.empty();
}
/**
* Returns the {@link EMail} as XML.
*
* @return the XML
*/
public Document toXML() {
final MCRJAXBContent<EMail> content = new MCRJAXBContent<>(JAXB_CONTEXT, this);
try {
return content.asXML();
} catch (final IOException e) {
throw new MCRException("Exception while transforming EMail to JDOM document.", e);
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final int maxLen = 10;
StringBuilder builder = new StringBuilder();
builder.append("EMail [");
if (from != null) {
builder.append("from=");
builder.append(from);
builder.append(", ");
}
if (replyTo != null) {
builder.append("replyTo=");
builder.append(replyTo.subList(0, Math.min(replyTo.size(), maxLen)));
builder.append(", ");
}
if (to != null) {
builder.append("to=");
builder.append(to.subList(0, Math.min(to.size(), maxLen)));
builder.append(", ");
}
if (bcc != null) {
builder.append("bcc=");
builder.append(bcc.subList(0, Math.min(bcc.size(), maxLen)));
builder.append(", ");
}
if (subject != null) {
builder.append("subject=");
builder.append(subject);
builder.append(", ");
}
if (msgParts != null) {
builder.append("msgParts=");
builder.append(msgParts.subList(0, Math.min(msgParts.size(), maxLen)));
builder.append(", ");
}
if (parts != null) {
builder.append("parts=");
builder.append(parts.subList(0, Math.min(parts.size(), maxLen)));
}
builder.append(']');
return builder.toString();
}
@XmlRootElement(name = "body")
public static class MessagePart {
@XmlAttribute
public MessageType type = MessageType.TEXT;
@XmlValue
public String message;
MessagePart() {
}
public MessagePart(final String message) {
this.message = message;
}
public MessagePart(final String message, final MessageType type) {
this.message = message;
this.type = type;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final int maxLen = 50;
StringBuilder builder = new StringBuilder();
builder.append("MessagePart [");
if (type != null) {
builder.append("type=");
builder.append(type);
builder.append(", ");
}
if (message != null) {
builder.append("message=");
builder.append(message, 0, Math.min(message.length(), maxLen));
}
builder.append(']');
return builder.toString();
}
}
@XmlType(name = "mcrmailer-messagetype")
@XmlEnum
public enum MessageType {
@XmlEnumValue("text")
TEXT("text"),
@XmlEnumValue("html")
HTML("html");
private final String value;
MessageType(String v) {
value = v;
}
public String value() {
return value;
}
public static MessageType fromValue(String v) {
for (MessageType t : MessageType.values()) {
if (t.value.equals(v)) {
return t;
}
}
throw new IllegalArgumentException(v);
}
}
}
private static class SMTPAuthenticator extends jakarta.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MCRConfiguration2.getStringOrThrow("MCR.Mail.User"),
MCRConfiguration2.getStringOrThrow("MCR.Mail.Password"));
}
}
}
| 28,857 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserInformation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRUserInformation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
/**
* Encapsulates informations about the current authenticated user.
*
* A instance of this interface is always bound to {@link MCRSession}
* and can be requested via {@link MCRSession#getUserInformation()}.
* An implementer of this interface should bind the instance to the session via
* {@link MCRSession#setUserInformation(MCRUserInformation)}.
* @author Thomas Scheffler (yagee)
*
*/
public interface MCRUserInformation {
String ATT_PRIMARY_GROUP = "primaryGroup";
String ATT_REAL_NAME = "realName";
String ATT_EMAIL = "eMail";
/**
* The UserID is the information that is used in <em>user</em> clauses of the ACL System.
*/
String getUserID();
/**
* The role information is used in <em>group</em> clauses of the ACL System.
*/
boolean isUserInRole(String role);
/**
* Get additional attributes if they are provided by the underlying user system
* @param attribute user attribute name
* @return attribute value as String or null if no value is defined;
*/
String getUserAttribute(String attribute);
}
| 1,853 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPersistenceTransaction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRPersistenceTransaction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
/**
* Thread safety: Implementation must not ensure that concurrent access is without side effects.
*/
public interface MCRPersistenceTransaction {
/**
* preconditions in the backend are met and this instance should be used for transactions
* @return true if this instance is ready for transaction handling, e.g. underlaying database is configured
*/
boolean isReady();
/**
* Start a transaction.
* @throws IllegalStateException if <code>isActive()</code> is true
*/
void begin();
/**
* Commit the current transaction, writing any
* unflushed changes to the backend.
* @throws IllegalStateException if <code>isActive()</code> is false
*/
void commit();
/**
* Roll back the current transaction.
* @throws IllegalStateException if <code>isActive()</code> is false
*/
void rollback();
/**
* Determine whether the current transaction has been
* marked for rollback.
* @return boolean indicating whether the transaction has been
* marked for rollback
* @throws IllegalStateException if <code>isActive()</code> is false
*/
boolean getRollbackOnly();
/**
* Mark the current resource transaction so that the only possible outcome of the transaction is for the
* transaction to be rolled back.
*
* @throws IllegalStateException if <code>isActive()</code> is false
*/
void setRollbackOnly() throws IllegalStateException;
/**
* Indicate whether a transaction is in progress.
* @return boolean indicating whether transaction is
* in progress
*/
boolean isActive();
}
| 2,431 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConstants.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRConstants.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import org.apache.logging.log4j.LogManager;
import org.jdom2.Namespace;
import org.jdom2.xpath.XPathFactory;
import org.mycore.common.config.MCRConfiguration2;
/**
* This class replaces the deprecated MCRDefaults interface and provides some
* final static fields of common use.
*
* @author Jens Kupferschmidt
* @author Thomas Scheffler (yagee)
* @author Stefan Freitag (sasf)
* @author Frank Lützenkirchen
*/
public final class MCRConstants {
/** MCR.Metadata.DefaultLang */
public static final String DEFAULT_LANG = "de";
/** The default encoding */
public static final String DEFAULT_ENCODING = "UTF-8";
public static final Namespace XML_NAMESPACE = Namespace.getNamespace("xml", "http://www.w3.org/XML/1998/namespace");
public static final Namespace XLINK_NAMESPACE = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink");
/** the MARC 21 namespace */
public static final Namespace MARC21_NAMESPACE = Namespace.getNamespace("marc21", "http://www.loc.gov/MARC21/slim");
/** MARC 21 namespace schema location */
public static final String MARC21_SCHEMA_LOCATION = "http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd";
public static final XPathFactory XPATH_FACTORY = XPathFactory.instance();
/** The URL of the XSI */
private static final String XSI_URL = "http://www.w3.org/2001/XMLSchema-instance";
public static final Namespace XSI_NAMESPACE = Namespace.getNamespace("xsi", XSI_URL);
/** The URL of the XSL */
private static final String XSL_URL = "http://www.w3.org/1999/XSL/Transform";
public static final Namespace XSL_NAMESPACE = Namespace.getNamespace("xsl", XSL_URL);
/** The URL of the METS */
private static final String METS_URL = "http://www.loc.gov/METS/";
public static final Namespace METS_NAMESPACE = Namespace.getNamespace("mets", METS_URL);
/** The URL of the DV */
private static final String DV_URL = "http://dfg-viewer.de/";
public static final Namespace DV_NAMESPACE = Namespace.getNamespace("dv", DV_URL);
/** The URL of the LIDO */
private static final String LIDO_URL = "http://www.lido-schema.org";
public static final Namespace LIDO_NAMESPACE = Namespace.getNamespace("lido", LIDO_URL);
/** The URL of the MODS */
private static final String MODS_URL = "http://www.loc.gov/mods/v3";
public static final Namespace MODS_NAMESPACE = Namespace.getNamespace("mods", MODS_URL);
public static final Namespace ZS_NAMESPACE = Namespace.getNamespace("zs", "http://www.loc.gov/zing/srw/");
public static final Namespace ZR_NAMESPACE = Namespace.getNamespace("zr", "http://explain.z3950.org/dtd/2.0/");
public static final Namespace SRW_NAMESPACE = Namespace.getNamespace("srw", "http://www.loc.gov/zing/srw/");
public static final Namespace INFO_SRW_NAMESPACE = Namespace.getNamespace("info", "info:srw/schema/5/picaXML-v1.0");
public static final Namespace PIDEF_NAMESPACE = Namespace.getNamespace("pidef", "http://nbn-resolving.org/pidef");
public static final Namespace CROSSREF_NAMESPACE = Namespace.getNamespace("cr",
"http://www.crossref.org/schema/4.4.1");
public static final Namespace DIAG_NAMESPACE = Namespace.getNamespace("diag",
"http://www.loc.gov/zing/srw/diagnostic");
public static final Namespace EPICURLITE_NAMESPACE = Namespace.getNamespace("epicurlite",
"http://nbn-resolving.org/epicurlite");
public static final Namespace ALTO_NAMESPACE = Namespace
.getNamespace("alto", "http://www.loc.gov/standards/alto/ns-v2#");
public static final Namespace SKOS_NAMESPACE = Namespace
.getNamespace("skos", "http://www.w3.org/2004/02/skos/core#");
public static final Namespace RDF_NAMESPACE = Namespace
.getNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
/** The URL of the MCR */
private static final String MCR_URL = "http://www.mycore.org/";
public static final Namespace MCR_NAMESPACE = Namespace.getNamespace("mcr", MCR_URL);
private static final HashMap<String, Namespace> NAMESPACES_BY_PREFIX;
static {
NAMESPACES_BY_PREFIX = new HashMap<>();
Field[] fields = MCRConstants.class.getFields();
for (Field f : fields) {
if (f.getType() == Namespace.class) {
try {
Namespace namespace = (Namespace) f.get(null);
registerNamespace(namespace);
} catch (Exception e) {
LogManager.getLogger(MCRConstants.class).error(
"Error while initialising Namespace list and HashMap",
e);
}
}
}
MCRConfiguration2.getSubPropertiesMap("MCR.Namespace.")
.forEach(MCRConstants::registerNamespace);
}
private static void registerNamespace(String prefix, String uri) {
registerNamespace(Namespace.getNamespace(prefix, uri));
}
/**
* Adds and registers a standard namespace with prefix.
* Note that a default namespace without prefix will be ignored here!
*/
public static void registerNamespace(Namespace namespace) {
String prefix = namespace.getPrefix();
if ((prefix != null) && !prefix.isEmpty()) {
NAMESPACES_BY_PREFIX.put(prefix, namespace);
}
}
/**
* Returns a list of standard namespaces used in MyCoRe. Additional
* namespaces can be configured using properties like
* MCR.Namespace.<prefix>=<uri>
*/
public static Collection<Namespace> getStandardNamespaces() {
return NAMESPACES_BY_PREFIX.values();
}
/**
* Returns the namespace with the given standard prefix. Additional
* namespaces can be configured using properties like
* MCR.Namespace.<prefix>=<uri>
*/
public static Namespace getStandardNamespace(String prefix) {
return NAMESPACES_BY_PREFIX.get(prefix);
}
}
| 6,864 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRClassTools.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRClassTools.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Optional;
public class MCRClassTools {
private static volatile ClassLoader extendedClassLoader;
static {
updateClassLoader(); //first init
}
public static Object loadClassFromURL(String classPath, String className)
throws MalformedURLException, ReflectiveOperationException {
return loadClassFromURL(new File(classPath), className);
}
public static Object loadClassFromURL(File file, String className)
throws MalformedURLException, ReflectiveOperationException {
if (file.exists()) {
URL url = file.toURI().toURL();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url },
Thread.currentThread().getContextClassLoader());
Class<?> clazz = urlClassLoader.loadClass(className);
return clazz.getDeclaredConstructor().newInstance();
}
return null;
}
/**
* Loads a class via default ClassLoader or <code>Thread.currentThread().getContextClassLoader()</code>.
* @param classname Name of class
* @param <T> Type of Class
* @return the initialized class
* @throws ClassNotFoundException if both ClassLoader cannot load the Class
*/
public static <T> Class<? extends T> forName(String classname) throws ClassNotFoundException {
@SuppressWarnings("unchecked")
Class<? extends T> forName;
try {
forName = (Class<? extends T>) Class.forName(classname);
} catch (ClassNotFoundException cnfe) {
forName = (Class<? extends T>) Class.forName(classname, true, extendedClassLoader);
}
return forName;
}
/**
* @return a ClassLoader that should be used to load resources
*/
public static ClassLoader getClassLoader() {
return extendedClassLoader;
}
public static void updateClassLoader() {
extendedClassLoader = Optional.ofNullable(Thread.currentThread().getContextClassLoader())
.orElseGet(MCRClassTools.class::getClassLoader);
}
}
| 2,940 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHTTPClient.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRHTTPClient.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.IOException;
import java.net.URI;
import org.mycore.common.content.MCRContent;
public interface MCRHTTPClient {
MCRContent get(URI hrefURI) throws IOException;
void close();
}
| 957 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDeveloperTools.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRDeveloperTools.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
/**
* @author Sebastian Hofmann
*/
public class MCRDeveloperTools {
private static final Logger LOGGER = LogManager.getLogger();
/**
* @return true if any override is defined
*/
public static boolean overrideActive() {
return MCRConfiguration2.getString("MCR.Developer.Resource.Override").isPresent();
}
public static Stream<Path> getOverridePaths() {
if (!overrideActive()) {
return Stream.empty();
}
return MCRConfiguration2
.getOrThrow("MCR.Developer.Resource.Override", MCRConfiguration2::splitValue)
.map(Paths::get);
}
/**
* Reads the property <code>MCR.Developer.Resource.Override</code> and checks if any of the containing paths
* contains the path parameter.
* @param path the resource to override
* @param webResource if true META-INF/resources will be appended to the paths in the property
* @return the path to new file
*/
public static Optional<Path> getOverriddenFilePath(String path, boolean webResource) {
if (overrideActive()) {
final String[] pathParts = path.split("/");
return MCRConfiguration2
.getOrThrow("MCR.Developer.Resource.Override", MCRConfiguration2::splitValue)
.map(Paths::get)
.map(p -> webResource ? p.resolve("META-INF").resolve("resources") : p)
.map(p -> {
try {
return MCRUtils.safeResolve(p, pathParts);
} catch (MCRException | InvalidPathException e) {
LOGGER.debug("Exception in safeResolve", e);
return null;
}
})
.filter(Objects::nonNull)
.filter(Files::exists)
.peek(p -> LOGGER.debug("Found overridden Resource: {}", p.toAbsolutePath().toString()))
.findFirst();
}
return Optional.empty();
}
}
| 3,117 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStreamUtils.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRStreamUtils.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import com.google.common.collect.Iterators;
/**
* Helper methods to handle common Stream use cases.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRStreamUtils {
/**
* Short circuit for calling <code>flatten(node, subNodeSupplier, subNodeSupplier, t -> true)</code>
* @param node node that holds kind-of subtree.
* @param subNodeSupplier a function that delivers subtree items of next level
* @param streamProvider a function that makes a Stream of a Collection<T>, usually <code>Collection::stream</code> or <code>Collection::parallelStream</code>
* @see #flatten(Object, Function, Function, Predicate)
* @since 2016.04
*/
public static <T> Stream<T> flatten(T node, Function<T, Collection<T>> subNodeSupplier,
Function<Collection<T>, Stream<T>> streamProvider) {
return Stream.concat(Stream.of(node), subNodeSupplier.andThen(streamProvider).apply(node).flatMap(
subNode -> flatten(subNode, subNodeSupplier, streamProvider)));
}
/**
* Example:
* <pre>
* MCRCategory foo = MCRCategoryDAOFactory.getInstance().getCategory(MCRCategoryID.rootID("foo"), -1);
* Stream<MCRCategory> parentCategories = flatten(foo, MCRCategory::getChildren, true, MCRCategory::hasChildren);
* </pre>
* @param node first node the stream is made of
* @param subNodeSupplier a function that delivers subtree items of next level
* @param streamProvider a function that makes a Stream of a Collection<T>, usually <code>Collection::stream</code> or <code>Collection::parallelStream</code>
* @param filter a predicate that filters the element of the next level
* @since 2016.04
*/
public static <T> Stream<T> flatten(T node, Function<T, Collection<T>> subNodeSupplier,
Function<Collection<T>, Stream<T>> streamProvider, Predicate<T> filter) {
return Stream.concat(Stream.of(node),
subNodeSupplier.andThen(streamProvider).apply(node).filter(filter).flatMap(
subNode -> flatten(subNode, subNodeSupplier, streamProvider, filter)));
}
/**
* Transforms an Enumeration in a Stream.
* @param e the enumeration to transform
* @return a sequential, ordered Stream of unknown size
*/
public static <T> Stream<T> asStream(Enumeration<T> e) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(Iterators.forEnumeration(e), Spliterator.ORDERED), false);
}
/**
* Concats any number of Streams not just 2 as in {@link Stream#concat(Stream, Stream)}.
* @since 2016.04
*/
@SafeVarargs
public static <T> Stream<T> concat(Stream<T>... streams) {
return Stream.of(streams).reduce(Stream::concat).orElse(Stream.empty());
}
/**
* Stream distinct by filter function.
* <p>
* <code>
* persons.stream().filter(MCRStreamUtils.distinctByKey(p -> p.getName());
* </code>
* </p>
* It should be noted that for ordered parallel stream this solution does not guarantee
* which object will be extracted (unlike normal distinct()).
*
* @see <a href="https://stackoverflow.com/questions/23699371/java-8-distinct-by-property">stackoverflow</a>
* @param keyExtractor a compare function
* @return a predicate
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
/**
* Negates a predicate.
*
* @see <a href="https://stackoverflow.com/questions/28235764/how-can-i-negate-a-lambda-predicate">stackoverflow</a>
* @param predicate the predicate to negate
* @return the negated predicate
*/
public static <T> Predicate<T> not(Predicate<T> predicate) {
return predicate.negate();
}
}
| 5,047 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUsageException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRUsageException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
/**
* Instances of MCRUsageException are thrown when the MyCoRe API is used in an
* illegal way. For example, this could happen when you provide illegal
* arguments to a method.
*
* @author Frank Lützenkirchen
*/
public class MCRUsageException extends MCRException {
/**
* Creates a new MCRUsageException with an error message
*
* @param message
* the error message for this exception
*/
public MCRUsageException(String message) {
super(message);
}
/**
* Creates a new MCRUsageException with an error message and a reference to
* an exception thrown by an underlying system.
*
* @param message
* the error message for this exception
* @param exception
* the exception that was thrown by an underlying system
*/
public MCRUsageException(String message, Exception exception) {
super(message, exception);
}
}
| 1,710 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.logging.log4j.LogManager;
/**
* Instances of this class represent a general exception thrown by any part of
* the MyCoRe implementation classes.
*
* @author Jens Kupferschmidt
* @author Frank Lützenkirchen
*
* @see RuntimeException
*/
public class MCRException extends RuntimeException {
private static final long serialVersionUID = -3396055962010289244L;
/**
* Creates a new MCRException with an error message
*
* @param message
* the error message for this exception
*/
public MCRException(String message) {
super(message);
}
public MCRException(Throwable cause) {
super(cause);
}
/**
* Creates a new MCRException with an error message and a reference to an
* exception thrown by an underlying system. Normally, this exception will
* be the cause why we would throw an MCRException, e. g. when something in
* the datastore goes wrong.
*
* @param message
* the error message for this exception
* @param cause
* the cause (which is saved for later retrieval by the {@link Throwable#getCause()} method).
* (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
public MCRException(String message, Throwable cause) {
super(message, cause);
}
/**
* Returns a String containing the invocation stack trace for this exception
*
* @return a String containing the invocation stack trace for this exception
*/
public String getStackTraceAsString() {
return getStackTraceAsString(this);
}
/**
* Returns a String containing the invocation stack trace of an exception
*
* @param ex
* the exception you want the stack trace of
* @return the invocation stack trace of an exception
*/
public static String getStackTraceAsString(Throwable ex) {
// We let Java print the stack trace to a buffer in memory to be able to
// get it as String:
try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
ex.printStackTrace(pw);
pw.flush();
return sw.toString();
} catch (IOException e) {
LogManager.getLogger(MCRException.class).warn("Error while transforming stack trace to String.", e);
return null;
}
}
}
| 3,302 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCache.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRCache.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.mycore.services.mbeans.MCRJMXBridge;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
/**
* Instances of this class can be used as object cache. Each MCRCache has a certain capacity, the maximum number of
* objects the cache will hold. When the cache is full and another object is put into the cache, the cache will discard
* the least recently used object to get place for the new object. The cache will always hold the most recently used
* objects by updating its internal structure whenever an object is get from the cache or put into the cache. The cache
* also provides methods for getting the current cache hit rate and fill rate. Like in a hashtable, an MCRCache uses a
* unique key for each object.
*
* @see java.util.Hashtable
* @author Frank Lützenkirchen
*/
public class MCRCache<K, V> {
/** Tch type string for the MCRCacheJMXBridge */
protected String type;
Cache<K, MCRCacheEntry<V>> backingCache;
private long capacity;
/**
* Creates a new cache with a given capacity.
*
* @param capacity
* the maximum number of objects this cache will hold
* @param type
* the type string for MCRCacheJMXBridge
*/
public MCRCache(long capacity, String type) {
backingCache = CacheBuilder.newBuilder().recordStats().maximumSize(capacity).build();
this.capacity = capacity;
this.type = type;
Object mbean = new MCRCacheManager(this);
MCRJMXBridge.register(mbean, "MCRCache", type);
}
/**
* A small sample program for testing this class.
*/
public static void main(String[] args) {
MCRCache<String, String> cache = new MCRCache<>(4, "Small Sample Program");
System.out.println(cache);
cache.put("a", "Anton");
cache.put("b", "Bohnen");
cache.put("c", "Cache");
System.out.println(cache);
cache.get("d");
cache.get("c");
cache.put("d", "Dieter");
cache.put("e", "Egon");
cache.put("f", "Frank");
cache.get("c");
System.out.println(cache);
}
/**
* Puts an object into the cache, storing it under the given key. If the cache is already full, the least recently
* used object will be removed from the cache first. If the cache already contains an entry under the key provided,
* this entry is replaced.
*
* @param key
* the non-null key to store the object under
* @param value
* the non-null object to be put into the cache
*/
public void put(K key, V value) {
if (key == null) {
throw new NullPointerException("The key of a cache entry may not be null.");
}
if (value == null) {
throw new NullPointerException("The value of a cache entry may not be null.");
}
MCRCacheEntry<V> entry = new MCRCacheEntry<>(value);
backingCache.put(key, entry);
}
/**
* Puts an object into the cache, storing it under the given key. If the cache is already full, the least recently
* used object will be removed from the cache first. If the cache already contains an entry under the key provided,
* this entry is replaced.
*
* @param key
* the non-null key to store the object under
* @param value
* the non-null object to be put into the cache
* @param insertTime
* the given last modified time for this key
*/
public void put(K key, V value, long insertTime) {
if (key == null) {
throw new NullPointerException("The key of a cache entry may not be null.");
}
if (value == null) {
throw new NullPointerException("The value of a cache entry may not be null.");
}
MCRCacheEntry<V> entry = new MCRCacheEntry<>(value);
entry.insertTime = insertTime;
backingCache.put(key, entry);
}
/**
* Removes an object from the cache for the given key.
*
* @param key
* the key for the object you want to remove from this cache
*/
public void remove(K key) {
if (key == null) {
throw new MCRUsageException("The value of the argument key is null.");
}
backingCache.invalidate(key);
}
/**
* Returns an object from the cache for the given key, or null if there currently is no object in the cache with
* this key.
*
* @param key
* the key for the object you want to get from this cache
* @return the cached object, or null
*/
public V get(K key) {
MCRCacheEntry<V> found = backingCache.getIfPresent(key);
return found == null ? null : found.value;
}
/**
* Returns an object from the cache for the given key, but only if the cache entry is not older than the given
* timestamp. If there currently is no object in the cache with this key, null is returned. If the cache entry is
* older than the timestamp, the entry is removed from the cache and null is returned.
*
* @param key
* the key for the object you want to get from this cache
* @param time
* the timestamp to check that the cache entry is up to date
* @return the cached object, or null
*/
public V getIfUpToDate(K key, long time) {
MCRCacheEntry<V> found = backingCache.getIfPresent(key);
if (found == null || found.insertTime < time) {
return null;
}
if (found.insertTime >= time) {
found.lookUpTime = System.currentTimeMillis();
return found.value;
}
backingCache.invalidate(key);
return null;
}
/**
* Returns an object from the cache for the given key, but only if the cache entry is not older than the given
* timestamp of the {@link ModifiedHandle}. In contrast to {@link #getIfUpToDate(Object, long)} you can submit your
* own handle that returns the last modified timestamp after a certain period is over. Use this method if
* determining lastModified date is rather expensive and cache access is often.
*
* @param key
* the key for the object you want to get from this cache
* @param handle
* the timestamp to check that the cache entry is up to date
* @return the cached object, or null
* @throws IOException
* thrown by {@link ModifiedHandle#getLastModified()}
* @since 2.1.81
*/
public V getIfUpToDate(K key, ModifiedHandle handle) throws IOException {
MCRCacheEntry<V> found = backingCache.getIfPresent(key);
if (found == null) {
return null;
}
if (System.currentTimeMillis() - found.lookUpTime > handle.getCheckPeriod()) {
if (found.insertTime >= handle.getLastModified()) {
found.lookUpTime = System.currentTimeMillis();
return found.value;
}
backingCache.invalidate(key);
return null;
} else {
return found.value;
}
}
/**
* Returns the number of objects currently cached.
*
* @return the number of objects currently cached
*/
public long getCurrentSize() {
backingCache.cleanUp();
return backingCache.size();
}
/**
* Returns the capacity of this cache. This is the maximum number of objects this cache will hold at a time.
*
* @return the capacity of this cache
*/
public long getCapacity() {
return capacity;
}
/**
* Changes the capacity of this cache. This is the maximum number of objects that will be cached at a time. If the
* new capacity is smaller than the current number of objects in the cache, the least recently used objects will be
* removed from the cache.
*
* @param capacity
* the maximum number of objects this cache will hold
*/
public synchronized void setCapacity(long capacity) {
this.capacity = capacity;
Cache<K, MCRCacheEntry<V>> newCache = CacheBuilder.newBuilder().recordStats().maximumSize(capacity).build();
newCache.putAll(backingCache.asMap());
Cache<K, MCRCacheEntry<V>> oldCache = backingCache;
backingCache = newCache;
oldCache.invalidateAll();
}
/**
* Returns true if this cache is full.
*
* @return true if this cache is full
*/
public boolean isFull() {
backingCache.cleanUp();
return backingCache.size() == capacity;
}
/**
* Returns true if this cache is empty.
*
* @return true if this cache is empty
*/
public boolean isEmpty() {
backingCache.cleanUp();
return backingCache.size() == 0;
}
/**
* Returns the fill rate of this cache. This is the current number of objects in the cache diveded by its capacity.
*
* @return the fill rate of this cache as double value
*/
public double getFillRate() {
return capacity == 0 ? 1.0 : (double) getCurrentSize() / (double) capacity;
}
/**
* Returns the hit rate of this cache. This is the number of successful hits divided by the total number of get
* requests so far. Using this ratio can help finding the appropriate cache capacity.
*
* @return the hit rate of this cache as double value
*/
public double getHitRate() {
return backingCache.stats().hitRate();
}
/**
* Clears the cache by removing all entries from the cache
*/
public void clear() {
backingCache.invalidateAll();
}
/**
* Returns a String containing information about cache capacity, size, current fill rate and hit rate. Useful for
* testing and debugging.
*/
@Override
public String toString() {
return "Cache capacity: " + capacity + "\n" + "Cache size: " + backingCache.size() + "\n"
+ "Cache fill rate: " + getFillRate() + "\n" + "Cache hit rate: " + getHitRate();
}
public void close() {
MCRJMXBridge.unregister("MCRCache", type);
clear();
}
/**
* Returns an iterable list of keys to the cached objects.
*/
public List<K> keys() {
return Collections.list(Collections.enumeration(backingCache.asMap().keySet()));
}
/**
* @author Thomas Scheffler (yagee)
*/
public interface ModifiedHandle {
/**
* check distance in ms. After this period of time use {@link #getLastModified()} to check if object is still
* up-to-date.
*/
long getCheckPeriod();
/**
* returns timestamp when the cache value was last modified.
*/
long getLastModified() throws IOException;
}
private static class MCRCacheEntry<V> {
public long lookUpTime;
V value;
long insertTime;
MCRCacheEntry(V value) {
this.value = value;
this.insertTime = System.currentTimeMillis();
}
}
}
| 12,025 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPersistenceException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/MCRPersistenceException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common;
/**
* Instances of this class represent a general exception thrown by the
* persistency layer of the MyCoRe implementation. This will be the case when
* the datastore reports an error, for example.
*
* @author Jens Kupferschmidt
* @author Frank Lützenkirchen
*/
public class MCRPersistenceException extends MCRException {
/**
* Creates a new MCRPersistenceException with an error message
*
* @param message
* the error message for this exception
*/
public MCRPersistenceException(String message) {
super(message);
}
/**
* Creates a new MCRPersistenceException with an error message and a
* reference to an exception thrown by an underlying system.
*
* @param message
* the error message for this exception
* @param exception
* the exception that was thrown by an underlying system
*/
public MCRPersistenceException(String message, Exception exception) {
super(message, exception);
}
}
| 1,790 | 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-base/src/main/java/org/mycore/common/log4j2/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/>.
*/
/**
* Prodvides classes that can be used with Log4J2
*
* @author Thomas Scheffler (yagee)
*/
package org.mycore.common.log4j2;
| 859 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionThreadContext.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/log4j2/MCRSessionThreadContext.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.log4j2;
import org.apache.logging.log4j.ThreadContext;
import org.mycore.common.MCRSession;
import org.mycore.common.events.MCRSessionEvent;
import org.mycore.common.events.MCRSessionListener;
/**
* Adds MCRSession information to the current {@link ThreadContext}.
*
* <dl>
* <dt>loginId</dt><dd>current user id</dd>
* <dt>ipAddress</dt><dd>see {@link MCRSession#getCurrentIP()}</dd>
* <dt>mcrSession</dt><dd>see {@link MCRSession#getID()}</dd>
* <dt>language</dt><dd>see {@link MCRSession#getCurrentLanguage()}</dd>
* </dl>
*
* @author Thomas Scheffler (yagee)
* @see <a href="https://logging.apache.org/log4j/2.x/manual/thread-context.html">ThreadContext description</a>
* @see ThreadContext
*/
public class MCRSessionThreadContext implements MCRSessionListener {
@Override
public void sessionEvent(MCRSessionEvent event) {
switch (event.getType()) {
case activated -> {
ThreadContext.put("ipAddress", event.getSession().getCurrentIP());
ThreadContext.put("loginId", event.getSession().getUserInformation().getUserID());
ThreadContext.put("mcrSession", event.getSession().getID());
ThreadContext.put("language", event.getSession().getCurrentLanguage());
}
case passivated -> ThreadContext.clearMap();
default -> {
}
}
}
}
| 2,146 | 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-base/src/main/java/org/mycore/common/log4j2/lookups/package-info.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Provides custom lookups that provide informations on MyCoRe.
* @author Thomas Scheffler (yagee)
*/
package org.mycore.common.log4j2.lookups;
| 877 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationLookup.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/log4j2/lookups/MCRConfigurationLookup.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.log4j2.lookups;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;
import org.mycore.common.config.MCRConfiguration2;
/**
* Lookup a value in {@link MCRConfiguration2}. Uses <code>key</code> as property key.
*
* @author Thomas Scheffler
*/
@Plugin(
name = "mcrcfg",
category = StrLookup.CATEGORY)
public class MCRConfigurationLookup implements StrLookup {
@Override
public String lookup(String key) {
return MCRConfiguration2.getString(key).orElse(null);
}
@Override
public String lookup(LogEvent event, String key) {
return lookup(key);
}
}
| 1,464 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUserInformationLookup.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/log4j2/lookups/MCRUserInformationLookup.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.log4j2.lookups;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;
import org.mycore.common.MCRSessionMgr;
/**
* Allows to access information on the current user. This lookup returns <code>null</code> if <code>key == null</code>
* or {@link MCRSessionMgr#hasCurrentSession()} returns <code>false</code>. <code>key</code> may be either
* <dl>
* <dt>id
* <dt>
* <dd>returns the current user id</dd>
* <dt>role:{role1},{role2},...,{roleN}<dt>
* <dd>returns the first role the current user is in<dd>
* </dl>
*
* @author Thomas Scheffler (yagee)
*/
@Plugin(
name = "mcruser",
category = StrLookup.CATEGORY)
public class MCRUserInformationLookup implements StrLookup {
private static final Pattern ROLE_SEPARATOR = Pattern.compile(",");
private static final String ROLE_PREFIX = "role:";
@Override
public String lookup(String key) {
return getValue(key);
}
@Override
public String lookup(LogEvent event, String key) {
return lookup(key);
}
private static String getValue(String key) {
if (key == null || !MCRSessionMgr.hasCurrentSession()) {
return null;
}
if (Objects.equals(key, "id")) {
return MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
} else if (key.startsWith(ROLE_PREFIX)) {
Optional<String> firstMatchingRole = ROLE_SEPARATOR
.splitAsStream(key.substring(ROLE_PREFIX.length()))
.filter(role -> MCRSessionMgr.getCurrentSession().getUserInformation().isUserInRole(role))
.findFirst();
if (firstMatchingRole.isPresent()) {
return firstMatchingRole.get();
}
}
return null;
}
}
| 2,706 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRUniqueFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/log4j2/filter/MCRUniqueFilter.java | package org.mycore.common.log4j2.filter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.message.ParameterizedMessage;
/**
* Detects duplicate instances of logging events that have the same parameters for a given format.
* Uses an LRU cache to only filters up to a maximum amount of parameter sets per format. The cache size per
* format con be configured with the <code>cacheSizePerFormat</code> configuration value; defaults to
* <code>1000</code>.
* <p>
* By default, the result of a match is <code>DENY</code> and on a mismatch is <code>NEUTRAL</code>.
*/
@Plugin(name = "MCRUniqueFilter", category = Node.CATEGORY, elementType = Filter.ELEMENT_TYPE)
public class MCRUniqueFilter extends AbstractFilter {
private final int cacheSizePerFormat;
private final Map<String, Set<List<Object>>> cacheByFormat = new HashMap<>();
private MCRUniqueFilter(int cacheSizePerFormat, Result onMatch, Result onMismatch) {
super(onMatch, onMismatch);
this.cacheSizePerFormat = cacheSizePerFormat;
}
@Override
public Result filter(LogEvent event) {
if (event.getMessage() instanceof ParameterizedMessage message) {
List<Object> parameters = Arrays.asList(message.getParameters());
Set<List<Object>> cache = getCache(message.getFormat());
if (cache.contains(parameters)) {
return onMatch;
} else {
cache.add(parameters);
}
}
return onMismatch;
}
private Set<List<Object>> getCache(String format) {
return cacheByFormat.computeIfAbsent(format, f -> createCache());
}
private Set<List<Object>> createCache() {
return Collections.newSetFromMap(new LinkedHashMap<>() {
@Override
protected boolean removeEldestEntry(Map.Entry<List<Object>, Boolean> eldest) {
return size() > cacheSizePerFormat;
}
});
}
@PluginFactory
public static MCRUniqueFilter createFilter(
@PluginAttribute(value = "cacheSizePerFormat", defaultInt = 1000) int cacheSizePerFormat,
@PluginAttribute("onMatch") Result match, @PluginAttribute("onMismatch") Result mismatch) {
Result onMatch = match == null ? Result.DENY : match;
Result onMismatch = mismatch == null ? Result.NEUTRAL : mismatch;
return new MCRUniqueFilter(cacheSizePerFormat, onMatch, onMismatch);
}
}
| 3,005 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProperties.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRProperties.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import org.apache.logging.log4j.LogManager;
/**
* Like {@link Properties} but with in-place replacement of properties that want to append a value.
*
* Properties for System.getProperties() have always precedence for Properties defined here.
*
* <pre>
* key=value1
* key=%key%,value2
* </pre>
*
* will be resolved to
*
* <pre>
* key=value1,value2
* </pre>
*
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
public class MCRProperties extends Properties {
private static final long serialVersionUID = 8801587133852810123L;
@Override
public synchronized Object put(Object key, Object value) {
return putString((String) key, (String) value);
}
private Object putString(String key, String value) {
String systemProperty = System.getProperties().getProperty(key);
if (systemProperty != null && !systemProperty.equals(value)) {
LogManager.getLogger(getClass()).error("Cannot overwrite system property: {}={}", key, value);
return systemProperty;
}
String oldValue = (String) super.get(key);
String newValue = oldValue == null ? value : value.replaceAll('%' + key + '%', oldValue);
if (!newValue.equals(value) && newValue.startsWith(",")) {
//replacement took place, but starts with 'empty' value
newValue = newValue.substring(1);
}
return super.put(key, newValue);
}
@Override
public synchronized Object get(Object key) {
String systemProperty = System.getProperties().getProperty((String) key);
return systemProperty != null ? systemProperty : super.get(key);
}
Map<String, String> getAsMap() {
@SuppressWarnings("rawtypes")
Map compileFix = this;
@SuppressWarnings("unchecked")
Map<String, String> returns = compileFix;
return returns;
}
/**
* Creates a new <code>MCRProperties</code> instance with the values
* of the given properties.
*/
public static MCRProperties copy(Properties properties) {
MCRProperties p = new MCRProperties();
p.putAll(properties);
return p;
}
@Override
public void store(OutputStream out, String comments) throws IOException {
toSortedProperties().store(out, comments);
}
@Override
public void store(Writer writer, String comments) throws IOException {
toSortedProperties().store(writer, comments);
}
@Override
public void storeToXML(OutputStream os, String comment, Charset charset) throws IOException {
toSortedProperties().storeToXML(os, comment, charset);
}
private Properties toSortedProperties() {
Properties sortedProps = new Properties() {
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
Set<Map.Entry<Object, Object>> sortedSet = new TreeSet<>(
Comparator.comparing(o -> o.getKey().toString()));
sortedSet.addAll(super.entrySet());
return sortedSet;
}
@Override
public Set<Object> keySet() {
return new TreeSet<>(super.keySet());
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<>(super.keySet()));
}
};
sortedProps.putAll(this);
return sortedProps;
}
}
| 4,540 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultConfigurationLoader.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRDefaultConfigurationLoader.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.io.input.TeeInputStream;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRFileContent;
import org.mycore.common.content.MCRStreamContent;
import org.mycore.common.content.MCRURLContent;
/**
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
public class MCRDefaultConfigurationLoader implements MCRConfigurationLoader {
MCRProperties properties, deprecated;
public MCRDefaultConfigurationLoader() {
properties = new MCRProperties();
try (InputStream in = getConfigInputStream()) {
loadFromContent(new MCRStreamContent(in));
} catch (IOException e) {
throw new MCRConfigurationException("Could not load MyCoRe properties.", e);
}
deprecated = new MCRProperties();
try (InputStream in = getDeprecatedConfigInputStream()) {
deprecated.load(in);
} catch (IOException e) {
throw new MCRConfigurationException("Could not load deprecated MyCoRe properties.", e);
}
}
private InputStream getConfigInputStream() throws IOException {
MCRConfigurationInputStream configurationInputStream = MCRConfigurationInputStream
.getMyCoRePropertiesInstance();
File configFile = MCRConfigurationDir.getConfigFile("mycore.active.properties");
if (configFile != null) {
FileOutputStream fout = new FileOutputStream(configFile);
return new TeeInputStream(configurationInputStream, fout, true);
}
return configurationInputStream;
}
private InputStream getDeprecatedConfigInputStream() throws IOException {
MCRConfigurationInputStream deprecatedInputStream = new MCRConfigurationInputStream("deprecated.properties");
File configFile = MCRConfigurationDir.getConfigFile("deprecated.active.properties");
if (configFile != null) {
FileOutputStream fout = new FileOutputStream(configFile);
return new TeeInputStream(deprecatedInputStream, fout, true);
}
return deprecatedInputStream;
}
@Override
public Map<String, String> load() {
return properties.getAsMap();
}
@Override
public Map<String, String> loadDeprecated() {
return deprecated.getAsMap();
}
/**
* Loads configuration properties from a specified properties file and adds
* them to the properties currently set. This method scans the <CODE>
* CLASSPATH</CODE> for the properties file, it may be a plain file, but
* may also be located in a zip or jar file. If the properties file contains
* a property called <CODE>MCR.Configuration.Include</CODE>, the files
* specified in that property will also be read. Multiple include files have
* to be separated by spaces or colons.
*
* @param filename
* the properties file to be loaded
* @throws MCRConfigurationException
* if the file can not be loaded
*/
private void loadFromFile(String filename) {
File mycoreProperties = new File(filename);
MCRContent input = null;
try {
if (mycoreProperties.canRead()) {
input = new MCRFileContent(mycoreProperties);
} else {
URL url = this.getClass().getResource("/" + filename);
if (url == null) {
throw new MCRConfigurationException("Could not find file or resource:" + filename);
}
input = new MCRURLContent(url);
}
loadFromContent(input);
} catch (IOException e) {
String name = input == null ? filename : input.getSystemId();
throw new MCRConfigurationException("Could not load configuration from: " + name, e);
}
}
private void loadFromContent(MCRContent input) throws IOException {
try (InputStream in = input.getInputStream()) {
properties.load(in);
}
String include = properties.getProperty("MCR.Configuration.Include", null);
if (include != null) {
StringTokenizer st = new StringTokenizer(include, ", ");
properties.remove("MCR.Configuration.Include");
while (st.hasMoreTokens()) {
loadFromFile(st.nextToken());
}
}
}
}
| 5,326 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import org.mycore.common.MCRException;
/**
* Instances of this class represent an exception thrown because of an error in the MyCoRe configuration. Normally this
* will be the case when a configuration property that is required is not set or has an illegal value.
*
* @author Jens Kupferschmidt
* @author Frank Lützenkirchen
*/
public class MCRConfigurationException extends MCRException {
private static final long serialVersionUID = 1L;
/**
* Creates a new MCRConfigurationException with an error message
*
* @param message
* the error message for this exception
*/
public MCRConfigurationException(String message) {
super(message);
}
/**
* Creates a new MCRConfigurationException with an error message and a reference to an exception thrown by an
* underlying system.
*
* @param message
* the error message for this exception
* @param cause
* the exception that was thrown by an underlying system
*/
public MCRConfigurationException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,916 | 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-base/src/main/java/org/mycore/common/config/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/>.
*/
/**
* Holds classes that handling configuration and initialization tasks.
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
package org.mycore.common.config;
| 895 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
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.common.MCRPropertiesResolver;
public final class MCRConfigurationBase {
static final Pattern PROPERTY_SPLITTER = Pattern.compile(",");
/**
* The properties instance that stores the values that have been read from every configuration file. These
* properties are unresolved
*/
private static MCRProperties baseProperties = new MCRProperties();
/**
* The same as baseProperties but all %properties% are resolved.
*/
private static MCRProperties resolvedProperties = new MCRProperties();
/**
* List of deprecated properties with their new name
*/
private static MCRProperties deprecatedProperties = new MCRProperties();
private static File lastModifiedFile;
static {
try {
createLastModifiedFile();
} catch (IOException e) {
throw new MCRConfigurationException("Could not initialize MyCoRe configuration", e);
}
}
private MCRConfigurationBase() {
}
/**
* returns the last point in time when the MyCoRe system was last modified. This method can help you to validate
* caches not under your controll, e.g. client caches.
*
* @see System#currentTimeMillis()
*/
public static long getSystemLastModified() {
return lastModifiedFile.lastModified();
}
/**
* signalize that the system state has changed. Call this method when ever you changed the persistency layer.
*/
public static void systemModified() {
try {
if (!lastModifiedFile.exists()) {
createLastModifiedFile();
} else {
Files.setLastModifiedTime(lastModifiedFile.toPath(), FileTime.from(Instant.now()));
}
} catch (IOException ioException) {
throw new MCRException("Could not change modify date of file " + lastModifiedFile.getAbsolutePath(),
ioException);
}
}
/**
* Creates a new .systemTime file in MCR.datadir.
*/
private static synchronized void createLastModifiedFile() throws IOException {
final String dataDirKey = "MCR.datadir";
if (getResolvedProperties().containsKey(dataDirKey)) {
Optional<File> dataDir = getString(dataDirKey)
.map(File::new);
if (dataDir.filter(File::exists)
.filter(File::isDirectory).isPresent()) {
lastModifiedFile = dataDir.map(p -> new File(p, ".systemTime")).get();
} else {
dataDir
.ifPresent(d -> System.err.println("WARNING: MCR.dataDir does not exist: " + d.getAbsolutePath()));
}
}
if (lastModifiedFile == null) {
try {
lastModifiedFile = File.createTempFile("MyCoRe", ".systemTime");
lastModifiedFile.deleteOnExit();
} catch (IOException e) {
throw new MCRException("Could not create temporary file, please set property MCR.datadir");
}
}
if (!lastModifiedFile.exists()) {
try (FileOutputStream fout = new FileOutputStream(lastModifiedFile)) {
fout.write(new byte[0]);
}
//allow other users to change this file
lastModifiedFile.setWritable(true, false);
}
}
private static void debug() {
String comments = "Active mycore properties";
File resolvedPropertiesFile = MCRConfigurationDir.getConfigFile("mycore.resolved.properties");
if (resolvedPropertiesFile != null) {
try (FileOutputStream fout = new FileOutputStream(resolvedPropertiesFile)) {
getResolvedProperties().store(fout, comments + "\nDo NOT edit this file!");
} catch (IOException e) {
LogManager.getLogger()
.warn("Could not store resolved properties to {}", resolvedPropertiesFile.getAbsolutePath(),
e);
}
}
Logger logger = LogManager.getLogger();
if (logger.isDebugEnabled()) {
try (StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw)) {
getResolvedProperties().store(out, comments);
out.flush();
sw.flush();
logger.debug(sw.toString());
} catch (IOException e) {
logger.debug("Error while debugging mycore properties.", e);
}
}
}
/**
* Substitute all %properties%.
*/
protected static synchronized void resolveProperties() {
MCRProperties tmpProperties = MCRProperties.copy(getBaseProperties());
MCRPropertiesResolver resolver = new MCRPropertiesResolver(tmpProperties);
resolvedProperties = MCRProperties.copy(resolver.resolveAll(tmpProperties));
}
private static void checkForDeprecatedProperties(Map<String, String> props) {
Map<String, String> depUsedProps = props.entrySet().stream()
.filter(e -> getDeprecatedProperties().containsKey(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, e -> getDeprecatedProperties().getAsMap().get(e.getKey())));
if (!depUsedProps.isEmpty()) {
throw new MCRConfigurationException(
depUsedProps.entrySet().stream().map(e -> e.getKey() + " ==> " + e.getValue())
.collect(Collectors.joining("\n",
"Found deprecated properties that are defined but will NOT BE USED. "
+ "Please use the replacements:\n",
"\n")));
}
}
private static void checkForDeprecatedProperty(String name) throws MCRConfigurationException {
if (getDeprecatedProperties().containsKey(name)) {
throw new MCRConfigurationException("Cannot set deprecated property " + name + ". Please use "
+ getDeprecatedProperties().getProperty(name) + " instead.");
}
}
protected static MCRProperties getResolvedProperties() {
return resolvedProperties;
}
protected static MCRProperties getBaseProperties() {
return baseProperties;
}
protected static MCRProperties getDeprecatedProperties() {
return deprecatedProperties;
}
/**
* Returns the configuration property with the specified name as a String.
*
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as a String
* @throws MCRConfigurationException
* if the properties are not initialized
*/
public static Optional<String> getString(String name) {
if (Objects.requireNonNull(name, "MyCoRe property name must not be null.").trim().isEmpty()) {
throw new MCRConfigurationException("MyCoRe property name must not be empty.");
}
if (!name.trim().equals(name)) {
throw new MCRConfigurationException(
"MyCoRe property name must not contain trailing or leading whitespaces: '" + name + "'");
}
if (getBaseProperties().isEmpty()) {
throw new MCRConfigurationException("MCRConfiguration is still not initialized");
}
return getStringUnchecked(name);
}
static Optional<String> getStringUnchecked(String name) {
checkForDeprecatedProperty(name);
return Optional.ofNullable(getResolvedProperties().getProperty(name, null));
}
/**
* Sets the configuration property with the specified name to a new <CODE>
* String</CODE> value. If the parameter <CODE>value</CODE> is <CODE>
* null</CODE>, the property will be deleted.
*
* @param name
* the non-null and non-empty name of the configuration property
* @param value
* the new value of the configuration property, possibly <CODE>
* null</CODE>
*/
static void set(String name, String value) {
checkForDeprecatedProperty(name);
if (value == null) {
getBaseProperties().remove(name);
} else {
getBaseProperties().setProperty(name, value);
}
resolveProperties();
}
public static synchronized void initialize(Map<String, String> deprecated, Map<String, String> props,
boolean clear) {
if (clear) {
deprecatedProperties.clear();
}
deprecatedProperties.putAll(deprecated);
checkForDeprecatedProperties(props);
if (clear) {
getBaseProperties().clear();
} else {
getBaseProperties().entrySet()
.removeIf(e -> props.containsKey(e.getKey()) && props.get(e.getKey()) == null);
}
getBaseProperties().putAll(
props.entrySet()
.stream()
.filter(e -> e.getKey() != null)
.filter(e -> e.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
resolveProperties();
debug();
}
}
| 10,423 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationInputStream.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationInputStream.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRFileContent;
import org.mycore.common.content.MCRURLContent;
/**
* A InputStream from (preferably) property files. All available InputStreams are combined in this order:
* <ol>
* <li>mycore-base</li>
* <li>other mycore-components</li>
* <li>application modules</li>
* <li>installation specific files</li>
* </ol>
*
* @author Thomas Scheffler (yagee)
* @author Robert Stephan
* @since 2013.12
*/
public class MCRConfigurationInputStream extends InputStream {
private static final String MYCORE_PROPERTIES = "mycore.properties";
// latin1 for properties
private static final byte[] LINE_BREAK = System.getProperty("line.separator").getBytes(StandardCharsets.ISO_8859_1);
InputStream in;
private Enumeration<? extends InputStream> e;
private boolean empty;
/**
* Combined Stream of all config files named <code>filename</code> available via
* {@link MCRRuntimeComponentDetector#getAllComponents()}.
*
* @param filename
* , e.g. mycore.properties or messages_de.properties
*/
public MCRConfigurationInputStream(String filename) throws IOException {
this(filename, null);
}
private MCRConfigurationInputStream(String filename, InputStream initStream) throws IOException {
super();
this.empty = true;
this.e = getPropertyInputStreams(filename, initStream);
if (e.hasMoreElements()) {
nextStream();
}
}
/**
* {@link InputStream} that includes all properties from {@link MCRRuntimeComponentDetector#getAllComponents()} and
* <strong>mycore.properties</strong>. Use system property <code>MCR.Configuration.File</code> to configure
* alternative property file.
*
* @since 2014.04
*/
public static MCRConfigurationInputStream getMyCoRePropertiesInstance() throws IOException {
File configurationDirectory = MCRConfigurationDir.getConfigurationDirectory();
InputStream initStream = null;
if (configurationDirectory != null) {
LogManager.getLogger().info("Current configuration directory: {}",
configurationDirectory.getAbsolutePath());
// set MCR.basedir, is normally overwritten later
if (configurationDirectory.isDirectory()) {
initStream = getBaseDirInputStream(configurationDirectory);
}
}
return new MCRConfigurationInputStream(MYCORE_PROPERTIES, initStream);
}
public boolean isEmpty() {
return empty;
}
private Enumeration<? extends InputStream> getPropertyInputStreams(String filename, InputStream initStream)
throws IOException {
List<InputStream> cList = new ArrayList<>();
if (initStream != null) {
empty = false;
cList.add(initStream);
}
for (MCRComponent component : MCRRuntimeComponentDetector.getAllComponents()) {
InputStream is = component.getConfigFileStream(filename);
if (is != null) {
empty = false;
String comment = "\n\n#\n#\n# Component: " + component.getName() + "\n#\n#\n";
cList.add(new ByteArrayInputStream(comment.getBytes(StandardCharsets.ISO_8859_1)));
cList.add(is);
//workaround if last property is not terminated with line break
cList.add(new ByteArrayInputStream(LINE_BREAK));
} else {
cList.add(new ByteArrayInputStream(
("# Unable to find " + filename + " in " + component.getResourceBase() + "\n")
.getBytes(StandardCharsets.ISO_8859_1)));
}
}
InputStream propertyStream = getConfigFileStream(filename);
if (propertyStream != null) {
empty = false;
cList.add(propertyStream);
cList.add(new ByteArrayInputStream(LINE_BREAK));
}
File localProperties = MCRConfigurationDir.getConfigFile(filename);
if (localProperties != null && localProperties.canRead()) {
empty = false;
LogManager.getLogger().info("Loading additional properties from {}", localProperties.getAbsolutePath());
cList.add(new FileInputStream(localProperties));
cList.add(new ByteArrayInputStream(LINE_BREAK));
}
return Collections.enumeration(cList);
}
private static ByteArrayInputStream getBaseDirInputStream(File configurationDirectory) throws IOException {
Properties dataProp = new Properties();
//On Windows we require forward slashes
dataProp.setProperty("MCR.basedir", configurationDirectory.getAbsolutePath().replace('\\', '/'));
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
dataProp.store(out, null);
return new ByteArrayInputStream(out.toByteArray());
}
private static InputStream getConfigFileStream(String filename) throws IOException {
File cfgFile = new File(filename);
MCRContent input = null;
if (cfgFile.canRead()) {
input = new MCRFileContent(cfgFile);
} else {
URL url = MCRConfigurationInputStream.class.getClassLoader().getResource(filename);
if (url != null) {
input = new MCRURLContent(url);
}
}
return input == null ? null : input.getInputStream();
}
/**
* return an enumeration of input streams of configuration files
* found in MyCoRe components and modules, respecting the proper loading order
*/
public static LinkedHashMap<String, byte[]> getConfigFileContents(String filename) throws IOException {
LinkedHashMap<String, byte[]> map = new LinkedHashMap<>();
for (MCRComponent component : MCRRuntimeComponentDetector.getAllComponents()) {
try (InputStream is = component.getConfigFileStream(filename)) {
if (is != null) {
map.put(component.getName(), is.readAllBytes());
}
}
}
// load config file from classpath
try (InputStream configStream = MCRConfigurationInputStream.getConfigFileStream(filename)) {
if (configStream != null) {
LogManager.getLogger().debug("Loaded config file from classpath: " + filename);
map.put("classpath_" + filename, configStream.readAllBytes());
}
}
//load config file from app config dir
File localConfigFile = MCRConfigurationDir.getConfigFile(filename);
if (localConfigFile != null && localConfigFile.canRead()) {
LogManager.getLogger().debug("Loaded config file from config dir: " + filename);
try (FileInputStream fis = new FileInputStream(localConfigFile)) {
map.put("configdir_" + filename, fis.readAllBytes());
}
}
return map;
}
/**
* Continues reading in the next stream if an EOF is reached.
*/
final void nextStream() throws IOException {
if (in != null) {
in.close();
}
if (e.hasMoreElements()) {
in = e.nextElement();
if (in == null) {
throw new NullPointerException();
}
} else {
in = null;
}
}
@Override
public int available() throws IOException {
if (in == null) {
return 0; // no way to signal EOF from available()
}
return in.available();
}
@Override
public int read() throws IOException {
if (in == null) {
return -1;
}
int c = in.read();
if (c == -1) {
nextStream();
return read();
}
return c;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (in == null) {
return -1;
}
int n = in.read(b, off, len);
if (n <= 0) {
nextStream();
return read(b, off, len);
}
return n;
}
@Override
public void close() throws IOException {
do {
nextStream();
} while (in != null);
}
}
| 9,566 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstanceName.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRInstanceName.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Represents a property name that can be used to convey the class name of a class that should be instantiated.
*/
public class MCRInstanceName {
private final String actual;
private final String canonical;
private final Suffix suffix;
private MCRInstanceName(String canonical, Suffix suffix) {
this.actual = suffix.appendTo(canonical);
this.canonical = canonical;
this.suffix = suffix;
}
/**
* Creates a {@link MCRInstanceName} given a <em>name</em>.
* <p>
* If the given <em>name</em> ends with <code>.Class</code> or <code>.class</code>, that suffix is removed from
* the {@link MCRInstanceName#canonical()} form and made available as the {@link MCRInstanceName#suffix()}.
* <p>
* In such a case, both <code>Class</code> and <code>class</code> are reported as
* {@link MCRInstanceName#ignoredKeys()} that should not be included in the
* {@link MCRInstanceConfiguration#properties()} of an {@link MCRInstanceConfiguration} using the created
* {@link MCRInstanceName}.
*
* @param name the name
* @return the name
*/
public static MCRInstanceName of(String name) {
int index = name.lastIndexOf(".");
if (index == -1) {
return of(name, "", name);
} else {
return of(name, name.substring(0, index), name.substring(index + 1));
}
}
private static MCRInstanceName of(String fullName, String leadingSegments, String lastSegment) {
for (Suffix suffix : Suffix.representedValues()) {
if (Objects.equals(lastSegment, suffix.representation)) {
return new MCRInstanceName(leadingSegments, suffix);
}
}
return new MCRInstanceName(fullName, Suffix.NONE);
}
public String actual() {
return actual;
}
public String canonical() {
return canonical;
}
public Suffix suffix() {
return suffix;
}
public List<String> ignoredKeys() {
return suffix.ignoredKeys;
}
public MCRInstanceName subName(String segment) {
if (canonical.isEmpty()) {
return new MCRInstanceName(segment, suffix);
} else {
return new MCRInstanceName(canonical + "." + segment, suffix);
}
}
@Override
public String toString() {
return "MCRInstanceName {" +
"actual=" + actual + ", " +
"canonical=" + canonical + ", " +
"suffix=" + suffix + "}";
}
public enum Suffix {
NONE(null, Collections.emptyList()),
UPPER_CASE("Class", Arrays.asList("Class", "class")),
LOWER_CASE("class", Arrays.asList("Class", "class"));
private static final Suffix[] REPRESENTED_VALUES = Arrays.stream(values())
.filter(suffix -> suffix.representation != null)
.collect(Collectors.toList())
.toArray(new Suffix[0]);
private final String representation;
private final List<String> ignoredKeys;
Suffix(String representation, List<String> ignoredKeys) {
this.representation = representation;
this.ignoredKeys = ignoredKeys;
}
public Optional<String> representation() {
return Optional.ofNullable(representation);
}
public static Suffix[] representedValues() {
return REPRESENTED_VALUES;
}
public String appendTo(String string) {
if (representation == null) {
return string;
} else {
if (string.isEmpty()) {
return representation;
} else {
return string + "." + representation;
}
}
}
}
}
| 4,737 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationDir.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationDir.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRDeveloperTools;
import org.mycore.common.MCRUtils;
import jakarta.servlet.ServletContext;
/**
* This helper class determines in which directory to look for addition configuration files.
*
* The configuration directory can be set with the system property or environment variable <code>MCR.ConfigDir</code>.
*
* The directory path is build this way:
* <ol>
* <li>System property <code>MCR.Home</code> defined
* <ol>
* <li><code>System.getProperty("MCR.Home")</code></li>
* <li><code>{prefix+'-'}{appName}</code></li>
* </ol>
* </li>
* <li>Windows:
* <ol>
* <li><code>%LOCALAPPDATA%</code></li>
* <li>MyCoRe</li>
* <li><code>{prefix+'-'}{appName}</code></li>
* </ol>
* </li>
* <li>other systems
* <ol>
* <li><code>$HOME</code></li>
* <li>.mycore</li>
* <li><code>{prefix+'-'}{appName}</code></li>
* </ol>
* </li>
* </ol>
*
* <code>{prefix}</code> can be defined by setting System property <code>MCR.DataPrefix</code>.
* <code>{appName}</code> is always lowercase String determined using this
* <ol>
* <li>System property <code>MCR.AppName</code></li>
* <li>System property <code>MCR.NameOfProject</code></li>
* <li>Servlet Context Init Parameter <code>appName</code>
* <li>Servlet Context Path (if not root context, {@link ServletContext#getContextPath()})</li>
* <li>Servlet Context Name ({@link ServletContext#getServletContextName()}) with space characters removed</li>
* <li>base name of jar including this class</li>
* <li>the String <code>"default"</code></li>
* </ol>
*
* @author Thomas Scheffler (yagee)
* @see System#getProperties()
* @since 2013.12
*/
public class MCRConfigurationDir {
public static final String DISABLE_CONFIG_DIR_PROPERTY = "MCR.DisableConfigDir";
public static final String CONFIGURATION_DIRECTORY_PROPERTY = "MCR.ConfigDir";
private static ServletContext SERVLET_CONTEXT = null;
private static String APP_NAME = null;
private static File getMyCoReDirectory() {
String mcrHome = System.getProperty("MCR.Home");
if (mcrHome != null) {
return new File(mcrHome);
}
//Windows Vista onwards:
String localAppData = isWindows() ? System.getenv("LOCALAPPDATA") : null;
//on every other platform
String userDir = System.getProperty("user.home");
String parentDir = localAppData != null ? localAppData : userDir;
return new File(parentDir, getConfigBaseName());
}
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows");
}
private static String getConfigBaseName() {
return isWindows() ? "MyCoRe" : ".mycore";
}
private static String getSource(Class<MCRConfigurationDir> clazz) {
if (clazz == null) {
return null;
}
ProtectionDomain protectionDomain = clazz.getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource == null) {
System.err.println("Cannot get CodeSource.");
return null;
}
URL location = codeSource.getLocation();
String fileName = location.getFile();
File sourceFile = new File(fileName);
return sourceFile.getName();
}
private static String getAppName() {
if (APP_NAME == null) {
APP_NAME = buildAppName();
}
return APP_NAME;
}
private static String buildAppName() {
String appName = System.getProperty("MCR.AppName");
if (appName != null) {
return appName;
}
String nameOfProject = System.getProperty("MCR.NameOfProject");
if (nameOfProject != null) {
return nameOfProject;
}
if (SERVLET_CONTEXT != null) {
String servletAppName = SERVLET_CONTEXT.getInitParameter("appName");
if (servletAppName != null && !servletAppName.isEmpty()) {
return servletAppName;
}
String contextPath = SERVLET_CONTEXT.getContextPath();
if (!contextPath.isEmpty()) {
return contextPath.substring(1);//remove leading '/'
}
String servletContextName = SERVLET_CONTEXT.getServletContextName();
if (servletContextName != null
&& !(servletContextName.trim().isEmpty() || servletContextName.contains("/"))) {
return servletContextName.replaceAll("\\s", "");
}
}
String sourceFileName = getSource(MCRConfigurationDir.class);
if (sourceFileName != null) {
int beginIndex = sourceFileName.lastIndexOf('.') - 1;
if (beginIndex > 0) {
sourceFileName = sourceFileName.substring(0, beginIndex);
}
return sourceFileName.replaceAll("-\\d.*", "");//strips version
}
return "default";
}
private static String getPrefix() {
String dataPrefix = System.getProperty("MCR.DataPrefix");
return dataPrefix == null ? "" : dataPrefix + "-";
}
static void setServletContext(ServletContext servletContext) {
SERVLET_CONTEXT = servletContext;
APP_NAME = null;
}
/**
* Returns the configuration directory for this MyCoRe instance.
* @return null if System property {@value #DISABLE_CONFIG_DIR_PROPERTY} is set.
*/
public static File getConfigurationDirectory() {
if (System.getProperties().containsKey(CONFIGURATION_DIRECTORY_PROPERTY)) {
return new File(System.getProperties().getProperty(CONFIGURATION_DIRECTORY_PROPERTY));
}
if (System.getenv().containsKey(CONFIGURATION_DIRECTORY_PROPERTY)) {
return new File(System.getenv(CONFIGURATION_DIRECTORY_PROPERTY));
}
if (!System.getProperties().containsKey(DISABLE_CONFIG_DIR_PROPERTY)) {
return new File(getMyCoReDirectory(), getPrefix() + getAppName());
}
return null;
}
/**
* Returns a File object, if {@link #getConfigurationDirectory()} does not return <code>null</code>
* and directory exists.
* @param relativePath relative path to file or directory with configuration directory as base.
* @return null if configuration directory does not exist or is disabled.
*/
public static File getConfigFile(String relativePath) {
File configurationDirectory = getConfigurationDirectory();
if (configurationDirectory == null || !configurationDirectory.isDirectory()) {
return null;
}
return MCRUtils.safeResolve(configurationDirectory.toPath(), relativePath).toFile();
}
/**
* Returns URL of a config resource.
* Same as {@link #getConfigResource(String, ClassLoader)} with second argument <code>null</code>.
* @param relativePath as defined in {@link #getConfigFile(String)}
*/
public static URL getConfigResource(String relativePath) {
return getConfigResource(relativePath, null);
}
/**
* Returns URL of a config resource.
* If {@link #getConfigFile(String)} returns an existing file for "resources"+{relativePath}, its URL is returned.
* In any other case this method returns the same as {@link ClassLoader#getResource(String)}
* @param relativePath as defined in {@link #getConfigFile(String)}
* @param classLoader a classLoader to resolve the resource (see above), null defaults to this class' class loader
*/
public static URL getConfigResource(String relativePath, ClassLoader classLoader) {
if (MCRDeveloperTools.overrideActive()) {
final Optional<Path> overriddenFilePath = MCRDeveloperTools.getOverriddenFilePath(relativePath, false);
if (overriddenFilePath.isPresent()) {
try {
return overriddenFilePath.get().toUri().toURL();
} catch (MalformedURLException e) {
// Ignore
}
}
}
File resolvedFile = getConfigFile("resources/" + relativePath);
if (resolvedFile != null && resolvedFile.exists()) {
try {
return resolvedFile.toURI().toURL();
} catch (MalformedURLException e) {
LogManager.getLogger(MCRConfigurationDir.class)
.warn("Exception while returning URL for file: {}", resolvedFile, e);
}
}
return getClassPathResource(relativePath, classLoader == null ? MCRClassTools.getClassLoader() : classLoader);
}
private static URL getClassPathResource(String relativePath, ClassLoader classLoader) {
URL currentUrl = classLoader.getResource(relativePath);
if (SERVLET_CONTEXT != null && currentUrl != null) {
Enumeration<URL> resources = null;
try {
resources = classLoader.getResources(relativePath);
} catch (IOException e) {
LogManager.getLogger(MCRConfigurationDir.class)
.error("Error while retrieving resource: {}", relativePath, e);
}
if (resources != null) {
File configDir = getConfigurationDirectory();
String configDirURL = configDir.toURI().toString();
@SuppressWarnings("unchecked")
List<String> libsOrder = (List<String>) SERVLET_CONTEXT.getAttribute(ServletContext.ORDERED_LIBS);
int pos = Integer.MAX_VALUE;
while (resources.hasMoreElements()) {
URL testURL = resources.nextElement();
String testURLStr = testURL.toString();
if (testURLStr.contains(configDirURL)) {
return testURL; //configuration directory always wins
}
if (testURLStr.startsWith("file:")) {
//local files should generally win
pos = -1;
currentUrl = testURL;
}
if (pos > 0 && libsOrder != null /*if <absolute-ordering> present in web.xml */) {
for (int i = 0; i < libsOrder.size(); i++) {
if (testURLStr.contains(libsOrder.get(i)) && i < pos) {
currentUrl = testURL;
pos = i;
}
}
}
}
}
}
return currentUrl;
}
}
| 11,868 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationDirSetup.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationDirSetup.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.File;
import java.lang.reflect.InaccessibleObjectException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.web.Log4jServletContainerInitializer;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.events.MCRStartupHandler;
import org.mycore.common.events.MCRStartupHandler.AutoExecutable;
import org.mycore.common.log4j2.MCRSessionThreadContext;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
/**
* Called by {@link MCRStartupHandler} on start up to setup {@link MCRConfiguration2}.
*
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
public class MCRConfigurationDirSetup implements AutoExecutable {
private static final StatusLogger LOGGER = StatusLogger.getLogger();
public static void loadExternalLibs() {
File resourceDir = MCRConfigurationDir.getConfigFile("resources");
if (resourceDir == null) {
//no configuration dir exists
return;
}
Optional<URLClassLoader> classLoaderOptional = Stream
.of(MCRClassTools.getClassLoader(), Thread.currentThread().getContextClassLoader())
.filter(URLClassLoader.class::isInstance)
.map(URLClassLoader.class::cast)
.findFirst();
if (classLoaderOptional.isEmpty()) {
System.err
.println(classLoaderOptional.getClass() + " is unsupported for adding extending CLASSPATH at runtime.");
return;
}
File libDir = MCRConfigurationDir.getConfigFile("lib");
URLClassLoader urlClassLoader = classLoaderOptional.get();
Set<URL> currentCPElements = Stream.of(urlClassLoader.getURLs()).collect(Collectors.toSet());
try {
Class<? extends ClassLoader> classLoaderClass = urlClassLoader.getClass();
BiConsumer<ClassLoader, URL> addUrlMethod = addToClassPath(classLoaderClass);
getFileStream(resourceDir, libDir)
.filter(Objects::nonNull)
.map(File::toURI)
.map(u -> {
try {
return u.toURL();
} catch (Exception e) {
// should never happen for "file://" URIS
return null;
}
})
.filter(Objects::nonNull)
.filter(u -> !currentCPElements.contains(u))
.peek(u -> System.out.println("Adding to CLASSPATH: " + u))
.forEach(url -> addUrlMethod.accept(urlClassLoader, url));
} catch (InaccessibleObjectException | ReflectiveOperationException | SecurityException e) {
LogManager.getLogger(MCRConfigurationInputStream.class)
.warn("{} does not support adding additional JARs at runtime", urlClassLoader.getClass(), e);
}
}
/**
* Returns a BiConsumer that adds a URL to the classpath of a ClassLoader instance of <code>classLoaderClass</code>.
*/
private static BiConsumer<ClassLoader, URL> addToClassPath(Class<? extends ClassLoader> classLoaderClass)
throws NoSuchMethodException {
Method method;
Function<URL, ?> argumentMapper;
final Method addURL = getDeclaredMethod(classLoaderClass, "addURL", URL.class);
//URLClassLoader does not allow to setAccessible(true) anymore in java >=16
if (addURL.trySetAccessible()) {
//works well in Tomcat
System.out.println("Using " + addURL + " to modify classpath.");
method = addURL;
argumentMapper = u -> u;
} else {
final Method jettyFallback = getDeclaredMethod(classLoaderClass, "addClassPath", String.class);
System.out.println("Using " + jettyFallback + " to modify classpath.");
argumentMapper = URL::toString;
method = jettyFallback;
}
Method finalMethod = method;
Function<URL, ?> finalArgumentMapper = argumentMapper;
return (cl, url) -> {
try {
finalMethod.invoke(cl, finalArgumentMapper.apply(url));
} catch (IllegalAccessException | InvocationTargetException e) {
LOGGER.error("Could not add {} to current classloader.", url, e);
}
};
}
private static Method getDeclaredMethod(Class<? extends ClassLoader> clazz, String method, Class... args)
throws NoSuchMethodException {
try {
return clazz.getDeclaredMethod(method, args);
} catch (NoSuchMethodException e) {
try {
if (ClassLoader.class.isAssignableFrom(clazz.getSuperclass())) {
return getDeclaredMethod((Class<? extends ClassLoader>) clazz.getSuperclass(), method, args);
}
} catch (NoSuchMethodException e2) {
throw e;
}
throw e;
}
}
private static Stream<File> getFileStream(File resourceDir, File libDir) {
Stream<File> toClassPath = Stream.of(resourceDir);
if (libDir.isDirectory()) {
File[] listFiles = libDir
.listFiles((dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(".jar"));
if (listFiles.length != 0) {
toClassPath = Stream.concat(toClassPath, Stream.of(listFiles));
}
}
return toClassPath;
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getName()
*/
@Override
public String getName() {
return "Setup of MCRConfigurationDir";
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#getPriority()
*/
@Override
public int getPriority() {
return Integer.MAX_VALUE - 100;
}
/* (non-Javadoc)
* @see org.mycore.common.events.MCRStartupHandler.AutoExecutable#startUp(jakarta.servlet.ServletContext)
*/
@Override
public void startUp(ServletContext servletContext) {
MCRConfigurationDir.setServletContext(servletContext);
loadExternalLibs();
MCRConfigurationLoader configurationLoader = MCRConfigurationLoaderFactory.getConfigurationLoader();
Map<String, String> properties = configurationLoader.load();
final Map<String, String> deprecated = configurationLoader.loadDeprecated();
MCRConfigurationBase.initialize(deprecated, properties, true);
if (servletContext != null) {
Log4jServletContainerInitializer log4jInitializer = new Log4jServletContainerInitializer();
try {
log4jInitializer.onStartup(null, servletContext);
} catch (ServletException e) {
System.err.println("Could not start Log4J2 context");
}
}
String configFileKey = "log4j.configurationFile";
URL log4j2ConfigURL = null;
if (System.getProperty(configFileKey) == null) {
log4j2ConfigURL = MCRConfigurationDir.getConfigResource("log4j2.xml");
}
LoggerContext logCtx;
if (log4j2ConfigURL == null) {
logCtx = (LoggerContext) LogManager.getContext(false);
} else {
logCtx = (LoggerContext) LogManager.getContext(null, false, URI.create(log4j2ConfigURL.toString()));
}
logCtx.reconfigure();
System.out.printf(Locale.ROOT, "Using Log4J2 configuration at: %s%n",
logCtx.getConfiguration().getConfigurationSource().getLocation());
MCRSessionMgr.addSessionListener(new MCRSessionThreadContext());
}
}
| 8,972 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConcurrentHashMap.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConcurrentHashMap.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.config.MCRConfiguration2.SingletonKey;
/**
* A collision resistant ConcurrentHashMap for use in {@link MCRConfiguration2}.
* The collision resistance during update only works with {@link SingletonKey}s
* during the {@link #computeIfAbsent(SingletonKey, Function)} operation.
* <p> This class is not serializable despite its inherited implementation of {@link java.io.Serializable}
* @author Tobias Lenhardt [Hammer1279]
*/
@SuppressWarnings("unchecked")
class MCRConcurrentHashMap<K extends SingletonKey, V> extends ConcurrentHashMap<K, V> {
private HashMap<K, RemappedKey> keyMap = new HashMap<>();
// Disable serialization
@SuppressWarnings("unused")
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
throw new NotSerializableException();
}
@SuppressWarnings("unused")
private void writeObject(ObjectOutputStream ois)
throws IOException {
throw new NotSerializableException();
}
/**
* {@link ConcurrentHashMap#computeIfAbsent(Object, Function)} with added collision resistance
* for {@link SingletonKey}s to allow changes to the map during computation.
* In case of collision, the key is automatically remapped via {@link RemappedKey}.
* It is a wrapper to modify the hashcode of the given SingletonKey to assign a different bucket
* within the internal table, in an attempt to resolve the collision.
*
* <p>The mapping function must not modify the map during computation of any key other then a {@link SingletonKey}
* @see java.util.concurrent.ConcurrentHashMap#computeIfAbsent(java.lang.Object, java.util.function.Function)
*/
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (keyMap.containsKey(key)) {
return super.computeIfAbsent((K) keyMap.get(key), mappingFunction);
} else {
try {
return super.computeIfAbsent(key, mappingFunction);
} catch (IllegalStateException e) { // recursive update fix
LogManager.getLogger().warn("collision detected, remapping key...");
RemappedKey newKey = new RemappedKey(key);
keyMap.put(key, newKey);
return tryCompute(key, newKey, mappingFunction);
}
}
}
private V tryCompute(K key, RemappedKey newKey, Function<? super K, ? extends V> mappingFunction) {
try {
return super.computeIfAbsent((K) newKey, mappingFunction);
} catch (IllegalStateException err) {
LogManager.getLogger().warn("collision while remapping, regenerating seed...");
keyMap.put(key, newKey.reGenSeed());
return tryCompute(key, newKey, mappingFunction);
}
}
@Override
public V get(Object key) {
return keyMap.containsKey(key) ? super.get(keyMap.get(key)) : super.get(key);
}
/**
* Wrapper for {@link ConfigSingletonKey} to modify the HashCode value.
*/
private class RemappedKey implements SingletonKey {
private K key;
private int seed;
RemappedKey(K key) {
this.key = key;
this.seed = ThreadLocalRandom.current().nextInt();
}
@Override
public int hashCode() {
return key.hashCode() ^ seed;
}
/**
* Generates a new Seed to get a different HashCode
* @return {@code this} for chaining
*/
public RemappedKey reGenSeed() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
int newSeed;
do {
newSeed = random.nextInt();
} while (newSeed == seed);
this.seed = newSeed;
return this;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof MCRConcurrentHashMap<?, ?>.RemappedKey that)
&& this.seed == that.seed
&& Objects.equals(this.key, that.key);
}
@Override
public String property() {
return key.property();
}
@Override
public String classname() {
return key.classname();
}
}
}
| 5,446 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurableInstanceHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurableInstanceHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.MCRClassTools;
import org.mycore.common.config.annotation.MCRConfigurationProxy;
import org.mycore.common.config.annotation.MCRInstance;
import org.mycore.common.config.annotation.MCRInstanceList;
import org.mycore.common.config.annotation.MCRInstanceMap;
import org.mycore.common.config.annotation.MCRPostConstruction;
import org.mycore.common.config.annotation.MCRProperty;
import jakarta.inject.Singleton;
/**
* Creates Objects which are configured with properties.
*
* @author Sebastian Hofmann
*/
class MCRConfigurableInstanceHelper {
private static final ConcurrentMap<Class<?>, ClassInfo<?>> INFOS = new ConcurrentHashMap<>();
/**
* Checks if a class is annotated with {@link Singleton}.
*
* @param property the configuration property which contains the class
* @return true if the class in the property is annotated with {@link Singleton}
*/
public static boolean isSingleton(String property) {
return MCRConfiguration2.getString(property).stream()
.anyMatch(propertyVal -> getClass(property, propertyVal).getDeclaredAnnotation(Singleton.class) != null);
}
/**
* Creates a configured instance of a class .
*
* @param name the property which contains the class name
* @return the configured instance of T
* @throws MCRConfigurationException if the property is not right configured.
*/
public static <T> Optional<T> getInstance(String name) throws MCRConfigurationException {
MCRInstanceConfiguration configuration = MCRInstanceConfiguration.ofName(name);
String className = configuration.className();
if (className == null || className.isBlank()) {
return Optional.empty();
}
return Optional.of(getInstance(configuration));
}
public static <T> T getInstance(MCRInstanceConfiguration configuration) throws MCRConfigurationException {
String className = configuration.className();
if (className == null || className.isBlank()) {
throw new MCRConfigurationException("Missing or empty property: " + configuration.name().actual());
}
Class<T> targetClass = getClass(configuration.name().actual(), configuration.className());
return getInstance(targetClass, configuration);
}
@SuppressWarnings("unchecked")
private static <T> Class<T> getClass(String property, String className) {
try {
return (Class<T>) MCRClassTools.forName(className);
} catch (ClassNotFoundException e) {
throw new MCRConfigurationException("Missing class (" + className + ") configured in property: "
+ property, e);
}
}
@SuppressWarnings("unchecked")
private static <T> T getInstance(Class<T> targetClass, MCRInstanceConfiguration configuration) {
MCRConfigurationProxy productAnnotation = targetClass.getDeclaredAnnotation(MCRConfigurationProxy.class);
if (productAnnotation != null) {
Class<Supplier<T>> proxyClass = (Class<Supplier<T>>) productAnnotation.proxyClass();
return getInfo(proxyClass).getInstance(configuration).get();
} else {
return getInfo(targetClass).getInstance(configuration);
}
}
@SuppressWarnings("unchecked")
private static <T> ClassInfo<T> getInfo(Class<T> targetClass) {
return (ClassInfo<T>) INFOS.computeIfAbsent(targetClass, ClassInfo::new);
}
private static String methodNames(List<Method> methods) {
return methods.stream()
.map(Method::getName)
.collect(Collectors.joining(", "));
}
private static String targetTypeName(Target<?> target) {
return target.type().name().toLowerCase(Locale.ROOT);
}
private static String annotationNames(List<Source<?, ?>> sources) {
return sources.stream().map(MCRConfigurableInstanceHelper::annotationName).collect(Collectors.joining(", "));
}
private static String annotationName(Source<?, ?> source) {
return source.annotationClass().getName();
}
/**
* A {@link ClassInfo} is a helper class that gathers and holds some information about a target class.
* <p>
* This class gathers the following information about the target class:
* <ul>
* <li>
* A {@link Supplier} as a factory for creating instances of the target class.
* That factory is
* <ol>
* <li>
* preferably the target classes parameterless public constructor or
* </li>
* <li>
* a parameterless public static factory method whose name case-insensitively contains
* the word "instance".
* </li>
* </ol>
* An exception is thrown if neither kind of factory exists or if no suitable constructor but
* multiple suitable factory methods exists.
* </li>
* <li>
* A list of {@link Injector} that are executed after an instance of the target class has been created.
* Each injector binds together a {@link Source} and a {@link Target}.
* <br/>
* Sources implement the varying strategies that create values from configuration properties.
* Source implementations exist for all supported annotations:
* <ol>
* <li>{@link MCRProperty}</li>
* <li>{@link MCRInstance}</li>
* <li>{@link MCRInstanceMap}</li>
* <li>{@link MCRInstanceList}</li>
* <li>{@link MCRPostConstruction}</li>
* </ol>
* Since {@link MCRProperty} produces (based on the value of {@link MCRProperty#name()}) different kinds
* of values ({@link String} or {@link Map}), two different source implementations ({@link PropertySource},
* {@link AllPropertiesSource}) exists for that annotation.
* <br/>
* Targets are:
* <ul>
* <li>public fields,</li>
* <li>public methods with no parameter or</li>
* <li>public methods with one parameter.</li>
* </ul>
* The list of injectors is created by
* <ol>
* <li>
* examining all possible fields and methods
* (as {@link Injectable}, in {@link ClassInfo#findInjectors(Class)}),
* </li>
* <li>
* checking, if such a target is annotated with a supported annotation
* (using {@link AnnotationMapper#injectableToSource(Injectable)}),
* </li>
* <li>
* creating a corresponding source for that annotation
* (using {@link AnnotationMapper#annotationToSource(Annotation)}) and
* </li>
* <li>
* creating a corresponding target for that injectable
* (using {@link Injectable#toTarget()}).
* </li>
* </ol>
* An exception is thrown if multiple sources are detected for the same target (for example, because a method is
* annotated with {@link MCRProperty} and {@link MCRPostConstruction}), if the target is not allowed for the
* detected source (for example, {@link MCRPostConstruction} is only allowed on methods) or if the values
* produced by the source are assignment-incompatible with the target (for example, values produced by a
* {@link InstanceSource} are not assignment-compatible with {@link String}) (as far as type erasure allows it
* to determine this preemptively).
* <br/>
* The list is ordered by the type of target (fields first), the source annotation (see list above)
* and lastly the order attribute of the source annotations (i.e. {@link MCRProperty#order()}).
* </li>
* </ul>
* <p>
* It is intended that instances of this class are cached, such that the information about the target class
* only needs to be gathered once.
*/
private static class ClassInfo<T> {
private final Class<T> targetClass;
private final Supplier<T> factory;
private final List<Injector<T, ?>> injectors;
private ClassInfo(Class<T> targetClass) {
this.targetClass = targetClass;
this.factory = getFactory(targetClass);
this.injectors = findInjectors(targetClass);
}
private Supplier<T> getFactory(Class<T> targetClass) {
try {
return createConstructorFactory(findDefaultConstructor(targetClass));
} catch (NoSuchMethodException e) {
return createFactoryMethodFactory(findFactoryMethod(targetClass));
}
}
private Constructor<T> findDefaultConstructor(Class<T> targetClass) throws NoSuchMethodException {
return targetClass.getConstructor();
}
private Supplier<T> createConstructorFactory(Constructor<T> constructor) {
return () -> {
try {
return constructor.newInstance();
} catch (Exception e) {
throw new MCRConfigurationException("Unable to create an instance of "
+ constructor.getDeclaringClass().getName() + " using parameterless public constructor", e);
}
};
}
private Method findFactoryMethod(Class<T> targetClass) {
List<Method> factoryMethods = Stream.of(targetClass.getMethods())
.filter(method -> Modifier.isPublic(method.getModifiers()))
.filter(method -> Modifier.isStatic(method.getModifiers()))
.filter(method -> method.getReturnType().isAssignableFrom(targetClass))
.filter(method -> method.getParameterTypes().length == 0)
.filter(method -> !method.isVarArgs())
.filter(method -> method.getName().toLowerCase(Locale.ROOT).contains("instance"))
.toList();
if (factoryMethods.isEmpty()) {
throw new MCRConfigurationException("Class " + targetClass.getName()
+ " has no public, parameterless constructor and no suitable"
+ " (public, static, matching return type, parameterless, name containing 'instance')"
+ " factory method");
}
if (factoryMethods.size() != 1) {
throw new MCRConfigurationException("Class " + targetClass.getName()
+ " has no public, parameterless constructor but multiple suitable"
+ " (public, static, matching return type, parameterless, name containing 'instance')"
+ " factory methods (" + methodNames(factoryMethods) + ")");
}
return factoryMethods.get(0);
}
@SuppressWarnings("unchecked")
private Supplier<T> createFactoryMethodFactory(Method method) {
return () -> {
try {
return (T) method.invoke(method.getDeclaringClass(), (Object[]) null);
} catch (Exception e) {
throw new MCRConfigurationException("Unable to create an instance of "
+ method.getDeclaringClass().getName() + " using public, parameterless constructor", e);
}
};
}
private List<Injector<T, ?>> findInjectors(Class<T> targetClass) {
List<Injector<T, ?>> injectors = new LinkedList<>();
for (Field field : targetClass.getFields()) {
findInjector(new FieldInjectable(field)).ifPresent(injectors::add);
}
for (Method method : targetClass.getMethods()) {
findInjector(new MethodInjectable(method)).ifPresent(injectors::add);
}
Collections.sort(injectors);
return injectors;
}
private Optional<Injector<T, ?>> findInjector(Injectable injectable) {
List<Source<?, ?>> sources = new LinkedList<>();
for (SourceType sourceType : SourceType.values()) {
sourceType.mapper.injectableToSource(injectable).ifPresent(sources::add);
}
if (sources.isEmpty()) {
return Optional.empty();
}
Target<T> target = injectable.toTarget();
if (sources.size() != 1) {
throw new MCRConfigurationException("Target " + targetTypeName(target) + " '"
+ target.name() + "' has multiple annotations (" + annotationNames(sources)
+ ") in configured class " + targetClass.getName());
}
Source<?, ?> source = sources.get(0);
if (!source.allowedTargetTypes().contains(target.type())) {
throw new MCRConfigurationException("Target " + targetTypeName(target) + " '"
+ target.name() + "' is not allowed for annotation (" + annotationName(source)
+ ") in configured class " + targetClass.getName());
}
if (!target.isAssignableFrom(source.valueClass())) {
throw new MCRConfigurationException("Target " + targetTypeName(target) + " '"
+ target.name() + "' has incompatible type for annotation (" + annotationName(source)
+ ") in configured class " + targetClass.getName());
}
return Optional.of(new Injector<>(target, source));
}
public T getInstance(MCRInstanceConfiguration configuration) {
T instance = factory.get();
for (Injector<T, ?> injector : injectors) {
injector.inject(instance, configuration);
}
return instance;
}
}
private static abstract class Injectable {
public abstract <A extends Annotation> Optional<A> annotation(Class<A> annotationClass);
public abstract <T> Target<T> toTarget();
}
private static final class FieldInjectable extends Injectable {
private final Field field;
private FieldInjectable(Field field) {
this.field = field;
}
@Override
public <A extends Annotation> Optional<A> annotation(Class<A> annotationClass) {
return Optional.ofNullable(field.getDeclaredAnnotation(annotationClass));
}
@Override
public <T> Target<T> toTarget() {
return new FieldTarget<>(field);
}
}
private static final class MethodInjectable extends Injectable {
private final Method method;
private MethodInjectable(Method method) {
this.method = method;
}
@Override
public <A extends Annotation> Optional<A> annotation(Class<A> annotationClass) {
return Optional.ofNullable(method.getDeclaredAnnotation(annotationClass));
}
@Override
public <T> Target<T> toTarget() {
int numberOfParameters = method.getParameterTypes().length;
return switch (numberOfParameters) {
case 0 -> new NoParameterMethodTarget<>(method);
case 1 -> new SingleParameterMethodTarget<>(method);
default -> throw new MCRConfigurationException("Target method '" + method.getName() +
"' has an unexpected number of parameters (" + numberOfParameters +
") in configured class " + method.getDeclaringClass().getName());
};
}
}
private enum TargetType {
FIELD(0),
METHOD(1);
public final int order;
TargetType(int order) {
this.order = order;
}
}
private static abstract class Target<T> {
public abstract TargetType type();
public abstract Class<? super T> declaringClass();
public abstract String name();
public abstract boolean isAssignableFrom(Class<?> valueClass);
public abstract void set(T instance, Object value);
}
private static final class FieldTarget<T> extends Target<T> {
private final Field field;
private FieldTarget(Field field) {
this.field = field;
}
@Override
public TargetType type() {
return TargetType.FIELD;
}
@Override
@SuppressWarnings("unchecked")
public Class<? super T> declaringClass() {
return (Class<? super T>) field.getDeclaringClass();
}
@Override
public String name() {
return field.getName();
}
@Override
public boolean isAssignableFrom(Class<?> valueClass) {
return valueClass.isAssignableFrom(field.getType());
}
@Override
public void set(T instance, Object value) {
try {
field.set(instance, value);
} catch (Exception e) {
throw new MCRConfigurationException("Failed to set target field '" + name() + "' to '" + value
+ "' in configurable class " + field.getDeclaringClass().getName(), e);
}
}
}
private static abstract class MethodTarget<T> extends Target<T> {
private final Method method;
private MethodTarget(Method method) {
this.method = method;
}
@Override
public final TargetType type() {
return TargetType.METHOD;
}
@Override
@SuppressWarnings("unchecked")
public Class<? super T> declaringClass() {
return (Class<? super T>) method.getDeclaringClass();
}
@Override
public final String name() {
return method.getName();
}
}
private static class NoParameterMethodTarget<T> extends MethodTarget<T> {
private final Method method;
private NoParameterMethodTarget(Method method) {
super(method);
this.method = method;
}
@Override
public boolean isAssignableFrom(Class<?> valueClass) {
return true;
}
@Override
public void set(T instance, Object value) {
try {
method.invoke(instance);
} catch (Exception e) {
throw new MCRConfigurationException("Failed to call target method '" + name()
+ "' in configurable class " + method.getDeclaringClass().getName(), e);
}
}
}
private static class SingleParameterMethodTarget<T> extends MethodTarget<T> {
private final Method method;
private SingleParameterMethodTarget(Method method) {
super(method);
this.method = method;
}
@Override
public boolean isAssignableFrom(Class<?> valueClass) {
return method.getParameterTypes()[0].isAssignableFrom(valueClass);
}
@Override
public void set(T instance, Object value) {
try {
method.invoke(instance, value);
} catch (Exception e) {
throw new MCRConfigurationException("Failed to call target method '" + name() + "' with '"
+ value + "' in configurable class " + method.getDeclaringClass().getName(), e);
}
}
}
private enum SourceType {
PROPERTY(0, new AnnotationMapper<MCRProperty>() {
@Override
public Class<MCRProperty> annotationClass() {
return MCRProperty.class;
}
@Override
public Source<MCRProperty, ?> annotationToSource(MCRProperty annotation) {
if (Objects.equals("*", annotation.name())) {
return new AllPropertiesSource(annotation);
} else {
return new PropertySource(annotation);
}
}
}),
INSTANCE(0, new AnnotationMapper<MCRInstance>() {
@Override
public Class<MCRInstance> annotationClass() {
return MCRInstance.class;
}
@Override
public Source<MCRInstance, ?> annotationToSource(MCRInstance annotation) {
return new InstanceSource(annotation);
}
}),
INSTANCE_MAP(0, new AnnotationMapper<MCRInstanceMap>() {
@Override
public Class<MCRInstanceMap> annotationClass() {
return MCRInstanceMap.class;
}
@Override
public Source<MCRInstanceMap, ?> annotationToSource(MCRInstanceMap annotation) {
return new InstanceMapSource(annotation);
}
}),
INSTANCE_LIST(0, new AnnotationMapper<MCRInstanceList>() {
@Override
public Class<MCRInstanceList> annotationClass() {
return MCRInstanceList.class;
}
@Override
public Source<MCRInstanceList, ?> annotationToSource(MCRInstanceList annotation) {
return new InstanceListSource(annotation);
}
}),
POST_CONSTRUCTION(1, new AnnotationMapper<MCRPostConstruction>() {
@Override
public Class<MCRPostConstruction> annotationClass() {
return MCRPostConstruction.class;
}
@Override
public Source<MCRPostConstruction, ?> annotationToSource(MCRPostConstruction annotation) {
return new PostConstructionSource(annotation);
}
});
public final int order;
public final AnnotationMapper<? extends Annotation> mapper;
SourceType(int order, AnnotationMapper<? extends Annotation> mapper) {
this.order = order;
this.mapper = mapper;
}
}
private abstract static class AnnotationMapper<A extends Annotation> {
public abstract Class<A> annotationClass();
public abstract Source<A, ?> annotationToSource(A annotation);
public Optional<Source<A, ?>> injectableToSource(Injectable injectable) {
return injectable.annotation(annotationClass()).map(this::annotationToSource);
}
}
private static abstract class Source<A extends Annotation, V> {
public abstract SourceType type();
public abstract Class<A> annotationClass();
public abstract A annotation();
public abstract int order();
public abstract Set<TargetType> allowedTargetTypes();
public abstract Class<?> valueClass();
public abstract V get(MCRInstanceConfiguration configuration, Target<?> target);
}
private static class PropertySource extends Source<MCRProperty, String> {
protected final MCRProperty annotation;
private PropertySource(MCRProperty annotation) {
this.annotation = annotation;
}
@Override
public final SourceType type() {
return SourceType.PROPERTY;
}
@Override
public Class<MCRProperty> annotationClass() {
return MCRProperty.class;
}
@Override
public MCRProperty annotation() {
return annotation;
}
@Override
public final int order() {
return annotation.order();
}
@Override
public Set<TargetType> allowedTargetTypes() {
return EnumSet.allOf(TargetType.class);
}
@Override
public Class<?> valueClass() {
return String.class;
}
@Override
public String get(MCRInstanceConfiguration configuration, Target<?> target) {
String value;
if (!annotation.absolute()) {
value = configuration.properties().get(annotation.name());
} else {
value = configuration.fullProperties().get(annotation.name());
}
if (value == null && !Objects.equals("", annotation.defaultName())) {
value = configuration.fullProperties().get(annotation.defaultName());
if (value == null) {
throw new MCRConfigurationException("The default property "
+ annotation.defaultName() + " is missing");
}
}
if (value == null && annotation.required()) {
throw new MCRConfigurationException("The required property "
+ configuration.name().canonical() + "."
+ annotation.name() + " is missing");
}
return value;
}
}
private static class AllPropertiesSource extends Source<MCRProperty, Map<String, String>> {
protected final MCRProperty annotation;
private AllPropertiesSource(MCRProperty annotation) {
this.annotation = annotation;
}
@Override
public final SourceType type() {
return SourceType.PROPERTY;
}
@Override
public Class<MCRProperty> annotationClass() {
return MCRProperty.class;
}
@Override
public MCRProperty annotation() {
return annotation;
}
@Override
public final int order() {
return annotation.order();
}
@Override
public Set<TargetType> allowedTargetTypes() {
return EnumSet.allOf(TargetType.class);
}
@Override
public Class<?> valueClass() {
return Map.class;
}
@Override
public Map<String, String> get(MCRInstanceConfiguration configuration, Target<?> target) {
if (!annotation.absolute()) {
return configuration.properties();
} else {
return configuration.fullProperties();
}
}
}
private static class InstanceSource extends Source<MCRInstance, Object> {
protected final MCRInstance annotation;
private InstanceSource(MCRInstance annotation) {
this.annotation = annotation;
}
@Override
public final SourceType type() {
return SourceType.INSTANCE;
}
@Override
public Class<MCRInstance> annotationClass() {
return MCRInstance.class;
}
@Override
public MCRInstance annotation() {
return annotation;
}
@Override
public final int order() {
return annotation.order();
}
@Override
public Set<TargetType> allowedTargetTypes() {
return EnumSet.allOf(TargetType.class);
}
@Override
public Class<?> valueClass() {
return annotation.valueClass();
}
@Override
public Object get(MCRInstanceConfiguration configuration, Target<?> target) {
MCRInstanceConfiguration nestedConfiguration = configuration.nestedConfiguration(annotation().name());
String nestedClassName = nestedConfiguration.className();
if (nestedClassName == null || nestedClassName.isBlank()) {
if (annotation.required()) {
throw new MCRConfigurationException("Missing or empty property: "
+ nestedConfiguration.name().actual());
} else {
return null;
}
}
Object instance = getInstance(nestedConfiguration);
if (!annotation.valueClass().isAssignableFrom(instance.getClass())) {
throw new MCRConfigurationException("Configured instance of class " + instance.getClass().getName()
+ " is incompatible with annotation value class " + annotation.valueClass().getName()
+ " for target " + targetTypeName(target) + " '" + target.name()
+ "' in configured class " + target.declaringClass().getName());
}
return instance;
}
}
private static class InstanceMapSource extends Source<MCRInstanceMap, Map<String, Object>> {
protected final MCRInstanceMap annotation;
private InstanceMapSource(MCRInstanceMap annotation) {
this.annotation = annotation;
}
@Override
public final SourceType type() {
return SourceType.INSTANCE_MAP;
}
@Override
public Class<MCRInstanceMap> annotationClass() {
return MCRInstanceMap.class;
}
@Override
public MCRInstanceMap annotation() {
return annotation;
}
@Override
public final int order() {
return annotation.order();
}
@Override
public Set<TargetType> allowedTargetTypes() {
return EnumSet.allOf(TargetType.class);
}
@Override
public Class<?> valueClass() {
return Map.class;
}
@Override
public Map<String, Object> get(MCRInstanceConfiguration configuration, Target<?> target) {
Map<String, MCRInstanceConfiguration> nestedConfigurationMap = nestedConfigurationMap(configuration);
if (nestedConfigurationMap.isEmpty() && annotation.required()) {
throw new MCRConfigurationException("Missing configuration entries like: "
+ getExampleName(configuration, "A") + ", "
+ getExampleName(configuration, "B") + ", ...");
}
Map<String, Object> instanceMap = nestedConfigurationMap.entrySet()
.stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> getInstance(entry.getValue())));
instanceMap.values().forEach(instance -> {
if (!annotation.valueClass().isAssignableFrom(instance.getClass())) {
throw new MCRConfigurationException("Configured instance of class " + instance.getClass().getName()
+ " is incompatible with annotation value class " + annotation.valueClass().getName()
+ " for target " + targetTypeName(target) + " '" + target.name()
+ "' in configured class " + target.declaringClass().getName());
}
});
return instanceMap;
}
private Map<String, MCRInstanceConfiguration> nestedConfigurationMap(MCRInstanceConfiguration configuration) {
if (Objects.equals("", annotation.name())) {
return configuration.nestedConfigurationMap();
} else {
return configuration.nestedConfigurationMap(annotation().name());
}
}
private String getExampleName(MCRInstanceConfiguration configuration, String example) {
if (Objects.equals("", annotation.name())) {
return configuration.name().subName(example).actual();
} else {
return configuration.name().subName(annotation.name() + "." + example).actual();
}
}
}
private static class InstanceListSource extends Source<MCRInstanceList, List<Object>> {
protected final MCRInstanceList annotation;
private InstanceListSource(MCRInstanceList annotation) {
this.annotation = annotation;
}
@Override
public final SourceType type() {
return SourceType.INSTANCE_LIST;
}
@Override
public Class<MCRInstanceList> annotationClass() {
return MCRInstanceList.class;
}
@Override
public MCRInstanceList annotation() {
return annotation;
}
@Override
public final int order() {
return annotation.order();
}
@Override
public Set<TargetType> allowedTargetTypes() {
return EnumSet.allOf(TargetType.class);
}
@Override
public Class<?> valueClass() {
return List.class;
}
@Override
public List<Object> get(MCRInstanceConfiguration configuration, Target<?> target) {
List<MCRInstanceConfiguration> nestedConfigurationList = nestededConfigurationList(configuration);
if (nestedConfigurationList.isEmpty() && annotation.required()) {
throw new MCRConfigurationException("Missing configuration entries like: "
+ getExampleName(configuration, "1") + ", "
+ getExampleName(configuration, "2") + ", ...");
}
List<Object> instanceList = nestedConfigurationList
.stream().map(MCRConfigurableInstanceHelper::getInstance).toList();
instanceList.forEach(instance -> {
if (!annotation.valueClass().isAssignableFrom(instance.getClass())) {
throw new MCRConfigurationException("Configured instance of class " + instance.getClass().getName()
+ " is incompatible with annotation value class " + annotation.valueClass().getName()
+ " for target " + targetTypeName(target) + " '" + target.name()
+ "' in configured class " + target.declaringClass().getName());
}
});
return instanceList;
}
private List<MCRInstanceConfiguration> nestededConfigurationList(MCRInstanceConfiguration configuration) {
if (Objects.equals("", annotation.name())) {
return configuration.nestedConfigurationList();
} else {
return configuration.nestedConfigurationList(annotation().name());
}
}
private String getExampleName(MCRInstanceConfiguration configuration, String example) {
if (Objects.equals("", annotation.name())) {
return configuration.name().subName(example).actual();
} else {
return configuration.name().subName(annotation.name() + "." + example).actual();
}
}
}
private static class PostConstructionSource extends Source<MCRPostConstruction, String> {
protected final MCRPostConstruction annotation;
private PostConstructionSource(MCRPostConstruction annotation) {
this.annotation = annotation;
}
@Override
public final SourceType type() {
return SourceType.POST_CONSTRUCTION;
}
@Override
public Class<MCRPostConstruction> annotationClass() {
return MCRPostConstruction.class;
}
@Override
public MCRPostConstruction annotation() {
return annotation;
}
@Override
public final int order() {
return annotation.order();
}
@Override
public Set<TargetType> allowedTargetTypes() {
return EnumSet.allOf(TargetType.class);
}
@Override
public Class<?> valueClass() {
return String.class;
}
@Override
public String get(MCRInstanceConfiguration configuration, Target<?> target) {
return configuration.name().actual();
}
}
private static final class Injector<T, A extends Annotation> implements Comparable<Injector<?, ?>> {
private static final Comparator<Injector<?, ?>> COMPARATOR = Comparator
.comparing((Function<Injector<?, ?>, Integer>) injector -> injector.target.type().order)
.thenComparing(injector -> injector.source.type().order)
.thenComparing(injector -> injector.source.order());
private final Target<T> target;
private final Source<A, ?> source;
private Injector(Target<T> target, Source<A, ?> source) {
this.target = target;
this.source = source;
}
public void inject(T instance, MCRInstanceConfiguration configuration) {
Object value = source.get(configuration, target);
if (value != null) {
target.set(instance, value);
}
}
@Override
public int compareTo(Injector<?, ?> other) {
return COMPARATOR.compare(this, other);
}
}
}
| 37,845 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRuntimeComponentDetector.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRRuntimeComponentDetector.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import com.google.common.collect.Sets;
/**
* On first access this class detects all components, that is either MyCoRe components or application modules, that are
* available via the current ClassLoader. Every {@link Manifest} of the jar file requires to have a main attribute "POM"
* and application modules also need to have a "MCR-Application-Module" main attribute present.
*
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
public class MCRRuntimeComponentDetector {
private static final Logger LOGGER = LogManager.getLogger();
private static final Name ATT_POM = new Name("POM");
private static final Name ATT_MCR_APPLICATION_MODULE = new Name("MCR-Application-Module");
private static final Name ATT_MCR_ARTIFACT_ID = new Name("MCR-Artifact-Id");
private static final SortedSet<MCRComponent> ALL_COMPONENTS_LOW_TO_HIGH
= Collections.unmodifiableSortedSet(getConfiguredComponents());
private static final SortedSet<MCRComponent> ALL_COMPONENTS_HIGH_TO_LOW = reverseOf(ALL_COMPONENTS_LOW_TO_HIGH);
private static final SortedSet<MCRComponent> MYCORE_COMPONENTS_LOW_TO_HIGH
= subsetOf(ALL_COMPONENTS_LOW_TO_HIGH, MCRComponent::isMyCoReComponent);
private static final SortedSet<MCRComponent> MYCORE_COMPONENTS_HIGH_TO_LOW
= reverseOf(MYCORE_COMPONENTS_LOW_TO_HIGH);
private static final SortedSet<MCRComponent> APP_MODULES_LOW_TO_HIGH
= subsetOf(ALL_COMPONENTS_LOW_TO_HIGH, MCRComponent::isAppModule);
private static final SortedSet<MCRComponent> APP_MODULES_HIGH_TO_LOW = reverseOf(APP_MODULES_LOW_TO_HIGH);
private static <T extends Comparable<T>> SortedSet<T> reverseOf(SortedSet<T> set) {
return Collections.unmodifiableSortedSet(
set.stream().collect(Collectors.toCollection(() -> new TreeSet<>(Collections.reverseOrder()))));
}
private static <T> SortedSet<T> subsetOf(SortedSet<T> set, Predicate<T> filter) {
return Collections.unmodifiableSortedSet(
set.stream().filter(filter).collect(Collectors.toCollection(TreeSet::new)));
}
private static SortedSet<MCRComponent> getConfiguredComponents() {
try {
String underTesting = System.getProperty("MCRRuntimeComponentDetector.underTesting");
Enumeration<URL> resources = MCRClassTools.getClassLoader().getResources("META-INF/MANIFEST.MF");
if (!resources.hasMoreElements() && underTesting == null) {
LOGGER.warn("Did not find any Manifests.");
return Collections.emptySortedSet();
}
SortedSet<MCRComponent> components = Sets.newTreeSet();
while (resources.hasMoreElements()) {
URL manifestURL = resources.nextElement();
try (InputStream manifestStream = manifestURL.openStream()) {
Manifest manifest = new Manifest(manifestStream);
MCRComponent component = buildComponent(manifest, manifestURL);
if (component != null) {
components.add(component);
}
}
}
if (underTesting != null) {
//support JUnit-Tests
MCRComponent component = new MCRComponent(underTesting, new Manifest());
components.add(component);
}
return components;
} catch (IOException e) {
LOGGER.warn("Error while detecting MyCoRe components", e);
return Sets.newTreeSet();
}
}
private static MCRComponent buildComponent(Manifest manifest, URL manifestURL) throws IOException {
Attributes mainAttributes = manifest.getMainAttributes();
String artifactId = mainAttributes.getValue(ATT_MCR_ARTIFACT_ID);
String pomPropertiesPath = mainAttributes.getValue(ATT_POM);
boolean usePomProperties = false;
if (artifactId == null) {
if (!mainAttributes.containsKey(ATT_POM)) {
return null;
}
if (pomPropertiesPath == null) {
return null;
}
try (InputStream pi = MCRClassTools.getClassLoader().getResourceAsStream(
pomPropertiesPath)) {
if (pi == null) {
LOGGER.warn("Manifest entry {} set to \"{}\", but resource could not be loaded.", ATT_POM,
pomPropertiesPath);
return null;
}
Properties pomProperties = new Properties();
pomProperties.load(pi);
artifactId = (String) pomProperties.get("artifactId");
usePomProperties = true;
}
}
if (artifactId != null && artifactId.startsWith("mycore-")
|| mainAttributes.containsKey(ATT_MCR_APPLICATION_MODULE)) {
if (usePomProperties) {
LOGGER.warn("No Attribute \"{}\" in Manifest of {}.", ATT_MCR_ARTIFACT_ID,
mainAttributes.getValue(ATT_MCR_APPLICATION_MODULE));
LOGGER.warn("Change this in the future, pom.properties path definition is deprecated.");
LOGGER.info("Using artifactId in {}.", pomPropertiesPath);
}
return new MCRComponent(artifactId, manifest, extractJarFile(manifestURL));
}
return null;
}
private static File extractJarFile(URL manifestURL) {
try {
if (manifestURL.toExternalForm().startsWith("jar:")) {
return new File(new URI(manifestURL.getPath().replaceAll("!.*$", "")));
}
} catch (URISyntaxException e) {
LOGGER.error("Couldn't extract jar file path from MANIFEST.MF url.", e);
}
return null;
}
/**
* Returns all components sorted via their natural ordering.
*
* @see MCRComponent#compareTo(MCRComponent)
*/
public static SortedSet<MCRComponent> getAllComponents() {
return ALL_COMPONENTS_LOW_TO_HIGH;
}
/**
* Returns all components sorted via the given order
*
* @param order The order, defaults to {@link ComponentOrder#LOWEST_PRIORITY_FIRST}
* @see MCRComponent#compareTo(MCRComponent)
*/
public static SortedSet<MCRComponent> getAllComponents(ComponentOrder order) {
return order == ComponentOrder.LOWEST_PRIORITY_FIRST ? ALL_COMPONENTS_LOW_TO_HIGH
: ALL_COMPONENTS_HIGH_TO_LOW;
}
/**
* Returns only mycore components sorted via their natural ordering.
*
* @see MCRComponent#compareTo(MCRComponent)
*/
public static SortedSet<MCRComponent> getMyCoReComponents() {
return MYCORE_COMPONENTS_LOW_TO_HIGH;
}
/**
* Returns only mycore components sorted via the given order.
*
* @param order The order, defaults to {@link ComponentOrder#LOWEST_PRIORITY_FIRST}
* @see MCRComponent#compareTo(MCRComponent)
*/
public static SortedSet<MCRComponent> getMyCoReComponents(ComponentOrder order) {
return order == ComponentOrder.LOWEST_PRIORITY_FIRST ? MYCORE_COMPONENTS_LOW_TO_HIGH
: MYCORE_COMPONENTS_HIGH_TO_LOW;
}
/**
* Returns only application modules sorted via their natural ordering.
*
* @see MCRComponent#compareTo(MCRComponent)
*/
public static SortedSet<MCRComponent> getApplicationModules() {
return APP_MODULES_LOW_TO_HIGH;
}
/**
* Returns only application modules sorted via the given order.
*
* @param order The order, defaults to {@link ComponentOrder#LOWEST_PRIORITY_FIRST}
* @see MCRComponent#compareTo(MCRComponent)
*/
public static SortedSet<MCRComponent> getApplicationModules(ComponentOrder order) {
return order == ComponentOrder.LOWEST_PRIORITY_FIRST ? APP_MODULES_LOW_TO_HIGH
: APP_MODULES_HIGH_TO_LOW;
}
public enum ComponentOrder {
LOWEST_PRIORITY_FIRST,
HIGHEST_PRIORITY_FIRST;
}
}
| 9,401 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationLoader.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationLoader.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.util.Map;
/**
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
public interface MCRConfigurationLoader {
/**
* Returns a Map that should be used with {@link MCRConfigurationBase#initialize(Map, Map, boolean)}
*/
Map<String, String> load();
/**
* Returns a Map that contains deprecated properties as keys and ther updated name as value
* @since 2020.06
*/
Map<String, String> loadDeprecated();
}
| 1,222 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRComponent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRComponent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Manifest;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.status.StatusLogger;
import org.mycore.common.MCRClassTools;
import org.mycore.common.MCRException;
/**
* This class abstracts different MyCoRe component types.
* As every component (mycore component, application module) holds it configuration in different places,
* you can use this class to get uniform access to these configuration resources.
*
* As this class is immutable it could be used as key in a {@link Map}
* @author Thomas Scheffler (yagee)
* @since 2013.12
* @see MCRRuntimeComponentDetector
*/
public class MCRComponent implements Comparable<MCRComponent> {
private static final Logger LOGGER = StatusLogger.getLogger();
private static final String ATT_PRIORITY = "Priority";
private static final NumberFormat PRIORITY_FORMAT = getPriorityFormat();
private static NumberFormat getPriorityFormat() {
NumberFormat format = NumberFormat.getIntegerInstance(Locale.ROOT);
format.setGroupingUsed(false);
format.setMinimumIntegerDigits(3);
return format;
}
private static final String DEFAULT_PRIORITY = "99";
private enum Type {
base, component, module
}
private Type type;
private String name;
private File jarFile;
private String sortCriteria;
private String artifactId;
private Manifest manifest;
public MCRComponent(String artifactId, Manifest manifest) {
this(artifactId, manifest, null);
}
public MCRComponent(String artifactId, Manifest manifest, File jarFile) {
if (artifactId.startsWith("mycore-")) {
if (artifactId.endsWith("base")) {
type = Type.base;
setName("base");
} else {
type = Type.component;
setName(artifactId.substring("mycore-".length()));
}
} else {
type = Type.module;
setName(artifactId.replaceAll("[_-]?module", ""));
}
setJarFile(jarFile);
this.artifactId = artifactId;
this.manifest = manifest;
buildSortCriteria();
LOGGER.debug("{} is of type {} and named {}: {}", artifactId, type, getName(), jarFile);
}
private void buildSortCriteria() {
String priorityAtt = manifest.getMainAttributes().getValue(ATT_PRIORITY);
if (priorityAtt == null) {
priorityAtt = DEFAULT_PRIORITY;
LOGGER.debug("{} has DEFAULT priority {}", artifactId, priorityAtt);
} else {
LOGGER.debug("{} has priority {}", artifactId, priorityAtt);
}
int priority = Integer.parseInt(priorityAtt);
if (priority > 99 || priority < 0) {
throw new MCRException(artifactId + " has unsupported priority: " + priority);
}
priority += switch (type) {
case base -> 100;
case component -> 200;
case module -> 300;
default -> throw new MCRException("Do not support MCRComponenty of type: " + type);
};
this.sortCriteria = PRIORITY_FORMAT.format(priority) + getName();
}
public InputStream getConfigFileStream(String filename) {
String resourceBase = getResourceBase();
if (resourceBase == null) {
return null;
}
String resourceName = resourceBase + filename;
InputStream resourceStream = MCRClassTools.getClassLoader().getResourceAsStream(resourceName);
if (resourceStream != null) {
LOGGER.info("Reading config resource: {}", resourceName);
}
return resourceStream;
}
public URL getConfigURL(String filename) {
String resourceBase = getResourceBase();
if (resourceBase == null) {
return null;
}
String resourceName = resourceBase + filename;
URL resourceURL = MCRClassTools.getClassLoader().getResource(resourceName);
if (resourceURL != null) {
LOGGER.info("Reading config resource: {}", resourceName);
}
return resourceURL;
}
/**
* Returns resource base path to this components config resources.
*/
public String getResourceBase() {
return switch (type) {
case base -> "config/";
case component -> "components/" + getName() + "/config/";
case module -> "config/" + getName() + "/";
default -> {
LOGGER.debug("{}: there is no resource base for type {}", getName(), type);
yield null;
}
};
}
/**
* Returns true, if this component is part of MyCoRe
*/
public boolean isMyCoReComponent() {
return type == Type.base || type == Type.component;
}
/**
* Returns true, if this component is application module
*/
public boolean isAppModule() {
return type == Type.module;
}
/**
* A short name for this component.
* E.g. mycore-base would return "base" here.
*/
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
/**
* Returns the jar file or <code>null</code> if nothing was set.
*
* @return the jar file
*/
public File getJarFile() {
return jarFile;
}
private void setJarFile(File jarFile) {
this.jarFile = jarFile;
}
/**
* Returns the mainfest main attribute value for given attribute name.
*
* @param name the attribute name
* @return the attribute value
*/
public String getManifestMainAttribute(String name) {
return manifest.getMainAttributes().getValue(name);
}
/**
* Compares this component to other component.
* Basic order is:
* <ol>
* <li>complete</li>
* <li>base</li>
* <li>component</li>
* <li>module</li>
* </ol>
* If more than one component is in one of these groups, they are sorted alphabetically via {@link #getName()}.
*/
@Override
public int compareTo(MCRComponent o) {
return this.sortCriteria.compareTo(o.sortCriteria);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MCRComponent other)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return type == other.type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
switch (type) {
case base, component -> sb.append("mcr:");
case module -> sb.append("app:");
default -> {
}
}
sb.append(artifactId);
return sb.toString();
}
}
| 8,244 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationLoaderFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfigurationLoaderFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
/**
* @author Thomas Scheffler (yagee)
* @since 2013.12
*/
public class MCRConfigurationLoaderFactory {
public static MCRConfigurationLoader getConfigurationLoader() {
return new MCRDefaultConfigurationLoader();
}
}
| 999 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfiguration2.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRConfiguration2.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.MCRClassTools;
import org.mycore.common.function.MCRTriConsumer;
/**
* Provides methods to manage and read all configuration properties from the MyCoRe configuration files.
* The Properties used by this class are used from {@link MCRConfigurationBase}.
* <h2>NOTE</h2>
* <p><strong>All {@link Optional} values returned by this class are {@link Optional#empty() empty} if the property
* is not set OR the trimmed value {@link String#isEmpty() is empty}. If you want to distinguish between
* empty properties and unset properties use {@link MCRConfigurationBase#getString(String)} instead.</strong>
* </p>
* <p>
* Using this class is very easy, here is an example:
* </p>
* <PRE>
* // Get a configuration property as a String:
* String sValue = MCRConfiguration2.getString("MCR.String.Value").orElse(defaultValue);
*
* // Get a configuration property as a List of String (values are seperated by ","):
* List<String> lValue = MCRConfiguration2.getString("MCR.StringList.Value").stream()
* .flatMap(MCRConfiguration2::splitValue)
* .collect(Collectors.toList());
*
* // Get a configuration property as a long array (values are seperated by ","):
* long[] la = MCRConfiguration2.getString("MCR.LongList.Value").stream()
* .flatMap(MCRConfiguration2::splitValue)
* .mapToLong(Long::parseLong)
* .toArray();
*
* // Get a configuration property as an int, use 500 as default if not set:
* int max = MCRConfiguration2.getInt("MCR.Cache.Size").orElse(500);
* </PRE>
*
* There are some helper methods to help you with converting values
* <ul>
* <li>{@link #getOrThrow(String, Function)}</li>
* <li>{@link #splitValue(String)}</li>
* <li>{@link #instantiateClass(String)}</li>
* </ul>
*
* As you see, the class provides methods to get configuration properties as different data types and allows you to
* specify defaults. All MyCoRe configuration properties should start with "<CODE>MCR.</CODE>"
*
* Using the <CODE>set</CODE> methods allows client code to set new configuration properties or
* overwrite existing ones with new values.
*
* @author Thomas Scheffler (yagee)
* @since 2018.05
*/
public class MCRConfiguration2 {
private static ConcurrentHashMap<UUID, EventListener> LISTENERS = new ConcurrentHashMap<>();
static ConcurrentHashMap<SingletonKey, Object> instanceHolder = new MCRConcurrentHashMap<>();
public static Map<String, String> getPropertiesMap() {
return Collections.unmodifiableMap(MCRConfigurationBase.getResolvedProperties().getAsMap());
}
/**
* Returns a sub map of properties where key is transformed.
*
* <ol>
* <li>if property starts with <code>propertyPrefix</code>, the property is in the result map</li>
* <li>the key of the target map is the name of the property without <code>propertPrefix</code></li>
* </ol>
* Example for <code>propertyPrefix="MCR.Foo."</code>:
* <pre>
* MCR.Foo.Bar=Baz
* MCR.Foo.Hello=World
* MCR.Other.Prop=Value
* </pre>
* will result in
* <pre>
* Bar=Baz
* Hello=World
* </pre>
* @param propertyPrefix prefix of the property name
* @return a map of the properties as stated above
*/
public static Map<String, String> getSubPropertiesMap(String propertyPrefix) {
return MCRConfigurationBase.getResolvedProperties()
.getAsMap()
.entrySet()
.stream()
.filter(e -> e.getKey().startsWith(propertyPrefix))
.collect(Collectors.toMap(e -> e.getKey().substring(propertyPrefix.length()), Map.Entry::getValue));
}
/**
* Returns a new instance of the class specified in the configuration property with the given name.
* If you call a method on the returned Optional directly you need to set the type like this:
* <pre>
* MCRConfiguration2.<MCRMyType> getInstanceOf(name)
* .ifPresent(myTypeObj -> myTypeObj.method());
* </pre>
*
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as a String, or null
* @throws MCRConfigurationException
* if the class can not be loaded or instantiated
*/
public static <T> Optional<T> getInstanceOf(String name) throws MCRConfigurationException {
if (MCRConfigurableInstanceHelper.isSingleton(name)) {
return getSingleInstanceOf(name);
} else {
return MCRConfigurableInstanceHelper.getInstance(name);
}
}
/**
* Returns a instance of the class specified in the configuration property with the given name. If the class was
* previously instantiated by this method this instance is returned.
* If you call a method on the returned Optional directly you need to set the type like this:
* <pre>
* MCRConfiguration2.<MCRMyType> getSingleInstanceOf(name)
* .ifPresent(myTypeObj -> myTypeObj.method());
* </pre>
*
* @param name
* non-null and non-empty name of the configuration property
* @return the instance of the class named by the value of the configuration property
* @throws MCRConfigurationException
* if the class can not be loaded or instantiated
*/
public static <T> Optional<T> getSingleInstanceOf(String name) {
return getString(name)
.map(className -> new ConfigSingletonKey(name, className))
.map(key -> (T) instanceHolder.computeIfAbsent(key,
k -> MCRConfigurableInstanceHelper.getInstance(name).orElse(null)));
}
/**
* Returns a instance of the class specified in the configuration property with the given name. If the class was
* previously instantiated by this method this instance is returned.
* If you call a method on the returned Optional directly you need to set the type like this:
* <pre>
* MCRConfiguration2.<MCRMyType> getSingleInstanceOf(name, alternative)
* .ifPresent(myTypeObj -> myTypeObj.method());
* </pre>
*
* @param name
* non-null and non-empty name of the configuration property
* @param alternative
* alternative class if property is undefined
* @return the instance of the class named by the value of the configuration property
* @throws MCRConfigurationException
* if the class can not be loaded or instantiated
*/
public static <T> Optional<T> getSingleInstanceOf(String name, Class<? extends T> alternative) {
return MCRConfiguration2.<T>getSingleInstanceOf(name)
.or(() -> Optional.ofNullable(alternative)
.map(className -> new ConfigSingletonKey(name, className.getName()))
.map(key -> (T) MCRConfiguration2.instanceHolder.computeIfAbsent(key,
(k) -> MCRConfigurableInstanceHelper.getInstance(MCRInstanceConfiguration.ofClass(alternative)))));
}
/**
* Loads a Java Class defined in property <code>name</code>.
* @param name Name of the property
* @param <T> Supertype of class defined in <code>name</code>
* @return Optional of Class asignable to <code><T></code>
* @throws MCRConfigurationException
* if the the class can not be loaded or instantiated
*/
public static <T> Optional<Class<? extends T>> getClass(String name) throws MCRConfigurationException {
return getString(name).map(MCRConfiguration2::<T>getClassObject);
}
/**
* Returns the configuration property with the specified name.
* If the value of the property is empty after trimming the returned Optional is empty.
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as an {@link Optional Optional<String>}
*/
public static Optional<String> getString(String name) {
return MCRConfigurationBase.getString(name)
.map(String::trim)
.filter(s -> !s.isEmpty());
}
/**
* Returns the configuration property with the specified name as String.
*
* @param name
* the non-null and non-empty name of the configuration property
* @throws MCRConfigurationException
* if property is not set
*/
public static String getStringOrThrow(String name) {
return getString(name).orElseThrow(() -> createConfigurationException(name));
}
/**
* Returns the configuration property with the specified name.
*
* @param name
* the non-null and non-empty name of the configuration property
* @param mapper
* maps the String value to the return value
* @throws MCRConfigurationException
* if property is not set
*/
public static <T> T getOrThrow(String name, Function<String, ? extends T> mapper) {
return getString(name).map(mapper).orElseThrow(() -> createConfigurationException(name));
}
public static MCRConfigurationException createConfigurationException(String propertyName) {
return new MCRConfigurationException("Configuration property " + propertyName + " is not set.");
}
/**
* Splits a String value in a Stream of trimmed non-empty Strings.
*
* This method can be used to split a property value delimited by ',' into values.
*
* <p>
* Example:
* </p>
* <p>
* <code>
* MCRConfiguration2.getOrThrow("MCR.ListProp", MCRConfiguration2::splitValue)<br>
* .map(Integer::parseInt)<br>
* .collect(Collectors.toList())<br>
* </code>
* </p>
* @param value a property value
* @return a Stream of trimmed, non-empty Strings
*/
public static Stream<String> splitValue(String value) {
return MCRConfigurationBase.PROPERTY_SPLITTER.splitAsStream(value)
.map(String::trim)
.filter(s -> !s.isEmpty());
}
/**
* @return a list of properties which represent a configurable class
*/
public static Stream<String> getInstantiatablePropertyKeys(String prefix) {
return getSubPropertiesMap(prefix).entrySet()
.stream()
.filter(es -> {
String s = es.getKey();
if (!s.contains(".")) {
return true;
}
return (s.endsWith(".class") || s.endsWith(".Class")) &&
!s.substring(0, s.length() - ".class".length()).contains(".");
})
.filter(es -> es.getValue() != null)
.filter(es -> !es.getValue().isBlank())
.map(Map.Entry::getKey)
.map(prefix::concat);
}
/**
* Gets a list of properties which represent a configurable class and turns them in to a map.
* @return a map where the key is a String describing the configurable instance value
*/
public static <T> Map<String, Callable<T>> getInstances(String prefix) {
return getInstantiatablePropertyKeys(prefix)
.collect(Collectors.toMap(
k -> MCRInstanceName.of(k).canonical(),
v -> () -> (T) getInstanceOf(v).orElse(null)));
}
/**
* Returns the configuration property with the specified name as an <CODE>
* int</CODE> value.
*
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as an <CODE>int</CODE> value
* @throws NumberFormatException
* if the configuration property is not an <CODE>int</CODE> value
*/
public static Optional<Integer> getInt(String name) throws NumberFormatException {
return getString(name).map(Integer::parseInt);
}
/**
* Returns the configuration property with the specified name as a <CODE>
* long</CODE> value.
*
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as a <CODE>long</CODE> value
* @throws NumberFormatException
* if the configuration property is not a <CODE>long</CODE> value
*/
public static Optional<Long> getLong(String name) throws NumberFormatException {
return getString(name).map(Long::parseLong);
}
/**
* Returns the configuration property with the specified name as a <CODE>
* float</CODE> value.
*
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as a <CODE>float</CODE> value
* @throws NumberFormatException
* if the configuration property is not a <CODE>float</CODE> value
*/
public static Optional<Float> getFloat(String name) throws NumberFormatException {
return getString(name).map(Float::parseFloat);
}
/**
* Returns the configuration property with the specified name as a <CODE>
* double</CODE> value.
*
* @param name
* the non-null and non-empty name of the configuration property
* @return the value of the configuration property as a <CODE>double
* </CODE> value
* @throws NumberFormatException
* if the configuration property is not a <CODE>double</CODE> value
*/
public static Optional<Double> getDouble(String name) throws NumberFormatException {
return getString(name).map(Double::parseDouble);
}
/**
* Returns the configuration property with the specified name as a <CODE>
* boolean</CODE> value.
*
* @param name
* the non-null and non-empty name of the configuration property
* @return <CODE>true</CODE>, if and only if the specified property has the value <CODE>true</CODE>
*/
public static Optional<Boolean> getBoolean(String name) {
return getString(name).map(Boolean::parseBoolean);
}
/**
* Sets the configuration property with the specified name to a new <CODE>
* String</CODE> value. If the parameter <CODE>value</CODE> is <CODE>
* null</CODE>, the property will be deleted.
*
* @param name
* the non-null and non-empty name of the configuration property
* @param value
* the new value of the configuration property, possibly <CODE>
* null</CODE>
*/
public static void set(final String name, String value) {
Optional<String> oldValue = MCRConfigurationBase.getStringUnchecked(name);
MCRConfigurationBase.set(name, value);
LISTENERS
.values()
.stream()
.filter(el -> el.keyPredicate.test(name))
.forEach(el -> el.listener.accept(name, oldValue, Optional.ofNullable(value)));
}
public static void set(String name, Supplier<String> value) {
set(name, value.get());
}
public static <T> void set(String name, T value, Function<T, String> mapper) {
set(name, mapper.apply(value));
}
/**
* Adds a listener that is called after a new value is set.
*
* @param keyPredicate
* a filter upon the property name that if matches executes the listener
* @param listener
* a {@link MCRTriConsumer} with property name as first argument and than old and new value as Optional.
* @return a UUID to {@link #removePropertyChangeEventListener(UUID) remove the listener} later
*/
public static UUID addPropertyChangeEventLister(Predicate<String> keyPredicate,
MCRTriConsumer<String, Optional<String>, Optional<String>> listener) {
EventListener eventListener = new EventListener(keyPredicate, listener);
LISTENERS.put(eventListener.uuid, eventListener);
return eventListener.uuid;
}
public static boolean removePropertyChangeEventListener(UUID uuid) {
return LISTENERS.remove(uuid) != null;
}
public static <T> T instantiateClass(String className) {
return MCRConfigurableInstanceHelper.getInstance(MCRInstanceConfiguration.ofClass(className));
}
private static <T> Class<? extends T> getClassObject(String classname) {
try {
return MCRClassTools.forName(classname.trim());
} catch (ClassNotFoundException ex) {
throw new MCRConfigurationException("Could not load class.", ex);
}
}
private static class EventListener {
private Predicate<String> keyPredicate;
private MCRTriConsumer<String, Optional<String>, Optional<String>> listener;
private UUID uuid;
EventListener(Predicate<String> keyPredicate,
MCRTriConsumer<String, Optional<String>, Optional<String>> listener) {
this.keyPredicate = keyPredicate;
this.listener = listener;
this.uuid = UUID.randomUUID();
}
}
interface SingletonKey {
String property();
String classname();
}
record ConfigSingletonKey(String property, String classname) implements SingletonKey {
}
}
| 18,538 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstanceConfiguration.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/MCRInstanceConfiguration.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Represents an extract of properties (typically {@link MCRConfiguration2#getPropertiesMap()}) used to
* instantiate an object. Provides methods to extract nested configurations.
* <p>
* Generally speaking, a configuration has a {@link MCRInstanceConfiguration#name()} that represents the
* property key used to convey the {@link MCRInstanceConfiguration#className()} of the class that should
* be instantiated and {@link MCRInstanceConfiguration#properties()} that are relevant for instantiation
* (i.e. properties whose key originally started with the configuration name, but with that name removed
* from the start of such keys; a configuration name of <code>Foo.Bar</code> and a property key of
* <code>Foo.Bar.Baz</code> results in a property key <code>Baz</code> in the configurations properties).
* <p>
* Each configuration (top level or nested) keeps an unmodified reference to the properties used to create
* the top level configuration.
*/
public class MCRInstanceConfiguration {
private final MCRInstanceName name;
private final String className;
private final Map<String, String> properties;
private final Map<String, String> fullProperties;
private MCRInstanceConfiguration(MCRInstanceName name, String className, Map<String, String> properties,
Map<String, String> fullProperties) {
this.name = name;
this.className = className;
this.properties = properties;
this.fullProperties = fullProperties;
}
/**
* Shorthand for {@link MCRInstanceConfiguration#ofName(MCRInstanceName, Map)} that creates the name with
* {@link MCRInstanceName#of(String)} and uses {@link MCRConfiguration2#getPropertiesMap()} as the properties.
*
* @param name the name
* @return the configuration
*/
public static MCRInstanceConfiguration ofName(String name) {
return ofName(MCRInstanceName.of(name), MCRConfiguration2.getPropertiesMap());
}
/**
* Shorthand for {@link MCRInstanceConfiguration#ofName(MCRInstanceName, Map)} that creates the name with
* {@link MCRInstanceName#of(String)}.
*
* @param name the name
* @return the configuration
*/
public static MCRInstanceConfiguration ofName(String name, Map<String, String> properties) {
return ofName(MCRInstanceName.of(name), properties);
}
/**
* Shorthand for {@link MCRInstanceConfiguration#ofName(MCRInstanceName, Map)} that uses
* {@link MCRConfiguration2#getPropertiesMap()} as the properties.
*
* @param name the name
* @return the configuration
*/
public static MCRInstanceConfiguration ofName(MCRInstanceName name) {
return ofName(name, MCRConfiguration2.getPropertiesMap());
}
/**
* Creates a new configuration based on the given properties.
* <p>
* Example: Given an {@link MCRInstanceName} <code>Some.Instance.Name</code> and properties
* <ul>
* <li><code>Some.Instance.Name=some.instance.ClassName</code></li>
* <li><code>Some.Instance.Name.Key1=Value1</code></li>
* <li><code>Some.Instance.Name.Key2=Value1</code></li>
* </ul>
* this will return an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name</code>,
* the {@link MCRInstanceConfiguration#className()} <code>some.instance.ClassName</code>,
* {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=Value1</code></li>
* <li><code>Key2=Value2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the given properties.
* <p>
* Alternatively, the {@link MCRInstanceName} <code>Some.Instance.Name.Class</code> or
* <code>Some.Instance.Name.class</code> could have been used to convey the class name, in which case
* the keys <code>Class</code>, <code>class</code> and the empty key, if present,
* are not added to the {@link MCRInstanceConfiguration#properties()}.
* <p>
* Example: If <code>Some.Instance.Name.Class=some.instance.ClassName</code> would have been used
* to convey the class name, properties <code>Some.Instance.Name.class=Foo</code> and
* <code>Some.Instance.Name=Bar</code> would be ignored. The resulting
* {@link MCRInstanceConfiguration#properties()} would not contains entries with keys <code>class</code>
* or the empty key, respectively.
*
* @param name the name
* @param properties the properties
* @return the configuration
*/
public static MCRInstanceConfiguration ofName(MCRInstanceName name, Map<String, String> properties) {
String className = properties.get(name.actual());
Map<String, String> reducedProperties = reduceProperties(name, name.canonical(), properties);
return new MCRInstanceConfiguration(name, className, reducedProperties, properties);
}
private static Map<String, String> reduceProperties(MCRInstanceName name, String prefix,
Map<String, String> properties) {
Map<String, String> reducedProperties = new HashMap<>();
for (Map.Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.startsWith(prefix)) {
if (key.length() != prefix.length() && key.charAt(prefix.length()) == '.') {
String reducedKey = key.substring(prefix.length() + 1);
if (!name.ignoredKeys().contains(reducedKey)) {
reducedProperties.put(reducedKey, value);
}
}
}
}
return reducedProperties;
}
/**
* Shorthand for {@link MCRInstanceConfiguration#ofClass(String, Map)} that uses the given classes name
* and empty properties.
*
* @param instanceClass the class
* @return the configuration
*/
public static MCRInstanceConfiguration ofClass(Class<?> instanceClass) {
return ofClass(instanceClass.getName(), Collections.emptyMap());
}
/**
* Shorthand for {@link MCRInstanceConfiguration#ofClass(String, Map)} that uses the given classes name.
*
* @param instanceClass the class
* @return the configuration
*/
public static MCRInstanceConfiguration ofClass(Class<?> instanceClass, Map<String, String> properties) {
return ofClass(instanceClass.getName(), properties);
}
/**
* Shorthand for {@link MCRInstanceConfiguration#ofClass(String, Map)} that uses empty properties.
*
* @param className the class name
* @return the configuration
*/
public static MCRInstanceConfiguration ofClass(String className) {
return ofClass(className, Collections.emptyMap());
}
/**
* Creates a new configuration for a given class name and the given properties.
* <p>
* Example: Given a class name <code>some.instance.ClassName</code> and properties
* <ul>
* <li><code>Key1=Value1</code></li>
* <li><code>Key2=Value1</code></li>
* </ul>
* this will return an {@link MCRInstanceConfiguration}
* representing an empty {@link MCRInstanceConfiguration#name()},
* the {@link MCRInstanceConfiguration#className()} <code>some.instance.ClassName</code>,
* {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=Value1</code></li>
* <li><code>Key2=Value2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the given properties.
* <p>
*
* @param className the class name
* @param properties the properties
* @return the configuration
*/
public static MCRInstanceConfiguration ofClass(String className, Map<String, String> properties) {
MCRInstanceName name = MCRInstanceName.of(MCRInstanceName.Suffix.UPPER_CASE.representation().orElse(""));
name.ignoredKeys().forEach(properties::remove);
return new MCRInstanceConfiguration(name, className, properties, properties);
}
public MCRInstanceName name() {
return name;
}
public String className() {
return className;
}
public Map<String, String> properties() {
return properties;
}
public Map<String, String> fullProperties() {
return fullProperties;
}
/**
* Returns the configuration for a nested instance.
* <p>
* Example: Given an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceName} <code>Some.Instance.Name</code>, properties
* <ul>
* <li><code>Foo=some.nested.ClassName</code></li>
* <li><code>Foo.Key1=Value1</code></li>
* <li><code>Foo.Key2=Value2</code></li>
* <li><code>Bar=UnrelatedValue</code></li>
* </ul>
* and a <em>prefix</em> of <code>Foo</code>, this will return a an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassName</code>
* and properties
* <ul>
* <li><code>Key1=Value1</code></li>
* <li><code>Key2=Value2</code></li>
* </ul>
* <p>
* If an {@link MCRInstanceName} with suffix <code>.Class</code> or <code>.class</code> would have been used in
* the top level {@link MCRInstanceConfiguration}, the same suffix is used for nested configurations.
* <p>
* Example: If a property with suffix <code>.Class</code> would have been used to convey the class name in the
* top level configuration, property <code>Foo.Class</code> would be used to convey the class name for the
* nested configuration and properties <code>Foo.class</code> and <code>Foo</code> would be ignored.
* The resulting {@link MCRInstanceConfiguration#properties()} would not contain entries with keys
* <code>class</code> or the empty key, respectively.
*
* @param prefix the prefix
* @return the nested configuration
*/
public MCRInstanceConfiguration nestedConfiguration(String prefix) {
MCRInstanceName nestedName = name.subName(prefix);
String className = properties.get(nestedName.suffix().appendTo(prefix));
Map<String, String> reducedProperties = reduceProperties(nestedName, prefix, properties);
return new MCRInstanceConfiguration(nestedName, className, reducedProperties, fullProperties);
}
/**
* Returns a {@link Map} of configurations for nested instances, mapped by the first name segment.
* <p>
* Example: Given an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceName} <code>Some.Instance.Name</code>, properties
* <ul>
* <li><code>A=come.nested.ClassNameA</code></li>
* <li><code>A.Key1=ValueA1</code></li>
* <li><code>A.Key2=ValueA2</code></li>
* <li><code>B=some.nested.ClassNameB</code></li>
* <li><code>B.Key1=ValueB1</code></li>
* <li><code>B.Key2=ValueB2</code></li>
* </ul>
* this will return a map containing
* <ol>
* <li>
* an entry with key <code>A</code> mapping to an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.A</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassNameA</code>
* and {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueA1</code></li>
* <li><code>Key2=ValueA2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* <li>
* an entry with key <code>B</code> mapping to an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.B</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassNameB</code>
* and {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueB1</code></li>
* <li><code>Key2=ValueB2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* </ol>
* <p>
* If an {@link MCRInstanceName} with suffix <code>.Class</code> or <code>.class</code> would have been used in
* the top level {@link MCRInstanceConfiguration}, the same suffix is used for nested configurations.
* <p>
* Example: If a property with suffix <code>.Class</code> would have been used to convey the original class name
* in the top level configuration, properties <code>Foo.A.Class</code>/<code>Foo.B.Class</code> would be used to
* convey the class name for the nested configurations and properties
* <code>Foo.A.class</code>/<code>Foo.B.class</code> and <code>Foo.A</code>/<code>Foo.B</code> would be ignored.
* The resulting {@link MCRInstanceConfiguration#properties()} would not contain entries with keys
* <code>class</code> or the empty key, respectively.
*
* @return the nested configuration map
*/
public Map<String, MCRInstanceConfiguration> nestedConfigurationMap() {
Map<String, MCRInstanceConfiguration> nestedConfigurationMap = new HashMap<>();
for (Map.Entry<String, String> entry : properties().entrySet()) {
String key = entry.getKey();
int index = key.indexOf('.');
String nestedConfigurationKey = -1 == index ? key : key.substring(0, index);
if (!nestedConfigurationMap.containsKey(nestedConfigurationKey)) {
String nestedConfigurationSuffix = nestedConfigurationKey;
nestedConfigurationMap.put(nestedConfigurationKey, nestedConfiguration(nestedConfigurationSuffix));
}
}
return nestedConfigurationMap;
}
/**
* Returns a {@link Map} of configurations for nested instances with a common prefix, mapped by the
* name segment following that common prefix.
* <p>
* Example: Given an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceName} <code>Some.Instance.Name</code>, properties
* <ul>
* <li><code>Foo.A=come.nested.ClassNameA</code></li>
* <li><code>Foo.A.Key1=ValueA1</code></li>
* <li><code>Foo.A.Key2=ValueA2</code></li>
* <li><code>Foo.B=some.nested.ClassNameB</code></li>
* <li><code>Foo.B.Key1=ValueB1</code></li>
* <li><code>Foo.B.Key2=ValueB2</code></li>
* <li><code>Bar=UnrelatedValue</code></li>
* </ul>
* and a <em>commonPrefix</em> of <code>Foo</code>, this will return a map containing
* <ol>
* <li>
* an entry with key <code>A</code> mapping to an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.A</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassNameA</code>
* and {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueA1</code></li>
* <li><code>Key2=ValueA2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* <li>
* an entry with key <code>B</code> mapping to an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.B</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassNameB</code>
* and {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueB1</code></li>
* <li><code>Key2=ValueB2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* </ol>
* <p>
* If an {@link MCRInstanceName} with suffix <code>.Class</code> or <code>.class</code> would have been used in
* the top level {@link MCRInstanceConfiguration}, the same suffix is used for nested configurations.
* <p>
* Example: If a property with suffix <code>.Class</code> would have been used to convey the original class name
* in the top level configuration, properties <code>Foo.A.Class</code>/<code>Foo.B.Class</code> would be used to
* convey the class name for the nested configurations and properties
* <code>Foo.A.class</code>/<code>Foo.B.class</code> and <code>Foo.A</code>/<code>Foo.B</code> would be ignored.
* The resulting {@link MCRInstanceConfiguration#properties()} would not contain entries with keys
* <code>class</code> or the empty key, respectively.
*
* @param commonPrefix the common prefix
* @return the nested configuration map
*/
public Map<String, MCRInstanceConfiguration> nestedConfigurationMap(String commonPrefix) {
String commonSuffixWithDelimiter = commonPrefix + ".";
Map<String, MCRInstanceConfiguration> nestedConfigurationMap = new HashMap<>();
for (Map.Entry<String, String> entry : properties().entrySet()) {
String key = entry.getKey();
if (key.startsWith(commonSuffixWithDelimiter)) {
String remainingKey = key.substring(commonSuffixWithDelimiter.length());
int index = remainingKey.indexOf('.');
String nestedConfigurationKey = -1 == index ? remainingKey : remainingKey.substring(0, index);
if (!nestedConfigurationMap.containsKey(nestedConfigurationKey)) {
String nestedConfigurationSuffix = commonSuffixWithDelimiter + nestedConfigurationKey;
nestedConfigurationMap.put(nestedConfigurationKey, nestedConfiguration(nestedConfigurationSuffix));
}
}
}
return nestedConfigurationMap;
}
/**
* Returns a {@link List} of configurations for nested instances, ordered by the first name segment
* (which all must be integer values).
* <p>
* Example: Given an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceName} <code>Some.Instance.Name</code>, properties
* <ul>
* <li><code>1=some.nested.ClassName1</code></li>
* <li><code>1.Key1=ValueA1</code></li>
* <li><code>1.Key2=ValueA2</code></li>
* <li><code>3=some.nested.ClassName3</code></li>
* <li><code>3.Key1=ValueB1</code></li>
* <li><code>3.Key2=ValueB2</code></li>
* </ul>
* this will return a list containing
* <ol>
* <li>
* at index <code>0</code> an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.1</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassName1</code> and
* {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueA1</code></li>
* <li><code>Key2=ValueA2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* <li>
* at index <code>1</code> an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.3</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassName3</code> and
* {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueB1</code></li>
* <li><code>Key2=ValueB2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* </ol>
* <p>
* If an {@link MCRInstanceName} with suffix <code>.Class</code> or <code>.class</code> would have been used in
* the top level {@link MCRInstanceConfiguration}, the same suffix is used for nested configurations.
* <p>
* Example: If a property with suffix <code>.Class</code> would have been used to convey the original class name
* in the top level configuration, properties <code>Foo.1.Class</code>/<code>Foo.3.Class</code> would be used to
* convey the class name for the nested configurations and properties
* <code>Foo.1.class</code>/<code>Foo.3.class</code> and <code>Foo.1</code>/<code>Foo.3</code> would be ignored.
* The resulting {@link MCRInstanceConfiguration#properties()} would not contain entries with keys
* <code>class</code> or the empty key, respectively.
*
* @return the nested configuration list
*/
public List<MCRInstanceConfiguration> nestedConfigurationList() {
return mapToList(nestedConfigurationMap());
}
/**
* Returns a {@link List} of configurations for nested instances with a common prefix, ordered by the
* name segment following that common prefix (which all must be integer values).
* <p>
* Example: Given an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceName} <code>Some.Instance.Name</code>, properties
* <ul>
* <li><code>Foo.1=some.nested.ClassName1</code></li>
* <li><code>Foo.1.Key1=ValueA1</code></li>
* <li><code>Foo.1.Key2=ValueA2</code></li>
* <li><code>Foo.3=some.nested.ClassName3</code></li>
* <li><code>Foo.3.Key1=ValueB1</code></li>
* <li><code>Foo.3.Key2=ValueB2</code></li>
* <li><code>Bar=UnrelatedValue</code></li>
* </ul>
* and a <em>commonPrefix</em> of <code>Foo</code>, this will return a list containing
* <ol>
* <li>
* at index <code>0</code> an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.1</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassName1</code> and
* {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueA1</code></li>
* <li><code>Key2=ValueA2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* <li>
* at index <code>1</code> an {@link MCRInstanceConfiguration}
* representing the {@link MCRInstanceConfiguration#name()} <code>Some.Instance.Name.Foo.3</code>,
* {@link MCRInstanceConfiguration#className()} <code>some.nested.ClassName3</code> and
* {@link MCRInstanceConfiguration#properties()}
* <ul>
* <li><code>Key1=ValueB1</code></li>
* <li><code>Key2=ValueB2</code></li>
* </ul>
* and {@link MCRInstanceConfiguration#fullProperties()} that are equal to the the full properties of this
* configuration (i.e. the full properties used to create the top level configuration).
* </li>
* </ol>
* <p>
* If an {@link MCRInstanceName} with suffix <code>.Class</code> or <code>.class</code> would have been used in
* the top level {@link MCRInstanceConfiguration}, the same suffix is used for nested configurations.
* <p>
* Example: If a property with suffix <code>.Class</code> would have been used to convey the original class name
* in the top level configuration, properties <code>Foo.1.Class</code>/<code>Foo.3.Class</code> would be used to
* convey the class name for the nested configurations and properties
* <code>Foo.1.class</code>/<code>Foo.3.class</code> and <code>Foo.1</code>/<code>Foo.3</code> would be ignored.
* The resulting {@link MCRInstanceConfiguration#properties()} would not contain entries with keys
* <code>class</code> or the empty key, respectively.
*
* @param commonPrefix the common prefix
* @return the nested configuration list
*/
public List<MCRInstanceConfiguration> nestedConfigurationList(String commonPrefix) {
return mapToList(nestedConfigurationMap(commonPrefix));
}
private List<MCRInstanceConfiguration> mapToList(Map<String, MCRInstanceConfiguration> map) {
return map
.entrySet()
.stream()
.map(entry -> Map.entry(Integer.parseInt(entry.getKey()), entry.getValue()))
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
}
@Override
public String toString() {
return "MCRInstanceConfiguration {" +
"name=" + name + ", " +
"className=" + className + ", " +
"properties=" + properties + "}";
}
}
| 27,030 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPostConstruction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/annotation/MCRPostConstruction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to mark methods that should be called after the creation of the object.
* <p>
* The method may have a single parameter of type {@link String} for which, if present, the name of the
* configuration property containing the class name of the configured instance will be passed.
* <p>
* The method needs to be public.
*
* @author Sebastian Hofmann
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
@Inherited
public @interface MCRPostConstruction {
/**
* @return the order in which the annotated methods are processed. The higher the value, the later the
* method is processed.
*/
int order() default 0;
}
| 1,661 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProperty.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/annotation/MCRProperty.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.mycore.common.config.MCRConfigurationException;
/**
* This annotation is used to mark fields or methods that should be set to or called with a value of type
* {@link String} from the configuration properties.
* <p>
* The field or method needs to be public.
*
* @author Sebastian Hofmann
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Inherited
public @interface MCRProperty {
/**
* @return The name of property, or <code>*</code> for a map of all properties;
*/
String name();
/**
* @return true if the property specified by {@link MCRProperty#name()} has to be present in the properties.
* {@link MCRConfigurationException} is thrown if the property is required but not present.
*/
boolean required() default true;
/**
* @return true if the property is absolute and not specific for this instance e.g. MCR.NameOfProject.
*/
boolean absolute() default false;
/**
* @return The name for a default property that should be used as a default value if the property
* specified by {@link MCRProperty#name()} is not present in the properties. {@link MCRConfigurationException} is
* thrown if the default property is not present. The default property must be absolute, e.g. MCR.NameOfProject.
*/
String defaultName() default "";
/**
* @return the order in which the annotated fields or methods are processed. The higher the value, the later the
* field or method is processed. All fields are processed first, then all methods are processed.
*/
int order() default 0;
}
| 2,615 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstanceList.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/annotation/MCRInstanceList.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.mycore.common.config.MCRConfigurationException;
/**
* This annotation is used to mark fields or methods that should be set to or called with
* a list of configured instances of a type compatible with {@link MCRInstanceList#valueClass()}
* which are configured from the configuration properties.
* <p>
* The field or method needs to be public.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Inherited
public @interface MCRInstanceList {
/**
* @return The prefix for names of properties containing the class names.
*/
String name() default "";
/**
* @return The class or a superclass of the configured instances.
*/
Class<?> valueClass();
/**
* @return true if the at least one sub-property of the property specified by {@link MCRInstanceMap#name()}
* has to be present in the properties. {@link MCRConfigurationException} is thrown if the property is required
* but not present.
*/
boolean required() default true;
/**
* @return the order in which the annotated fields or methods are processed. The higher the value, the later the
* field or method is processed. All fields are processed first, then all methods are processed.
*/
int order() default 0;
}
| 2,282 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstance.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/annotation/MCRInstance.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.mycore.common.config.MCRConfigurationException;
/**
* This annotation is used to mark fields or methods that should be set to or called with
* a configured instance of a type compatible with {@link MCRInstance#valueClass()}
* which is configured from the configuration properties.
* <p>
* The field or method needs to be public.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Inherited
public @interface MCRInstance {
/**
* @return The name of property containing the class name.
*/
String name();
/**
* @return The class or a superclass of the configured instance.
*/
Class<?> valueClass();
/**
* @return true if the property specified by {@link MCRInstance#name()} has to be present in the properties.
* {@link MCRConfigurationException} is thrown if the property is required but not present.
*/
boolean required() default true;
/**
* @return the order in which the annotated fields or methods are processed. The higher the value, the later the
* field or method is processed. All fields are processed first, then all methods are processed.
*/
int order() default 0;
}
| 2,194 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRInstanceMap.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/annotation/MCRInstanceMap.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.mycore.common.config.MCRConfigurationException;
/**
* This annotation is used to mark fields or methods that should be set to or called with
* a map of configured instances of a type compatible with {@link MCRInstanceMap#valueClass()}
* which are configured from the configuration properties.
* <p>
* The field or method needs to be public.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Inherited
public @interface MCRInstanceMap {
/**
* @return The prefix for names of properties containing the class names.
*/
String name() default "";
/**
* @return The class or a superclass of the configured instances.
*/
Class<?> valueClass();
/**
* @return true if the at least one sub-property of the property specified by {@link MCRInstanceMap#name()}
* has to be present in the properties. {@link MCRConfigurationException} is thrown if the property is required
* but not present.
*/
boolean required() default true;
/**
* @return the order in which the annotated fields or methods are processed. The higher the value, the later the
* field or method is processed. All fields are processed first, then all methods are processed.
*/
int order() default 0;
}
| 2,279 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfigurationProxy.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/config/annotation/MCRConfigurationProxy.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.config.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.Supplier;
/**
* This annotation is used to mark classes that shouldn't be configured directly. Instead, an instance of
* a {@link Supplier} is configured that is then used to supply the actually requested instance.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
@Inherited
public @interface MCRConfigurationProxy {
/**
* @return The class that is configured and used to supply the actually requested instance.
*/
Class<? extends Supplier<?>> proxyClass();
}
| 1,503 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRParameterCollector.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRParameterCollector.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.xml.transform.Transformer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Verifier;
import org.mycore.common.MCRConstants;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
/**
* Collects parameters used in XSL transformations, by copying them from
* MCRConfiguration, from the HTTP and MyCoRe session, from request attributes etc.
*
* @author Frank Lützenkirchen
*/
public class MCRParameterCollector {
private static final Logger LOGGER = LogManager.getLogger(MCRParameterCollector.class);
/** The collected parameters */
private Map<String, Object> parameters = new HashMap<>();
/** If true (which is default), only those parameters starting with "XSL." are copied from session and request */
private boolean onlySetXSLParameters = true;
private boolean modified = true;
private int hashCode;
/**
* Collects parameters The collecting of parameters is done in steps,
* each step may overwrite parameters that already have been set.
*
* First, all configuration properties from MCRConfiguration are copied.
* Second, those variables stored in the HTTP session, that start with "XSL." are copied.
* Next, variables stored in the MCRSession are copied.
* Next, HTTP request parameters are copied.
*
* Only those parameters starting with "XSL." are copied from session and request,
*
* @param request the HttpRequest causing the XSL transformation, must NOT be null
*/
public MCRParameterCollector(HttpServletRequest request) {
this(request, true);
}
/**
* Collects parameters The collecting of parameters is done in steps,
* each step may overwrite parameters that already have been set.
*
* First, all configuration properties from MCRConfiguration are copied.
* Second, those variables stored in the HTTP session, that start with "XSL." are copied.
* Next, variables stored in the MCRSession are copied.
* Next, HTTP request parameters are copied.
* Next, HTTP request attributes are copied.
*
* @param request the HttpRequest causing the XSL transformation, must NOT be null
* @param onlySetXSLParameters if true, only those parameters starting with "XSL."
* are copied from session and request
*/
public MCRParameterCollector(HttpServletRequest request, boolean onlySetXSLParameters) {
this.onlySetXSLParameters = onlySetXSLParameters;
setFromConfiguration();
HttpSession session = request.getSession(false);
if (session != null) {
setFromSession(session);
}
if (!MCRSessionMgr.isLocked()) {
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
setFromSession(mcrSession);
setUnmodifyableParameters(mcrSession, request);
}
setFromRequestParameters(request);
setFromRequestAttributes(request);
setFromRequestHeader(request);
if (session != null) {
setSessionID(session, request.isRequestedSessionIdFromCookie());
}
debugSessionParameters();
}
/**
* Collects parameters The collecting of parameters is done in steps,
* each step may overwrite parameters that already have been set.
*
* First, all configuration properties from MCRConfiguration are copied.
* Next, those variables stored in the MCRSession that start with "XSL." are copied.
*/
public MCRParameterCollector() {
this(true);
}
/**
* Collects parameters The collecting of parameters is done in steps,
* each step may overwrite parameters that already have been set.
*
* First, all configuration properties from MCRConfiguration are copied.
* Next, those variables stored in the MCRSession are copied.
*
* @param onlySetXSLParameters if true, only those parameters starting with "XSL." are copied from session
*/
public MCRParameterCollector(boolean onlySetXSLParameters) {
this.onlySetXSLParameters = onlySetXSLParameters;
setFromConfiguration();
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
setFromSession(mcrSession);
setUnmodifyableParameters(mcrSession, null);
debugSessionParameters();
}
/**
* Sets the parameter with the given name
*/
public void setParameter(String name, Object value) {
parameters.put(name, value);
modified = true;
}
/**
* Sets all parameters from the given map
*/
public void setParameters(Map<String, String> param) {
parameters.putAll(param);
modified = true;
}
/**
* Sets the parameter only if it is not empty and starts with "XSL." or onlySetXSLParameters is false
*/
private void setXSLParameter(String name, String value) {
if ((value == null) || value.isEmpty()) {
return;
}
if (name.startsWith("XSL.")) {
parameters.put(name.substring(4), value);
} else if (!onlySetXSLParameters) {
parameters.put(name, value);
}
}
/**
* Returns the parameter with the given name
*/
public String getParameter(String name, String defaultValue) {
Object val = parameters.get(name);
return (val == null) ? defaultValue : val.toString();
}
/**
* Returns the parameter map.
*/
public Map<String, Object> getParameterMap() {
return Collections.unmodifiableMap(parameters);
}
/**
* Copies all MCRConfiguration properties as XSL parameters. Characters that are valid in property names
* but invalid in XML names are replaced with an underscore. Colons are replaced with underscores as well,
* because this character is used as a namespace separater in namespace-aware XML.
*/
private void setFromConfiguration() {
for (Map.Entry<String, String> property : MCRConfiguration2.getPropertiesMap().entrySet()) {
parameters.put(xmlSafe(property.getKey()), property.getValue());
}
}
private String xmlSafe(String key) {
StringBuilder builder = new StringBuilder();
if (key.length() != 0) {
char first = key.charAt(0);
builder.append(first == ':' || !Verifier.isXMLNameStartCharacter(first) ? "_" : first);
for (int i = 1, n = key.length(); i < n; i++) {
char following = key.charAt(i);
builder.append(following == ':' || !Verifier.isXMLNameCharacter(following) ? "_" : following);
}
}
return builder.toString();
}
/**
* Sets those session variables as XSL parameters that start with "XSL.",
* others will be ignored. The "XSL." prefix is cut off from the name.
*/
private void setFromSession(HttpSession session) {
for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
String name = e.nextElement();
setXSLParameter(name, session.getAttribute(name).toString());
}
}
/**
* Sets those session variables as XSL parameters that start with "XSL.",
* others will be ignored. The "XSL." prefix is cut off from the name.
*/
private void setFromSession(MCRSession session) {
Objects.requireNonNull(session, "Session needs to be not null!");
for (Map.Entry<Object, Object> entry : session.getMapEntries()) {
String key = entry.getKey().toString();
if (entry.getValue() != null) {
setXSLParameter(key, entry.getValue().toString());
}
}
}
/**
* Sets those request attributes as XSL parameters that start with "XSL.",
* others will be ignored. The "XSL." prefix is cut off from the name.
*/
private void setFromRequestParameters(HttpServletRequest request) {
for (Enumeration<String> e = request.getParameterNames(); e.hasMoreElements();) {
String name = e.nextElement();
if (!(name.endsWith(".SESSION"))) {
setXSLParameter(name, request.getParameter(name));
}
}
}
/**
* Sets those request parameters as XSL parameters that start with "XSL.",
* others will be ignored. The "XSL." prefix is cut off from the name.
*/
private void setFromRequestAttributes(HttpServletRequest request) {
for (Enumeration<String> e = request.getAttributeNames(); e.hasMoreElements();) {
String name = e.nextElement();
if (!(name.endsWith(".SESSION"))) {
final Object attributeValue = request.getAttribute(name);
if (attributeValue != null) {
setXSLParameter(name, attributeValue.toString());
}
}
}
}
/**
* Sets the ID of the current session as parameter
*/
private void setSessionID(HttpSession session, boolean isFromCookie) {
String sessionParam = MCRConfiguration2.getString("MCR.Session.Param").orElse(";jsessionid=");
String jSessionID = sessionParam + session.getId();
parameters.put("JSessionID", jSessionID);
if (!isFromCookie) {
parameters.put("HttpSession", jSessionID);
}
}
/**
* Sets some parameters that must not be overwritten by the request, for example
* the user ID and the URL of the web application.
*
*/
private void setUnmodifyableParameters(MCRSession session, HttpServletRequest request) {
parameters.put("CurrentUser", session.getUserInformation().getUserID());
parameters.put("CurrentLang", session.getCurrentLanguage());
parameters.put("WebApplicationBaseURL", MCRFrontendUtil.getBaseURL());
parameters.put("ServletsBaseURL", MCRServlet.getServletBaseURL());
String defaultLang = MCRConfiguration2.getString("MCR.Metadata.DefaultLang").orElse(MCRConstants.DEFAULT_LANG);
parameters.put("DefaultLang", defaultLang);
String userAgent = request != null ? request.getHeader("User-Agent") : null;
if (userAgent != null) {
parameters.put("User-Agent", userAgent);
}
}
private void debugSessionParameters() {
LOGGER.debug("XSL.HttpSession ={}", parameters.get("HttpSession"));
LOGGER.debug("XSL.JSessionID ={}", parameters.get("JSessionID"));
LOGGER.debug("XSL.CurrentUser ={}", parameters.get("CurrentUser"));
LOGGER.debug("XSL.Referer ={}", parameters.get("Referer"));
}
/** Sets the request and referer URL */
private void setFromRequestHeader(HttpServletRequest request) {
parameters.put("RequestURL", getCompleteURL(request));
parameters.put("Referer", request.getHeader("Referer") != null ? request.getHeader("Referer") : "");
parameters.put("UserAgent", request.getHeader("User-Agent") != null ? request.getHeader("User-Agent") : "");
}
/**
* Calculates the complete request URL, so that mod_proxy is supported
*/
private String getCompleteURL(HttpServletRequest request) {
StringBuilder buffer = getBaseURLUpToHostName();
//when called by MCRErrorServlet
String errorURI = (String) request.getAttribute("jakarta.servlet.error.request_uri");
buffer.append(errorURI != null ? errorURI : request.getRequestURI());
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
buffer.append('?').append(queryString);
}
String url = buffer.toString();
LOGGER.debug("Complete request URL : {}", url);
return url;
}
private StringBuilder getBaseURLUpToHostName() {
int schemeLength = "https://".length();
String baseURL = MCRFrontendUtil.getBaseURL();
StringBuilder buffer = new StringBuilder(baseURL);
if (baseURL.length() < schemeLength) {
return buffer;
}
int pos = buffer.indexOf("/", schemeLength);
buffer.delete(pos, buffer.length());
return buffer;
}
/**
* Sets XSL parameters for the given transformer by taking them from the
* properties object provided.
*
* @param transformer
* the Transformer object thats parameters should be set
*/
public void setParametersTo(Transformer transformer) {
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
transformer.setParameter(entry.getKey(), entry.getValue());
}
}
public static MCRParameterCollector getInstanceFromUserSession() {
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
MCRServletJob job = (MCRServletJob) mcrSession.get("MCRServletJob");
return job == null ? new MCRParameterCollector() : new MCRParameterCollector(job.getRequest());
}
public int hashCode() {
if (modified) {
int result = LOGGER.hashCode();
//order of map should not harm result
result += parameters.entrySet().stream().mapToInt(Map.Entry::hashCode).sum();
hashCode = result;
modified = false;
}
return hashCode;
}
}
| 14,575 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTemplatesCompiler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRTemplatesCompiler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.Source;
import javax.xml.transform.SourceLocator;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xml.utils.WrappedRuntimeException;
import org.mycore.common.MCRExceptionCauseFinder;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.xml.MCRURIResolver;
/**
* Compiles XSL sources, reports compile errors and returns transformer
* instances for compiled templates.
*
* @author Frank Lützenkirchen
*/
public class MCRTemplatesCompiler {
private static final Logger LOGGER = LogManager.getLogger(MCRTemplatesCompiler.class);
/** The XSL transformer factory to use */
private static SAXTransformerFactory factory;
static {
System.setProperty("javax.xml.transform.TransformerFactory",
"org.apache.xalan.processor.TransformerFactoryImpl");
TransformerFactory tf = TransformerFactory.newInstance();
LOGGER.info("Transformerfactory: {}", tf.getClass().getName());
if (!tf.getFeature(SAXTransformerFactory.FEATURE)) {
throw new MCRConfigurationException("Could not load a SAXTransformerFactory for use with XSLT");
}
factory = (SAXTransformerFactory) tf;
factory.setURIResolver(MCRURIResolver.instance());
factory.setErrorListener(new ErrorListener() {
public void error(TransformerException ex) {
throw new WrappedRuntimeException(MCRExceptionCauseFinder.getCause(ex));
}
public void fatalError(TransformerException ex) {
throw new WrappedRuntimeException(MCRExceptionCauseFinder.getCause(ex));
}
public void warning(TransformerException ex) {
LOGGER.warn(ex.getMessageAndLocation());
}
});
}
/** Compiles the given XSL source code */
public static Templates compileTemplates(MCRTemplatesSource ts) {
try {
Source source = ts.getSource();
return factory.newTemplates(source);
} catch (Exception exc) {
LOGGER.error("Error while compiling template", exc);
Exception cause = MCRExceptionCauseFinder.getCause(exc);
String msg = buildErrorMessage(ts.getKey(), cause);
throw new MCRConfigurationException(msg, cause);
}
}
/** Returns a new transformer for the compiled XSL templates
*/
public static Transformer getTransformer(Templates templates) throws TransformerConfigurationException {
return factory.newTransformerHandler(templates).getTransformer();
}
private static String buildErrorMessage(String resource, Exception cause) {
StringBuilder msg = new StringBuilder("Error compiling XSL stylesheet ");
msg.append(resource);
if (cause instanceof TransformerException tex) {
msg.append("\n").append(tex.getMessage());
SourceLocator sl = tex.getLocator();
if (sl != null) {
msg.append(" (").append(sl.getSystemId()).append(") ");
msg.append(" at line ").append(sl.getLineNumber());
msg.append(" column ").append(sl.getColumnNumber());
}
}
return msg.toString();
}
}
| 4,398 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSLTransformerFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRXSLTransformerFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import java.io.IOException;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import org.mycore.common.MCRCache;
import org.mycore.common.config.MCRConfiguration2;
/**
* Returns a Transformer for a given XSL source, providing caching of
* already compiled XSL stylesheets. The cache size can be set via
* MCR.LayoutService.XSLCacheSize (default is 200).
*
* @author Frank Lützenkirchen
*/
public class MCRXSLTransformerFactory {
/** A cache of already compiled stylesheets */
private static MCRCache<String, Templates> cache;
private static long checkPeriod;
static {
int cacheSize = MCRConfiguration2.getInt("MCR.LayoutService.XSLCacheSize").orElse(200);
checkPeriod = MCRConfiguration2.getLong("MCR.LayoutService.LastModifiedCheckPeriod").orElse(10000L);
cache = new MCRCache<>(cacheSize, MCRXSLTransformerFactory.class.getName());
}
/** Returns the compiled XSL templates cached for the given source, if it is up-to-date. */
private static Templates getCachedTemplates(MCRTemplatesSource source) throws IOException {
String key = source.getKey();
return cache.getIfUpToDate(key, source.getModifiedHandle(checkPeriod));
}
/** Compiles the given XSL source, and caches the result */
private static Templates compileTemplates(MCRTemplatesSource source) {
Templates templates = MCRTemplatesCompiler.compileTemplates(source);
cache.put(source.getKey(), templates);
return templates;
}
/** Returns a transformer for the given XSL source
*/
public static Transformer getTransformer(MCRTemplatesSource source)
throws IOException, TransformerConfigurationException {
Templates templates = getCachedTemplates(source);
if (templates == null) {
templates = compileTemplates(source);
}
return MCRTemplatesCompiler.getTransformer(templates);
}
}
| 2,780 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLazyStreamSource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRLazyStreamSource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import javax.xml.transform.stream.StreamSource;
import org.mycore.common.MCRException;
/**
* A {@link StreamSource} that offers a lazy initialization to {@link #getInputStream()}.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRLazyStreamSource extends StreamSource {
private InputStreamSupplier inputStreamSupplier;
public MCRLazyStreamSource(InputStreamSupplier inputStreamSupplier, String systemId) {
super(systemId);
this.inputStreamSupplier = Optional.ofNullable(inputStreamSupplier).orElse(() -> null);
}
@Override
public void setInputStream(InputStream inputStream) {
inputStreamSupplier = () -> inputStream;
}
@Override
public InputStream getInputStream() {
try {
return inputStreamSupplier.get();
} catch (IOException e) {
throw new MCRException(e);
}
}
@FunctionalInterface
public interface InputStreamSupplier {
InputStream get() throws IOException;
}
}
| 1,857 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTemplatesSource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRTemplatesSource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import java.io.IOException;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRClassTools;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.common.xml.MCRXMLResource;
import org.xml.sax.SAXException;
/**
* Represents an XSL file that will be used in XSL transformation and which is loaded
* as a resource. The object provides helper methods to support caching of the compiled
* templates file.
*
* @author Thomas Scheffler (yagee)
* @author Frank Lützenkirchen
*/
public class MCRTemplatesSource {
private static final Logger LOGGER = LogManager.getLogger(MCRTemplatesSource.class);
/** The path to the XSL resource */
private String resource;
/**
* @param resource the path to the XSL file, which will be loaded as a resource
*/
public MCRTemplatesSource(String resource) {
this.resource = resource;
}
/** Have to use SAX here to resolve entities */
public SAXSource getSource() throws SAXException, ParserConfigurationException {
try {
return (SAXSource) MCRURIResolver.instance().resolve("resource:" + resource, null);
} catch (TransformerException e) {
throw new SAXException(e);
}
}
/** Returns the path to the XSL file, for use as a caching key */
public String getKey() {
return resource;
}
@Override
public String toString() {
return resource;
}
public URL getURL() {
try {
return MCRXMLResource.instance().getURL(resource, MCRClassTools.getClassLoader());
} catch (IOException e) {
LOGGER.warn("Could not determine URL of resource {}", resource, e);
return null;
}
}
/** Returns the timestamp the XSL file was last modified on the filesystem. */
public long getLastModified() {
try {
return MCRXMLResource.instance().getLastModified(resource, MCRClassTools.getClassLoader());
} catch (IOException e) {
LOGGER.warn("Could not determine last modified date of resource {}", resource);
return -1;
}
}
public MCRCache.ModifiedHandle getModifiedHandle(long checkPeriod) {
return MCRXMLResource.instance().getModifiedHandle(resource, MCRClassTools.getClassLoader(),
checkPeriod);
}
}
| 3,355 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRErrorListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRErrorListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.SourceLocator;
import javax.xml.transform.TransformerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xml.utils.WrappedRuntimeException;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class MCRErrorListener implements ErrorListener {
private static Logger LOGGER = LogManager.getLogger(MCRErrorListener.class);
private TransformerException exceptionThrown;
private String lastMessage;
public static MCRErrorListener getInstance() {
return new MCRErrorListener();
}
private MCRErrorListener() {
this.exceptionThrown = null;
}
public TransformerException getExceptionThrown() {
return exceptionThrown;
}
private boolean triggerException(TransformerException e) {
if (exceptionThrown != null) {
return false;
} else {
exceptionThrown = e;
return true;
}
}
/* (non-Javadoc)
* @see javax.xml.transform.ErrorListener#warning(javax.xml.transform.TransformerException)
*/
@Override
public void warning(TransformerException exception) {
exception = unwrapException(exception);
StackTraceElement[] stackTrace = exception.getStackTrace();
if (stackTrace.length > 0 && stackTrace[0].getMethodName().equals("message")) {
//org.apache.xalan.transformer.MsgMgr.message to print a message
String messageAndLocation = getMyMessageAndLocation(exception);
this.lastMessage = messageAndLocation;
LOGGER.info(messageAndLocation);
} else {
LOGGER.warn("Exception while XSL transformation:{}", exception.getMessageAndLocation());
}
}
/* (non-Javadoc)
* @see javax.xml.transform.ErrorListener#error(javax.xml.transform.TransformerException)
*/
@Override
public void error(TransformerException exception) throws TransformerException {
exception = unwrapException(exception);
if (triggerException(exception)) {
LOGGER.error("Exception while XSL transformation:{}", exception.getMessageAndLocation());
}
throw exception;
}
/* (non-Javadoc)
* @see javax.xml.transform.ErrorListener#fatalError(javax.xml.transform.TransformerException)
*/
@Override
public void fatalError(TransformerException exception) throws TransformerException {
exception = unwrapException(exception);
StackTraceElement[] stackTrace = exception.getStackTrace();
if (stackTrace.length > 0 && stackTrace[0].getMethodName().equals("execute")
&& stackTrace[0].getClassName().endsWith("ElemMessage")) {
LOGGER.debug("Original exception: ", exception);
exception = new TransformerException(lastMessage);
}
if (triggerException(exception)) {
LOGGER.fatal("Exception while XSL transformation.", exception);
}
throw exception;
}
public static TransformerException unwrapException(TransformerException exception) {
Throwable cause = exception.getCause();
while (cause != null) {
if (cause instanceof TransformerException te) {
return unwrapException(te);
}
if (cause instanceof WrappedRuntimeException wrte) {
cause = wrte.getException();
} else {
cause = cause.getCause();
}
}
return exception;
}
public static String getMyMessageAndLocation(TransformerException exception) {
SourceLocator locator = exception.getLocator();
StringBuilder msg = new StringBuilder();
if (locator != null) {
String systemID = locator.getSystemId();
int line = locator.getLineNumber();
int col = locator.getColumnNumber();
if (systemID != null) {
msg.append("SystemID: ");
msg.append(systemID);
}
if (line != 0) {
msg.append(" [");
msg.append(line);
if (col != 0) {
msg.append(',');
msg.append(col);
}
msg.append(']');
}
}
msg.append(": ");
msg.append(exception.getMessage());
return msg.toString();
}
}
| 5,231 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSLInfoServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/MCRXSLInfoServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.xml.transform.TransformerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.util.IteratorIterable;
import org.mycore.common.MCRConstants;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.content.MCRJDOMContent;
import org.mycore.common.xml.MCRURIResolver;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import org.xml.sax.SAXException;
/**
* Lists all *.xsl stylesheets in the web application located in any
* WEB-INF/lib/*.jar or WEB-INF/classes/[MCR.Layout.Transformer.Factory.XSLFolder]/ or in {@link MCRConfigurationDir},
* outputs the dependencies (import/include) and contained templates.
*
* @author Frank Lützenkirchen
*/
public final class MCRXSLInfoServlet extends MCRServlet {
private static final Logger LOGGER = LogManager.getLogger(MCRXSLInfoServlet.class);
private final Map<String, Stylesheet> stylesheets = new HashMap<>();
private final Set<String> unknown = new HashSet<>();
private final String xslFolder =
MCRConfiguration2.getStringOrThrow("MCR.Layout.Transformer.Factory.XSLFolder") + "/";
protected void doGetPost(MCRServletJob job) throws Exception {
if ("true".equals(job.getRequest().getParameter("reload"))) {
stylesheets.clear();
}
if (stylesheets.isEmpty()) {
LOGGER.info("Collecting stylesheet information....");
findInConfigDir();
findXSLinClassesDir();
findXSLinLibJars();
inspectStylesheets();
handleUnknownStylesheets();
}
buildOutput(job);
}
private void findInConfigDir() throws IOException {
final File configDir = MCRConfigurationDir.getConfigurationDirectory();
if (configDir == null) {
return;
}
findInConfigResourcesDir(configDir);
findInConfigLibDir(configDir);
}
private void findInConfigResourcesDir(File configDir) throws IOException {
final Path resources = configDir.toPath().resolve("resources");
final Path xslResourcesPath = resources.resolve("xsl");
doForFilesRecursive(xslResourcesPath, n -> n.endsWith(".xsl"),
file -> foundStylesheet(resources.toUri().relativize(file.toUri()).toString(),
configDir.toPath().relativize(file).toString()));
}
private void findInConfigLibDir(File configDir) throws IOException {
final Path lib = configDir.toPath().resolve("lib");
try {
doForFilesRecursive(lib, n -> n.endsWith(".jar"),
file -> {
try (InputStream in = Files.newInputStream(file)) {
findInJarInputStream(configDir.toPath().relativize(file).toString(), in);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (UncheckedIOException uioe) {
throw uioe.getCause();
}
}
private void doForFilesRecursive(Path baseDir, Predicate<String> lowerCaseCheck, Consumer<Path> pathConsumer)
throws IOException {
if (Files.isDirectory(baseDir)) {
Files.walkFileTree(baseDir, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (lowerCaseCheck.test(file.getFileName().toString().toLowerCase(Locale.ROOT))) {
pathConsumer.accept(file);
}
return super.visitFile(file, attrs);
}
});
}
}
private void inspectStylesheets() {
for (Entry<String, Stylesheet> entry : stylesheets.entrySet()) {
entry.getValue().inspect();
}
}
private void handleUnknownStylesheets() {
while (!unknown.isEmpty()) {
Set<String> list = new HashSet<>(unknown);
unknown.clear();
for (String name : list) {
Stylesheet s = new Stylesheet(name);
stylesheets.put(name, s);
s.inspect();
}
}
}
private void buildOutput(MCRServletJob job) throws IOException, TransformerException, SAXException {
Element output = new Element("stylesheets");
for (Entry<String, Stylesheet> entry : stylesheets.entrySet()) {
Stylesheet stylesheet = entry.getValue();
output.addContent(stylesheet.buildXML());
}
getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(output));
}
private void findXSLinLibJars() throws IOException {
for (String path : diveInto("/WEB-INF/lib/")) {
if (path.endsWith(".jar")) {
findXSLinJar(path);
}
}
}
private Set<String> diveInto(String base) {
LOGGER.info("Diving into {}...", base);
Set<String> paths = getServletContext().getResourcePaths(base);
Set<String> more = new HashSet<>();
if (paths != null) {
more.addAll(paths);
for (String path : paths) {
if (path.endsWith("/")) {
more.addAll(diveInto(path));
}
}
}
return more;
}
private void findXSLinJar(String pathOfJarFile) throws IOException {
LOGGER.info("Diving into {}...", pathOfJarFile);
try (InputStream in = getServletContext().getResourceAsStream(pathOfJarFile)) {
findInJarInputStream(pathOfJarFile, in);
}
}
private void findInJarInputStream(String pathOfJarFile, InputStream in) throws IOException {
try (ZipInputStream zis = new ZipInputStream(in)) {
for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
String name = ze.getName();
if (name.startsWith(xslFolder) && name.endsWith(".xsl")) {
foundStylesheet(name, pathOfJarFile);
}
zis.closeEntry();
}
}
}
private void findXSLinClassesDir() {
String base = "/WEB-INF/classes/" + xslFolder;
for (String path : diveInto(base)) {
if (path.endsWith(".xsl")) {
foundStylesheet(path, base);
}
}
}
private void foundStylesheet(String path, String source) {
String file = path.substring(path.lastIndexOf(xslFolder) + 4);
LOGGER.info("Found {} in {}", file, source);
Stylesheet stylesheet = getStylesheet(file);
if (source.startsWith("/WEB-INF/")) {
source = source.substring("/WEB-INF/".length()); // cut off
}
stylesheet.origin.add(source);
}
private Stylesheet getStylesheet(String name) {
return stylesheets.computeIfAbsent(name, Stylesheet::new);
}
class Stylesheet {
String name;
Set<String> origin = new HashSet<>();
Set<String> includes = new HashSet<>();
Set<String> imports = new HashSet<>();
List<Element> templates = new ArrayList<>();
Element xsl;
Stylesheet(String name) {
this.name = name;
}
void inspect() {
resolveXSL();
if (xsl != null) {
listTemplates();
findIncludes("include", includes);
findIncludes("import", imports);
}
}
private void resolveXSL() {
String uri = "resource:" + xslFolder + name;
resolveXSL(uri);
if (xsl == null) {
resolveXSL(name);
if (xsl != null) {
origin.add("URIResolver");
}
}
}
private void resolveXSL(String uri) {
try {
xsl = MCRURIResolver.instance().resolve(uri);
} catch (Exception ex) {
String msg = "Exception resolving stylesheet " + name;
LOGGER.warn(msg, ex);
}
}
private void findIncludes(String tag, Set<String> set) {
List<Element> includes = xsl.getChildren(tag, MCRConstants.XSL_NAMESPACE);
for (Element include : includes) {
String href = include.getAttributeValue("href");
LOGGER.info("{} {}s {}", name, tag, href);
set.add(href);
if (!stylesheets.containsKey(href)) {
unknown.add(href);
}
}
}
private void listTemplates() {
List<Element> list = xsl.getChildren("template", MCRConstants.XSL_NAMESPACE);
IteratorIterable<Element> callTemplateElements = xsl
.getDescendants(Filters.element("call-template", MCRConstants.XSL_NAMESPACE));
List<Element> templates = new ArrayList<>(list);
HashSet<String> callNames = new HashSet<>();
for (Element callTemplate : callTemplateElements) {
String name = callTemplate.getAttributeValue("name");
if (callNames.add(name)) {
templates.add(callTemplate);
}
}
for (Element template : templates) {
Element copy = template.clone();
copy.removeContent();
this.templates.add(copy);
}
}
Element buildXML() {
Element elem = new Element("stylesheet");
elem.setAttribute("name", name);
addValues(elem, "origin", origin);
addValues(elem, "includes", includes);
addValues(elem, "imports", imports);
for (Element template : templates) {
elem.addContent(template.clone());
}
return elem;
}
private void addValues(Element parent, String tag, Set<String> set) {
for (String value : set) {
parent.addContent(new Element(tag).setText(value));
}
}
}
}
| 11,752 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Counter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xsl/extensions/Counter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xsl.extensions;
/**
* @author Thomas Scheffler (yagee)
*
*/
public class Counter {
private int value;
public Counter() {
this.value = 0;
}
public static int next(Counter ctr) {
return ++ctr.value;
}
public static int reset(Counter ctr) {
return set(ctr, 0);
}
public static int set(Counter ctr, int newValue) {
int oldValue = ctr.value;
ctr.value = newValue;
return oldValue;
}
public static int get(Counter ctr) {
return ctr.value;
}
}
| 1,301 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableStatusListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableStatusListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.EventListener;
/**
* Base interface to listen to {@link MCRProcessableStatus} changes.
*
* @author Matthias Eichner
*/
public interface MCRProcessableStatusListener extends EventListener {
/**
* Is fired when the status of the {@link MCRProcessable} has changed.
*
* @param source the source {@link MCRProcessable}
* @param oldStatus the old status
* @param newStatus the new status
*/
void onStatusChange(MCRProcessable source, MCRProcessableStatus oldStatus, MCRProcessableStatus newStatus);
}
| 1,326 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
/**
* Describes an object which can be processed. A processable has a
* name, a user id, a status, a create-, start- and end time and is
* {@link MCRProgressable}.
*
* @author Matthas Eichner
*/
public interface MCRProcessable extends MCRListenableProgressable {
/**
* Returns a human readable name.
*
* @return name of this process
*/
String getName();
/**
* Returns the id of the user who created this processable.
*
* @return the user id responsible for the processable
*/
String getUserId();
/**
* The status of this process.
*
* @return the status
*/
MCRProcessableStatus getStatus();
/**
* Returns true if this task was created but not started yet.
*
* @return true if this task is just created.
*/
default boolean isCreated() {
return MCRProcessableStatus.created.equals(getStatus());
}
/**
* Returns true if this task is currently processing.
*
* @return true if this task is processing
*/
default boolean isProcessing() {
return MCRProcessableStatus.processing.equals(getStatus());
}
/**
* Returns true if this task was cancelled before it completed normally.
*
* @return true if this task is cancelled
*/
default boolean isCanceled() {
return MCRProcessableStatus.canceled.equals(getStatus());
}
/**
* Returns true if this task failed before it completed normally. One can assume
* that {@link #getError()} does not return null in such case.
*
* @return true if the process failed
*/
default boolean isFailed() {
return MCRProcessableStatus.failed.equals(getStatus());
}
/**
* Returns true if this task was successful and completed normally.
*
* @return true if this task was successful
*/
default boolean isSuccessful() {
return MCRProcessableStatus.successful.equals(getStatus());
}
/**
* Returns true if this processable completed. Completion may be due to normal termination,
* an exception, or cancellation -- in all of these cases, this method will return true.
*
* @return true if this processable completed
*/
default boolean isDone() {
return isCanceled() || isFailed() || isSuccessful();
}
/**
* Returns the error if the processable failed. This will return
* null if the status != failed.
*
* @return the error occurred while processing
*/
Throwable getError();
/**
* Time (instant) the process was started. Returns null if the process was not started yet.
*
* @return the time the process was started
*/
Instant getStartTime();
/**
* Time (instant) this processable was created.
*
* @return the time the processable was created
*/
Instant getCreateTime();
/**
* Time (instant) this processable finished. Either successfully, canceled
* or with an error. If the processable is not finished this will return
* null.
*
* @return the time the processable finished
*/
Instant getEndTime();
/**
* Calculates the duration between starting and finishing the processable.
*
* @return the duration or null if the processable is not finished yet
*/
default Duration took() {
if (getStartTime() == null || getEndTime() == null) {
return null;
}
return Duration.between(getStartTime(), getEndTime());
}
/**
* Returns a map of properties assigned to this processable.
*
* @return the properties map
*/
Map<String, Object> getProperties();
/**
* A shortcut for getProperties().get(name).
*
* @param name the name of the property
* @return the property value or null
*/
default Object getProperty(String name) {
return getProperties().get(name);
}
/**
* Returns the property for the given name. The property
* will be cast to the specified type. Be aware that a
* ClassCastException is thrown if the type does not match.
*
* @param name name of property
* @param type object type of the property
* @return the property value or null
*/
@SuppressWarnings("unchecked")
default <T> T getPropertyAs(String name, Class<T> type) {
Object property = getProperty(name);
if (property == null) {
return null;
}
return (T) property;
}
/**
* Adds a new {@link MCRProcessableStatusListener} to this {@link MCRProcessable}.
*
* @param listener the listener to add
*/
void addStatusListener(MCRProcessableStatusListener listener);
/**
* Removes a {@link MCRProcessableStatusListener} from this {@link MCRProcessable}.
*
* @param listener the listener to remove
*/
void removeStatusListener(MCRProcessableStatusListener listener);
}
| 5,870 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRListenableProgressable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRListenableProgressable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
/**
* Same as a {@link MCRProgressable} but can listen to progress change events.
*
* @author Matthias Eichner
*/
public interface MCRListenableProgressable extends MCRProgressable {
/**
* Adds a new {@link MCRProgressableListener} to this {@link MCRProgressable}.
*
* @param listener the listener to add
*/
void addProgressListener(MCRProgressableListener listener);
/**
* Removes a {@link MCRProgressableListener} from this {@link MCRProgressable}.
*
* @param listener the listener to remove
*/
void removeProgressListener(MCRProgressableListener listener);
}
| 1,394 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableDefaultCollection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableDefaultCollection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Base implementation of a processable collection.
*
* @author Matthias Eichner
*/
public class MCRProcessableDefaultCollection implements MCRProcessableCollection {
private static Logger LOGGER = LogManager.getLogger();
private String name;
private final List<MCRProcessable> processables;
private Map<String, Object> properties;
private final List<MCRProcessableCollectionListener> listenerList;
/**
* Creates a new collection with the given a human readable name.
*
* @param name name of this collection
*/
public MCRProcessableDefaultCollection(String name) {
this.name = name;
this.processables = Collections.synchronizedList(new ArrayList<>());
this.properties = new HashMap<>();
this.listenerList = Collections.synchronizedList(new ArrayList<>());
}
/**
* Returns the human readable name of this collection.
*/
public String getName() {
return name;
}
@Override
public void add(MCRProcessable processable) {
this.processables.add(processable);
fireAdded(processable);
}
@Override
public void remove(MCRProcessable processable) {
this.processables.remove(processable);
fireRemoved(processable);
}
@Override
public Stream<MCRProcessable> stream() {
List<MCRProcessable> snapshot;
synchronized (this.processables) {
snapshot = new ArrayList<>(this.processables);
}
return snapshot.stream();
}
@Override
public boolean isEmpty() {
return this.processables.isEmpty();
}
@Override
public Map<String, Object> getProperties() {
return this.properties;
}
public void setProperty(String propertyName, Object propertyValue) {
Object oldValue = this.properties.get(propertyName);
if (oldValue == null && propertyValue == null) {
return;
}
if (propertyValue == null) {
this.properties.remove(propertyName);
firePropertyChanged(propertyName, oldValue, null);
return;
}
if (propertyValue.equals(oldValue)) {
return;
}
this.properties.put(propertyName, propertyValue);
firePropertyChanged(propertyName, oldValue, propertyValue);
}
@Override
public void addListener(MCRProcessableCollectionListener listener) {
this.listenerList.add(listener);
}
@Override
public void removeListener(MCRProcessableCollectionListener listener) {
this.listenerList.remove(listener);
}
protected void fireAdded(MCRProcessable processable) {
List<MCRProcessableCollectionListener> listeners = listenersSnapshot();
listeners.forEach(listener -> {
try {
listener.onAdd(this, processable);
} catch (Exception exc) {
LOGGER.error("Unable to inform collection listener due internal error", exc);
}
});
}
protected void fireRemoved(MCRProcessable processable) {
List<MCRProcessableCollectionListener> listeners = listenersSnapshot();
listeners.forEach(listener -> {
try {
listener.onRemove(this, processable);
} catch (Exception exc) {
LOGGER.error("Unable to inform collection listener due internal error", exc);
}
});
}
protected void firePropertyChanged(String propertyName, Object oldValue, Object newValue) {
List<MCRProcessableCollectionListener> listeners = listenersSnapshot();
listeners.forEach(listener -> {
try {
listener.onPropertyChange(this, propertyName, oldValue, newValue);
} catch (Exception exc) {
LOGGER.error("Unable to inform collection listener due internal error", exc);
}
});
}
private List<MCRProcessableCollectionListener> listenersSnapshot() {
synchronized (this.listenerList) {
return new ArrayList<>(this.listenerList);
}
}
}
| 5,144 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableCollectionListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableCollectionListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.EventListener;
/**
* Base event listener interface for adding/removing {@link MCRProcessable} of
* {@link MCRProcessableCollection}.
*
* @author Matthias Eichner
*/
public interface MCRProcessableCollectionListener extends EventListener {
/**
* Fired when a processable was added.
*
* @param source the source collection
* @param processable the processable added
*/
void onAdd(MCRProcessableCollection source, MCRProcessable processable);
/**
* Fired when a processable was removed.
*
* @param source the source collection
* @param processable the processable removed
*/
void onRemove(MCRProcessableCollection source, MCRProcessable processable);
/**
* Fired when a property changed.
*
* @param source the source collection
* @param name the name of the property
* @param oldValue the old value
* @param newValue the new value
*/
void onPropertyChange(MCRProcessableCollection source, String name, Object oldValue, Object newValue);
}
| 1,842 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableTask.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableTask.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
/**
* Helper class to encapsulate a task within a processable. If the task
* implements the {@link MCRListenableProgressable} interface the
* progress will be delegated.
*
* @author Matthias Eichner
*/
public abstract class MCRProcessableTask<T> extends MCRAbstractProcessable {
protected T task;
public MCRProcessableTask(T task) {
super();
this.task = task;
delegateProgressable();
}
public T getTask() {
return task;
}
protected void delegateProgressable() {
if (this.task instanceof MCRListenableProgressable progressableTask) {
progressableTask.addProgressListener(new MCRProgressableListener() {
@Override
public void onProgressTextChange(MCRProgressable source, String oldProgressText,
String newProgressText) {
setProgressText(newProgressText);
}
@Override
public void onProgressChange(MCRProgressable source, Integer oldProgress, Integer newProgress) {
setProgress(newProgress);
}
});
}
}
}
| 1,935 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProgressable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProgressable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
/**
* Interface to apply a progress to a process.
*
* @author Matthias Eichner
*/
public interface MCRProgressable {
/**
* Returns a value between 0-100 which determines the progress.
* Can return null if the process is not started yet.
*
* @return the progress between 0-100 or null
*/
Integer getProgress();
/**
* Returns a human readable text indicating the state of the progress.
*
* @return progress text
*/
String getProgressText();
}
| 1,278 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableRegistry.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableRegistry.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.stream.Stream;
import org.mycore.common.config.MCRConfiguration2;
/**
* Registry for {@link MCRProcessable} and {@link MCRProcessableCollection}.
* Can be used for managing and monitoring purposes.
*
* @author Matthias Eichner
*/
public interface MCRProcessableRegistry {
/**
* Return the default instance of the processable registry
*
* @return the singleton instance
*/
static MCRProcessableRegistry getSingleInstance() {
return MCRConfiguration2
.<MCRProcessableRegistry>getSingleInstanceOf("MCR.Processable.Registry.Class").orElseThrow();
}
/**
* Registers a new collection to the registry.
*
* @param collection the collection to register
*/
void register(MCRProcessableCollection collection);
/**
* Removes a collection from the registry
*
* @param collection the collection to remove
*/
void unregister(MCRProcessableCollection collection);
/**
* Streams all the collections of this registry.
*
* @return stream of the registry content.
*/
Stream<MCRProcessableCollection> stream();
/**
* Adds a new listener.
*
* @param listener the listener to add
*/
void addListener(MCRProcessableRegistryListener listener);
/**
* Removes a listener.
*
* @param listener the listener to remove
*/
void removeListener(MCRProcessableRegistryListener listener);
}
| 2,251 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableCollection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableCollection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.Map;
import java.util.stream.Stream;
/**
* Defines a collection of coherent {@link MCRProcessable}.
*
* @author Matthias Eichner
*/
public interface MCRProcessableCollection {
/**
* Returns a human readable name about this registry container.
*
* @return name of this container
*/
String getName();
/**
* Adds a new {@link MCRProcessable} to this container.
*
* @param processable the processable to add
*/
void add(MCRProcessable processable);
/**
* Removes a {@link MCRProcessable} from the container.
*/
void remove(MCRProcessable processable);
/**
* Streams all {@link MCRProcessable} registered by this container.
*
* @return stream of {@link MCRProcessable}
*/
Stream<MCRProcessable> stream();
/**
* Checks if this collection contains any processable.
*
* @return true if this collection contains at least on processable
*/
boolean isEmpty();
/**
* Returns a map of properties assigned to this processable.
*
* @return the properties map
*/
Map<String, Object> getProperties();
/**
* A shortcut for getProperties().get(name).
*
* @param name the name of the property
* @return the property value or null
*/
default Object getProperty(String name) {
return getProperties().get(name);
}
/**
* Returns the property for the given name. The property
* will be cast to the specified type. Be aware that a
* ClassCastException is thrown if the type does not match.
*
* @param name name of property
* @param type object type of the property
* @return the property value or null
*/
@SuppressWarnings("unchecked")
default <T> T getPropertyAs(String name, Class<T> type) {
Object property = getProperty(name);
if (property == null) {
return null;
}
return (T) property;
}
/**
* Adds a new listener.
*
* @param listener the listener to add
*/
void addListener(MCRProcessableCollectionListener listener);
/**
* Removes a listener.
*
* @param listener the listener to remove
*/
void removeListener(MCRProcessableCollectionListener listener);
}
| 3,103 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractProgressable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRAbstractProgressable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Base implementation for an {@link MCRProgressable}. If you use this class
* make sure to call {@link #setProgress(Integer)} and {@link #setProgressText(String)}
* to invoke the {@link MCRProgressableListener}.
*
* @author Matthias Eichner
*/
public class MCRAbstractProgressable implements MCRListenableProgressable {
protected Integer progress;
protected String progressText;
protected final List<MCRProgressableListener> progressListener;
public MCRAbstractProgressable() {
this.progress = null;
this.progressText = null;
this.progressListener = Collections.synchronizedList(new ArrayList<>());
}
/**
* Sets the progress for this process.
*
* @param progress the new progress between 0 and 100
*/
public void setProgress(Integer progress) {
if (progress < 0 || progress > 100) {
throw new IllegalArgumentException(
"Cannot set progress to " + progress + ". It has to be between 0 and 100.");
}
Integer oldProgress = this.progress;
this.progress = progress;
fireProgressChanged(oldProgress);
}
/**
* Sets the progress text for this process.
*
* @param progressText the new progress text
*/
public void setProgressText(String progressText) {
String oldProgressText = this.progressText;
this.progressText = progressText;
fireProgressTextChanged(oldProgressText);
}
@Override
public Integer getProgress() {
return this.progress;
}
@Override
public String getProgressText() {
return this.progressText;
}
@Override
public void addProgressListener(MCRProgressableListener listener) {
this.progressListener.add(listener);
}
@Override
public void removeProgressListener(MCRProgressableListener listener) {
this.progressListener.remove(listener);
}
protected void fireProgressChanged(Integer oldProgress) {
synchronized (this.progressListener) {
this.progressListener.forEach(listener -> listener.onProgressChange(this, oldProgress, getProgress()));
}
}
protected void fireProgressTextChanged(String oldProgressText) {
synchronized (this.progressListener) {
this.progressListener
.forEach(listener -> listener.onProgressTextChange(this, oldProgressText, getProgressText()));
}
}
}
| 3,316 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableStatus.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableStatus.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
/**
* The status of one {@link MCRProcessable}. Can be one of created,
* processing, canceled, failed or successful.
*
* @author Matthias Eichner
*/
public enum MCRProcessableStatus {
/**
* The process is created and not started yet.
*/
created,
/**
* The process is currently running.
*/
processing,
/**
* Canceled by the user and not by an error.
*/
canceled,
/**
* An exception/error occurred while processing.
*/
failed,
/**
* The process is successfully done.
*/
successful
}
| 1,349 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableRegistryListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProcessableRegistryListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
/**
* Base event listener interface for adding/removing {@link MCRProcessableCollection} of
* an {@link MCRProcessableRegistry}.
*
* @author Matthias Eichner
*/
public interface MCRProcessableRegistryListener {
/**
* Fired when a collection was added.
*
* @param source the source registry
* @param collection the collection added
*/
void onAdd(MCRProcessableRegistry source, MCRProcessableCollection collection);
/**
* Fired when a collection was removed.
*
* @param source the source registry
* @param collection the collection removed
*/
void onRemove(MCRProcessableRegistry source, MCRProcessableCollection collection);
}
| 1,469 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAbstractProcessable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRAbstractProcessable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.MCRSessionMgr;
/**
* Can be used as base class for an {@link MCRProcessable}. This class offers some
* convenient methods but does not handle everything.
*
* <p>
* If you extend this class make sure to call {@link #setStatus(MCRProcessableStatus)},
* {@link #setProgress(Integer)} and {@link #setProgressText(String)}. Otherwise the
* event handlers are not fired.
* </p>
*
* @author Matthias Eichner
*/
public class MCRAbstractProcessable extends MCRAbstractProgressable implements MCRProcessable {
protected String name;
protected String userId;
protected MCRProcessableStatus status;
protected Throwable error;
protected Instant createTime;
protected Instant startTime;
protected Instant endTime;
protected Map<String, Object> properties;
protected final List<MCRProcessableStatusListener> statusListener;
public MCRAbstractProcessable() {
super();
this.name = null;
if (MCRSessionMgr.hasCurrentSession()) {
// do not create a new session! (getCurrentSession() is wrong named!)
this.userId = MCRSessionMgr.getCurrentSession().getUserInformation().getUserID();
}
this.status = MCRProcessableStatus.created;
this.error = null;
this.createTime = Instant.now();
this.startTime = null;
this.endTime = null;
this.properties = new HashMap<>();
this.statusListener = Collections.synchronizedList(new ArrayList<>());
}
/**
* Sets the name for this process.
*
* @param name human readable name
*/
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
/**
* Sets the user identifier responsible for this processable.
*
* @param userId the user id
*/
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getUserId() {
return this.userId;
}
@Override
public Throwable getError() {
return this.error;
}
/**
* Sets the internal processable error. This will set the status to failed.
*
* @param error the error
*/
public void setError(Throwable error) {
this.error = error;
setStatus(MCRProcessableStatus.failed);
}
/**
* Sets the new status. If the status is equal "processing" the startTime is set, if the status is equal
* "successful", "failed" or "canceled" the endTime is set. This will call the fireStatusChanged method.
*
* @param status the new status
*/
public void setStatus(MCRProcessableStatus status) {
MCRProcessableStatus oldStatus = this.status;
this.status = status;
if (status.equals(MCRProcessableStatus.processing)) {
this.startTime = Instant.now();
}
if (status.equals(MCRProcessableStatus.successful) || status.equals(MCRProcessableStatus.failed) ||
status.equals(MCRProcessableStatus.canceled)) {
this.endTime = Instant.now();
}
fireStatusChanged(oldStatus);
}
@Override
public MCRProcessableStatus getStatus() {
return this.status;
}
@Override
public Instant getStartTime() {
return this.startTime;
}
@Override
public Instant getCreateTime() {
return this.createTime;
}
@Override
public Instant getEndTime() {
return this.endTime;
}
@Override
public Map<String, Object> getProperties() {
return this.properties;
}
@Override
public void addStatusListener(MCRProcessableStatusListener listener) {
this.statusListener.add(listener);
}
@Override
public void removeStatusListener(MCRProcessableStatusListener listener) {
this.statusListener.remove(listener);
}
protected void fireStatusChanged(MCRProcessableStatus oldStatus) {
synchronized (this.statusListener) {
this.statusListener.forEach(listener -> {
try {
listener.onStatusChange(this, oldStatus, getStatus());
} catch (Exception exc) {
LogManager.getLogger().error("Unable to execute onStatusChange() on listener '{}' for '{}'",
listener.getClass().getName(), getName(), exc);
}
});
}
}
}
| 5,456 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProgressableListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/MCRProgressableListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing;
import java.util.EventListener;
/**
* Base interface to listen to {@link MCRProgressable} changes.
*
* @author Matthias Eichner
*/
public interface MCRProgressableListener extends EventListener {
/**
* Is fired when the progress of the {@link MCRProgressable} has changed.
*
* @param source the source {@link MCRProgressable}
* @param oldProgress the old progress
* @param newProgress the new progress
*/
void onProgressChange(MCRProgressable source, Integer oldProgress, Integer newProgress);
/**
* Is fired when the progress text of the {@link MCRProgressable} has changed.
*
* @param source the source {@link MCRProgressable}
* @param oldProgressText the old progress text
* @param newProgressText the new progress text
*/
void onProgressTextChange(MCRProgressable source, String oldProgressText, String newProgressText);
}
| 1,680 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCentralProcessableRegistry.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/processing/impl/MCRCentralProcessableRegistry.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.processing.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.processing.MCRProcessableCollection;
import org.mycore.common.processing.MCRProcessableRegistry;
import org.mycore.common.processing.MCRProcessableRegistryListener;
/**
* Central base implementation for a processable registry.
*
* @author Matthias Eichner
*/
public class MCRCentralProcessableRegistry implements MCRProcessableRegistry {
private static Logger LOGGER = LogManager.getLogger();
private final List<MCRProcessableCollection> collections;
private final List<MCRProcessableRegistryListener> listenerList;
public MCRCentralProcessableRegistry() {
this.collections = Collections.synchronizedList(new ArrayList<>());
this.listenerList = Collections.synchronizedList(new ArrayList<>());
}
/**
* Registers a new collection to the registry.
*
* @param collection the collection to register
*/
public void register(MCRProcessableCollection collection) {
synchronized (this.collections) {
if (this.collections.contains(collection)) {
LOGGER.warn("Don't add same collection twice!");
return;
}
this.collections.add(collection);
}
fireAdded(collection);
}
/**
* Removes a collection from the registry
*
* @param collection the collection to remove
*/
public void unregister(MCRProcessableCollection collection) {
this.collections.remove(collection);
fireRemoved(collection);
}
/**
* Streams all the collections of this registry.
*
* @return stream of the registry content.
*/
public Stream<MCRProcessableCollection> stream() {
List<MCRProcessableCollection> snapshot;
synchronized (this.collections) {
snapshot = new ArrayList<>(this.collections);
}
return snapshot.stream();
}
@Override
public void addListener(MCRProcessableRegistryListener listener) {
this.listenerList.add(listener);
}
@Override
public void removeListener(MCRProcessableRegistryListener listener) {
this.listenerList.remove(listener);
}
protected void fireAdded(MCRProcessableCollection collection) {
List<MCRProcessableRegistryListener> listeners = listenersSnapshot();
listeners.forEach(listener -> {
try {
listener.onAdd(this, collection);
} catch (Exception exc) {
LOGGER.error("Unable to inform registry listener due internal error", exc);
}
});
}
protected void fireRemoved(MCRProcessableCollection collection) {
List<MCRProcessableRegistryListener> listeners = listenersSnapshot();
listeners.forEach(listener -> {
try {
listener.onRemove(this, collection);
} catch (Exception exc) {
LOGGER.error("Unable to inform registry listener due internal error", exc);
}
});
}
private List<MCRProcessableRegistryListener> listenersSnapshot() {
synchronized (this.listenerList) {
return new ArrayList<>(this.listenerList);
}
}
}
| 4,173 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRServletContainerInitializer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRServletContainerInitializer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventorFactory;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCRServletContainerInitializer implements ServletContainerInitializer {
/* (non-Javadoc)
* @see jakarta.servlet.ServletContainerInitializer#onStartup(java.util.Set, jakarta.servlet.ServletContext)
*/
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
final boolean runClassLoaderLeakPreventor = runClassLoaderLeakPreventor();
ClassLoaderLeakPreventor leakPreventor = null;
if (runClassLoaderLeakPreventor) {
final ClassLoaderLeakPreventorFactory leakPreventorFactory = new ClassLoaderLeakPreventorFactory();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
leakPreventor = leakPreventorFactory.newLeakPreventor(classLoader);
leakPreventor.runPreClassLoaderInitiators();
}
MCRShutdownHandler shutdownHandler = MCRShutdownHandler.getInstance();
shutdownHandler.isWebAppRunning = true;
shutdownHandler.leakPreventor = leakPreventor;
MCRStartupHandler.startUp(ctx);
//Make sure logging is configured
final Logger logger = LogManager.getLogger();
if (logger.isDebugEnabled()) {
try {
Enumeration<URL> resources = MCRClassTools.getClassLoader().getResources("META-INF/web-fragment.xml");
while (resources.hasMoreElements()) {
logger.debug("Found: {}", resources.nextElement());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("This class is here: {}", getSource(this.getClass()));
}
//see https://jakarta.ee/specifications/platform/9/apidocs/jakarta/servlet/servletcontext#ORDERED_LIBS
@SuppressWarnings("unchecked")
List<String> loadOrderWebFragments = (List<String>) ctx.getAttribute(ServletContext.ORDERED_LIBS);
if (loadOrderWebFragments == null) {
logger.info("Loading Order by web-fragment.xml: NOT SPECIFIED");
} else {
logger.info("Loading Order by web-fragment.xml: " + String.join(", ", loadOrderWebFragments));
}
}
private static String getSource(final Class<? extends MCRServletContainerInitializer> clazz) {
if (clazz == null) {
return null;
}
ProtectionDomain protectionDomain = clazz.getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource == null) {
LogManager.getLogger().warn("Cannot get CodeSource.");
return null;
}
URL location = codeSource.getLocation();
String fileName = location.getFile();
File sourceFile = new File(fileName);
return sourceFile.getName();
}
private boolean runClassLoaderLeakPreventor() {
//do not run ClassLoaderLeakPreventor by default on JRE 17
String defaultValue = (Runtime.version().feature() > 11) ? Boolean.FALSE.toString() : Boolean.TRUE.toString();
final String propValue = System.getProperty("MCR.ClassLoaderLeakPreventor", defaultValue);
return Boolean.parseBoolean(propValue);
}
}
| 4,648 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRServletContextListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRServletContextListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
/**
* is a shutdown hook for the current <code>ServletContext</code>. For this class to register itself as a shutdown hook
* to the current ServletContext please add the following code to your web.xml (allready done in MyCoRe-shipped
* version):
*
* <pre>
* <listener>
* <listener-class>org.mycore.common.events.MCRServletContextListener</listener-class>
* </listener>
* </pre>
*
* @author Thomas Scheffler (yagee)
* @see org.mycore.common.events.MCRShutdownHandler
* @since 1.3
*/
public class MCRServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
}
public void contextDestroyed(ServletContextEvent sce) {
// shutdown event
MCRShutdownHandler.getInstance().shutDown();
}
}
| 1,692 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREvent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCREvent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Represents an event that occured in the MyCoRe system. Events are of a
* predefined event type like create, update, delete and an object type like
* object or file. They can be handled by MCREventHandler implementations.
* Events are automatically created by some MyCoRe components and are forwarded
* to the handlers by MCREventManager.
*
* @author Frank Lützenkirchen
*/
public class MCREvent {
/** Pre-defined event types * */
public enum EventType {
CREATE, UPDATE, DELETE, REPAIR, INDEX, MOVE, CUSTOM;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ROOT);
}
}
/** Pre-defined event objects * */
public enum ObjectType {
OBJECT("MCRObject"),
DERIVATE("MCRDerivate"),
CLASS("MCRClassification"),
PATH("MCRPath"),
USER("MCRUser"),
CUSTOM("MCREvent");
private final String className;
ObjectType(String className) {
this.className = className;
}
public String getClassName() {
return this.className;
}
public static ObjectType fromClassName(String className) {
for (ObjectType b : ObjectType.values()) {
if (b.className.equalsIgnoreCase(className)) {
return b;
}
}
return null;
}
@Override
public String toString() {
return className;
}
}
public static final String PATH_KEY = "MCRPath";
public static final String FILEATTR_KEY = PATH_KEY + ":attr";
public static final String OBJECT_KEY = "object";
public static final String OBJECT_OLD_KEY = "object.old";
public static final String DERIVATE_KEY = "derivate";
public static final String DERIVATE_OLD_KEY = "derivate.old";
public static final String USER_KEY = "user";
public static final String USER_OLD_KEY = "user.old";
public static final String CLASS_KEY = "class";
public static final String CLASS_OLD_KEY = "class.old";
/** The object type like object or file * */
private ObjectType objType;
private String customObjectType;
/** The event type like create, update or delete * */
private EventType evtType;
private String customEventType;
/** A hashtable to store event related, additional data */
private Hashtable<String, Object> data = new Hashtable<>();
/**
* Creates a new event object of the given object type (object, file) and
* event type (create, update, delete)
*/
public MCREvent(ObjectType objType, EventType evtType) {
checkNonCustomObjectType(objType);
checkNonCustomEventType(evtType);
initTypes(objType, evtType);
}
private void initTypes(ObjectType objType, EventType evtType) {
this.objType = objType;
this.evtType = evtType;
}
private static void checkNonCustomObjectType(ObjectType objType) {
if (objType == ObjectType.CUSTOM) {
throw new IllegalArgumentException("'CUSTOM' is not a supported object type here.");
}
}
private static void checkNonCustomEventType(EventType evtType) {
if (evtType == EventType.CUSTOM) {
throw new IllegalArgumentException("'CUSTOM' is not a supported event type here.");
}
}
private MCREvent(String customObjectType, String customEventType) {
initTypes(ObjectType.CUSTOM, EventType.CUSTOM);
this.customObjectType = Objects.requireNonNull(customObjectType);
this.customEventType = Objects.requireNonNull(customEventType);
}
private MCREvent(ObjectType objType, String customEventType) {
checkNonCustomObjectType(objType);
initTypes(objType, EventType.CUSTOM);
this.customEventType = Objects.requireNonNull(customEventType);
}
private MCREvent(String customObjectType, EventType evtType) {
checkNonCustomEventType(evtType);
initTypes(ObjectType.CUSTOM, evtType);
this.customObjectType = Objects.requireNonNull(customObjectType);
}
public static MCREvent customEvent(String otherObjectType, String otherEventType) {
return new MCREvent(otherObjectType, otherEventType);
}
public static MCREvent customEvent(ObjectType objType, String otherEventType) {
return new MCREvent(objType, otherEventType);
}
public static MCREvent customEvent(String otherObjectType, EventType evtType) {
return new MCREvent(otherObjectType, evtType);
}
/**
* Returns the object type of this event
*
* @return the object type of this event
*/
public ObjectType getObjectType() {
return objType;
}
/**
* Returns the custom object type.
*
* @return null, if {@link #getObjectType()} != {@link ObjectType#CUSTOM}
*/
public String getCustomObjectType() {
return customObjectType;
}
/**
* Returns the event type of this event
*
* @return the event type of this event
*/
public EventType getEventType() {
return evtType;
}
/**
* Returns the custom event type.
*
* @return null, if {@link #getEventType()} != {@link EventType#CUSTOM}
*/
public String getCustomEventType() {
return customEventType;
}
/**
* returns an object from event data
*
* @param key - the object key
* @return an object from event data
*/
public Object get(String key) {
return data.get(key);
}
/**
* adds an object to the event data
* @param key - the key for the object
* @param value - the object itself
*/
public void put(String key, Object value) {
data.put(key, value);
}
/**
* return the entries of the event data
* (1x called in wfc.mail.MCRMailEventhandler)
* @return the entrySet of the the data of the event
*/
public Set<Map.Entry<String, Object>> entrySet() {
return data.entrySet();
}
}
| 6,995 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionEvent.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRSessionEvent.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import org.mycore.common.MCRSession;
/**
*
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public class MCRSessionEvent {
public enum Type {
activated, created, destroyed, passivated
}
private Type type;
private MCRSession session;
private int concurrentAccessors;
public MCRSessionEvent(MCRSession session, Type type, int concurrentAccessors) {
this.session = session;
this.type = type;
this.concurrentAccessors = concurrentAccessors;
}
/**
* Return how many threads accessed the session at time the event occured.
*/
public int getConcurrentAccessors() {
return concurrentAccessors;
}
/**
* Return the MCRSession on which this event occured.
*/
public MCRSession getSession() {
return session;
}
/**
* Return the event type of this event.
*/
public Type getType() {
return type;
}
@Override
public String toString() {
return "MCRSessionEvent['" + getSession() + "'," + getType() + "," + getConcurrentAccessors() + "]'";
}
}
| 1,883 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStartupHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRStartupHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDirSetup;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.config.MCRRuntimeComponentDetector;
import org.mycore.common.xml.MCRURIResolver;
import jakarta.servlet.ServletContext;
/**
* Initializes classes that implement {@link AutoExecutable} interface that are defined via
* <code>MCR.Startup.Class</code> property.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRStartupHandler {
/**
* Can set <code>true</code> or <code>false</code> as {@link ServletContext#setAttribute(String, Object)} to skip
* errors on startup.
*/
public static final String HALT_ON_ERROR = "MCR.Startup.haltOnError";
private static final Logger LOGGER = LogManager.getLogger();
private static boolean isWebApp;
public static void startUp(ServletContext servletContext) {
//setup configuration
MCRConfigurationDirSetup dirSetup = new MCRConfigurationDirSetup();
dirSetup.startUp(servletContext);
isWebApp = servletContext != null;
//initialize ClassLoader here, so it can be used later reliably.
MCRClassTools.updateClassLoader();
ClassLoader resourceClassLoader = MCRClassTools.getClassLoader();
LOGGER.info("The following ClassLoader is used: {}", resourceClassLoader);
LOGGER.info("I have these components for you: {}", MCRRuntimeComponentDetector.getAllComponents());
LOGGER.info("I have these mycore components for you: {}", MCRRuntimeComponentDetector.getMyCoReComponents());
LOGGER.info("I have these app modules for you: {}", MCRRuntimeComponentDetector.getApplicationModules());
if (servletContext != null) {
LOGGER.info("Library order: {}", servletContext.getAttribute(ServletContext.ORDERED_LIBS));
}
MCRConfiguration2.getString("MCR.Startup.Class")
.map(MCRConfiguration2::splitValue)
.orElseGet(Stream::empty)
.map(MCRStartupHandler::getAutoExecutable)
//reverse ordering: highest priority first
.sorted((o1, o2) -> Integer.compare(o2.getPriority(), o1.getPriority()))
.forEachOrdered(autoExecutable -> startExecutable(servletContext, autoExecutable));
//initialize MCRURIResolver
MCRURIResolver.init(servletContext);
}
public static boolean isWebApp() {
return isWebApp;
}
private static void startExecutable(ServletContext servletContext, AutoExecutable autoExecutable) {
LOGGER.info("{}: Starting {}", autoExecutable.getPriority(), autoExecutable.getName());
try {
autoExecutable.startUp(servletContext);
} catch (ExceptionInInitializerError | RuntimeException e) {
boolean haltOnError = servletContext == null || servletContext.getAttribute(HALT_ON_ERROR) == null
|| Boolean.parseBoolean((String) servletContext.getAttribute(HALT_ON_ERROR));
if (haltOnError) {
throw e;
}
LOGGER.warn(e.toString());
}
}
private static AutoExecutable getAutoExecutable(String className) {
try {
return (AutoExecutable) MCRClassTools.forName(className).getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new MCRConfigurationException("Could not initialize 'MCR.Startup.Class': " + className, e);
}
}
public interface AutoExecutable {
/**
* returns a name to display on start-up.
*/
String getName();
/**
* If order is important returns as 'heigher' priority.
*/
int getPriority();
/**
* This method get executed by {@link MCRStartupHandler#startUp(ServletContext)}
*/
void startUp(ServletContext servletContext);
}
}
| 4,873 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRShutdownHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRShutdownHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
/**
* is a wrapper for shutdown hooks. When used inside a web application this shutdown hook is bound to the
* ServletContext. If not this hook is bound to the Java Runtime. Every <code>Closeable</code> that is added via
* <code>addCloseable()</code> will be closed at shutdown time. Do not forget to remove any closeable via
* <code>removeCloseable()</code> to remove any instances. For registering this hook for a web application see
* <code>MCRServletContextListener</code>
*
* @author Thomas Scheffler (yagee)
* @see org.mycore.common.events.MCRShutdownThread
* @see org.mycore.common.events.MCRServletContextListener
* @since 1.3
*/
public class MCRShutdownHandler {
private static final int ADD_CLOSEABLE_TIMEOUT = 10;
private static final String PROPERTY_SYSTEM_NAME = "MCR.CommandLineInterface.SystemName";
private static MCRShutdownHandler SINGLETON = new MCRShutdownHandler();
private final ConcurrentSkipListSet<Closeable> requests = new ConcurrentSkipListSet<>();
private final ReentrantReadWriteLock shutdownLock = new ReentrantReadWriteLock();
private volatile boolean shuttingDown = false;
boolean isWebAppRunning;
ClassLoaderLeakPreventor leakPreventor;
private MCRShutdownHandler() {
isWebAppRunning = false;
}
private void init() {
if (!isWebAppRunning) {
MCRShutdownThread.getInstance();
}
}
public static MCRShutdownHandler getInstance() {
return SINGLETON;
}
public void addCloseable(MCRShutdownHandler.Closeable c) {
Objects.requireNonNull(c);
init();
boolean hasShutDownLock;
try {
hasShutDownLock = shutdownLock.readLock().tryLock(ADD_CLOSEABLE_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new MCRException("Could not aquire shutdown lock in time", e);
}
try {
if (hasShutDownLock && !shuttingDown) {
requests.add(c);
} else {
throw new MCRException("Cannot register Closeable while shutting down application.");
}
} finally {
if (hasShutDownLock) {
shutdownLock.readLock().unlock();
}
}
}
public void removeCloseable(MCRShutdownHandler.Closeable c) {
Objects.requireNonNull(c);
if (!shuttingDown) {
requests.remove(c);
}
}
void shutDown() {
Logger logger = LogManager.getLogger();
String cfgSystemName = "MyCoRe:";
try {
cfgSystemName = MCRConfiguration2.getStringOrThrow(PROPERTY_SYSTEM_NAME) + ":";
} catch (MCRConfigurationException e) {
//may occur early if there is an error starting mycore up or in JUnit tests
logger.warn("Error getting '" + PROPERTY_SYSTEM_NAME + "': {}", e.getMessage());
}
final String system = cfgSystemName;
System.out.println(system + " Shutting down system, please wait...\n");
runClosables();
System.out.println(system + " closing any remaining MCRSession instances, please wait...\n");
MCRSessionMgr.close();
System.out.println(system + " Goodbye, and remember: \"Alles wird gut.\"\n");
LogManager.shutdown();
SINGLETON = null;
// may be needed in webapp to release file handles correctly.
if (leakPreventor != null) {
ClassLoaderLeakPreventor myLeakPreventor = leakPreventor;
leakPreventor = null;
myLeakPreventor.runCleanUps();
}
}
void runClosables() {
Logger logger = LogManager.getLogger();
logger.debug(() -> "requests: " + requests);
Closeable[] closeables = requests.stream().toArray(Closeable[]::new);
Stream.of(closeables)
.peek(c -> logger.debug("Prepare Closing (1): {}", c))
.forEach(Closeable::prepareClose); //may add more Closeables MCR-1726
shutdownLock.writeLock().lock();
try {
shuttingDown = true;
//during shut down more request may come in MCR-1726
final List<Closeable> alreadyPrepared = Arrays.asList(closeables);
requests.stream()
.filter(c -> !alreadyPrepared.contains(c))
.peek(c -> logger.debug("Prepare Closing (2): {}", c))
.forEach(Closeable::prepareClose);
requests.stream()
.peek(c -> logger.debug("Closing: {}", c))
.forEach(Closeable::close);
} finally {
shutdownLock.writeLock().unlock();
}
}
/**
* Object is cleanly closeable via <code>close()</code>-call.
*
* @author Thomas Scheffler (yagee)
*/
@FunctionalInterface
public interface Closeable extends Comparable<Closeable> {
/**
* The default priority
*/
int DEFAULT_PRIORITY = 5;
/**
* prepare for closing this object that implements <code>Closeable</code>. This is the first part of the closing
* process. As a object may need database access to close cleanly this method can be used to be ahead of
* database outtake.
*/
default void prepareClose() {
//should be overwritten if needed;
}
/**
* cleanly closes this object that implements <code>Closeable</code>. You can provide some functionality to
* close open files and sockets or so.
*/
void close();
/**
* Returns the priority. A Closeable with a higher priority will be closed before a Closeable with a lower
* priority. Default priority is 5.
*/
default int getPriority() {
return DEFAULT_PRIORITY;
}
@Override
default int compareTo(Closeable other) {
//MCR-1941: never return 0 if !this.equals(other)
return Comparator.comparingInt(Closeable::getPriority)
.thenComparingLong(Closeable::hashCode)
.compare(other, this);
}
}
}
| 7,523 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREventHandler.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCREventHandler.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import org.mycore.common.MCRException;
/**
* Objects that implement this interface can react when some kind of predefined
* event happens in MyCoRe. Implementing classes are registered using the
* configuration property
*
* MCR.EventHandler.[objType].X.Class=[package and class name]
*
* where [objType] is the object type like "MCRObject" or "MCRFile" and X is a
* number starting from 1. For event handlers that are indexers of the searcher
* package, there is a special syntax
*
* MCR.EventHandler.[objType].X.Indexer=[searcherID]
*
* where [searcherID] is the ID of the searcher that also is an indexer. Event
* handlers are called in the same order as they are registered in the
* properties file.
*
* @author Frank Lützenkirchen
*/
public interface MCREventHandler {
/**
* Handles an event. The handler is responsible for filtering the event type
* it is interested in and wants to react on.
*
* @param evt
* the Event object containing information about the event
*/
void doHandleEvent(MCREvent evt) throws MCRException;
/**
* Handles rollback of event handling. The handler should roll back the
* changes that previously were made for this event, because a successor in
* the event handler list caused an exception.
*
* @param evt
* the Event object containing information about the event
*/
void undoHandleEvent(MCREvent evt) throws MCRException;
}
| 2,251 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRShutdownThread.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRShutdownThread.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* is a shutdown hook for the current <code>Runtime</code>.
*
* This class registers itself as a shutdown hook to the JVM.
*
* There is no way to instanciate this class somehow. This will be done by MCRShutdownHandler.
*
* @author Thomas Scheffler (yagee)
* @see java.lang.Runtime#addShutdownHook(java.lang.Thread)
* @see org.mycore.common.events.MCRShutdownHandler
* @since 1.3
*/
public class MCRShutdownThread extends Thread {
private static final Logger LOGGER = LogManager.getLogger(MCRShutdownThread.class);
private static final MCRShutdownThread SINGLETON = new MCRShutdownThread();
private MCRShutdownThread() {
setName("MCR-exit");
LOGGER.info("adding MyCoRe ShutdownHook");
Runtime.getRuntime().addShutdownHook(this);
}
static MCRShutdownThread getInstance() {
return SINGLETON;
}
@Override
public void run() {
MCRShutdownHandler sh = MCRShutdownHandler.getInstance();
if (sh != null) {
sh.shutDown();
}
}
}
| 1,892 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREventHandlerBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCREventHandlerBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.classifications2.MCRCategory;
import org.mycore.datamodel.metadata.MCRDerivate;
import org.mycore.datamodel.metadata.MCRObject;
/**
* Abstract helper class that can be subclassed to implement event handlers more
* easily.
*
* @author Frank Lützenkirchen
* @author Jens Kupferschmidt
*/
public abstract class MCREventHandlerBase implements MCREventHandler {
private static Logger logger = LogManager.getLogger(MCREventHandlerBase.class);
/**
* This method handle all calls for EventHandler for the event types
* MCRObject, MCRDerivate and MCRFile.
*
* @param evt
* The MCREvent object
*/
public void doHandleEvent(MCREvent evt) {
if (evt.getObjectType() == MCREvent.ObjectType.OBJECT) {
MCRObject obj = (MCRObject) evt.get("object");
if (obj != null) {
logger.debug("{} handling {} {}", getClass().getName(), obj.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> handleObjectCreated(evt, obj);
case UPDATE -> handleObjectUpdated(evt, obj);
case DELETE -> handleObjectDeleted(evt, obj);
case REPAIR -> handleObjectRepaired(evt, obj);
case INDEX -> handleObjectIndex(evt, obj);
default -> logger
.warn("Can't find method for an object data handler for event type {}", evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
return;
}
if (evt.getObjectType() == MCREvent.ObjectType.DERIVATE) {
MCRDerivate der = (MCRDerivate) evt.get("derivate");
if (der != null) {
logger.debug("{} handling {} {}", getClass().getName(), der.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> handleDerivateCreated(evt, der);
case UPDATE -> handleDerivateUpdated(evt, der);
case DELETE -> handleDerivateDeleted(evt, der);
case REPAIR -> handleDerivateRepaired(evt, der);
case INDEX -> updateDerivateFileIndex(evt, der);
default -> logger
.warn("Can't find method for a derivate data handler for event type {}",
evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
return;
}
if (evt.getObjectType() == MCREvent.ObjectType.PATH) {
Path path = (Path) evt.get(MCREvent.PATH_KEY);
if (path != null) {
if (!path.isAbsolute()) {
logger.warn("Cannot handle path events on non absolute paths: {}", path);
}
logger.debug("{} handling {} {}", getClass().getName(), path, evt.getEventType());
BasicFileAttributes attrs = (BasicFileAttributes) evt.get(MCREvent.FILEATTR_KEY);
if (attrs == null && evt.getEventType() != MCREvent.EventType.DELETE) {
logger.warn("BasicFileAttributes for {} was not given. Resolving now.", path);
try {
attrs = Files.getFileAttributeView(path, BasicFileAttributeView.class).readAttributes();
} catch (IOException e) {
logger.error("Could not get BasicFileAttributes from path: {}", path, e);
}
}
switch (evt.getEventType()) {
case CREATE -> handlePathCreated(evt, path, attrs);
case UPDATE -> handlePathUpdated(evt, path, attrs);
case DELETE -> handlePathDeleted(evt, path, attrs);
case REPAIR -> handlePathRepaired(evt, path, attrs);
case INDEX -> updatePathIndex(evt, path, attrs);
default -> logger.warn("Can't find method for Path data handler for event type {}",
evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
return;
}
if (evt.getObjectType() == MCREvent.ObjectType.CLASS) {
MCRCategory cl = (MCRCategory) evt.get("class");
if (cl != null) {
logger.debug("{} handling {} {}", getClass().getName(), cl.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> handleClassificationCreated(evt, cl);
case UPDATE -> handleClassificationUpdated(evt, cl);
case DELETE -> handleClassificationDeleted(evt, cl);
case REPAIR -> handleClassificationRepaired(evt, cl);
default -> logger.warn("Can't find method for a classification data handler for event type {}",
evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
}
}
/**
* This method roll back all calls for EventHandler for the event types
* MCRObject, MCRDerivate and MCRFile.
*
* @param evt
* The MCREvent object
*/
public void undoHandleEvent(MCREvent evt) {
if (evt.getObjectType() == MCREvent.ObjectType.OBJECT) {
MCRObject obj = (MCRObject) evt.get("object");
if (obj != null) {
logger.debug("{} handling {} {}", getClass().getName(), obj.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> undoObjectCreated(evt, obj);
case UPDATE -> undoObjectUpdated(evt, obj);
case DELETE -> undoObjectDeleted(evt, obj);
case REPAIR -> undoObjectRepaired(evt, obj);
default -> logger
.warn("Can't find method for an object data handler for event type {}", evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
return;
}
if (evt.getObjectType() == MCREvent.ObjectType.DERIVATE) {
MCRDerivate der = (MCRDerivate) evt.get("derivate");
if (der != null) {
logger.debug("{} handling {}{}", getClass().getName(), der.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> undoDerivateCreated(evt, der);
case UPDATE -> undoDerivateUpdated(evt, der);
case DELETE -> undoDerivateDeleted(evt, der);
case REPAIR -> undoDerivateRepaired(evt, der);
default -> logger
.warn("Can't find method for a derivate data handler for event type {}",
evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
return;
}
if (evt.getObjectType() == MCREvent.ObjectType.PATH) {
Path path = (Path) evt.get(MCREvent.PATH_KEY);
if (path != null) {
if (!path.isAbsolute()) {
logger.warn("Cannot handle path events on non absolute paths: {}", path);
}
logger.debug("{} handling {} {}", getClass().getName(), path, evt.getEventType());
BasicFileAttributes attrs = (BasicFileAttributes) evt.get(MCREvent.FILEATTR_KEY);
if (attrs == null && evt.getEventType() != MCREvent.EventType.DELETE) {
logger.warn("BasicFileAttributes for {} was not given. Resolving now.", path);
try {
attrs = Files.getFileAttributeView(path, BasicFileAttributeView.class).readAttributes();
} catch (IOException e) {
logger.error("Could not get BasicFileAttributes from path: {}", path, e);
}
}
switch (evt.getEventType()) {
case CREATE -> undoPathCreated(evt, path, attrs);
case UPDATE -> undoPathUpdated(evt, path, attrs);
case DELETE -> undoPathDeleted(evt, path, attrs);
case REPAIR -> undoPathRepaired(evt, path, attrs);
default -> logger.warn("Can't find method for Path data handler for event type {}",
evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
return;
}
if (evt.getObjectType() == MCREvent.ObjectType.CLASS) {
MCRCategory obj = (MCRCategory) evt.get(MCREvent.CLASS_KEY);
if (obj != null) {
logger.debug("{} handling {} {}", getClass().getName(), obj.getId(), evt.getEventType());
switch (evt.getEventType()) {
case CREATE -> undoClassificationCreated(evt, obj);
case UPDATE -> undoClassificationUpdated(evt, obj);
case DELETE -> undoClassificationDeleted(evt, obj);
case REPAIR -> undoClassificationRepaired(evt, obj);
default -> logger.warn("Can't find method for an classification data handler for event type {}",
evt.getEventType());
}
return;
}
logger.warn("Can't find method for " + evt.getObjectType() + " for event type {}", evt.getEventType());
}
}
/** This method does nothing. It is very useful for debugging events. */
public void doNothing(MCREvent evt, Object obj) {
logger.debug("{} does nothing on {} {} {}", getClass().getName(), evt.getEventType(), evt.getObjectType(),
obj.getClass().getName());
}
/**
* Handles classification created events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void handleClassificationCreated(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles classification updated events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void handleClassificationUpdated(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles classification deleted events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void handleClassificationDeleted(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles classification repair events. This implementation does nothing and should
* be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void handleClassificationRepaired(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles object created events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void handleObjectCreated(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles object updated events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void handleObjectUpdated(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles object deleted events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void handleObjectDeleted(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles object repair events. This implementation does nothing and should
* be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void handleObjectRepaired(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
protected void handleObjectIndex(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles derivate created events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void handleDerivateCreated(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
/**
* Handles derivate updated events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
/**
* Handles derivate deleted events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void handleDerivateDeleted(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
/**
* Handles derivate repair events. This implementation does nothing and
* should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void handleDerivateRepaired(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
protected void handlePathUpdated(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void handlePathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void handlePathRepaired(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void updatePathIndex(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void handlePathCreated(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
/**
* Handles undo of classification created events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void undoClassificationCreated(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles undo of classification updated events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void undoClassificationUpdated(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles undo of classification deleted events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void undoClassificationDeleted(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles undo of classification repaired events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRClassification that caused the event
*/
protected void undoClassificationRepaired(MCREvent evt, MCRCategory obj) {
doNothing(evt, obj);
}
/**
* Handles undo of object created events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void undoObjectCreated(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles undo of object updated events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void undoObjectUpdated(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles undo of object deleted events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void undoObjectDeleted(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles undo of object repaired events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param obj
* the MCRObject that caused the event
*/
protected void undoObjectRepaired(MCREvent evt, MCRObject obj) {
doNothing(evt, obj);
}
/**
* Handles undo of derivate created events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void undoDerivateCreated(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
/**
* Handles undo of derivate updated events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void undoDerivateUpdated(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
/**
* Handles undo of derivate deleted events. This implementation does nothing
* and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void undoDerivateDeleted(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
/**
* Handles undo of derivate repaired events. This implementation does
* nothing and should be overwritted by subclasses.
*
* @param evt
* the event that occured
* @param der
* the MCRDerivate that caused the event
*/
protected void undoDerivateRepaired(MCREvent evt, MCRDerivate der) {
doNothing(evt, der);
}
protected void undoPathCreated(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void undoPathUpdated(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void undoPathDeleted(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
protected void undoPathRepaired(MCREvent evt, Path path, BasicFileAttributes attrs) {
doNothing(evt, path);
}
/**
* Updates the index content of the given file.
*/
protected void updateDerivateFileIndex(MCREvent evt, MCRDerivate file) {
doNothing(evt, file);
}
}
| 22,501 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRHttpSessionListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRHttpSessionListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionResolver;
import org.mycore.frontend.servlets.MCRServlet;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
/**
* Handles different HttpSession events.
*
* This class is used to free up MCRSessions when their associated HttpSession
* is destroyed or a new MCRSession replaces an old one.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRHttpSessionListener implements HttpSessionListener {
private static final Logger LOGGER = LogManager.getLogger();
/*
* (non-Javadoc)
*
* @see jakarta.servlet.http.HttpSessionListener#sessionCreated(jakarta.servlet.http.HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent hse) {
LOGGER.debug(() -> "HttpSession " + hse.getSession().getId() + " is being created by: " + hse.getSource());
}
/*
* (non-Javadoc)
*
* @see jakarta.servlet.http.HttpSessionListener#sessionDestroyed(jakarta.servlet.http.HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent hse) {
// clear MCRSessions
HttpSession httpSession = hse.getSession();
LOGGER.debug(() -> "HttpSession " + httpSession.getId() + " is being destroyed by " + hse.getSource()
+ ", clearing up.");
LOGGER.debug("Removing any MCRSessions from HttpSession");
Optional.ofNullable(httpSession.getAttribute(MCRServlet.ATTR_MYCORE_SESSION))
.map(MCRSessionResolver.class::cast).flatMap(MCRSessionResolver::resolveSession)
.ifPresent(MCRSession::close);
httpSession.removeAttribute(MCRServlet.ATTR_MYCORE_SESSION);
LOGGER.debug("Clearing up done");
}
}
| 2,675 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCREventManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCREventManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
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.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
/**
* Acts as a multiplexer to forward events that are created to all registered
* event handlers, in the order that is configured in mycore properties. For
* information how to configure, see MCREventHandler javadocs.
*
* @see MCREventHandler
* @see MCREventHandlerBase
*
* @author Frank Lützenkirchen
*/
public class MCREventManager {
public static final String CONFIG_PREFIX = "MCR.EventHandler.";
/** Call event handlers in forward direction (create, update) */
public static final boolean FORWARD = true;
/** Call event handlers in backward direction (delete) */
public static final boolean BACKWARD = false;
private static Logger logger = LogManager.getLogger(MCREventManager.class);
private static MCREventManager instance;
/** Table of all configured event handlers * */
private ConcurrentHashMap<String, List<MCREventHandler>> handlers;
private MCREventManager() {
handlers = new ConcurrentHashMap<>();
Map<String, String> props = MCRConfiguration2.getPropertiesMap()
.entrySet()
.stream()
.filter(p -> p.getKey().startsWith(CONFIG_PREFIX))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
List<String> propertyKeyList = new ArrayList<>(props.size());
for (Object name : props.keySet()) {
String key = name.toString();
if (!key.startsWith(CONFIG_PREFIX + "Mode.")) {
propertyKeyList.add(key);
}
}
Collections.sort(propertyKeyList);
for (String propertyKey : propertyKeyList) {
EventHandlerProperty eventHandlerProperty = new EventHandlerProperty(propertyKey);
String type = eventHandlerProperty.getType();
String mode = eventHandlerProperty.getMode();
logger.debug("EventManager instantiating handler {} for type {}", props.get(propertyKey), type);
if (propKeyIsSet(propertyKey)) {
addEventHandler(type, getEventHandler(mode, propertyKey));
}
}
}
/**
* The singleton manager instance
*
* @return the single event manager
*/
public static synchronized MCREventManager instance() {
if (instance == null) {
instance = new MCREventManager();
}
return instance;
}
private boolean propKeyIsSet(String propertyKey) {
return MCRConfiguration2.getString(propertyKey).isPresent();
}
private List<MCREventHandler> getOrCreateEventHandlerListOfType(String type) {
return handlers.computeIfAbsent(type, k -> new ArrayList<>());
}
/**
* This method is called by the component that created the event and acts as
* a multiplexer that invokes all registered event handlers doHandleEvent
* methods. If something goes wrong and an exception is caught, the
* undoHandleEvent methods of all event handlers that are at a position
* BEFORE the failed one, will be called in reversed order. The parameter
* direction controls the order in which the event handlers are called.
*
* @see MCREventHandler#doHandleEvent
* @see MCREventHandlerBase
*
* @param evt
* the event that happened
* @param direction
* the order in which the event handlers are called
*/
public void handleEvent(MCREvent evt, boolean direction) {
final String objectType = evt.getObjectType() == MCREvent.ObjectType.CUSTOM ? evt.getCustomObjectType()
: evt.getObjectType().getClassName();
List<MCREventHandler> list = handlers.get(objectType);
if (list == null) {
return;
}
int first = direction ? 0 : list.size() - 1;
int last = direction ? list.size() - 1 : 0;
int step = direction ? 1 : -1;
int undoPos = first;
Exception handleEventExceptionCaught = null;
final String eventType = evt.getEventType() == MCREvent.EventType.CUSTOM ? evt.getCustomEventType()
: evt.getEventType().name();
for (int i = first; i != last + step; i += step) {
MCREventHandler eh = list.get(i);
logger.debug("EventManager {} {} calling handler {}", objectType, eventType,
eh.getClass().getName());
try {
eh.doHandleEvent(evt);
} catch (Exception ex) {
handleEventExceptionCaught = ex;
logger.error("Exception caught while calling event handler", ex);
logger.error("Trying rollback by calling undo method of event handlers");
undoPos = i;
break;
}
}
// Rollback by calling undo of successfull handlers
for (int i = undoPos - step; i != first - step; i -= step) {
MCREventHandler eh = list.get(i);
logger.debug("EventManager {} {} calling undo of handler {}", objectType, eventType,
eh.getClass().getName());
try {
eh.undoHandleEvent(evt);
} catch (Exception ex) {
logger.error("Exception caught while calling undo of event handler", ex);
}
}
if (handleEventExceptionCaught != null) {
String msg = "Exception caught in EventHandler, rollback by calling undo of successfull handlers done.";
throw new MCRException(msg, handleEventExceptionCaught);
}
}
/** Same as handleEvent( evt, MCREventManager.FORWARD ) */
public void handleEvent(MCREvent evt) throws MCRException {
handleEvent(evt, MCREventManager.FORWARD);
}
/**
* Appends the event handler to the end of the list.
*
* @param type type of event e.g. MCRObject
*/
public MCREventManager addEventHandler(MCREvent.ObjectType type, MCREventHandler handler) {
checkNonCustomObjectType(type);
return addEventHandler(type.getClassName(), handler);
}
private static void checkNonCustomObjectType(MCREvent.ObjectType type) {
if (type == MCREvent.ObjectType.CUSTOM) {
throw new IllegalArgumentException("'CUSTOM' object type is unsupported here.");
}
}
/**
* Appends the event handler to the end of the list.
*
* @param type type of event e.g. MCRObject
*/
public MCREventManager addEventHandler(String type, MCREventHandler handler) {
getOrCreateEventHandlerListOfType(type).add(handler);
return this;
}
/**
* Inserts the event handler at the specified position.
*
* @param type type of event e.g. MCRObject
* @param index index at which the specified element is to be inserted
*/
public MCREventManager addEventHandler(MCREvent.ObjectType type, MCREventHandler handler, int index) {
checkNonCustomObjectType(type);
return addEventHandler(type.getClassName(), handler, index);
}
/**
* Inserts the event handler at the specified position.
*
* @param type type of event e.g. MCRObject
* @param index index at which the specified element is to be inserted
*/
public MCREventManager addEventHandler(String type, MCREventHandler handler, int index) {
getOrCreateEventHandlerListOfType(type).add(index, handler);
return this;
}
/**
* Removes the specified event handler.
*
* @param type type of event handler
* @param handler the event handler to remove
*/
public MCREventManager removeEventHandler(MCREvent.ObjectType type, MCREventHandler handler) {
checkNonCustomObjectType(type);
return removeEventHandler(type.getClassName(), handler);
}
/**
* Removes the specified event handler.
*
* @param type type of event handler
* @param handler the event handler to remove
*/
public MCREventManager removeEventHandler(String type, MCREventHandler handler) {
List<MCREventHandler> handlerList = this.handlers.get(type);
handlerList.remove(handler);
if (handlerList.isEmpty()) {
this.handlers.remove(type);
}
return this;
}
/**
* Removes all event handler of the specified type.
*
* @param type type to removed
*/
public MCREventManager removeEventHandler(MCREvent.ObjectType type) {
checkNonCustomObjectType(type);
return removeEventHandler(type.getClassName());
}
/**
* Removes all event handler of the specified type.
*
* @param type type to removed
*/
public MCREventManager removeEventHandler(String type) {
this.handlers.remove(type);
return this;
}
/**
* Clears the <code>MCREventManager</code> so that it contains no <code>MCREventHandler</code>.
*/
public MCREventManager clear() {
this.handlers.clear();
return this;
}
public MCREventHandler getEventHandler(String mode, String propertyValue) {
if (Objects.equals(mode, "Class")) {
return MCRConfiguration2.<MCREventHandler>getSingleInstanceOf(propertyValue)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(propertyValue));
}
String className = CONFIG_PREFIX + "Mode." + mode;
MCREventHandlerInitializer configuredInitializer = MCRConfiguration2
.<MCREventHandlerInitializer>getSingleInstanceOf(className)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(className));
return configuredInitializer.getInstance(propertyValue);
}
public interface MCREventHandlerInitializer {
MCREventHandler getInstance(String propertyValue);
}
/**
* Parse the property key of event handlers, extract type and mode.
*
* @see MCREventHandler
*
* @author Huu Chi Vu
*
*/
private static class EventHandlerProperty {
private String type;
private String mode;
EventHandlerProperty(String propertyKey) {
String[] splitedKey = propertyKey.split("\\.");
if (splitedKey.length != 5) {
throw new MCRConfigurationException("Property key " + propertyKey + " for event handler not valid.");
}
this.setType(splitedKey[2]);
this.setMode(splitedKey[4]);
}
public String getType() {
return type;
}
private void setType(String type) {
this.type = type;
}
public String getMode() {
return mode;
}
private void setMode(String mode) {
this.mode = mode;
}
}
}
| 11,967 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRSessionListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRSessionListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
/**
* @author Thomas Scheffler (yagee)
*
* @since 2.0
*/
public interface MCRSessionListener {
void sessionEvent(MCRSessionEvent event);
}
| 912 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJanitorEventHandlerBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/events/MCRJanitorEventHandlerBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.events;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRUserInformation;
/**
* A EventHandler which runs as {@link MCRSystemUserInformation#getJanitorInstance()}.
*/
public class MCRJanitorEventHandlerBase extends MCREventHandlerBase {
@Override
public void doHandleEvent(MCREvent evt) {
MCRUserInformation prevUserInformation = MCRSessionMgr.getCurrentSession().getUserInformation();
try {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getGuestInstance());
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getJanitorInstance());
super.doHandleEvent(evt);
} finally {
MCRSessionMgr.getCurrentSession().setUserInformation(MCRSystemUserInformation.getGuestInstance());
MCRSessionMgr.getCurrentSession().setUserInformation(prevUserInformation);
}
}
}
| 1,743 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLParserImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLParserImpl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Paths;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaderJDOMFactory;
import org.mycore.common.MCRException;
import org.mycore.common.content.MCRContent;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.EntityResolver2;
/**
* Parses XML content using specified {@link XMLReaderJDOMFactory}.
*
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public class MCRXMLParserImpl implements MCRXMLParser {
private static final String FEATURE_NAMESPACES = "http://xml.org/sax/features/namespaces";
private static final String FEATURE_SCHEMA_SUPPORT = "http://apache.org/xml/features/validation/schema";
private static final String FEATURE_FULL_SCHEMA_SUPPORT
= "http://apache.org/xml/features/validation/schema-full-checking";
private static final String MSG = "Error while parsing XML document: ";
private boolean validate;
private SAXBuilder builder;
public MCRXMLParserImpl(XMLReaderJDOMFactory factory) {
this(factory, false);
}
public MCRXMLParserImpl(XMLReaderJDOMFactory factory, boolean silent) {
this.validate = factory.isValidating();
builder = new SAXBuilder(factory);
builder.setFeature(FEATURE_NAMESPACES, true);
builder.setFeature(FEATURE_SCHEMA_SUPPORT, validate);
builder.setFeature(FEATURE_FULL_SCHEMA_SUPPORT, false);
builder.setErrorHandler(new MCRXMLParserErrorHandler(silent));
builder.setEntityResolver(new AbsoluteToRelativeResolver(MCREntityResolver.instance()));
}
public boolean isValidating() {
return validate;
}
public Document parseXML(MCRContent content) throws IOException, JDOMException {
InputSource source = content.getInputSource();
return builder.build(source);
}
@Override
public XMLReader getXMLReader() throws SAXException, ParserConfigurationException {
try {
return builder.getXMLReaderFactory().createXMLReader();
} catch (JDOMException e) {
Throwable cause = e.getCause();
if (e != null) {
if (cause instanceof SAXException se) {
throw se;
}
if (cause instanceof ParserConfigurationException pce) {
throw pce;
}
}
throw new MCRException(e);
}
}
/**
* Xerces 2.11.0 does not provide a relative systemId if baseURI is a XML file to be validated by a schema specified
* in systemId. This EntityResolver makes a relative systemId so that the fallback could conform to the defined
* interface.
*
* @author Thomas Scheffler (yagee)
*/
private static class AbsoluteToRelativeResolver implements EntityResolver2 {
private EntityResolver2 fallback;
private static Logger LOGGER = LogManager.getLogger(MCRXMLParserImpl.class);
private static URI baseDirURI = Paths.get("").toAbsolutePath().toUri();
AbsoluteToRelativeResolver(EntityResolver2 fallback) {
this.fallback = fallback;
}
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return fallback.resolveEntity(publicId, systemId);
}
@Override
public InputSource getExternalSubset(String name, String baseURI) throws SAXException, IOException {
return fallback.getExternalSubset(name, baseURI);
}
@Override
public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId)
throws SAXException, IOException {
if (baseURI == null) {
//check if baseDirURI is part of systemID and seperate
try {
String relativeURI = baseDirURI.relativize(URI.create(systemId)).toString();
if (!systemId.equals(relativeURI)) {
return resolveEntity(name, publicId, baseDirURI.toString(), relativeURI);
}
} catch (RuntimeException e) {
LOGGER.debug("Could not separate baseURI from {}", systemId, e);
}
}
String relativeSystemId = relativize(baseURI, systemId);
if (relativeSystemId.equals(systemId)) {
LOGGER.debug("Try to use EntityResolver interface");
InputSource inputSource = resolveEntity(publicId, systemId);
if (inputSource != null) {
LOGGER.debug("Found resource in EntityResolver interface");
return inputSource;
}
}
return fallback.resolveEntity(name, publicId, baseURI, relativeSystemId);
}
private static String relativize(String baseURI, String systemId) {
if (baseURI == null) {
return systemId;
}
baseURI = normalize(baseURI);
int pos = baseURI.lastIndexOf('/');
String prefix = baseURI.substring(0, pos + 1);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("prefix of baseURI ''{}'' is: {}", baseURI, prefix);
LOGGER.debug("systemId: {} prefixed? {}", systemId, systemId.startsWith(prefix));
}
if (prefix.length() > 0 && systemId.startsWith(prefix)) {
systemId = systemId.substring(prefix.length());
LOGGER.debug("new systemId: {}", systemId);
return systemId;
}
return systemId;
}
private static String normalize(String baseURI) {
try {
return URI.create(baseURI).normalize().toString();
} catch (RuntimeException e) {
LOGGER.debug("Error while normalizing {}", baseURI, e);
return baseURI;
}
}
}
}
| 7,057 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRCache;
import org.mycore.common.MCRClassTools;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationDir;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.MCRURLContent;
/**
* provides a cache for reading XML resources.
*
* Cache size can be configured by property
* <code>MCR.MCRXMLResouce.Cache.Size</code> which defaults to <code>100</code>.
*
* @author Thomas Scheffler (yagee)
*/
public class MCRXMLResource {
private static final MCRCache<String, CacheEntry> RESOURCE_CACHE = new MCRCache<>(
MCRConfiguration2.getInt("MCR.MCRXMLResource.Cache.Size").orElse(100),
"XML resources");
private static MCRXMLResource instance = new MCRXMLResource();
private static Logger LOGGER = LogManager.getLogger(MCRXMLResource.class);
private MCRXMLResource() {
}
/**
* @return singleton instance
*/
public static MCRXMLResource instance() {
return instance;
}
private static URLConnection getResourceURLConnection(String name, ClassLoader classLoader) throws IOException {
LOGGER.debug("Reading xml from classpath resource {}", name);
URL url = MCRConfigurationDir.getConfigResource(name, classLoader);
LOGGER.debug("Resource URL:{}", url);
if (url == null) {
return null;
}
return url.openConnection();
}
private static MCRContent getDocument(URL url) {
return new MCRURLContent(url);
}
private static void closeURLConnection(URLConnection con) throws IOException {
if (con == null) {
return;
}
con.getInputStream().close();
}
public URL getURL(String name) throws IOException {
return getURL(name, MCRClassTools.getClassLoader());
}
public URL getURL(String name, ClassLoader classLoader) throws IOException {
URLConnection con = getResourceURLConnection(name, classLoader);
if (con == null) {
return null;
}
try {
return con.getURL();
} finally {
closeURLConnection(con);
}
}
/**
* Returns MCRContent using ClassLoader of MCRXMLResource class
*
* @param name
* resource name
* @see MCRXMLResource#getResource(String, ClassLoader)
*/
public MCRContent getResource(String name) throws IOException {
return getResource(name, MCRClassTools.getClassLoader());
}
/**
* returns xml as byte array using ClassLoader of MCRXMLResource class
*
* @param name
* resource name
* @see MCRXMLResource#getRawResource(String, ClassLoader)
*/
public byte[] getRawResource(String name) throws IOException {
return getRawResource(name, MCRClassTools.getClassLoader());
}
/**
* Returns MCRContent of resource.
*
* A cache is used to avoid reparsing if the source of the resource did not
* change.
*
* @param name
* the resource name
* @param classLoader
* a ClassLoader that should be used to locate the resource
* @return a parsed Document of the resource or <code>null</code> if the
* resource is not found
* @throws IOException
* if resource cannot be loaded
*/
public MCRContent getResource(String name, ClassLoader classLoader) throws IOException {
ResourceModifiedHandle modifiedHandle = getModifiedHandle(name, classLoader, 10000);
CacheEntry entry = RESOURCE_CACHE.getIfUpToDate(name, modifiedHandle);
URL resolvedURL = modifiedHandle.getURL();
if (entry != null && (resolvedURL == null || entry.resourceURL.equals(resolvedURL))) {
LOGGER.debug("Using cached resource {}", name);
return entry.content;
}
if (resolvedURL == null) {
LOGGER.warn("Could not resolve resource: {}", name);
return null;
}
entry = new CacheEntry();
RESOURCE_CACHE.put(name, entry);
entry.resourceURL = resolvedURL;
entry.content = getDocument(entry.resourceURL);
return entry.content;
}
public ResourceModifiedHandle getModifiedHandle(String name, ClassLoader classLoader, long checkPeriod) {
return new ResourceModifiedHandle(name, classLoader, checkPeriod);
}
/**
* Returns raw XML resource as byte array. Note that no cache will be used.
*
* @param name
* the resource name
* @param classLoader
* a ClassLoader that should be used to locate the resource
* @return unparsed xml of the resource or <code>null</code> if the
* resource is not found
* @throws IOException
* if resource cannot be loaded
*/
public byte[] getRawResource(String name, ClassLoader classLoader) throws IOException {
URLConnection con = getResourceURLConnection(name, classLoader);
if (con == null) {
return null;
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(64 * 1024);
InputStream in = new BufferedInputStream(con.getInputStream())) {
IOUtils.copy(in, baos);
return baos.toByteArray();
} finally {
closeURLConnection(con);
}
}
public long getLastModified(String name, ClassLoader classLoader) throws IOException {
URLConnection con = getResourceURLConnection(name, classLoader);
try {
return con == null ? -1 : con.getLastModified();
} finally {
closeURLConnection(con);
}
}
public boolean exists(String name, ClassLoader classLoader) throws IOException {
final URLConnection resourceURLConnection = getResourceURLConnection(name, classLoader);
try {
return resourceURLConnection != null;
} finally {
closeURLConnection(resourceURLConnection);
}
}
private static class CacheEntry {
URL resourceURL;
MCRContent content;
}
public static class ResourceModifiedHandle implements MCRCache.ModifiedHandle {
private long checkPeriod;
private String name;
private ClassLoader classLoader;
private URL resolvedURL;
public ResourceModifiedHandle(String name, ClassLoader classLoader, long checkPeriod) {
this.name = name;
this.classLoader = classLoader;
this.checkPeriod = checkPeriod;
}
public URL getURL() {
return this.resolvedURL == null ? MCRConfigurationDir.getConfigResource(name, classLoader)
: this.resolvedURL;
}
@Override
public long getCheckPeriod() {
return checkPeriod;
}
@Override
public long getLastModified() throws IOException {
URLConnection con = getResourceURLConnection(name, classLoader);
if (con == null) {
return -1;
}
try {
long lastModified = con.getLastModified();
resolvedURL = con.getURL();
LOGGER.debug("{} last modified: {}", name, lastModified);
return lastModified;
} finally {
closeURLConnection(con);
}
}
}
}
| 8,528 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXSLTransformation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXSLTransformation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.File;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.output.SAXOutputter;
import org.jdom2.transform.JDOMResult;
import org.jdom2.transform.JDOMSource;
/**
* This class implements XSLTransformation functions to be used in all other
* MyCoRe packages. The class is implemented as singleton and should be very
* easy to use. So here is an example:
*
* <PRE>
* // Get an instance of the class
* MCRXSLTransformation transformation = MCRXSLTransformation.getInstance();
* // Get the template: myStylesheet could be a String (i.e. a filename),
* // a File or a StreamSource Templates
* templates = transformation.getStylesheet(myStylesheet);
* // Next, you are in need of a TransformerHandler:
* TransformerHandler th = transformation.getTransformerHandler(templates);
* // Now you are able to set some properties (if you want!):
* Properties parameters = new Properties(); ...
* transformation.setParameters(th, parameters);
* // Finally, you need an OutputStream and might get at work:
* OutputStream out = response.getOutputStream();
* transformation.transform(jdom, th, out);
* // You might also want to transform into something different, perhaps a ZIP-File:
* OutputStream out = new ZipOutputStream(response.getOutputStream());
* ((ZipOutputStream) out).setLevel(Deflater.BEST_COMPRESSION);
* ZipEntry ze = new ZipEntry("_index.htm");
* ((ZipOutputStream) out).putNextEntry(ze); ...
* // After all this work is done, you could close the OutputStream:
* out.close();
* // This is not done by <CODE>transform</CODE>, the later example
* // should show, why. *
* </PRE>
*
* @author Werner Gresshoff
*
* @deprecated use {@link org.mycore.common.xsl.MCRXSLTransformerFactory} or
* {@link org.mycore.common.content.transformer.MCRXSLTransformer} instead
*/
@Deprecated
public class MCRXSLTransformation {
private static Logger LOGGER = LogManager.getLogger(MCRXSLTransformation.class);
private static SAXTransformerFactory saxFactory = null;
private static TransformerFactory factory = TransformerFactory.newInstance();
private static final Map EMPTY_PARAMETERS = Collections.unmodifiableMap(new HashMap(0, 1));
private static MCRXSLTransformation singleton = null;
static {
factory.setURIResolver(MCRURIResolver.instance());
try {
TransformerFactory tf = TransformerFactory.newInstance();
if (tf.getFeature(SAXTransformerFactory.FEATURE)) {
saxFactory = (SAXTransformerFactory) tf;
saxFactory.setURIResolver(MCRURIResolver.instance());
} else {
LOGGER.fatal("TransformerFactory could not be initialized.");
}
} catch (TransformerFactoryConfigurationError tfce) {
if (tfce.getMessage() != null) {
LOGGER.fatal(tfce.getMessage());
} else {
LOGGER.fatal("Error in TranformerFactory configuration.");
}
}
}
/**
* Method getInstance. Creates an instance of MCRXSLTransformation, when
* called the first time.
*
* @return MCRXSLTransformation
*/
public static synchronized MCRXSLTransformation getInstance() {
if (singleton == null) {
singleton = new MCRXSLTransformation();
}
return singleton;
}
/**
* Method getStylesheet. Returns a precompiled stylesheet.
*
* @param stylesheet
* Full path to the stylesheet
* @return Templates The precompiled Stylesheet
*/
public Templates getStylesheet(String stylesheet) {
File styleFile = new File(stylesheet);
if (!styleFile.exists()) {
LOGGER.fatal("The Stylesheet doesn't exist: {}", stylesheet);
return null;
}
return getStylesheet(styleFile);
}
/**
* Method getStylesheet. Returns a precompiled stylesheet.
*
* @param stylesheet
* A File with the stylesheet code
* @return Templates The precompiled Stylesheet
*/
public Templates getStylesheet(File stylesheet) {
return getStylesheet(new StreamSource(stylesheet));
}
/**
* Method getStylesheet. Returns a precompiled stylesheet.
*
* @param stylesheet
* A StreamSource
* @return Templates The precompiled Stylesheet
*/
public Templates getStylesheet(Source stylesheet) {
try {
return saxFactory.newTemplates(stylesheet);
} catch (TransformerConfigurationException tcx) {
LOGGER.fatal(tcx.getMessageAndLocation());
return null;
}
}
/**
* Method getTransformerHandler. Returns a TransformerHandler for the given
* Template.
*
* @return TransformerHandler
*/
public TransformerHandler getTransformerHandler(Templates stylesheet) {
try {
return saxFactory.newTransformerHandler(stylesheet);
} catch (TransformerConfigurationException tcx) {
LOGGER.fatal(tcx.getMessageAndLocation());
return null;
}
}
/**
* Method setParameters. Set some parameters which can be used by the
* Stylesheet for the transformation.
*
*/
public static void setParameters(TransformerHandler handler, Map parameters) {
setParameters(handler.getTransformer(), parameters);
}
/**
* Method setParameters. Set some parameters which can be used by the
* Stylesheet for the transformation.
*
*/
public static void setParameters(Transformer transformer, Map parameters) {
for (Object o : parameters.keySet()) {
String name = o.toString();
String value = parameters.get(name).toString();
transformer.setParameter(name, value);
}
}
/**
* Method transform. Transforms a JDOM-Document to the given OutputStream
*
*/
public void transform(Document in, TransformerHandler handler, OutputStream out) {
handler.setResult(new StreamResult(out));
try {
new SAXOutputter(handler).output(in);
} catch (JDOMException ex) {
LOGGER.error("Error while transforming an XML document with an XSL stylesheet.");
}
}
/**
* Method transform. Transforms a JDOM-Document <i>in </i> with a given
* <i>stylesheet </i> to a new document.
*
* @param in
* A JDOM-Document.
* @param stylesheet
* The Filename with complete path (this is not a servlet!) of
* the stylesheet.
* @return Document The new document or null, if an exception was thrown.
*/
public static Document transform(Document in, String stylesheet) {
return transform(in, stylesheet, EMPTY_PARAMETERS);
}
/**
* Method transform. Transforms a JDOM-Document <i>in </i> with a given
* <i>stylesheet </i> to a new document.
*
* @param in
* A JDOM-Document.
* @param stylesheet
* The Filename with complete path (this is not a servlet!) of
* the stylesheet.
* @param parameters
* parameters used by the stylesheet for transformation
* @return Document The new document or null, if an exception was thrown.
*/
public static Document transform(Document in, String stylesheet, Map parameters) {
return transform(in, new StreamSource(new File(stylesheet)), parameters);
}
/**
* Method transform. Transforms a JDOM-Document <i>in </i> with a given
* <i>stylesheet </i> to a new document.
*
* @param in
* A JDOM-Document.
* @param stylesheet
* The Filename with complete path (this is not a servlet!) of
* the stylesheet.
* @param parameters
* parameters used by the stylesheet for transformation
* @return Document The new document or null, if an exception was thrown.
*/
public static Document transform(Document in, Source stylesheet, Map parameters) {
try {
Transformer transformer = factory.newTransformer(stylesheet);
setParameters(transformer, parameters);
return transform(in, transformer);
} catch (TransformerException e) {
LOGGER.fatal(e.getMessage(), e);
return null;
}
}
/**
* transforms a jdom Document via XSLT.
*
* @param in Document input
* @param transformer Transformer handling the transformation process
* @return the transformation result as jdom Document
* @throws TransformerException if transformation fails
*/
public static Document transform(Document in, Transformer transformer) throws TransformerException {
JDOMResult out = new JDOMResult();
transformer.transform(new JDOMSource(in), out);
return out.getDocument();
}
}
| 10,535 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPropertiesResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRPropertiesResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import org.jdom2.DocType;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.config.MCRConfiguration2;
/**
* Resolves the property values for the given key or key prefix.<br><br>
* <br>
* Syntax: <code>property:{key-prefix}*</code> or <br>
* <code>property:{key}</code>
* <br>
* Result for a key prefix: <code> <br>
* <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <br>
* <properties> <br>
* <entry key="key1">value1</property> <br>
* <entry key="key2">value2</property> <br>
* <entry key="key3">value3</property> <br>
* </properties> <br>
* </code>
* If no entries with the given key prefix exist, a properties element without entry elements is returned.
* <br>
* Result for a key: <code> <br>
* <entry key="key">value</property>
* </code>
* If no entry with the given key exists, an entry element without text content is returned.
*/
public class MCRPropertiesResolver implements URIResolver {
@Override
public Source resolve(String href, String base) {
String target = href.substring(href.indexOf(":") + 1);
if (target.endsWith("*")) {
return resolveKeyPrefix(target.substring(0, target.length() - 1));
} else {
return resolveKey(target);
}
}
private JDOMSource resolveKeyPrefix(String keyPrefix) {
final Element propertiesElement = new Element("properties");
MCRConfiguration2.getSubPropertiesMap(keyPrefix).forEach((key, value) -> {
final Element entryElement = new Element("entry");
entryElement.setAttribute("key", keyPrefix + key);
entryElement.setText(value);
propertiesElement.addContent(entryElement);
});
return new JDOMSource(asPropertiesDocument(propertiesElement));
}
private Document asPropertiesDocument(Element propertiesElement) {
final Document document = new Document();
document.setDocType(getPropertiesDocType());
document.setContent(propertiesElement);
return document;
}
private DocType getPropertiesDocType() {
return new DocType("properties", "SYSTEM", "http://java.sun.com/dtd/properties.dtd");
}
private JDOMSource resolveKey(String key) {
final Element entryElement = new Element("entry");
entryElement.setAttribute("key", key);
String value = MCRConfiguration2.getPropertiesMap().get(key);
if (value != null) {
entryElement.setText(value);
}
return new JDOMSource(entryElement);
}
}
| 3,581 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRXMLParserFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRXMLParserFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import static org.jdom2.JDOMConstants.SAX_FEATURE_NAMESPACES;
import static org.jdom2.JDOMConstants.SAX_FEATURE_NAMESPACE_PREFIXES;
import static org.jdom2.JDOMConstants.SAX_FEATURE_VALIDATION;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.jdom2.JDOMException;
import org.jdom2.input.sax.XMLReaderJDOMFactory;
import org.jdom2.input.sax.XMLReaderSAX2Factory;
import org.mycore.common.config.MCRConfiguration2;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Returns validating or non-validating XML parsers.
*
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public class MCRXMLParserFactory {
private static boolean VALIDATE_BY_DEFAULT = MCRConfiguration2.getBoolean("MCR.XMLParser.ValidateSchema")
.orElse(true);
private static XMLReaderJDOMFactory nonValidatingFactory = new MCRXMLReaderSAX2Factory(false);
private static XMLReaderJDOMFactory validatingFactory = new MCRXMLReaderSAX2Factory(true);
private static ThreadLocal<MCRXMLParserImpl> nonValidating = ThreadLocal.withInitial(
() -> new MCRXMLParserImpl(nonValidatingFactory));
private static ThreadLocal<MCRXMLParserImpl> validating = ThreadLocal.withInitial(
() -> new MCRXMLParserImpl(validatingFactory));
private static ThreadLocal<MCRXMLParserImpl> nonValidatingSilent = ThreadLocal.withInitial(
() -> new MCRXMLParserImpl(nonValidatingFactory, true));
private static ThreadLocal<MCRXMLParserImpl> validatingSilent = ThreadLocal.withInitial(
() -> new MCRXMLParserImpl(validatingFactory, true));
/** Returns a validating parser */
public static MCRXMLParser getValidatingParser() {
return validating.get();
}
/** Returns a non-validating parser */
public static MCRXMLParser getNonValidatingParser() {
return nonValidating.get();
}
/**
* Returns a parser. The configuration property
* MCR.XMLParser.ValidateSchema (default false) will
* determine if the parser will validate or not.
*/
public static MCRXMLParser getParser() {
return VALIDATE_BY_DEFAULT ? validating.get() : nonValidating.get();
}
/**
* Returns a parser.
*
* @param validate if true, the parser will validate the XML against the schema.
*/
public static MCRXMLParser getParser(boolean validate) {
return getParser(validate, false);
}
/**
* Returns a parser.
*
* @param validate if true, the parser will validate the XML against the schema.
* @param silent if true, exception's are not logged
*/
public static MCRXMLParser getParser(boolean validate, boolean silent) {
if (silent) {
return validate ? validatingSilent.get() : nonValidatingSilent.get();
} else {
return validate ? validating.get() : nonValidating.get();
}
}
/*
* required in Java 10 as ClassLoader used in super does not find the driver
*/
private static class MCRXMLReaderSAX2Factory extends XMLReaderSAX2Factory {
MCRXMLReaderSAX2Factory(boolean validate) {
super(validate);
}
@Override
public XMLReader createXMLReader() throws JDOMException {
try {
XMLReader reader = MCRXMLHelper
.asSecureXMLReader(SAXParserFactory.newDefaultInstance().newSAXParser().getXMLReader());
reader.setFeature(SAX_FEATURE_VALIDATION, isValidating());
reader.setFeature(SAX_FEATURE_NAMESPACES, true);
reader.setFeature(SAX_FEATURE_NAMESPACE_PREFIXES, true);
return reader;
} catch (SAXException | ParserConfigurationException e) {
throw new JDOMException("Unable to create SAX2 XMLReader.", e);
}
}
}
}
| 4,672 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRLayoutService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/common/xml/MCRLayoutService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.common.xml;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Objects;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.content.MCRContent;
import org.mycore.common.content.transformer.MCRContentTransformer;
import org.mycore.common.content.transformer.MCRParameterizedTransformer;
import org.mycore.common.xsl.MCRParameterCollector;
import org.xml.sax.SAXException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Does the layout for other MyCoRe servlets by transforming XML input to
* various output formats, using XSL stylesheets.
*
* @author Frank Lützenkirchen
* @author Thomas Scheffler (yagee)
*/
public class MCRLayoutService {
private static final int INITIAL_BUFFER_SIZE = 32 * 1024;
static final Logger LOGGER = LogManager.getLogger(MCRLayoutService.class);
private static final MCRLayoutService SINGLETON = new MCRLayoutService();
private static final String TRANSFORMER_FACTORY_PROPERTY = "MCR.Layout.Transformer.Factory";
public static MCRLayoutService instance() {
return SINGLETON;
}
public void sendXML(HttpServletRequest req, HttpServletResponse res, MCRContent xml) throws IOException {
res.setContentType("text/xml; charset=UTF-8");
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
StreamResult result = new StreamResult(res.getOutputStream());
transformer.transform(xml.getSource(), result);
} catch (TransformerException e) {
throw new MCRException(e);
}
res.flushBuffer();
}
public void doLayout(HttpServletRequest req, HttpServletResponse res, MCRContent source) throws IOException,
TransformerException, SAXException {
if (res.isCommitted()) {
LOGGER.warn("Response already committed: {}:{}", res.getStatus(), res.getContentType());
return;
}
String docType = source.getDocType();
try {
MCRParameterCollector parameter = new MCRParameterCollector(req);
MCRContentTransformer transformer = getContentTransformer(docType, parameter);
String filename = getFileName(req, parameter);
transform(res, transformer, source, parameter, filename);
} catch (IOException | TransformerException | SAXException ex) {
throw ex;
} catch (MCRException ex) {
// Check if it is an error page to suppress later recursively
// generating an error page when there is an error in the stylesheet
if (!Objects.equals(docType, "mcr_error")) {
throw ex;
}
String msg = "Error while generating error page!";
LOGGER.warn(msg, ex);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
} catch (Exception e) {
throw new MCRException(e);
}
}
public MCRContent getTransformedContent(HttpServletRequest req, HttpServletResponse res, MCRContent source)
throws IOException, TransformerException, SAXException {
String docType = source.getDocType();
try {
MCRParameterCollector parameter = new MCRParameterCollector(req);
MCRContentTransformer transformer = getContentTransformer(docType, parameter);
String filename = getFileName(req, parameter);
return transform(transformer, source, parameter, filename);
} catch (IOException | TransformerException | SAXException ex) {
throw ex;
} catch (MCRException ex) {
// Check if it is an error page to suppress later recursively
// generating an error page when there is an error in the stylesheet
if (!Objects.equals(docType, "mcr_error")) {
throw ex;
}
String msg = "Error while generating error page!";
LOGGER.warn(msg, ex);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
return null;
} catch (Exception e) {
throw new MCRException(e);
}
}
public static MCRContentTransformer getContentTransformer(String docType, MCRParameterCollector parameter) {
String transformerId = parameter.getParameter("Transformer", null);
if (transformerId == null) {
String style = parameter.getParameter("Style", "default");
transformerId = new MessageFormat("{0}-{1}", Locale.ROOT).format(new Object[] { docType, style });
}
MCRLayoutTransformerFactory factory = MCRConfiguration2.<MCRLayoutTransformerFactory>getInstanceOf(
TRANSFORMER_FACTORY_PROPERTY)
.orElseGet(MCRLayoutTransformerFactory::new);
return factory.getTransformer(transformerId);
}
private String getFileName(HttpServletRequest req, MCRParameterCollector parameter) {
String filename = parameter.getParameter("FileName", null);
if (filename != null) {
if (req.getServletPath().contains(filename)) {
//filter out MCRStaticXMLFileServlet as it defines "FileName"
return extractFileName(req.getServletPath());
}
return filename;
}
if (req.getPathInfo() != null) {
return extractFileName(req.getPathInfo());
}
return new MessageFormat("{0}-{1}", Locale.ROOT).format(
new Object[] { extractFileName(req.getServletPath()), String.valueOf(System.currentTimeMillis()) });
}
private String extractFileName(String filename) {
int filePosition = filename.lastIndexOf('/') + 1;
filename = filename.substring(filePosition);
filePosition = filename.lastIndexOf('.');
if (filePosition > 0) {
filename = filename.substring(0, filePosition);
}
return filename;
}
private void transform(HttpServletResponse response, MCRContentTransformer transformer, MCRContent source,
MCRParameterCollector parameter, String filename) throws IOException, TransformerException, SAXException {
try {
String fileExtension = transformer.getFileExtension();
if (fileExtension != null && fileExtension.length() > 0) {
filename += "." + fileExtension;
}
response.setHeader("Content-Disposition",
transformer.getContentDisposition() + ";filename=\"" + filename + "\"");
String ct = transformer.getMimeType();
String enc = transformer.getEncoding();
if (enc != null) {
response.setCharacterEncoding(enc);
response.setContentType(ct + "; charset=" + enc);
} else {
response.setContentType(ct);
}
LOGGER.debug("MCRLayoutService starts to output {}", response.getContentType());
ServletOutputStream servletOutputStream = response.getOutputStream();
long start = System.currentTimeMillis();
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(INITIAL_BUFFER_SIZE);
if (transformer instanceof MCRParameterizedTransformer paramTransformer) {
paramTransformer.transform(source, bout, parameter);
} else {
transformer.transform(source, bout);
}
endCurrentTransaction();
response.setContentLength(bout.size());
bout.writeTo(servletOutputStream);
} finally {
LOGGER.debug("MCRContent transformation took {} ms.", System.currentTimeMillis() - start);
}
} catch (TransformerException | IOException | SAXException e) {
throw e;
} catch (Exception e) {
Throwable cause = e.getCause();
while (cause != null) {
if (cause instanceof TransformerException te) {
throw te;
} else if (cause instanceof SAXException se) {
throw se;
} else if (cause instanceof IOException ioe) {
throw ioe;
}
cause = cause.getCause();
}
throw new IOException(e);
}
}
private MCRContent transform(MCRContentTransformer transformer, MCRContent source, MCRParameterCollector parameter,
String filename) throws IOException, TransformerException, SAXException {
LOGGER.debug("MCRLayoutService starts to output {}", getMimeType(transformer));
long start = System.currentTimeMillis();
try {
if (transformer instanceof MCRParameterizedTransformer paramTransformer) {
return paramTransformer.transform(source, parameter);
} else {
return transformer.transform(source);
}
} finally {
LOGGER.debug("MCRContent transformation took {} ms.", System.currentTimeMillis() - start);
}
}
private String getMimeType(MCRContentTransformer transformer) throws IOException, TransformerException,
SAXException {
try {
return transformer.getMimeType();
} catch (IOException | TransformerException | SAXException | RuntimeException e) {
throw e;
} catch (Exception e) {
return "application/octet-stream";
}
}
/**
* Called before sending data to end hibernate transaction.
*/
private static void endCurrentTransaction() {
MCRSessionMgr.getCurrentSession();
MCRTransactionHelper.commitTransaction();
}
}
| 11,218 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.