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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MCRTransactionableCallable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRTransactionableCallable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Objects;
import java.util.concurrent.Callable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
/**
* Encapsulates a {@link Callable} with a mycore session and a database transaction.
*
* @author Matthias Eichner
*/
public class MCRTransactionableCallable<V> implements Callable<V>, MCRDecorator<Callable<V>> {
private static final Logger LOGGER = LogManager.getLogger();
private Callable<V> callable;
protected MCRSession session;
/**
* Creates a new {@link Callable} encapsulating the {@link #call()} method with a new
* {@link MCRSession} and a database transaction. Afterwards the transaction will
* be committed and the session will be released and closed.
*
* <p>If you want to execute your callable in the context of an already existing
* session use the {@link MCRTransactionableCallable#MCRTransactionableCallable(Callable, MCRSession)}
* constructor instead.
*
* @param callable the callable to execute within a session and transaction
*/
public MCRTransactionableCallable(Callable<V> callable) {
this.callable = Objects.requireNonNull(callable, "callable must not be null");
}
/**
* Creates a new {@link Callable} encapsulating the {@link #call()} method with a new
* a database transaction. The transaction will be created in the context of the
* given session. Afterwards the transaction will be committed and the session
* will be released (but not closed!).
*
* @param callable the callable to execute within a session and transaction
* @param session the session to use
*/
public MCRTransactionableCallable(Callable<V> callable, MCRSession session) {
this.callable = Objects.requireNonNull(callable, "callable must not be null");
this.session = Objects.requireNonNull(session, "session must not be null");
}
@Override
public V call() throws Exception {
boolean newSession = this.session == null;
MCRSessionMgr.unlock();
boolean closeSession = newSession && !MCRSessionMgr.hasCurrentSession();
if (newSession) {
this.session = MCRSessionMgr.getCurrentSession();
}
MCRSessionMgr.setCurrentSession(this.session);
try {
MCRTransactionHelper.beginTransaction();
return this.callable.call();
} finally {
try {
MCRTransactionHelper.commitTransaction();
} catch (Exception commitExc) {
LOGGER.error("Error while commiting transaction.", commitExc);
try {
MCRTransactionHelper.rollbackTransaction();
} catch (Exception rollbackExc) {
LOGGER.error("Error while rollbacking transaction.", commitExc);
}
} finally {
MCRSessionMgr.releaseCurrentSession();
if (closeSession && session != null) {
session.close();
}
}
}
}
@Override
public Callable<V> get() {
return callable;
}
}
| 4,061 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPrioritySupplier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRPrioritySupplier.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
/**
* A supplier with a priority.
*
* <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a>
*
* @author Matthias Eichner
*
* @param <T> the type of results supplied by this supplier
*/
public class MCRPrioritySupplier<T> implements Supplier<T>, MCRPrioritizable {
private static AtomicLong CREATION_COUNTER = new AtomicLong(0);
private Supplier<T> delegate;
private int priority;
private long created;
public MCRPrioritySupplier(Supplier<T> delegate, int priority) {
this.delegate = delegate;
this.priority = priority;
this.created = CREATION_COUNTER.incrementAndGet();
}
@Override
public T get() {
return delegate.get();
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public long getCreated() {
return created;
}
/**
* use this instead of {@link CompletableFuture#supplyAsync(Supplier, Executor)}
*
* This method keep the priority
*/
public CompletableFuture<T> runAsync(ExecutorService es) {
CompletableFuture<T> result = new CompletableFuture<>();
MCRPrioritySupplier<T> supplier = this;
class MCRAsyncPrioritySupplier
implements Runnable, MCRPrioritizable, CompletableFuture.AsynchronousCompletionTask {
@Override
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public void run() {
try {
if (!result.isDone()) {
result.complete(supplier.get());
}
} catch (Throwable t) {
result.completeExceptionally(t);
}
}
@Override
public int getPriority() {
return supplier.getPriority();
}
@Override
public long getCreated() {
return supplier.getCreated();
}
}
es.execute(new MCRAsyncPrioritySupplier());
return result;
}
}
| 3,124 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRFixedUserCallable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRFixedUserCallable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Objects;
import java.util.concurrent.Callable;
import org.mycore.common.MCRException;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRUserInformation;
/**
* Encapsulates a {@link Callable} with a mycore session belonging to a specific user and a database transaction.
*
* @author Matthias Eichner
*/
public class MCRFixedUserCallable<V> extends MCRTransactionableCallable<V> {
private MCRUserInformation userInfo;
/**
* Creates a new {@link Callable} encapsulating the {@link #call()} method with a new
* <b>SYSTEM</b> {@link MCRSession} and a database transaction. Afterwards the transaction will
* be committed and the session will be released and closed.
*
* @param callable the callable to execute within a <b>SYSTEM</b> session and transaction
* @param userInfo specify the user this callable should run
*/
public MCRFixedUserCallable(Callable<V> callable, MCRUserInformation userInfo) {
super(callable);
this.userInfo = Objects.requireNonNull(userInfo);
}
@Override
public V call() throws Exception {
final boolean hasSession = MCRSessionMgr.hasCurrentSession();
MCRSessionMgr.unlock();
this.session = MCRSessionMgr.getCurrentSession();
try {
MCRUserInformation currentUser = this.session.getUserInformation();
if (hasSession) {
if (!currentUser.equals(userInfo)) {
throw new MCRException(
"MCRFixedUserCallable is bound to " + currentUser.getUserID() + " and not to "
+ userInfo.getUserID() + ".");
}
} else {
this.session.setUserInformation(userInfo);
}
return super.call();
} finally {
if (!hasSession && this.session != null) {
this.session.close();
}
}
}
}
| 2,766 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDecorator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRDecorator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Optional;
import com.google.common.reflect.TypeToken;
/**
* Classes can implement this interface if they want to use
* the decorator pattern. Contains some static helper methods
* to check if an instance is implementing the decorator.
*
* @author Matthias Eichner
*/
public interface MCRDecorator<V> {
/**
* Returns the enclosing instance.
*
* @return the decorated instance
*/
V get();
/**
* Checks if the given object is decorated by this interface.
*
* @param decorator the interface to check
* @return true if the instance is decorated by an MCRDecorator
*/
static boolean isDecorated(Object decorator) {
return TypeToken.of(decorator.getClass()).getTypes().interfaces().stream()
.filter(tt -> tt.isSubtypeOf(MCRDecorator.class)).findAny().isPresent();
}
/**
* Returns an optional with the enclosing value of the decorator. The decorator
* should implement the {@link MCRDecorator} interface. If not, an empty optional
* is returned.
*
* <ul>
* <li>get: MCRDecorator -> <b>MCRDecorator</b> -> MCRDecorator -> object
* <li>resolve: MCRDecorator -> MCRDecorator -> MCRDecorator -> <b>object</b>
* </ul>
*
* @param decorator the MCRDecorator
* @return an optional with the decorated instance
*/
@SuppressWarnings("unchecked")
static <V> Optional<V> get(Object decorator) {
if (isDecorated(decorator)) {
try {
return Optional.of(((MCRDecorator<V>) decorator).get());
} catch (Exception exc) {
return Optional.empty();
}
}
return Optional.empty();
}
/**
* Same as {@link #get()}, but returns the last object which does not implement
* the decorator interface anymore.
*
* <ul>
* <li>get: MCRDecorator -> <b>MCRDecorator</b> -> MCRDecorator -> object
* <li>resolve: MCRDecorator -> MCRDecorator -> MCRDecorator -> <b>object</b>
* </ul>
*
* @param decorator the MCRDecorator
* @return an optional with the decorated instance
*/
static <V> Optional<V> resolve(Object decorator) {
Optional<V> base = get(decorator);
while (base.isPresent()) {
Optional<V> nextLevel = get(base.get());
if (nextLevel.isPresent()) {
base = nextLevel;
} else {
break;
}
}
return base;
}
}
| 3,340 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPrioritizable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRPrioritizable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Comparator;
/**
* Objects can implement this interface if they are capable of being prioritized.
*
* @author Matthias Eichner
*/
public interface MCRPrioritizable extends Comparable<MCRPrioritizable> {
/**
* Returns the priority.
*/
int getPriority();
long getCreated();
@Override
default int compareTo(MCRPrioritizable o) {
return Comparator.nullsLast(
Comparator.comparingInt(MCRPrioritizable::getPriority)
.reversed()
.thenComparingLong(MCRPrioritizable::getCreated))
.compare(this, o);
}
}
| 1,382 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRRunnableComperator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRRunnableComperator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Comparator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Supplier;
/**
* A {@link CompletableFuture} encapsulates a {@link Supplier} with an <code>AsyncSupply</code>.
* This make a {@link ThreadPoolExecutor} with a {@link PriorityBlockingQueue} useless. To
* regain the {@link Comparable} feature we have to unwrap the <code>AsyncSupply</code> and
* compare the original {@link Runnable}.
*
* <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a>
*
* Note: this comparator imposes orderings that are inconsistent with equals.
*
* @author Matthias Eichner
*/
public class MCRRunnableComperator implements Comparator<Runnable> {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public int compare(Runnable o1, Runnable o2) {
if (isComparable(o1, o2)) {
return ((Comparable) o1).compareTo(o2);
}
return -1;
}
private boolean isComparable(Runnable o1, Runnable o2) {
return o1 instanceof Comparable && o2 instanceof Comparable;
}
}
| 2,027 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTransactionableRunnable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRTransactionableRunnable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Objects;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRTransactionHelper;
/**
* Encapsulates a {@link Runnable} with a mycore session and a database transaction.
*
* @author Matthias Eichner
*/
public class MCRTransactionableRunnable implements Runnable, MCRDecorator<Runnable> {
private static final Logger LOGGER = LogManager.getLogger();
protected Runnable runnable;
private MCRSession session;
/**
* Creates a new {@link Runnable} encapsulating the {@link #run()} method with a new
* {@link MCRSession} and a database transaction. Afterwards the transaction will
* be committed and the session will be released and closed.
*
* <p>If you want to execute your runnable in the context of an already existing
* session use the {@link MCRTransactionableRunnable#MCRTransactionableRunnable(Runnable, MCRSession)}
* constructor instead.
*
* @param runnable the runnable to execute within a session and transaction
*/
public MCRTransactionableRunnable(Runnable runnable) {
this.runnable = Objects.requireNonNull(runnable, "runnable must not be null");
}
/**
* Creates a new {@link Runnable} encapsulating the {@link #run()} method with a new
* a database transaction. The transaction will be created in the context of the
* given session. Afterwards the transaction will be committed and the session
* will be released (but not closed!).
*
* @param runnable the runnable to execute within a session and transaction
* @param session the session to use
*/
public MCRTransactionableRunnable(Runnable runnable, MCRSession session) {
this.runnable = Objects.requireNonNull(runnable, "runnable must not be null");
this.session = Objects.requireNonNull(session, "session must not be null");
}
@Override
public void run() {
boolean newSession = this.session == null;
MCRSessionMgr.unlock();
boolean closeSession = newSession && !MCRSessionMgr.hasCurrentSession();
if (newSession) {
this.session = MCRSessionMgr.getCurrentSession();
}
MCRSessionMgr.setCurrentSession(this.session);
MCRTransactionHelper.beginTransaction();
try {
this.runnable.run();
} finally {
try {
MCRTransactionHelper.commitTransaction();
} catch (Exception commitExc) {
LOGGER.error("Error while commiting transaction.", commitExc);
try {
MCRTransactionHelper.rollbackTransaction();
} catch (Exception rollbackExc) {
LOGGER.error("Error while rollbacking transaction.", commitExc);
}
} finally {
MCRSessionMgr.releaseCurrentSession();
if (closeSession && session != null) {
session.close();
}
}
}
}
@Override
public Runnable get() {
return this.runnable;
}
}
| 3,982 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRReadWriteGuard.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRReadWriteGuard.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
/**
* A MCRReadWriteGuard acts like a {@link ReadWriteLock} but automatically wraps read and write operations accordingly.
* @author Thomas Scheffler (yagee)
*/
public class MCRReadWriteGuard {
private Lock readLock;
private Lock writeLock;
public MCRReadWriteGuard() {
this(new ReentrantReadWriteLock());
}
public MCRReadWriteGuard(ReadWriteLock readWriteLock) {
readLock = readWriteLock.readLock();
writeLock = readWriteLock.writeLock();
}
/**
* Executes the read operation while the read lock is locked.
* This is a sharable lock. Many <code>reader</code> can be executed simultaneously
* when no write operation is running.
* @param reader a read operation that should be guarded.
* @return result of {@link Supplier#get()}
*/
public <T> T read(Supplier<T> reader) {
readLock.lock();
try {
return reader.get();
} finally {
readLock.unlock();
}
}
/**
* Executes the write operation while the write lock is locked.
* This is an exclusive lock. So no other read or write operation
* can be executed while <code>operation</code> is running.
*/
public void write(Runnable operation) {
writeLock.lock();
try {
operation.run();
} finally {
writeLock.unlock();
}
}
public <T> T lazyLoad(Supplier<Boolean> check, Runnable operation, Supplier<T> reader) {
readLock.lock();
boolean holdsReadLock = true;
try {
if (check.get()) {
holdsReadLock = false;
readLock.unlock();
write(operation);
}
} finally {
if (holdsReadLock) {
readLock.unlock();
}
}
return reader.get();
}
}
| 2,827 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPool.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRPool.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
/**
* A MCRPool allows thread safe pooling of thread unsafe objects.
* @param <T>
*/
public class MCRPool<T> {
private final BlockingQueue<T> pool;
private final Semaphore objectCreationPermit;
private final Supplier<T> objectCreator;
/**
* Creates an MCRPool of the given size
* @param size capacity of the pool
* @param supplier return values for {@link #acquire()}, called not more than size times
*/
public MCRPool(int size, Supplier<T> supplier) {
this.pool = new ArrayBlockingQueue<>(size, true);
this.objectCreationPermit = new Semaphore(size, false);
this.objectCreator = supplier;
}
/**
* Acquires a value from the pool.
* The caller has to make sure that any instance returned is released afterwards.
* @throws InterruptedException if interrupted while waiting
*/
public T acquire() throws InterruptedException {
final T earlyTry = pool.poll(0, TimeUnit.NANOSECONDS);
if (earlyTry != null) {
return earlyTry;
}
if (objectCreationPermit.tryAcquire(0, TimeUnit.NANOSECONDS)) {
//create up to 'size' objects
return objectCreator.get();
}
return pool.take();
}
/**
* Puts the resource back into the pool.
*/
public void release(T resource) {
pool.add(resource);
}
}
| 2,365 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDelayedRunnable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/MCRDelayedRunnable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.primitives.Ints;
/**
* Encapsulates a {@link Runnable} with in a object that can be fed into a
* DelayQueue
*
* Note: This class has a natural ordering that is inconsistent with equals.
* Note: Two objects of this class are equal, if their ids are equal
* (other properties are ignored).
*
* @author Robert Stephan
*
*/
public class MCRDelayedRunnable implements Delayed, Runnable, MCRDecorator<Runnable> {
private static AtomicLong ATOMIC_SYSTEM_TIME = new AtomicLong(System.currentTimeMillis());
protected Runnable runnable;
private long startTimeInMs = -1;
private String id;
/**
* Creates a new {@link MCRDelayedRunnable} encapsulating a Runnable for delayed execution.
*
* @param id, - the id of the runnable (used for equals-check)
* @param delayInMs - the time in (ms) the task should be delayed
* @param runnable the runnable to execute within a session and transaction
*/
public MCRDelayedRunnable(String id, long delayInMs, Runnable runnable) {
this.id = id;
this.runnable = Objects.requireNonNull(runnable, "runnable must not be null");
long current = ATOMIC_SYSTEM_TIME.accumulateAndGet(System.currentTimeMillis(), (x, y) -> Math.max(x + 1, y));
startTimeInMs = current + delayInMs;
}
@Override
public void run() {
this.runnable.run();
}
@Override
public Runnable get() {
return this.runnable;
}
public String getId() {
return id;
}
/**
* order objects by their startTime
*/
@Override
public int compareTo(Delayed o) {
return Ints.saturatedCast(this.startTimeInMs - ((MCRDelayedRunnable) o).startTimeInMs);
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startTimeInMs - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hash(id);
return result;
}
/**
* two objects are equal, if they have the same id
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MCRDelayedRunnable other = (MCRDelayedRunnable) obj;
return Objects.equals(id, other.id);
}
}
| 3,478 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableSupplier.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableSupplier.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent.processing;
import java.time.Instant;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.Supplier;
import org.mycore.common.MCRException;
import org.mycore.common.processing.MCRProcessable;
import org.mycore.common.processing.MCRProcessableStatus;
import org.mycore.common.processing.MCRProcessableTask;
import org.mycore.common.processing.MCRProgressable;
import org.mycore.util.concurrent.MCRDecorator;
import org.mycore.util.concurrent.MCRPrioritySupplier;
/**
* A processable supplier combines a {@link Supplier} and a {@link MCRProcessable}.
* The supplier will be executed with the help of an {@link CompletableFuture}.
* To get the future call {@link #getFuture()}.
*
* @author Matthias Eichner
*
* @param <R> the result of the task
*/
public class MCRProcessableSupplier<R> extends MCRProcessableTask<Callable<R>> implements Supplier<R> {
protected CompletableFuture<R> future;
/**
* Creates a new {@link MCRProcessableSupplier} by the already committed task and its future.
*
* @param task the task which should be executed
* @param future the future
* @return a new processable supplier
*/
public static <T> MCRProcessableSupplier<T> of(Callable<T> task, CompletableFuture<T> future) {
MCRProcessableSupplier<T> ps = new MCRProcessableSupplier<>(task);
ps.future = future;
return ps;
}
/**
* Creates a new {@link MCRProcessableSupplier} by submitting the task to the executorService with
* the given priority.
*
* @param task the task to submit
* @param executorService the executor service
* @param priority the priority
* @return a new processable supplier
*/
public static <T> MCRProcessableSupplier<T> of(Callable<T> task, ExecutorService executorService,
Integer priority) {
MCRProcessableSupplier<T> ps = new MCRProcessableSupplier<>(task);
ps.future = new MCRPrioritySupplier<>(ps, priority).runAsync(executorService);
return ps;
}
/**
* Private constructor,
*
* @param task the task itself
*/
private MCRProcessableSupplier(Callable<R> task) {
super(task);
}
/**
* Gets the result of the task. Will usually be called by the executor service
* and should not be executed directly.
*/
@Override
public R get() {
try {
this.setStatus(MCRProcessableStatus.processing);
this.startTime = Instant.now();
R result = getTask().call();
this.setStatus(MCRProcessableStatus.successful);
return result;
} catch (InterruptedException exc) {
this.error = exc;
this.setStatus(MCRProcessableStatus.canceled);
throw new MCRException(this.error);
} catch (Exception exc) {
this.error = exc;
this.setStatus(MCRProcessableStatus.failed);
throw new MCRException(this.error);
}
}
/**
* The future the task is assigned to.
*
* @return the future
*/
public CompletableFuture<R> getFuture() {
return future;
}
/**
* Returns true if this task 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 task completed
*/
public boolean isFutureDone() {
return future.isDone();
}
/**
* Same as {@link Future#cancel(boolean)}.
*
* @param mayInterruptIfRunning true if the thread executing this task should be interrupted;
* otherwise, in-progress tasks are allowed to complete
* @return false if the task could not be cancelled, typically because it has already
* completed normally; true otherwise
*/
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
/**
* Returns an integer between 0-100 indicating the progress
* of the processable. Can return null if the task is not started
* yet or the task is not an instance of {@link MCRProgressable}.
*
* @return the progress between 0-100 or null
*/
@Override
public Integer getProgress() {
if (task instanceof MCRProgressable progressable) {
return progressable.getProgress();
}
return super.getProgress();
}
/**
* Returns a human readable text indicating the state of the progress.
*
* @return progress text
*/
@Override
public String getProgressText() {
if (task instanceof MCRProgressable progressable) {
return progressable.getProgressText();
}
return super.getProgressText();
}
/**
* Returns the name of this process. If no name is set
* this returns the simplified class name of the task.
*
* @return a human readable name of this processable task
*/
@Override
public String getName() {
String name = super.getName();
if (name == null) {
return MCRDecorator.resolve(this.task).map(object -> {
if (object instanceof MCRProcessable processable) {
return processable.getName();
}
return object.toString();
}).orElse(this.task.toString());
}
return name;
}
}
| 6,351 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableFactory.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableFactory.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent.processing;
import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.PriorityBlockingQueue;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.processing.MCRListenableProgressable;
import org.mycore.common.processing.MCRProcessable;
import org.mycore.common.processing.MCRProcessableCollection;
import org.mycore.common.processing.MCRProgressable;
import org.mycore.common.processing.MCRProgressableListener;
import org.mycore.util.concurrent.MCRDecorator;
import org.mycore.util.concurrent.MCRRunnableComperator;
/**
* Factory and utility methods for {@link MCRProcessableExecutor}.
*
* @author Matthias Eichner
*/
public abstract class MCRProcessableFactory {
/**
* Returns a {@link Callable} object that, when
* called, runs the given task and returns {@code null}.
* It also takes care if the task implements the
* {@link MCRProgressable} interface by calling the runnable
* implementation.
*
* @param task the task to run
* @return a callable object
* @throws NullPointerException if task null
*/
public static Callable<Object> progressableCallable(Runnable task) {
if (task == null) {
throw new NullPointerException();
}
return new RunnableProgressableAdapter<>(task);
}
/**
* Creates a new {@link MCRProcessableExecutor}.
*
* <p>
* Be aware that you should shutdown the delegate with the {@link MCRShutdownHandler}
* by yourself. This method will not do this for you!
* </p>
*
* <p><b>
* If you like to have priority support you have to use a thread pool with a
* {@link PriorityBlockingQueue}!
* </b></p>
*
* @param delegate the thread pool delegate
* @return a newly created thread pool
*/
public static MCRProcessableExecutor newPool(ExecutorService delegate) {
return new MCRProcessableThreadPoolExecutorHelper(delegate);
}
/**
* Creates a new {@link MCRProcessableExecutor}. Each task submitted will be
* automatically added to the given collection and removed if complete.
*
* <p>
* Be aware that you should shutdown the delegate with the {@link MCRShutdownHandler}
* by yourself. This method will not do this for you!
* </p>
*
* <p><b>
* If you like to have priority support you have to use a thread pool with a
* {@link PriorityBlockingQueue}!
* </b></p>
*
* @param delegate the thread pool delegate
* @param collection the collection which will be linked with the pool
* @return a newly created thread pool
*/
public static MCRProcessableExecutor newPool(ExecutorService delegate, MCRProcessableCollection collection) {
return new MCRProcessableThreadPoolExecutorHelper(delegate, collection);
}
/**
* Creates new PriorityBlockingQueue for runnables. Uses the {@link MCRRunnableComperator}
* for comparision.
*
* @return a new priority blocking queue
*/
public static PriorityBlockingQueue<Runnable> newPriorityBlockingQueue() {
int initialCapacity = 11; //taken from java.util.concurrent.PriorityBlockingQueue.DEFAULT_INITIAL_CAPACITY
return new PriorityBlockingQueue<>(initialCapacity, Comparator.nullsLast(new MCRRunnableComperator()));
}
/**
* Helper class glueing a thread pool and a collection together.
*/
private static class MCRProcessableThreadPoolExecutorHelper implements MCRProcessableExecutor {
private ExecutorService executor;
private MCRProcessableCollection collection;
MCRProcessableThreadPoolExecutorHelper(ExecutorService delegate) {
this(delegate, null);
}
MCRProcessableThreadPoolExecutorHelper(ExecutorService delegate, MCRProcessableCollection collection) {
this.executor = delegate;
this.collection = collection;
}
/*
* (non-Javadoc)
* @see org.mycore.util.concurrent.processing.ProcessableExecutor#submit(java.util.concurrent.Callable, int)
*/
@Override
public <R> MCRProcessableSupplier<R> submit(Callable<R> callable, int priority) {
MCRProcessableSupplier<R> supplier = MCRProcessableSupplier.of(callable, this.executor, priority);
if (this.collection != null) {
MCRProcessable processable = supplier;
if (callable instanceof MCRProcessable p1) {
processable = p1;
} else if (callable instanceof RunnableProgressableAdapter adapter
&& adapter.get() instanceof MCRProcessable p2) {
processable = p2;
}
this.collection.add(processable);
supplier.getFuture().whenComplete((result, throwable) -> {
this.collection.remove(supplier);
if (throwable != null) {
LogManager.getLogger().error("Error while processing '{}'", supplier.getName(), throwable);
}
});
}
return supplier;
}
@Override
public ExecutorService getExecutor() {
return this.executor;
}
}
/**
* A callable that runs given task and returns given result
*/
private record RunnableProgressableAdapter<T>(Runnable task)
implements Callable<T>, MCRListenableProgressable, MCRDecorator<Runnable> {
@Override
public T call() {
task.run();
return null;
}
@Override
public Integer getProgress() {
if (task instanceof MCRProgressable progressable) {
return progressable.getProgress();
}
return null;
}
@Override
public String getProgressText() {
if (task instanceof MCRProgressable progressable) {
return progressable.getProgressText();
}
return null;
}
@Override
public void addProgressListener(MCRProgressableListener listener) {
if (task instanceof MCRListenableProgressable listenableProgressable) {
listenableProgressable.addProgressListener(listener);
}
}
@Override
public void removeProgressListener(MCRProgressableListener listener) {
if (task instanceof MCRListenableProgressable listenableProgressable) {
listenableProgressable.removeProgressListener(listener);
}
}
@Override
public Runnable get() {
return task;
}
@Override
public String toString() {
return task.toString();
}
}
}
| 7,713 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRProcessableExecutor.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/util/concurrent/processing/MCRProcessableExecutor.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent.processing;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
/**
* A processable executor uses a {@link ExecutorService} to submit
* given tasks and returns a {@link MCRProcessableSupplier}.
*
* @author Matthias Eichner
*/
public interface MCRProcessableExecutor {
/**
* Submits the runnable with priority zero (executed at last).
*
* @param runnable the runnable to submit
* @return a {@link MCRProcessableSupplier} with no result
*/
default MCRProcessableSupplier<?> submit(Runnable runnable) {
return submit(runnable, 0);
}
/**
* Submits the runnable with the given priority.
*
* @param runnable the runnable to submit
* @return a {@link MCRProcessableSupplier} with no result
*/
default MCRProcessableSupplier<?> submit(Runnable runnable, int priority) {
return submit(MCRProcessableFactory.progressableCallable(runnable), priority);
}
/**
* Submits the callable with priority zero (executed at last).
*
* @param callable the callable to submit
* @return a {@link MCRProcessableSupplier} with the result of R
*/
default <R> MCRProcessableSupplier<R> submit(Callable<R> callable) {
return submit(callable, 0);
}
/**
* Submits the callable with the given priority.
*
* @param callable the callable to submit
* @return a {@link MCRProcessableSupplier} with the result of R
*/
<R> MCRProcessableSupplier<R> submit(Callable<R> callable, int priority);
/**
* Returns the underlying executor service.
*
* <p><b>
* You should not submit task to this thread pool directly. Use the submit
* methods of this class instead.
* </b></p>
*
* @return the thread pool.
*/
ExecutorService getExecutor();
}
| 2,633 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCryptKeyNoPermissionException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCryptKeyNoPermissionException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import org.mycore.common.MCRCatchException;
public class MCRCryptKeyNoPermissionException extends MCRCatchException {
private String errorCode;
public MCRCryptKeyNoPermissionException(String errorMessage) {
super(errorMessage);
}
public MCRCryptKeyNoPermissionException(String errorMessage, String errorCode) {
super(errorMessage);
this.errorCode = errorCode;
}
public MCRCryptKeyNoPermissionException(String message, Throwable cause) {
super(message, cause);
}
public String getErrorCode() {
return errorCode;
}
}
| 1,350 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCryptCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCryptCommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import java.nio.file.FileAlreadyExistsException;
import java.security.InvalidKeyException;
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.config.MCRConfiguration2;
import org.mycore.frontend.cli.MCRAbstractCommands;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
/**
* This class provides a set of commands for the org.mycore.crypt management
* which can be used by the command line interface.
*
* @author Paul Borchert
*/
@MCRCommandGroup(name = "Crypt Commands")
public class MCRCryptCommands extends MCRAbstractCommands {
/** The logger */
private static Logger LOGGER = LogManager.getLogger(MCRCryptCommands.class.getName());
/**
* list all cipher configuration
*
*/
@MCRCommand(syntax = "show cipher configuration",
help = "The command list all chipher configured in mycore.properties",
order = 10)
public static void showChipherConfig() {
Map<String, String> subProps = MCRConfiguration2.getSubPropertiesMap("MCR.Crypt.Cipher");
LOGGER.info("Cipher configuration: \n"
+ subProps.entrySet()
.stream()
.sorted(Map.Entry.<String, String>comparingByKey()) //.reversed())
.map(entry -> "MCR.Crypt.Cipher" + entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("\n")));
}
/**
* generate keyfile for cipher {0}
*
* @param cipherid
* String id of cipher configured in properties
*/
@MCRCommand(syntax = "generate keyfile for cipher {0}",
help = "The command generate the keyfile for the cipher configured in mycore.properties. "
+ "Fails if key file exists.",
order = 20)
public static void generateKeyFile(String cipherid)
throws MCRCryptKeyFileNotFoundException, MCRCryptCipherConfigurationException {
LOGGER.info("Start generateKeyFile");
try {
MCRCipher cipher = MCRCipherManager.getUnIntitialisedCipher(cipherid);
cipher.generateKeyFile();
cipher.init(cipherid);
LOGGER.info("Keyfile generated.");
} catch (InvalidKeyException e) {
throw new MCRCryptCipherConfigurationException("Generation of keyfile goes wrong. Key is invalid.", e);
} catch (FileAlreadyExistsException e) {
LOGGER.info("Keyfile already exists. No keyfile generated.");
}
}
/**
* generate and overwrite of keyfile of cipher {0}
*
* @param cipherid
* String id of cipher configured in properties
*/
@MCRCommand(syntax = "overwrite keyfile for cipher {0}",
help = "The command generate on overwrite the keyfile for the cipher configured in mycore.properties."
+ " Fails if key file exists.",
order = 20)
public static void overwriteKeyFile(String cipherid)
throws MCRCryptCipherConfigurationException, MCRCryptKeyFileNotFoundException {
LOGGER.info("Start overwriteKeyFile");
try {
MCRCipher cipher = MCRCipherManager.getUnIntitialisedCipher(cipherid);
cipher.overwriteKeyFile();
cipher.init(cipherid);
LOGGER.info("Keyfile overwriten.");
} catch (InvalidKeyException e) {
throw new MCRCryptCipherConfigurationException("Generation of keyfile goes wrong. Key is invalid.", e);
}
}
/**
* encrypt {0} with cipher {1}
*
* @param value
* The value to be encrypted
*
* @param cipherid
* String id of cipher configured in properties
*/
@MCRCommand(syntax = "encrypt {0} with cipher {1}",
help = "The command encrypt the value with cipher.",
order = 30)
public static void encrypt(String value, String cipherid)
throws MCRCryptKeyNoPermissionException, MCRCryptKeyFileNotFoundException,
MCRCryptCipherConfigurationException {
MCRCipher cipher = MCRCipherManager.getCipher(cipherid);
LOGGER.info("Encrypted Value: " + cipher.encrypt(value));
}
/**
* decrypt {0} with cipher {1}
*
* @param value
* The value to be decrypted
*
* @param cipherid
* String id of cipher configured in properties
*/
@MCRCommand(syntax = "decrypt {0} with cipher {1}",
help = "The command encrypt the value with cipher.",
order = 40)
public static void decrypt(String value, String cipherid)
throws MCRCryptKeyNoPermissionException, MCRCryptKeyFileNotFoundException,
MCRCryptCipherConfigurationException {
MCRCipher cipher = MCRCipherManager.getCipher(cipherid);
LOGGER.info("Decrypted Value: " + cipher.decrypt(value));
}
}
| 5,726 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCipherManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCipherManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import java.security.InvalidKeyException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
/**
* Create Instances of MCRCipher as configured in mycore.properties.
* The cipher is defined by the java class.
* The secret key is saved in an keyfile.
*
* MCR.Crypt.Cipher.abstract.Class=org.mycore.crypt.MCRAESCipher
* MCR.Crypt.Cipher.abstract.KeyFile=example_1.secret
*
*/
public class MCRCipherManager {
private static Logger LOGGER = LogManager.getLogger(MCRCipherManager.class.getName());
/**
* Create a single instance of a MCRCipher and initialize it. If the cipher can't initialized an exception
* will thrown. Common issue is an missing key. In this case the methods throws
* a MCRCryptKeyFileNotFoundException.
*
* @param id ID of cipher as configured
* @return instance of cipher
*/
public static MCRCipher getCipher(String id) throws MCRCryptKeyFileNotFoundException {
LOGGER.debug("getCipher for id {} .", id);
String propertiy = "MCR.Crypt.Cipher." + id + ".class";
MCRCipher cipher = MCRConfiguration2.<MCRCipher>getSingleInstanceOf(propertiy)
.orElseThrow(
() -> new MCRCryptCipherConfigurationException(
"Property " + propertiy + "not configured or class not found."));
if (!cipher.isInitialised()) {
LOGGER.debug("init Cipher for id {} .", id);
try {
cipher.init(id);
} catch (InvalidKeyException e) {
throw new MCRCryptCipherConfigurationException("Can't initialize cipher. Key is invalid.", e);
}
}
return cipher;
}
/**
* Create a single instance of a MCRCipher without initialising it.
* The resulting instance can used to generate an new key.
*
* @param id ID of cipher as configured
* @return instance of cipher
*/
public static MCRCipher getUnIntitialisedCipher(String id) {
LOGGER.debug("getCipher for id {} .", id);
String propertiy = "MCR.Crypt.Cipher." + id + ".class";
MCRCipher cipher = MCRConfiguration2.<MCRCipher>getSingleInstanceOf(propertiy)
.orElseThrow(
() -> new MCRCryptCipherConfigurationException(
"Property " + propertiy + "not configured or class not found."));
cipher.reset();
return cipher;
}
}
| 3,256 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCryptKeyFileNotFoundException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCryptKeyFileNotFoundException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import java.io.FileNotFoundException;
public class MCRCryptKeyFileNotFoundException extends FileNotFoundException {
private static final long serialVersionUID = 1L;
private String errorCode;
public MCRCryptKeyFileNotFoundException(String errorMessage) {
super(errorMessage);
}
public MCRCryptKeyFileNotFoundException(String errorMessage, String errorCode) {
super(errorMessage);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
| 1,286 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCryptCipherConfigurationException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCryptCipherConfigurationException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import org.mycore.common.config.MCRConfigurationException;
public class MCRCryptCipherConfigurationException extends MCRConfigurationException {
private static final long serialVersionUID = 1L;
private String errorCode;
public MCRCryptCipherConfigurationException(String errorMessage) {
super(errorMessage);
}
public MCRCryptCipherConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public MCRCryptCipherConfigurationException(String errorMessage, String errorCode) {
super(errorMessage);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
| 1,444 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCryptResolver.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCryptResolver.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import java.util.Set;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom2.Element;
import org.jdom2.transform.JDOMSource;
import org.mycore.common.MCRException;
/**
* This class provides an URIResolver for encryption and decryption.
*
* URI Pattern:
* crypt:{encrypt/decrypt}:{cipherid}:{value}
*
* where
* <ul>
* <li>encrypt/decrypt - the action to act an value</li>
* <li>cipherid - ID of the cipher</li>
* <li>value - string to be encryptet or decypted</li>
* </ul>
* @author Paul Borchert
*/
public class MCRCryptResolver implements URIResolver {
public static final String XML_PREFIX = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
private static final Logger LOGGER = LogManager.getLogger(MCRCryptResolver.class);
private static final Set<String> ACTIONS = Set.of("encrypt", "decrypt");
@Override
public Source resolve(String s, String s1) throws TransformerException {
String[] parts = s.split(":", 4);
if (parts.length != 4) {
throw new TransformerException(
"Malformed CrypResolver uri. Must be crypt:{encrypt/decrypt}:{cipherid}:{value}");
}
if (!ACTIONS.contains(parts[1])) {
throw new TransformerException("The crypt action must be one of encrypt or decrypt.");
}
String action = parts[1];
String cipherID = parts[2];
String value = parts[3];
String returnString = "";
try {
MCRCipher cipher = MCRCipherManager.getCipher(cipherID);
returnString = action.equals("encrypt") ? cipher.encrypt(value) : cipher.decrypt(value);
} catch (MCRCryptKeyFileNotFoundException e) {
LOGGER.error(MCRException.getStackTraceAsString(e));
returnString = action.equals("encrypt") ? "" : value;
} catch (MCRCryptKeyNoPermissionException e) {
LOGGER.info("No permission to read cryptkey" + cipherID + ".");
returnString = action.equals("encrypt") ? "" : value;
} catch (MCRCryptCipherConfigurationException e) {
LOGGER.error(e.getStackTraceAsString());
LOGGER.error("Invalid configuration or key.");
returnString = action.equals("encrypt") ? "" : value;
}
final Element root = new Element("value");
root.setText(returnString);
return new JDOMSource(root);
}
}
| 3,323 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRAESCipher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRAESCipher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.common.config.annotation.MCRProperty;
public class MCRAESCipher extends MCRCipher {
private static final Logger LOGGER = LogManager.getLogger();
private String keyFile;
private SecretKey secretKey;
private Cipher encryptCipher;
private Cipher decryptCipher;
@MCRProperty(name = "KeyFile")
public void setKeyFile(String path) {
keyFile = path;
}
public MCRAESCipher() {
secretKey = null;
encryptCipher = null;
decryptCipher = null;
}
public void init(String id) throws MCRCryptKeyFileNotFoundException, InvalidKeyException {
cipherID = id;
String encodedKey = null;
try {
LOGGER.info("Get key from file {}.", keyFile);
encodedKey = Files.readString(FileSystems.getDefault().getPath(keyFile));
byte[] decodedKey = java.util.Base64.getDecoder().decode(encodedKey);
LOGGER.info("Set secret key");
secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
encryptCipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
decryptCipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
} catch (NoSuchFileException e) {
throw new MCRCryptKeyFileNotFoundException(
"Keyfile " + keyFile
+ " not found. Generate new one with CLI command or copy file to path.");
} catch (IllegalArgumentException e) {
throw new InvalidKeyException("Error while decoding key from keyFile " + keyFile + "!", e);
} catch (IOException e) {
throw new MCRException("Can't read keyFile " + keyFile + ".", e);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new MCRCryptCipherConfigurationException(
"The algorithm AES/ECB/PKCS5PADDING ist not provided by this Java version."
+ "Update Java or configure an other chipher in mycore.properties.",
e);
}
}
public boolean isInitialised() {
return (secretKey != null && encryptCipher != null && decryptCipher != null);
}
public void reset() {
secretKey = null;
encryptCipher = null;
decryptCipher = null;
}
public void generateKeyFile() throws FileAlreadyExistsException {
try {
LOGGER.info("generate Key File");
String cryptKey = generateKey();
Path keyPath = FileSystems.getDefault().getPath(keyFile);
Files.createDirectories(keyPath.getParent());
Files.writeString(keyPath, cryptKey, StandardOpenOption.CREATE_NEW);
} catch (NoSuchAlgorithmException e) {
throw new MCRCryptCipherConfigurationException(
"Error while generating keyfile: The configured algorithm is not available.", e);
} catch (FileAlreadyExistsException e) {
throw new FileAlreadyExistsException(keyFile, null,
"A crypt key shouldn't be generated if it allready exists. "
+ " If you are aware of the consequences use overwriteKeyFile().");
} catch (IOException e) {
throw new MCRException("Error while write key to file.", e);
}
}
public void overwriteKeyFile() {
try {
LOGGER.info("overwrite Key File");
String cryptKey = generateKey();
Path keyPath = FileSystems.getDefault().getPath(keyFile);
Files.createDirectories(keyPath.getParent());
Files.writeString(keyPath, cryptKey);
} catch (NoSuchAlgorithmException e) {
throw new MCRCryptCipherConfigurationException(
"Error while generating keyfile. The configured algorithm is not available.", e);
} catch (IOException e) {
throw new MCRException("Error while write key to file.", e);
}
}
private String generateKey() throws NoSuchAlgorithmException {
SecretKey tmpSecretKey = KeyGenerator.getInstance("AES").generateKey();
return java.util.Base64.getEncoder().encodeToString(tmpSecretKey.getEncoded());
}
protected String encryptImpl(String text) throws MCRCryptCipherConfigurationException {
byte[] encryptedBytes = encryptImpl(text.getBytes(StandardCharsets.UTF_8));
String encryptedString = java.util.Base64.getEncoder().encodeToString(encryptedBytes);
return encryptedString;
}
protected String decryptImpl(String text) throws MCRCryptCipherConfigurationException {
byte[] encryptedBytes = java.util.Base64.getDecoder().decode(text);
byte[] decryptedBytes = decryptImpl(encryptedBytes);
String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
return decryptedText;
}
protected byte[] encryptImpl(byte[] bytes) throws MCRCryptCipherConfigurationException {
try {
byte[] encryptedBytes = encryptCipher.doFinal(bytes);
return encryptedBytes;
} catch (BadPaddingException | IllegalBlockSizeException e) {
throw new MCRCryptCipherConfigurationException("Can't encrypt value - wrong configuration.", e);
}
}
protected byte[] decryptImpl(byte[] bytes) throws MCRCryptCipherConfigurationException {
try {
byte[] decryptedBytes = decryptCipher.doFinal(bytes);
return decryptedBytes;
} catch (BadPaddingException | IllegalBlockSizeException e) {
throw new MCRCryptCipherConfigurationException("Can't decrypt value - "
+ " possible issues: corrupted crypted value, wrong configuration or bad key.", e);
}
}
}
| 7,367 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRCipher.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-base/src/main/java/org/mycore/crypt/MCRCipher.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.crypt;
import java.nio.file.FileAlreadyExistsException;
import java.security.InvalidKeyException;
import org.mycore.access.MCRAccessManager;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.common.config.annotation.MCRProperty;
/**
* Abstract class of a concrete cipherimplementation
*
* After checking the permission call the encrypt an decrypt
* functionality. The permission is set by acl.
*
* Example for chipher with id abstract:
* crypt:abstract {encrypt:decrypt} "administrators only"
*
* @author Paul Borchert
*
*/
public abstract class MCRCipher {
protected String cipherID;
private boolean aclEnabled = true;
/**
* Initialize the chipher by reading the key from file. If the cipher can't initialized an exception
* will thrown. Common issue is an missing key. In this case the methods throws
* a MCRCryptKeyFileNotFoundException.
*
* Needs the id of cipher as parameter, because the id can't be set during
* instanciating by getSingleInstanceOf.
*
* @param id ID of cipher as configured
*/
abstract public void init(String id) throws MCRCryptKeyFileNotFoundException, InvalidKeyException;
/**
* Return whether cipher has been initialized.
*/
abstract public boolean isInitialised();
/**
* Revert init process.
*/
abstract public void reset();
/**
* If no keyfile exsits, generate the secret key an write it
* to the keyfile.
*/
abstract public void generateKeyFile() throws FileAlreadyExistsException;
/**
* Generate the secret key an write it to the keyfile. Overwrites
* exsisting keyfile.
*/
abstract public void overwriteKeyFile();
public boolean getAclEnabled() {
return aclEnabled;
}
@MCRProperty(name = "EnableACL", required = false)
public void setAclEnabled(final String enabled) {
if ("true".equalsIgnoreCase(enabled) || "false".equalsIgnoreCase(enabled)) {
aclEnabled = Boolean.parseBoolean(enabled);
} else {
throw new MCRConfigurationException("MCRCrypt: " + enabled + " is not a valid boolean.");
}
}
public String encrypt(String text) throws MCRCryptKeyNoPermissionException {
if (checkPermission("encrypt")) {
return encryptImpl(text);
} else {
throw new MCRCryptKeyNoPermissionException("No Permission to encrypt with the chiper " + cipherID + ".");
}
}
public byte[] encrypt(byte[] bytes) throws MCRCryptKeyNoPermissionException {
if (checkPermission("encrypt")) {
return encryptImpl(bytes);
} else {
throw new MCRCryptKeyNoPermissionException("No Permission to encrypt with the chiper " + cipherID + ".");
}
}
public String decrypt(String text) throws MCRCryptKeyNoPermissionException {
if (checkPermission("decrypt")) {
return decryptImpl(text);
} else {
throw new MCRCryptKeyNoPermissionException("No Permission to decrypt with the chiper " + cipherID + ".");
}
}
public byte[] decrypt(byte[] bytes) throws MCRCryptKeyNoPermissionException {
if (checkPermission("decrypt")) {
return decryptImpl(bytes);
} else {
throw new MCRCryptKeyNoPermissionException("No Permission to decrypt with the chiper " + cipherID + ".");
}
}
private boolean checkPermission(String action) {
if (aclEnabled) {
return MCRAccessManager.checkPermission("crypt:cipher:" + cipherID, action);
}
return true;
}
abstract protected String encryptImpl(String text);
abstract protected String decryptImpl(String text);
abstract protected byte[] encryptImpl(byte[] bytes);
abstract protected byte[] decryptImpl(byte[] bytes);
}
| 4,659 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPackerMock.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-packer/src/test/java/org/mycore/services/packaging/MCRPackerMock.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.packaging;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.mycore.common.config.MCRConfiguration2;
public class MCRPackerMock extends MCRPacker {
public static final String TEST_VALUE = "testValue";
public static final String TEST_CONFIGURATION_KEY = "testConfiguration";
public static final String TEST_PARAMETER_KEY = "testParameter";
public static final String FINISHED_PROPERTY = MCRPackerMock.class + ".finished";
public static final String SETUP_CHECKED_PROPERTY = MCRPackerMock.class + ".checked";
@Override
public void checkSetup() {
MCRConfiguration2.set(SETUP_CHECKED_PROPERTY, String.valueOf(true));
}
@Override
public void pack() throws ExecutionException {
Map<String, String> configuration = getConfiguration();
if (!configuration.containsKey(TEST_CONFIGURATION_KEY)
&& configuration.get("testConfiguration").equals(TEST_VALUE)) {
throw new ExecutionException(new Exception(TEST_CONFIGURATION_KEY + " invalid!"));
}
if (!getParameters().containsKey(TEST_PARAMETER_KEY) && configuration.get("testParameter").equals(TEST_VALUE)) {
throw new ExecutionException(new Exception(TEST_PARAMETER_KEY + " is invalid!"));
}
MCRConfiguration2.set(FINISHED_PROPERTY, String.valueOf(true));
}
@Override
public void rollback() {
}
}
| 2,185 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPackerManagerTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-packer/src/test/java/org/mycore/services/packaging/MCRPackerManagerTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.packaging;
import java.util.Hashtable;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.processing.impl.MCRCentralProcessableRegistry;
import org.mycore.services.queuedjob.MCRJob;
public class MCRPackerManagerTest extends MCRJPATestCase {
public static final String TEST_PACKER_ID = "testPacker";
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Override
protected Map<String, String> getTestProperties() {
// Set up example configuration
Map<String, String> testProperties = super.getTestProperties();
String testPackerPrefix = MCRPacker.PACKER_CONFIGURATION_PREFIX + TEST_PACKER_ID + ".";
testProperties.put(testPackerPrefix + "Class", MCRPackerMock.class.getName());
testProperties.put(testPackerPrefix + MCRPackerMock.TEST_CONFIGURATION_KEY, MCRPackerMock.TEST_VALUE);
testProperties.put("MCR.QueuedJob.activated", "true");
testProperties.put("MCR.QueuedJob.JobThreads", "2");
testProperties.put("MCR.QueuedJob.TimeTillReset", "10");
testProperties.put("MCR.Processable.Registry.Class", MCRCentralProcessableRegistry.class.getName());
return testProperties;
}
@Test
public void testPackerConfigurationStart() throws Exception {
Map<String, String> parameterMap = new Hashtable<>();
// add packer parameter
parameterMap.put("packer", TEST_PACKER_ID);
// add test parameter
parameterMap.put(MCRPackerMock.TEST_PARAMETER_KEY, MCRPackerMock.TEST_VALUE);
MCRJob packerJob = MCRPackerManager.startPacking(parameterMap);
Assert.assertNotNull("The Packer job is not present!", packerJob);
endTransaction();
Thread.sleep(1000);
startNewTransaction();
int waitTime = 10;
while (waitTime > 0 && !MCRConfiguration2.getBoolean(MCRPackerMock.FINISHED_PROPERTY).orElse(false)
&& !MCRConfiguration2.getBoolean(MCRPackerMock.SETUP_CHECKED_PROPERTY).orElse(false)) {
Thread.sleep(1000);
waitTime -= 1;
}
Assert.assertTrue("PackerJob did not finish in time!", waitTime > 0);
}
}
| 3,104 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPackerManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-packer/src/main/java/org/mycore/services/packaging/MCRPackerManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.packaging;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
import org.mycore.common.MCRUsageException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.services.queuedjob.MCRJob;
import org.mycore.services.queuedjob.MCRJobQueue;
import org.mycore.services.queuedjob.MCRJobQueueManager;
/**
* <p>Used to pack packages in a specific format, using {@link MCRJobQueue}.</p>
* <p>You have to define a packer id and assign a packer class which extends {@link MCRPacker}.</p>
* <code>
* MCR.Packaging.Packer.MyPackerID.Class = org.mycore.packaging.MyPackerClass
* </code>
* <p>
* <p>You now have to pass properties required by the packer:</p>
* <code>
* MCR.Packaging.Packer.MyPackerID.somePropertyForPacker = value
* </code>
* <p>
*
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRPackerManager {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCRJobQueue PACKER_JOB_QUEUE = initializeJobQueue();
private static MCRJobQueue initializeJobQueue() {
LOGGER.info("Initializing jobQueue for Packaging!");
return MCRJobQueueManager.getInstance().getJobQueue(MCRPackerJobAction.class);
}
/**
* Creates and starts a new PackagingJob.
* <p>The rights you need to start a Packer depends on the implementation!</p>
* @param jobParameters the parameters which will be passed to the job. (Should include a packer)
* @return the created MCRJob
* @throws MCRUsageException if invalid parameters are passed to the packer
* @throws MCRAccessException if the current user doesn't have the rights to use the packer(on a specific object).
*/
public static MCRJob startPacking(Map<String, String> jobParameters) throws MCRUsageException, MCRAccessException {
String packer = jobParameters.get("packer");
if (packer == null) {
LOGGER.error("No Packer parameter found!");
return null;
}
checkPacker(packer, jobParameters);
MCRJob mcrJob = new MCRJob(MCRPackerJobAction.class);
mcrJob.setParameters(jobParameters);
if (!PACKER_JOB_QUEUE.offer(mcrJob)) {
throw new MCRException("Could not add Job to Queue!");
}
return mcrJob;
}
private static void checkPacker(String packer, Map<String, String> jobParameters)
throws MCRUsageException, MCRAccessException {
MCRPacker instance = MCRConfiguration2
.getOrThrow("MCR.Packaging.Packer." + packer + ".Class", MCRConfiguration2::instantiateClass);
instance.setParameter(jobParameters);
instance.setConfiguration(MCRPackerJobAction.getConfiguration(packer));
instance.checkSetup();
}
}
| 3,634 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPacker.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-packer/src/main/java/org/mycore/services/packaging/MCRPacker.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.packaging;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRUsageException;
/**
* Base class for every Packer. You should implement {@link #pack()} and {@link #rollback()}.
* The will be initialized two times. One time to just call {@link #checkSetup()} and one time to {@link #pack()}
*/
public abstract class MCRPacker {
public static final String PACKER_CONFIGURATION_PREFIX = "MCR.Packaging.Packer.";
private Map<String, String> configuration;
private Map<String, String> parameter;
/**
* should check if all required parameters are set!
* @throws MCRUsageException if parameters are illegal
* @throws MCRAccessException if the Users doesn't have the rights to use the Packer
*/
public abstract void checkSetup() throws MCRUsageException, MCRAccessException;
/**
* This method will be called and the MCRPacker should start packing according to the {@link #getConfiguration()}
* and {@link #getParameters()}!<br>
* <b>WARNING: do all checks for parameters and user access in {@link #checkSetup()}, because the packer is already
* stored in the DB if <code>pack</code> is called and the pack JOB runs a System-User instead of the User who
* produces the call.</b>
*
* @throws ExecutionException Unable to pack
*/
public abstract void pack() throws ExecutionException;
/**
* This method can be called in case of error and the MCRPacker should clean up trash from {@link #pack()}
*/
public abstract void rollback();
/**
* @return a unmodifiable map with all properties (MCR.Packaging.Packer.MyPackerID. prefix will be removed from key)
* of this packer-id.
*/
protected final Map<String, String> getConfiguration() {
return Collections.unmodifiableMap(this.configuration);
}
final void setConfiguration(Map<String, String> configuration) {
this.configuration = configuration;
}
/**
* @return a unmodifiable map with parameters of a specific {@link MCRPackerJobAction}.
*/
protected final Map<String, String> getParameters() {
return Collections.unmodifiableMap(this.parameter);
}
final void setParameter(Map<String, String> parameter) {
this.parameter = parameter;
}
}
| 3,167 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPackerJobAction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-packer/src/main/java/org/mycore/services/packaging/MCRPackerJobAction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.packaging;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.services.queuedjob.MCRJob;
import org.mycore.services.queuedjob.MCRJobAction;
/**
* Used to run a {@link MCRPacker} inside a {@link org.mycore.services.queuedjob.MCRJobQueue}
*
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRPackerJobAction extends MCRJobAction {
private static final Logger LOGGER = LogManager.getLogger();
private MCRPacker packerInstance;
public MCRPackerJobAction(MCRJob job) {
super(job);
}
@Override
public final boolean isActivated() {
return true;
}
@Override
public String name() {
return "MCRPackerJobAction-" + getPackerId();
}
private String getPackerId() {
return getParameters().get("packer");
}
public MCRPacker getPackerInstance() {
return this.packerInstance;
}
@Override
public final void execute() throws ExecutionException {
String packerId = getPackerId();
Map<String, String> packerConfiguration = getConfiguration(packerId);
packerInstance = MCRConfiguration2.getOrThrow(MCRPacker.PACKER_CONFIGURATION_PREFIX + packerId + ".Class",
MCRConfiguration2::instantiateClass);
Map<String, String> parameters = getParameters();
packerInstance.setParameter(parameters);
packerInstance.setConfiguration(packerConfiguration);
LOGGER.info(() -> {
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append(getPackerId()).append(" starts packing with parameters: ");
parameters.forEach((key, value) -> messageBuilder.append(key).append('=').append(value).append(';'));
return messageBuilder.toString();
});
packerInstance.pack();
}
protected final Map<String, String> getParameters() {
return this.job.getParameters();
}
public static Map<String, String> getConfiguration(String packerId) {
String packerConfigPrefix = MCRPacker.PACKER_CONFIGURATION_PREFIX + packerId + ".";
return MCRConfiguration2.getPropertiesMap()
.entrySet()
.stream()
.filter(p -> p.getKey().startsWith(packerConfigPrefix))
.collect(
Collectors.toMap(e -> e.getKey().substring(packerConfigPrefix.length()), Map.Entry::getValue));
}
@Override
public void rollback() {
if (packerInstance != null) {
packerInstance.rollback();
}
}
}
| 3,485 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRPackerServlet.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-packer/src/main/java/org/mycore/services/packaging/MCRPackerServlet.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.packaging;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRUsageException;
import org.mycore.frontend.servlets.MCRServlet;
import org.mycore.frontend.servlets.MCRServletJob;
import org.mycore.services.queuedjob.MCRJob;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>Servlet for {@link MCRPackerManager}.</p>
* <p>
* <p>You can pass a <code>redirect</code> parameter to the servlet!</p>
* <p>The rights you need to start a Packer depends on the implementation!</p>
* @author Sebastian Hofmann (mcrshofm)
*/
public class MCRPackerServlet extends MCRServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LogManager.getLogger();
@Override
protected void doGetPost(MCRServletJob job) throws IOException {
String packer = job.getRequest().getParameter("packer");
if (packer == null || packer.isEmpty()) {
try {
job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "No or invalid 'packer' parameter!");
} catch (IOException e) {
LOGGER.error("Error while sending request error to client!", e);
return;
}
}
Map<String, String> jobParameters = resolveJobParameters(job);
try {
MCRJob mcrJob = MCRPackerManager.startPacking(jobParameters);
if (mcrJob == null) {
job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "No packer parameter!");
}
} catch (MCRAccessException e) {
job.getResponse().sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
} catch (MCRUsageException e) {
job.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Parameters: " + e.getMessage());
}
if (jobParameters.containsKey("redirect")) {
String redirect = jobParameters.get("redirect");
job.getResponse().sendRedirect(job.getResponse().encodeRedirectURL(redirect));
}
}
private Map<String, String> resolveJobParameters(MCRServletJob job) {
return job.getRequest().getParameterMap()
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> (e.getValue().length >= 1) ? e.getValue()[0] : ""));
}
}
| 3,283 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestJobAction2.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRTestJobAction2.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.concurrent.ExecutionException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
/**
* @author Ren\u00E9 Adler (eagle)
*
*/
public class MCRTestJobAction2 extends MCRJobAction {
public static final String ERROR_MESSAGE = "Error parameter was set to true";
private static Logger LOGGER = LogManager.getLogger(MCRTestJobAction2.class);
/**
* @param job
*/
public MCRTestJobAction2(MCRJob job) {
super(job);
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#isActivated()
*/
@Override
public boolean isActivated() {
return true;
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#name()
*/
@Override
public String name() {
return this.getClass().getSimpleName();
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#execute()
*/
@Override
public void execute() throws ExecutionException {
LOGGER.info("job num: {}", job.getParameter("count"));
job.setParameter("done", "true");
if (job.getParameters().containsKey("error") && Boolean.parseBoolean(job.getParameter("error"))) {
throw new MCRException(ERROR_MESSAGE);
}
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#rollback()
*/
@Override
public void rollback() {
LOGGER.info(job);
job.setParameter("done", "false");
}
}
| 2,332 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobResetterTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRJobResetterTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.ArrayDeque;
import java.util.Date;
import java.util.Queue;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRJPATestCase;
import org.mycore.services.queuedjob.config2.MCRConfiguration2JobConfig;
public class MCRJobResetterTest extends MCRJPATestCase {
@Test
public void testResetJobsWithAction() {
MCRMockJobDAO mockDAO = new MCRMockJobDAO();
// save reset jobs to this queues
Queue<MCRJob> reset1 = new ArrayDeque<>();
Queue<MCRJob> reset2 = new ArrayDeque<>();
MCRConfiguration2JobConfig config = new MCRConfiguration2JobConfig();
// create resetter with mockDAO and reset queues
MCRJobResetter resetter = new MCRJobResetter(mockDAO, (action) -> {
switch (action.getSimpleName()) {
case "MCRTestJobAction" -> {
return reset1;
}
case "MCRTestJobAction2" -> {
return reset2;
}
default -> {
return null;
}
}
}, config);
long elevenMinutesAgo = new Date().getTime() - 60 * 1000 * 11;
long nineMinutesAgo = new Date().getTime() - 60 * 1000 * 9;
MCRJob job = new MCRJob();
job.setAction(MCRTestJobAction.class);
job.setParameter("count", "1");
job.setStatus(MCRJobStatus.ERROR);
job.setAdded(new Date(elevenMinutesAgo));
job.setStart(new Date(elevenMinutesAgo));
mockDAO.daoOfferedJobs.add(job);
MCRJob job2 = new MCRJob();
job2.setAction(MCRTestJobAction2.class);
job2.setParameter("count", "2");
job2.setStatus(MCRJobStatus.ERROR);
job2.setAdded(new Date(elevenMinutesAgo));
job2.setStart(new Date(elevenMinutesAgo));
mockDAO.daoOfferedJobs.add(job2);
MCRJob job3 = new MCRJob();
job3.setAction(MCRTestJobAction.class);
job3.setParameter("count", "3");
job3.setStatus(MCRJobStatus.ERROR);
job3.setAdded(new Date(nineMinutesAgo));
job3.setStart(new Date(nineMinutesAgo));
mockDAO.daoOfferedJobs.add(job3);
MCRJob job4 = new MCRJob();
job4.setAction(MCRTestJobAction2.class);
job4.setParameter("count", "4");
job4.setStatus(MCRJobStatus.ERROR);
job4.setAdded(new Date(nineMinutesAgo));
job4.setStart(new Date(nineMinutesAgo));
mockDAO.daoOfferedJobs.add(job4);
MCRJob job5 = new MCRJob();
job5.setAction(MCRTestJobAction2.class);
job5.setParameter("count", "5");
job5.setStatus(MCRJobStatus.NEW);
job5.setAdded(new Date(elevenMinutesAgo));
job5.setStart(new Date(elevenMinutesAgo));
mockDAO.daoOfferedJobs.add(job5);
MCRJob job6 = new MCRJob();
job6.setAction(MCRTestJobAction2.class);
job6.setParameter("count", "5");
job6.setStatus(MCRJobStatus.MAX_TRIES);
job6.setAdded(new Date(elevenMinutesAgo));
job6.setStart(new Date(elevenMinutesAgo));
mockDAO.daoOfferedJobs.add(job5);
Assert.assertEquals("offered jobs should be 6", 6, mockDAO.daoOfferedJobs.size());
Assert.assertEquals("resetted jobs in queue1 should be 0", 0, reset1.size());
Assert.assertEquals("resetted jobs in queue2 should be 0", 0, reset2.size());
resetter.resetJobsWithAction(MCRTestJobAction.class);
Assert.assertEquals("resetted jobs in queue1 should be 1", 1, reset1.size());
Assert.assertEquals("resetted jobs in queue2 should be 0", 0, reset2.size());
Assert.assertEquals("reseted job should have count 1", "1",
reset1.poll().getParameter("count"));
resetter.resetJobsWithAction(MCRTestJobAction2.class);
Assert.assertEquals("resetted jobs in queue1 should be 0 (poll called)", 0, reset1.size());
Assert.assertEquals("resetted jobs in queue2 should be 1", 1, reset2.size());
Assert.assertEquals("reseted job should have count 2", "2",
reset2.poll().getParameter("count"));
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
}
}
| 5,148 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRTestJobAction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRTestJobAction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
/**
* @author René Adler (eagle)
*
*/
public class MCRTestJobAction extends MCRJobAction {
public static final String ERROR_MESSAGE = "Error parameter was set to true";
private static Logger LOGGER = LogManager.getLogger(MCRTestJobAction.class);
/**
* @param job
*/
public MCRTestJobAction(MCRJob job) {
super(job);
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#isActivated()
*/
@Override
public boolean isActivated() {
return true;
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#name()
*/
@Override
public String name() {
return this.getClass().getSimpleName();
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#execute()
*/
@Override
public void execute() {
LOGGER.info("job num: {}", job.getParameter("count"));
job.setParameter("done", "true");
if (job.getParameters().containsKey("error") && Boolean.parseBoolean(job.getParameter("error"))) {
throw new MCRException(ERROR_MESSAGE);
}
}
/* (non-Javadoc)
* @see org.mycore.services.queuedjob.MCRJobAction#rollback()
*/
@Override
public void rollback() {
LOGGER.info(job);
job.setParameter("done", "false");
}
}
| 2,250 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRMockJobDAO.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRMockJobDAO.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class MCRMockJobDAO implements MCRJobDAO {
public final List<MCRJob> daoOfferedJobs = new ArrayList<>();
Long id = 1L;
public boolean jobMatch(MCRJob job, Class<? extends MCRJobAction> action,
Map<String, String> params, List<MCRJobStatus> status) {
boolean actionEquals = action == null || Objects.equals(job.getAction(), action);
boolean paramsEquals = params == null || job.getParameters().entrySet().containsAll(params.entrySet());
boolean statusEquals = status == null || status.size() == 0 || status.contains(job.getStatus());
return actionEquals && paramsEquals && statusEquals;
}
@Override
public List<MCRJob> getJobs(Class<? extends MCRJobAction> action,
Map<String, String> params, List<MCRJobStatus> status,
Integer maxResults,
Integer offset) {
return daoOfferedJobs.stream().filter(j -> jobMatch(j, action, params, status))
.skip(offset == null ? 0 : offset)
.limit(maxResults == null ? daoOfferedJobs.size() : maxResults).toList();
}
@Override
public int getJobCount(Class<? extends MCRJobAction> action, Map<String, String> params,
List<MCRJobStatus> status) {
return getJobs(action, params, status, null, null).size();
}
@Override
public int removeJobs(Class<? extends MCRJobAction> action, Map<String, String> params,
List<MCRJobStatus> status) {
List<MCRJob> jobs = daoOfferedJobs.stream().filter(j -> jobMatch(j, action, params, status)).toList();
daoOfferedJobs.removeAll(jobs);
return jobs.size();
}
@Override
public MCRJob getJob(Class<? extends MCRJobAction> action, Map<String, String> params,
List<MCRJobStatus> status) {
List<MCRJob> jobs = getJobs(action, params, status, 5, 0);
if (jobs.size() > 1) {
throw new IllegalStateException("more than one job found");
}
return jobs.stream().findFirst().orElse(null);
}
@Override
public List<MCRJob> getNextJobs(Class<? extends MCRJobAction> action, Integer amount) {
return daoOfferedJobs.stream()
.filter(j -> Objects.equals(j.getAction(), action) && j.getStatus().equals(MCRJobStatus.NEW))
.sorted(Comparator.comparing(MCRJob::getAdded))
.limit(amount == null ? daoOfferedJobs.size() : amount).toList();
}
@Override
public int getRemainingJobCount(Class<? extends MCRJobAction> action) {
return (int) daoOfferedJobs.stream()
.filter(j -> Objects.equals(j.getAction(), action) && j.getStatus().equals(MCRJobStatus.NEW))
.count();
}
@Override
public boolean updateJob(MCRJob job) {
return daoOfferedJobs.remove(job) && daoOfferedJobs.add(job);
}
@Override
public boolean addJob(MCRJob job) {
job.setId(id++);
daoOfferedJobs.add(job);
return true;
}
@Override
public List<? extends Class<? extends MCRJobAction>> getActions() {
return List.of(MCRTestJobAction.class, MCRTestJobAction2.class);
}
}
| 4,019 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRJobQueueTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.common.MCRTestCase;
import org.mycore.services.queuedjob.config2.MCRConfiguration2JobConfig;
public class MCRJobQueueTest extends MCRTestCase {
private MCRMockJobDAO mockDAO;
@Override
public void setUp() throws Exception {
super.setUp();
mockDAO = new MCRMockJobDAO();
}
@Test
public void offer() throws InterruptedException {
final List<MCRJob> offeredJobs = new ArrayList<>();
final List<MCRJob> notifiedJobs = new ArrayList<>();
MCRJobQueue queue = new MCRJobQueue(MCRTestJobAction.class, new MCRConfiguration2JobConfig(), mockDAO);
MCRJobQueueEventListener listener = notifiedJobs::add;
queue.addListener(listener);
MCRJob job;
for (int c = 10; c > 0; c--) {
if (c == 5) {
queue.removeListener(listener);
}
job = new MCRJob();
job.setParameter("count", Integer.toString(c));
Assert.assertTrue("job should be offered", queue.offer(job));
Thread.sleep(2); // sleep to get different timestamps
offeredJobs.add(job);
}
Assert.assertEquals("offered jobs should be 10", offeredJobs.size(), mockDAO.daoOfferedJobs.size());
for (int c = 0; c < offeredJobs.size(); c++) {
Assert.assertEquals("offered jobs should be equal", offeredJobs.get(c), mockDAO.daoOfferedJobs.get(c));
}
Assert.assertEquals("notified jobs should be 5", 5, notifiedJobs.size());
for (int c = 0; c < notifiedJobs.size(); c++) {
Assert.assertEquals("notified jobs should be equal", offeredJobs.get(c), notifiedJobs.get(c));
}
// reading the same jobs should work, but the count needs to stay the same
for (MCRJob j : offeredJobs) {
Assert.assertTrue("job should not be offered", queue.offer(j));
}
Assert.assertEquals("offered jobs should be 10", offeredJobs.size(), mockDAO.daoOfferedJobs.size());
// the offered jobs should have the right action, the right status and a timestamp
for (MCRJob j : offeredJobs) {
Assert.assertEquals("job action should be MCRTestJobAction", MCRTestJobAction.class, j.getAction());
Assert.assertEquals("job status should be new", MCRJobStatus.NEW, j.getStatus());
Assert.assertTrue("job added timestamp should be set", j.getAdded().getTime() > 0);
}
// offer a job with different action should trigger an exception
job = new MCRJob(MCRTestJobAction2.class);
job.setParameter("count", Integer.toString(1));
try {
queue.offer(job);
Assert.fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
// expected
}
}
@Test
public void poll() {
MCRJobQueue queue = new MCRJobQueue(MCRTestJobAction.class, new MCRConfiguration2JobConfig(), mockDAO);
List<MCRJob> offeredJobs = new ArrayList<>();
MCRJob job;
for (int i = 0; i < 10; i++) {
job = new MCRJob();
job.setId((long) i + 1);
job.setAction(MCRTestJobAction.class);
job.setParameter("count", Integer.toString(i));
job.setStatus(MCRJobStatus.NEW);
job.setAdded(new java.util.Date(1000000 - (i * 100000))); // reverse the actual order
mockDAO.daoOfferedJobs.add(job);
offeredJobs.add(job);
}
// poll all jobs
List<MCRJob> polledJobs = new ArrayList<>();
MCRJob polledJob;
while ((polledJob = queue.poll()) != null) {
polledJobs.add(polledJob);
}
// compare offered and polled jobs order
offeredJobs.sort(Comparator.comparing(MCRJob::getAdded));
Assert.assertEquals("polled jobs should be 10", offeredJobs.size(), polledJobs.size());
for (int c = 0; c < offeredJobs.size(); c++) {
Assert.assertEquals("polled jobs should be equal", offeredJobs.get(c), polledJobs.get(c));
}
}
@Test
public void peek() {
MCRJobQueue queue = new MCRJobQueue(MCRTestJobAction.class, new MCRConfiguration2JobConfig(), mockDAO);
List<MCRJob> offeredJobs = new ArrayList<>();
MCRJob job;
for (int i = 0; i < 10; i++) {
job = new MCRJob();
job.setAction(MCRTestJobAction.class);
job.setParameter("count", Integer.toString(i));
job.setStatus(MCRJobStatus.NEW);
job.setAdded(new java.util.Date(1000000 - (i * 100000))); // reverse the actual order
mockDAO.daoOfferedJobs.add(job);
offeredJobs.add(job);
}
MCRJob peek = queue.peek();
Assert.assertEquals("peek should return the last added job", offeredJobs.get(9), peek);
MCRJob peek2 = queue.peek();
Assert.assertEquals("peek should return the same job", peek, peek2);
mockDAO.daoOfferedJobs.remove(peek);
MCRJob peek3 = queue.peek();
Assert.assertEquals("peek should return the next job", offeredJobs.get(8), peek3);
MCRJob peek4 = queue.peek();
Assert.assertEquals("peek should return the same job", peek3, peek4);
}
protected Map<String, String> getTestProperties() {
return super.getTestProperties();
}
}
| 6,310 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobThreadStarterTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRJobThreadStarterTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRException;
import org.mycore.common.MCRJPATestCase;
import org.mycore.common.processing.impl.MCRCentralProcessableRegistry;
import org.mycore.services.queuedjob.config2.MCRConfiguration2JobConfig;
import jakarta.persistence.EntityTransaction;
public class MCRJobThreadStarterTest extends MCRJPATestCase {
private static final Logger LOGGER = LogManager.getLogger();
private static List<MCRJob> getAllJobs(MCRJobDAOJPAImpl dao, Class<? extends MCRJobAction> action) {
return dao.getJobs(action, null, null, null, null);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testRun() {
MCRConfiguration2JobConfig config = new MCRConfiguration2JobConfig();
MCRJobDAOJPAImpl dao = new MCRJobDAOJPAImpl();
MCRJobQueue queue = new MCRJobQueue(MCRTestJobAction.class, config, dao);
MCRJobThreadStarter starter = new MCRJobThreadStarter(MCRTestJobAction.class, config, queue);
Date baseTime = new Date();
MCRJob job1 = new MCRJob(MCRTestJobAction.class);
job1.setParameter("count", "1");
job1.setParameter("error", "false");
job1.setStatus(MCRJobStatus.NEW);
job1.setAdded(new Date(baseTime.getTime() + 20));
queue.offer(job1);
MCRJob job2 = new MCRJob(MCRTestJobAction.class);
job2.setParameter("count", "2");
job2.setParameter("error", "false");
job2.setStatus(MCRJobStatus.NEW);
job2.setAdded(new Date(baseTime.getTime() + 40));
queue.offer(job2);
MCRJob job3 = new MCRJob(MCRTestJobAction.class);
job3.setParameter("count", "3");
job3.setParameter("error", "true");
job3.setStatus(MCRJobStatus.NEW);
job3.setAdded(new Date(baseTime.getTime() + 60));
queue.offer(job3);
EntityTransaction transaction = getEntityManager().get().getTransaction();
transaction.commit();
transaction.begin();
Thread thread = new Thread(starter);
thread.start();
try {
int maxWait = 10000;
int stepTime = 100;
while (getAllJobs(dao, job1.getAction()).stream()
.filter(j -> j.getStatus() == MCRJobStatus.FINISHED || j.getStatus() == MCRJobStatus.ERROR)
.count() < 3 && maxWait > 0) {
Thread.sleep(stepTime);
LOGGER.info("waiting for jobs to finish time left: {}", maxWait);
maxWait -= stepTime;
transaction.rollback(); // rollback to get new data in the next iteration
transaction.begin();
}
} catch (InterruptedException e) {
throw new MCRException(e);
}
long finishedJobCount
= getAllJobs(dao, job1.getAction()).stream().filter(j -> j.getStatus() == MCRJobStatus.FINISHED).count();
long errorJobCount
= getAllJobs(dao, job1.getAction()).stream().filter(j -> j.getStatus() == MCRJobStatus.ERROR).count();
Assert.assertEquals("Finished Job count should be 2", 2, finishedJobCount);
Assert.assertEquals("Error Job count should be 1", 1, errorJobCount);
}
@Override
protected Map<String, String> getTestProperties() {
Map<String, String> props = super.getTestProperties();
props.put("MCR.Processable.Registry.Class", MCRCentralProcessableRegistry.class.getName());
return props;
}
}
| 4,626 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobDAOJPAImplTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/test/java/org/mycore/services/queuedjob/MCRJobDAOJPAImplTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mycore.common.MCRJPATestCase;
import jakarta.persistence.EntityManager;
public class MCRJobDAOJPAImplTest extends MCRJPATestCase {
public static final String NEW_COUNT = "13";
MCRJobDAOJPAImpl dao;
MCRJob job1;
MCRJob job2;
MCRJob job3;
MCRJob job4;
MCRJob job5;
MCRJob xJob6;
MCRJob xJob7;
MCRJob xJob8;
HashMap<String, String> errorTrueParam;
HashMap<String, String> errorFalseParam;
List<MCRJob> allJobs;
List<MCRJob> xJobs;
private static void assertAllPresent(List<MCRJob> expected, List<MCRJob> jobs) {
Assert.assertEquals("There should be " + expected.size() + " jobs", expected.size(), jobs.size());
for (int i = 0; i < expected.size(); i++) {
Assert.assertTrue(
"Job " + expected.get(i).toString() + " should be in the list "
+ jobs.stream().map(MCRJob::toString).collect(Collectors.joining(", ")),
jobs.contains(expected.get(i)));
}
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
dao = new MCRJobDAOJPAImpl();
Date baseTime = new Date();
job1 = new MCRJob(MCRTestJobAction.class);
job1.setParameter("count", "1");
job1.setParameter("error", "false");
job1.setStatus(MCRJobStatus.NEW);
job1.setAdded(new Date(baseTime.getTime() + 20));
job2 = new MCRJob(MCRTestJobAction.class);
job2.setParameter("count", "2");
job2.setParameter("error", "false");
job2.setStatus(MCRJobStatus.PROCESSING);
job2.setAdded(new Date(baseTime.getTime() + 40));
job3 = new MCRJob(MCRTestJobAction.class);
job3.setParameter("count", "3");
job3.setParameter("error", "true");
job3.setStatus(MCRJobStatus.FINISHED);
job3.setAdded(new Date(baseTime.getTime() + 60));
job4 = new MCRJob(MCRTestJobAction2.class);
job4.setParameter("count", "4");
job4.setParameter("error", "true");
job4.setStatus(MCRJobStatus.ERROR);
job4.setAdded(new Date(baseTime.getTime() + 80));
job5 = new MCRJob(MCRTestJobAction2.class);
job5.setParameter("count", "5");
job5.setParameter("error", "true");
job5.setStatus(MCRJobStatus.MAX_TRIES);
job5.setAdded(new Date(baseTime.getTime() + 100));
xJob6 = new MCRJob(MCRTestJobAction.class);
xJob6.setParameter("count", "6");
xJob6.setParameter("error", "false");
xJob6.setStatus(MCRJobStatus.NEW);
xJob6.setAdded(new Date(baseTime.getTime() + 120));
xJob7 = new MCRJob(MCRTestJobAction.class);
xJob7.setParameter("count", "7");
xJob7.setParameter("error", "false");
xJob7.setStatus(MCRJobStatus.NEW);
xJob7.setAdded(new Date(baseTime.getTime() + 140));
xJob8 = new MCRJob(MCRTestJobAction.class);
xJob8.setParameter("count", "8");
xJob8.setParameter("error", "false");
xJob8.setStatus(MCRJobStatus.NEW);
xJob8.setAdded(new Date(baseTime.getTime() + 160));
errorTrueParam = new HashMap<>();
errorTrueParam.put("error", "true");
errorFalseParam = new HashMap<>();
errorFalseParam.put("error", "false");
allJobs = Stream.of(job1, job2, job3, job4, job5).collect(Collectors.toList());
xJobs = Stream.of(xJob6, xJob7, xJob8).collect(Collectors.toList());
}
@Test
public void getJobs() {
EntityManager em = getEntityManager().get();
allJobs.forEach(em::persist);
List<MCRJob> jobs = dao.getJobs(null, null, null, null, null);
assertAllPresent(allJobs, jobs);
jobs = dao.getJobs(null, Collections.emptyMap(), null, null, null);
assertAllPresent(allJobs, jobs);
jobs = dao.getJobs(null, null, Collections.emptyList(), null, null);
assertAllPresent(allJobs, jobs);
jobs = dao.getJobs(null, null, null, 5, null);
assertAllPresent(allJobs, jobs);
jobs = dao.getJobs(null, null, null, 4, null);
assertAllPresent(allJobs.subList(0, 4), jobs);
jobs = dao.getJobs(null, null, null, 3, null);
assertAllPresent(allJobs.subList(0, 3), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, null, null, null, null);
assertAllPresent(Arrays.asList(job1, job2, job3), jobs);
jobs = dao.getJobs(MCRTestJobAction2.class, null, null, null, null);
assertAllPresent(Arrays.asList(job4, job5), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, Collections.emptyMap(),
Stream.of(MCRJobStatus.NEW, MCRJobStatus.PROCESSING).toList(), null, null);
assertAllPresent(Arrays.asList(job1, job2), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, Collections.emptyMap(),
Stream.of(MCRJobStatus.NEW, MCRJobStatus.PROCESSING).toList(), 1, null);
assertAllPresent(List.of(job1), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, job1.getParameters(), null, null, null);
assertAllPresent(List.of(job1), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, job1.getParameters(), List.of(MCRJobStatus.PROCESSING), null, null);
assertAllPresent(Collections.emptyList(), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, errorFalseParam, null, null, null);
assertAllPresent(List.of(job1, job2), jobs);
jobs = dao.getJobs(MCRTestJobAction.class, errorTrueParam, null, null, null);
assertAllPresent(List.of(job3), jobs);
jobs = dao.getJobs(null, errorTrueParam, null, null, null);
assertAllPresent(List.of(job3, job4, job5), jobs);
jobs = dao.getJobs(MCRTestJobAction2.class, job1.getParameters(), null, null, null);
assertAllPresent(Collections.emptyList(), jobs);
jobs = dao.getJobs(MCRTestJobAction2.class, errorFalseParam, null, null, null);
assertAllPresent(Collections.emptyList(), jobs);
}
@Test
public void removeJobs() throws Exception {
EntityManager em = getEntityManager().get();
allJobs.forEach(em::persist);
dao.removeJobs(MCRTestJobAction.class, null, null);
List<MCRJob> resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(Arrays.asList(job4, job5), resultList);
dao.removeJobs(MCRTestJobAction2.class, null, null);
resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(Collections.emptyList(), resultList);
em = reset();
allJobs.forEach(em::persist);
dao.removeJobs(null, errorTrueParam, null);
resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(Arrays.asList(job1, job2), resultList);
em = reset();
allJobs.forEach(em::persist);
dao.removeJobs(null, errorFalseParam, null);
resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(Arrays.asList(job3, job4, job5), resultList);
em = reset();
allJobs.forEach(em::persist);
dao.removeJobs(null, null, List.of(MCRJobStatus.NEW, MCRJobStatus.PROCESSING));
resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(Arrays.asList(job3, job4, job5), resultList);
em = reset();
allJobs.forEach(em::persist);
dao.removeJobs(null, null, List.of(MCRJobStatus.ERROR, MCRJobStatus.MAX_TRIES));
resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(Arrays.asList(job1, job2, job3), resultList);
}
@Test
public void getJob() {
EntityManager em = getEntityManager().get();
allJobs.forEach(em::persist);
MCRJob job = dao.getJob(MCRTestJobAction.class, job1.getParameters(), List.of(MCRJobStatus.NEW));
Assert.assertEquals("Job 1 should be equal", job1, job);
job = dao.getJob(MCRTestJobAction.class, job1.getParameters(), List.of(MCRJobStatus.PROCESSING));
Assert.assertNull("Job 1 should be null", job);
job = dao.getJob(MCRTestJobAction.class, job1.getParameters(),
List.of(MCRJobStatus.NEW, MCRJobStatus.PROCESSING));
Assert.assertEquals("Job 1 should be equal", job1, job);
job = dao.getJob(MCRTestJobAction.class, job1.getParameters(), null);
Assert.assertEquals("Job 1 should be equal", job1, job);
job = dao.getJob(MCRTestJobAction.class, job1.getParameters(), Collections.emptyList());
Assert.assertEquals("Job 1 should be equal", job1, job);
job = dao.getJob(null, job1.getParameters(), null);
Assert.assertEquals("Job 1 should be equal", job1, job);
job = dao.getJob(MCRTestJobAction.class, job2.getParameters(), null);
Assert.assertEquals("Job 2 should be equal", job2, job);
try {
job = dao.getJob(MCRTestJobAction.class, null, null);
Assert.fail("There should be an IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
@Test
public void getNextJobs() {
EntityManager em = getEntityManager().get();
allJobs.forEach(em::persist);
xJobs.forEach(em::persist);
List<MCRJob> jobs = dao.getNextJobs(MCRTestJobAction.class, 1);
assertAllPresent(List.of(job1), jobs);
MCRJob j1 = em.merge(job1);
em.remove(j1);
jobs = dao.getNextJobs(MCRTestJobAction.class, 2);
assertAllPresent(List.of(xJob6, xJob7), jobs);
MCRJob j6 = em.merge(xJob6);
MCRJob j7 = em.merge(xJob7);
em.remove(j6);
em.remove(j7);
jobs = dao.getNextJobs(MCRTestJobAction.class, 2);
assertAllPresent(List.of(xJob8), jobs);
}
@Test
public void remainingJobCount() {
EntityManager em = getEntityManager().get();
allJobs.forEach(em::persist);
xJobs.forEach(em::persist);
int jobs = dao.getRemainingJobCount(MCRTestJobAction.class);
Assert.assertEquals("There should be 4 remaining jobs", 4, jobs);
MCRJob j1 = em.merge(job1);
em.remove(j1);
jobs = dao.getRemainingJobCount(MCRTestJobAction.class);
Assert.assertEquals("There should be 2 remaining jobs", 3, jobs);
MCRJob j6 = em.merge(xJob6);
MCRJob j7 = em.merge(xJob7);
em.remove(j6);
em.remove(j7);
jobs = dao.getRemainingJobCount(MCRTestJobAction.class);
Assert.assertEquals("There should be 1 remaining jobs", 1, jobs);
}
@Test
public void updateJob() {
EntityManager em = getEntityManager().get();
allJobs.forEach(em::persist);
MCRJob job1 = dao.getJob(MCRTestJobAction.class, this.job1.getParameters(), null);
Assert.assertEquals("Job 1 should be equal", this.job1, job1);
job1.setStatus(MCRJobStatus.ERROR);
dao.updateJob(job1);
job1 = dao.getJob(MCRTestJobAction.class, this.job1.getParameters(), null);
Assert.assertEquals("Job 1 Status should be ERROR", MCRJobStatus.ERROR, job1.getStatus());
job1.setParameter("count", NEW_COUNT);
dao.updateJob(job1);
job1 = dao.getJob(MCRTestJobAction.class, this.job1.getParameters(), null);
Assert.assertEquals("Job 1 Count should be 13", NEW_COUNT, job1.getParameter("count"));
}
@Test
public void addJob() {
EntityManager em = getEntityManager().get();
allJobs.forEach(job -> dao.addJob(job));
List<MCRJob> resultList = em.createQuery("SELECT j FROM MCRJob j", MCRJob.class).getResultList();
assertAllPresent(allJobs, resultList);
}
private EntityManager reset() throws Exception {
tearDown();
setUp();
return getEntityManager().get();
}
}
| 13,058 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobResetter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobResetter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
import org.mycore.mcr.cronjob.MCRCronjob;
import org.mycore.util.concurrent.MCRTransactionableRunnable;
/**
* Resets jobs that are in {@link MCRJobStatus#ERROR} for minimum the time defined in the job config.
*
* @author René Adler
*/
public class MCRJobResetter extends MCRCronjob {
private static final Logger LOGGER = LogManager.getLogger(MCRJobResetter.class);
private final MCRJobDAO dao;
private final MCRJobConfig config;
private Function<Class<? extends MCRJobAction>, Queue<MCRJob>> queueResolver;
/**
* Creates a new instance of {@link MCRJobResetter}. Uses {@link MCRJobQueueManager} to resolve dependencies.
* Used by the Cronjob system.
*/
public MCRJobResetter() {
this(MCRJobQueueManager.getInstance().getJobDAO(), MCRJobQueueManager.getInstance()::getJobQueue,
MCRJobQueueManager.getInstance().getJobConfig());
}
/**
* Creates a new instance of {@link MCRJobResetter}.
* @param dao the job dao to receive jobs from
* @param queueResolver the queue resolver to resolve the queue for a job action, which will be used add the
* resetted jobs to.
* @param config the job config to determine the time till reset
*/
MCRJobResetter(MCRJobDAO dao, Function<Class<? extends MCRJobAction>, Queue<MCRJob>> queueResolver,
MCRJobConfig config) {
this.dao = dao;
this.queueResolver = queueResolver;
this.config = config;
}
/**
* Resets jobs to {@link MCRJobStatus#NEW} that are in {@link MCRJobStatus#ERROR} for minimum the time defined
* @param action the action to reset jobs for
* @param config the job config
* @param dao the job dao to use
* @param queue the queue to add the resetted jobs to
* @param status the status of the jobs to reset
* @return the number of resetted jobs
*/
protected static long resetJobsWithAction(Class<? extends MCRJobAction> action, MCRJobConfig config, MCRJobDAO dao,
Queue<MCRJob> queue, MCRJobStatus status) {
Duration maxTimeDiff = config.timeTillReset(action).orElseGet(config::timeTillReset);
List<MCRJob> jobs = dao.getJobs(action, Collections.emptyMap(), List.of(status), null, null);
long current = System.currentTimeMillis();
return jobs.stream().filter(job -> {
long start = job.getStart().getTime();
Duration elapsedTime = Duration.ofMillis(current - start);
return maxTimeDiff.minus(elapsedTime).isNegative();
}).filter(queue::offer).count();
}
/**
* Resets jobs to {@link MCRJobStatus#NEW} that are in {@link MCRJobStatus#ERROR} for minimum the time defined
* @param action the action to reset jobs for
*/
protected void resetJobsWithAction(Class<? extends MCRJobAction> action) {
resetJobsWithAction(action, config, dao, queueResolver.apply(action), MCRJobStatus.ERROR);
}
/**
* Resets jobs to {@link MCRJobStatus#NEW} that are in {@link MCRJobStatus#ERROR} for minimum the time defined
* in {@link MCRJobConfig#timeTillReset()} or {@link MCRJobConfig#timeTillReset(Class)}.
*/
@Override
public void runJob() {
try {
new MCRTransactionableRunnable(() -> {
dao.getActions().forEach(this::resetJobsWithAction);
LOGGER.info("MCRJob checking is done");
}).run();
} catch (Exception e) {
throw new MCRException("Error while resetting jobs!", e);
}
}
@Override
public String getDescription() {
return "Resets jobs that took to long to perform action or produced errors.";
}
}
| 4,740 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueManager.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueManager.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.services.queuedjob.config2.MCRConfiguration2JobConfig;
/**
* Manages the {@link MCRJobQueue} and other related instances for all {@link MCRJobAction} implementations.
* @author Sebastian Hofmann
*/
public class MCRJobQueueManager {
private static final Logger LOGGER = LogManager.getLogger();
final Map<String, MCRJobQueue> queueInstances = new ConcurrentHashMap<>();
final Map<String, MCRJobThreadStarter> jobThreadStartInstances = new ConcurrentHashMap<>();
private final MCRJobDAO dao;
private final MCRJobConfig config;
MCRJobQueueManager(MCRJobDAO dao, MCRJobConfig config) {
this.dao = dao;
this.config = config;
}
/**
* @return the singleton instance of the {@link MCRJobQueueManager}
*/
public static MCRJobQueueManager getInstance() {
return InstanceHolder.INSTANCE;
}
private static boolean isJPAEnabled() {
return MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)
&& MCREntityManagerProvider.getEntityManagerFactory() != null;
}
private void initializeAction(Class<? extends MCRJobAction> action) {
String key = action.getName();
MCRJobConfig config = getJobConfig();
MCRJobQueue queue = queueInstances.computeIfAbsent(key, k -> {
MCRJobQueue queue1 = new MCRJobQueue(action, config, getJobDAO());
long count = MCRJobResetter.resetJobsWithAction(action, config, getJobDAO(), queue1,
MCRJobStatus.PROCESSING);
if (count > 0) {
LOGGER.info("Resetted {} processing jobs for action {} on startup!", count, action.getName());
}
return queue1;
});
boolean jpaEnabled = isJPAEnabled();
if (jpaEnabled) {
jobThreadStartInstances.computeIfAbsent(key, k -> {
MCRJobThreadStarter starter = new MCRJobThreadStarter(action, this.config, queue);
Thread jobThreadStarterThread = new Thread(starter);
jobThreadStarterThread.start();
return starter;
});
}
queue.setRunning(jpaEnabled);
}
/**
* Returns a singleton instance of this class.
*
* @param action the {@link MCRJobAction} or <code>null</code>
* @return the instance of this class
*/
public MCRJobThreadStarter getJobThreadStarter(Class<? extends MCRJobAction> action) {
initializeAction(action);
String key = action.getName();
return jobThreadStartInstances.get(key);
}
/**
* Returns a singleton instance of {@link MCRJobQueue} for the given {@link MCRJobAction}.
*
* @param action the {@link MCRJobAction} or <code>null</code>
* @return singleton instance of this class
*/
public MCRJobQueue getJobQueue(Class<? extends MCRJobAction> action) {
initializeAction(action);
String key = action.getName();
return queueInstances.get(key);
}
/***
* @return list of all {@link MCRJobQueue} instances
*/
public List<MCRJobQueue> getJobQueues() {
return new ArrayList<>(queueInstances.values());
}
/**
* @return the {@link MCRJobDAO} instance
*/
public MCRJobDAO getJobDAO() {
return dao;
}
/**
* @return the {@link MCRJobConfig} instance
*/
public MCRJobConfig getJobConfig() {
return config;
}
private static class InstanceHolder {
private static final MCRJobQueueManager INSTANCE = new MCRJobQueueManager(new MCRJobDAOJPAImpl(),
new MCRConfiguration2JobConfig());
}
}
| 4,757 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueue.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueue.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRException;
/**
* A queue for {@link MCRJob} instances. Provides queue logic for {@link MCRJobDAO}.
* @author Sebastian Hofmann
*/
public class MCRJobQueue extends AbstractQueue<MCRJob> implements EventListener {
private static final Logger LOGGER = LogManager.getLogger(MCRJobQueue.class);
private final Class<? extends MCRJobAction> action;
private final ReentrantLock pollLock;
private final MCRJobConfig config;
private final MCRJobDAO dao;
private final List<MCRJobQueueEventListener> listeners;
private boolean running;
/**
* Creates a new JobQueue instance.
* @param action the {@link MCRJobAction} the action this queue is responsible for
* @param config the {@link MCRJobConfig} which is used to determine if the queue is running
* @param dao the {@link MCRJobDAO} which is used to retrieve jobs
*/
protected MCRJobQueue(Class<? extends MCRJobAction> action, MCRJobConfig config, MCRJobDAO dao) {
this.config = config;
this.dao = dao;
this.action = action;
running = config.activated(action).orElseGet(config::activated);
pollLock = new ReentrantLock();
listeners = new ArrayList<>();
}
/**
* Returns a singleton instance of this class.
*
* @param action the {@link MCRJobAction} or <code>null</code>
* @return singleton instance of this class
* @deprecated use {@link MCRJobQueueManager#getInstance()} and {@link MCRJobQueueManager#getJobQueue(Class)}
* instead
*/
@Deprecated
public static MCRJobQueue getInstance(Class<? extends MCRJobAction> action) {
return MCRJobQueueManager.getInstance().getJobQueue(action);
}
/**
* @return next available job instance
*/
@Override
public MCRJob poll() {
if (!running || !config.activated(action).orElseGet(config::activated)) {
return null;
}
try {
pollLock.lock();
MCRJob job = dao.getNextJobs(action, 1).stream().findFirst().orElse(null);
if (job != null) {
job.setStart(new Date(System.currentTimeMillis()));
job.setStatus(MCRJobStatus.PROCESSING);
if (!dao.updateJob(job)) {
throw new MCRException("Could not update job " + job.getId() + " to status PROCESSING");
}
LOGGER.info("Receive job {} from DAO", job);
}
return job;
} finally {
pollLock.unlock();
}
}
/**
* removes next job.
* same as {@link #poll()} but never returns null
* @throws NoSuchElementException if {@link #poll()} would return null
*/
@Override
public MCRJob remove() throws NoSuchElementException {
if (!running) {
return null;
}
MCRJob job = poll();
if (job == null) {
throw new NoSuchElementException();
}
return job;
}
/**
* get next job without modifying it state to {@link MCRJobStatus#PROCESSING}
* @return the next job
*/
@Override
public MCRJob peek() {
if (!running) {
return null;
}
return dao.getNextJobs(action, 1).stream().findFirst().orElse(null);
}
/**
* removes next job.
* same as {@link #peek()} but never returns null
* @throws NoSuchElementException if {@link #peek()} would return null
*/
@Override
public MCRJob element() throws NoSuchElementException {
if (!running) {
return null;
}
MCRJob job = peek();
if (job == null) {
throw new NoSuchElementException();
}
return job;
}
/**
* adds {@link MCRJob} to queue and starts {@link MCRJobThreadStarter} if the queue is activated.
* alters date added to current time and status of job to {@link MCRJobStatus#NEW}
* @param job the job to add
* @return <code>true</code> if job was added
* @throws IllegalArgumentException if job action does not match queue action
*/
@Override
public boolean offer(MCRJob job) {
if (!running) {
return false;
}
if (job.getAction() == null) {
job.setAction(action);
} else if (!job.getAction().equals(action)) {
throw new IllegalArgumentException("Job action " + job.getAction() + " does not match queue action "
+ action);
}
boolean added;
job.setAdded(new Date());
job.setStatus(MCRJobStatus.NEW);
job.setStart(null);
if (job.getId() == null) {
LOGGER.info("Adding job {} to queue {}.", job.toString(), action.getName());
added = dao.addJob(job);
} else {
LOGGER.info("Update job {} in queue {}.", job.toString(), action.getName());
added = dao.updateJob(job);
}
if (added) {
this.listeners.forEach(l -> {
l.onJobAdded(job);
});
}
return added;
}
/**
* Deletes all jobs no matter what the current state is.
*/
@Override
public void clear() {
if (!running) {
return;
}
LOGGER.info("Clearing queue {}.", action.getName());
dao.removeJobs(action, Collections.emptyMap(), List.of(MCRJobStatus.NEW));
}
/**
* iterates over jobs of status {@link MCRJobStatus#NEW}
*
* does not change the status.
*/
@Override
public Iterator<MCRJob> iterator() {
return iterator(MCRJobStatus.NEW);
}
/**
* Builds iterator for jobs with given {@link MCRJobStatus} or <code>null</code> for all jobs.
* @param status the status or <code>null</code>
* @return the iterator
*/
public Iterator<MCRJob> iterator(MCRJobStatus status) {
if (!running) {
return Collections.emptyIterator();
}
List<MCRJob> jobs = dao.getJobs(action, Collections.emptyMap(),
Stream.ofNullable(status).collect(Collectors.toList()),
null, null);
return jobs.listIterator();
}
/**
* returns the current size of this queue
*/
@Override
public int size() {
if (!running) {
return 0;
}
return dao.getRemainingJobCount(action);
}
/**
* Returns a specific job from given parameters or null if not found.
*
* @param params the parameters
* @return the job
* @deprecated use {@link MCRJobDAO#getJobs(Class, Map, List, Integer, Integer)} instead.
* * The job queue should only be used for {@link MCRJobStatus#NEW} jobs, but this method returns all jobs.
*/
@Deprecated
public MCRJob getJob(Map<String, String> params) {
if (!running) {
return null;
}
return dao.getJob(action, params, Collections.emptyList());
}
/**
* Returns specific jobs by the given parameters or an empty list.
*
* @param params the parameters
* @return a list of jobs matching the given parameters
* @deprecated use {@link MCRJobDAO#getJobs(Class, Map, List, Integer, Integer)} instead.
* The job queue should only be used for {@link MCRJobStatus#NEW} jobs, but this method returns all jobs.
*/
@Deprecated
public List<MCRJob> getJobs(Map<String, String> params) {
return getJobs(action, params);
}
/**
* Returns specific jobs by the given parameters or an empty list.
*
* @param action the action class
* @param params the parameters
*
* @return a list of jobs matching the given parameters
* @deprecated use {@link MCRJobDAO#getJobs(Class, Map, List, Integer, Integer)} instead
* The job queue should only be used for {@link MCRJobStatus#NEW} jobs, but this method returns all jobs.
*/
@Deprecated
private List<MCRJob> getJobs(Class<? extends MCRJobAction> action, Map<String, String> params) {
if (!running) {
return null;
}
return dao.getJobs(action, params, Collections.emptyList(), null, null);
}
/**
* removes specific job from queue no matter what its current status is.
*
* @param action - the action class
* @param params - parameters to get jobs
* @return the number of jobs deleted
*/
public int remove(Class<? extends MCRJobAction> action, Map<String, String> params) {
if (!running) {
return 0;
}
return dao.removeJobs(action, params, Collections.emptyList());
}
/**
* Removes all jobs from queue of specified action.
*
* @param action - the action class
* @return the number of jobs deleted
*/
public int remove(Class<? extends MCRJobAction> action) {
if (!running) {
return 0;
}
return dao.removeJobs(action, Collections.emptyMap(), Collections.emptyList());
}
/**
* @return "MCRJobQueue"
*/
@Override
public String toString() {
return "MCRJobQueue for " + action.getName();
}
/**
* @return true if the queue is running and jobs can be added or removed
*/
public boolean isRunning() {
return running;
}
/**
* @param running if true, the queue is running, otherwise it is stopped and no jobs can be added or removed
*/
protected void setRunning(boolean running) {
this.running = running;
}
/**
* Adds a listener to this queue. The listener will be notified when a job is added.
* @param listener the listener to add
*/
public void addListener(MCRJobQueueEventListener listener) {
listeners.add(listener);
}
/**
* Removes a listener to this queue. The listener will not be notified anymore.
* @param listener the listener to remove
*/
public void removeListener(MCRJobQueueEventListener listener) {
listeners.remove(listener);
}
/**
* Returns the action class of this queue.
* @return the action class
*/
public Class<? extends MCRJobAction> getAction() {
return action;
}
}
| 11,511 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobActionConverter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobActionConverter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import org.mycore.common.MCRClassTools;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import jakarta.persistence.PersistenceException;
/**
* @author René Adler (eagle)
*/
@Converter
public class MCRJobActionConverter implements AttributeConverter<Class<? extends MCRJobAction>, String> {
@Override
public String convertToDatabaseColumn(Class<? extends MCRJobAction> actionClass) {
return actionClass.getName();
}
@Override
public Class<? extends MCRJobAction> convertToEntityAttribute(String actionClassString) {
try {
return MCRClassTools.forName(actionClassString);
} catch (ClassNotFoundException e) {
throw new PersistenceException("MCRJobAction class \"" + actionClassString + "\" not found!", e);
}
}
}
| 1,603 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobAction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobAction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.concurrent.ExecutionException;
/**
* <code>MCRJobAction</code> must be extended to do some work for given {@link MCRJob}.
*
* @author René Adler
*
*/
public abstract class MCRJobAction {
/**
* The job holding the parameters for the action.
*/
protected final MCRJob job;
/**
* The constructor of the job action with specific {@link MCRJob}.
* @param job the job holding the parameters for the action
*/
public MCRJobAction(MCRJob job) {
this.job = job;
}
/**
* Returns if this action is activated.
*
* @return <code>true</code> if activated, <code>false</code> if isn't
*/
public abstract boolean isActivated();
/**
* Returns the name of the action.
*
* @return the name
*/
public abstract String name();
/**
* Does the work for given {@link MCRJob}.
* @throws ExecutionException if an error occurs during execution
*/
public abstract void execute() throws ExecutionException;
/**
* When errors occurs during executing it can be necessary to rollback
* performed actions
*/
public abstract void rollback();
}
| 1,964 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobStatus.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobStatus.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
/**
* Possible status of a job.
* @author René Adler
*/
public enum MCRJobStatus {
/**
* job added to queue
*/
NEW,
/**
* job currently on processing
*/
PROCESSING,
/**
* job processing is finished successfully
*/
FINISHED,
/**
* job processing failed and reached maximum tries
*/
MAX_TRIES,
/**
* job processing failed, but can be resetted
*/
ERROR
}
| 1,213 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDefaultJobStatusListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRDefaultJobStatusListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The default implementation for {@link MCRJobStatusListener}
*
* @author shermann
* */
public class MCRDefaultJobStatusListener implements MCRJobStatusListener {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public void onProcessing(MCRJob job) {
LOGGER.debug("Processing {}", job.getAction().getName());
}
@Override
public void onSuccess(MCRJob job) {
LOGGER.debug("Finished {}", job.getAction().getName());
}
@Override
public void onError(MCRJob job, Exception e) {
LOGGER.debug(() -> "Error " + job.getAction().getName(), e);
}
}
| 1,487 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueInitializer.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueInitializer.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.events.MCRStartupHandler;
import org.mycore.util.concurrent.MCRTransactionableRunnable;
import jakarta.servlet.ServletContext;
/**
* Initializes the job queue on startup.
* @author Sebastian Hofmann
*/
public class MCRJobQueueInitializer implements MCRStartupHandler.AutoExecutable {
private static final Logger LOGGER = LogManager.getLogger();
@Override
public String getName() {
return getClass().getName();
}
@Override
public int getPriority() {
return 0;
}
@Override
public void startUp(ServletContext servletContext) {
if (MCRConfiguration2.getBoolean("MCR.Persistence.Database.Enable").orElse(true)
&& MCREntityManagerProvider.getEntityManagerFactory() != null) {
new MCRTransactionableRunnable(() -> {
MCRJobQueueManager manager = MCRJobQueueManager.getInstance();
manager.getJobDAO().getActions().stream().peek(q -> LOGGER.info("Initialize job queue {}", q))
.forEach(manager::getJobQueue);
}).run();
}
}
}
| 2,070 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobStatusListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobStatusListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
/**
* Interface one must implement to get notified about when an {@link MCRJob} has started, finished or failed.
*
* Add property
* "<code>MCR.QueuedJob.<MCRJobAction.getClass().getSimpleName()>.Listeners</code>"
* to your mycore.properties and provide an appropriate class implementing the interface.
*
* @author shermann
* */
public interface MCRJobStatusListener {
/**
* Will be called when the job has failed.
* @param job the job that failed
* @param e the exception that caused the failure
*/
void onError(MCRJob job, Exception e);
/**
* Will be called when the job has finished successfully.
* @param job the job that finished
*/
void onSuccess(MCRJob job);
/**
* Will be called when the job has started processing.
* @param job the job that started processing
*/
void onProcessing(MCRJob job);
}
| 1,661 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobConfig.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobConfig.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
/**
* Holds the configuration for the {@link MCRJobQueue} and related classes.
* @author Sebastian Hofmann
*/
public interface MCRJobConfig {
/**
* The time in seconds after which a job with the given action is reset to {@link MCRJobStatus#NEW} if it is in
* status {@link MCRJobStatus#ERROR} for this time.
* @param action the action
* @return the time as duration
*/
Optional<Duration> timeTillReset(Class<? extends MCRJobAction> action);
/**
* The count of tries that are allowed for the given action. After this count is reached, the job will be marked as
* {@link MCRJobStatus#MAX_TRIES} and will not be executed again.
* @param action the action
* @return the optional count
*/
Optional<Integer> maxTryCount(Class<? extends MCRJobAction> action);
/**
* The count of job threads that can be executed in parallel for the given action.
* @param action the action
* @return the optional count
*/
Optional<Integer> maxJobThreadCount(Class<? extends MCRJobAction> action);
/**
* A boolean value indicating if the given action is activated. Activated = false means that the job queue will not
* return jobs for this action or accept new jobs for this action.
* @param action the action
* @return the optional boolean value
*/
Optional<Boolean> activated(Class<? extends MCRJobAction> action);
/**
* The count of job threads that can be executed in parallel for all actions.
* @return the count
*/
Integer maxJobThreadCount();
/**
* The time in seconds after which a job is reset to {@link MCRJobStatus#NEW} if it is in status
* {@link MCRJobStatus#ERROR} for this time.
* @return the time as duration
*/
Duration timeTillReset();
/**
* The count of tries that are allowed for all actions. After this count is reached, the job will be marked as
* {@link MCRJobStatus#MAX_TRIES} and will not be executed again.
* @return the count
*/
Integer maxTryCount();
/**
* A boolean value indicating if the job queue is activated. Activated = false means that the job queue will not
* return jobs or accept new jobs.
* @return the boolean value
*/
Boolean activated();
/**
* Returns the list of {@link MCRJobStatusListener} for the given action.
* @param action the action
* @return the list of listeners
*/
List<MCRJobStatusListener> jobStatusListeners(Class<? extends MCRJobAction> action);
}
| 3,402 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobRunnable.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobRunnable.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.MCRTransactionHelper;
import org.mycore.common.processing.MCRAbstractProcessable;
import org.mycore.common.processing.MCRProcessableStatus;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.PersistenceException;
/**
* This class execute the specified action for {@link MCRJob} and performs {@link MCRJobAction#rollback()}
* if an error occurs.
*
* @author René Adler
*
*/
public class MCRJobRunnable extends MCRAbstractProcessable implements Runnable {
private static final Logger LOGGER = LogManager.getLogger(MCRJobRunnable.class);
/**
* The job to execute.
*/
protected final MCRJob job;
private final MCRJobConfig config;
private final List<MCRJobStatusListener> listeners;
private final MCRJobAction actionInstance;
/**
* Creates a new instance of {@link MCRJobRunnable}.
* @param job the job to execute
* @param config the job config to read the listeners from and retrieve the max retries
* @param additionalListeners additional listeners to add to the list of listeners
* @param actionInstance the action instance to execute
*/
public MCRJobRunnable(MCRJob job,
MCRJobConfig config,
List<MCRJobStatusListener> additionalListeners,
MCRJobAction actionInstance) {
this.job = job;
this.config = config;
this.actionInstance = actionInstance;
this.listeners = Stream.of(additionalListeners,
config.jobStatusListeners(job.getAction()))
.flatMap(List::stream).toList();
setName(this.job.getId() + " - " + this.job.getAction().getSimpleName());
setStatus(MCRProcessableStatus.created);
job.getParameters().forEach((k, v) -> this.getProperties().put(k, v));
}
public void run() {
//prepare environment
MCRSessionMgr.unlock();
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
mcrSession.setUserInformation(MCRSystemUserInformation.getSystemUserInstance());
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
Exception executionException = null;
listeners.forEach(l -> l.onProcessing(job));
//prepare job
transaction.begin();
MCRJob localJob;
setStatus(MCRProcessableStatus.processing);
job.setStart(new Date());
localJob = em.merge(job);
try {
transaction.commit();
} catch (PersistenceException e) {
executionException = e;
LOGGER.error("Could not start job {}", job.getId(), e);
transaction.rollback();
}
if (executionException == null) {
//execute job
MCRTransactionHelper.beginTransaction();
localJob = em.merge(localJob);
try {
actionInstance.execute();
MCRTransactionHelper.commitTransaction();
} catch (Exception ex) {
executionException = ex;
MCRTransactionHelper.rollbackTransaction();
try {
actionInstance.rollback();
} catch (RuntimeException e) {
executionException.addSuppressed(e);
LOGGER.error("Could not rollback job {}", job.getId(), e);
}
}
//handle result
transaction.begin();
localJob = em.merge(localJob);
localJob.setFinished(new Date());
if (executionException == null) {
handleSuccess(localJob);
} else {
handleException(localJob, executionException);
}
try {
transaction.commit();
} catch (PersistenceException e) {
LOGGER.error("Could not save result to job {}", job.getId(), e);
transaction.rollback();
if (executionException == null) {
executionException = e;
} else {
executionException.addSuppressed(e);
}
}
}
//inform listeners
final Exception finalException = executionException;
listeners.forEach(l -> {
if (finalException == null) {
l.onSuccess(job);
} else {
l.onError(job, finalException);
}
});
} finally {
//clean up
MCRSessionMgr.releaseCurrentSession();
mcrSession.close();
}
}
private void handleSuccess(MCRJob localJob) {
localJob.setStatus(MCRJobStatus.FINISHED);
setStatus(MCRProcessableStatus.successful);
}
private void handleException(MCRJob localJob, Exception executionException) {
try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);) {
executionException.printStackTrace(pw);
String exception = sw.toString();
if (exception.length() > MCRJob.EXCEPTION_MAX_LENGTH) {
exception = exception.substring(0, MCRJob.EXCEPTION_MAX_LENGTH);
}
//TODO: check if changes to entities are reflected in database at next transaction or lost
localJob.setException(exception);
} catch (IOException e) {
LOGGER.error("Could not set exception for job {}", job.getId(), e);
}
Integer tries = localJob.getTries();
if (tries == null) {
tries = 0; // tries can be null, otherwise old database entries will fail or can not be migrated
}
localJob.setTries(++tries);
if (tries >= config.maxTryCount(job.getAction()).orElseGet(config::maxTryCount)) {
localJob.setStatus(MCRJobStatus.MAX_TRIES);
} else {
localJob.setStatus(MCRJobStatus.ERROR);
}
setError(executionException);
}
}
| 7,513 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobDAOJPAImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobDAOJPAImpl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.NonUniqueResultException;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.MapJoin;
import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
/**
* JPA implementation of the {@link MCRJobDAO} interface.
* @author Sebastian Hofmann
*/
public class MCRJobDAOJPAImpl implements MCRJobDAO {
private static Optional<Predicate> getActionPredicate(Class<? extends MCRJobAction> action,
CriteriaBuilder cb, Root<MCRJob> jobRoot,
Predicate existingPredicate) {
if (action != null) {
if (existingPredicate == null) {
return Optional.of(cb.equal(jobRoot.get(MCRJob_.action), action));
} else {
return Optional.of(cb.and(existingPredicate, cb.equal(jobRoot.get(MCRJob_.action), action)));
}
}
return Optional.ofNullable(existingPredicate);
}
private static Optional<Predicate> getStatusPredicate(List<MCRJobStatus> statuses,
CriteriaBuilder cb,
Root<MCRJob> jobRoot) {
if (statuses != null) {
List<Predicate> statusPredicates = statuses.stream().map(status -> {
Path<MCRJobStatus> statusPath = jobRoot.get(MCRJob_.status);
return cb.equal(statusPath, status);
}).toList();
if (statusPredicates.size() > 0) {
return Optional.of(cb.or(statusPredicates.toArray(new Predicate[0])));
}
}
return Optional.empty();
}
private static CriteriaQuery<MCRJob> buildQuery(
CriteriaBuilder cb,
Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> statuses,
BiConsumer<CriteriaQuery<MCRJob>, Root<MCRJob>> actionApplier) {
CriteriaQuery<MCRJob> q = cb.createQuery(MCRJob.class);
Root<MCRJob> jobRoot = q.from(MCRJob.class);
actionApplier.accept(q, jobRoot);
q.orderBy(cb.asc(jobRoot.get(MCRJob_.ADDED)));
applyParamJoin(cb, params, jobRoot);
Optional<Predicate> predicate;
predicate = getStatusPredicate(statuses, cb, jobRoot);
predicate = getActionPredicate(action, cb, jobRoot, predicate.orElse(null));
predicate.ifPresent(q::where);
return q;
}
private static CriteriaQuery<Long> buildCountQuery(
CriteriaBuilder cb,
Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> statuses) {
CriteriaQuery<Long> q = cb.createQuery(Long.class);
Root<MCRJob> jobRoot = q.from(MCRJob.class);
q.select(cb.count(jobRoot));
applyParamJoin(cb, params, jobRoot);
Optional<Predicate> predicate;
predicate = getStatusPredicate(statuses, cb, jobRoot);
predicate = getActionPredicate(action, cb, jobRoot, predicate.orElse(null));
predicate.ifPresent(q::where);
return q;
}
private static void applyParamJoin(CriteriaBuilder cb, Map<String, String> params, Root<MCRJob> jobRoot) {
if (params == null || params.isEmpty()) {
return;
}
params.keySet().forEach(key -> {
MapJoin<MCRJob, String, String> parameterJoin = jobRoot.join(MCRJob_.parameters, JoinType.INNER);
Path<String> keyPath = parameterJoin.key();
Path<String> valuePath = parameterJoin.value();
parameterJoin.on(cb.equal(keyPath, key), cb.equal(valuePath, params.get(key)));
});
}
@Override
public List<MCRJob> getJobs(Class<? extends MCRJobAction> action, Map<String, String> params,
List<MCRJobStatus> status, Integer maxResults, Integer offset) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRJob> q = buildQuery(cb, action, params, status, CriteriaQuery::select);
TypedQuery<MCRJob> tq = em.createQuery(q);
if (maxResults != null) {
tq.setMaxResults(maxResults);
}
if (offset != null) {
tq.setFirstResult(offset);
}
return tq.getResultList();
}
@Override
public int getJobCount(Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> status) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = buildCountQuery(cb, action, params, status);
return em.createQuery(q).getSingleResult().intValue();
}
@Override
public int removeJobs(Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> status) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
List<MCRJob> jobs = getJobs(action, params, status, null, null);
int jobCount = jobs.size();
jobs.forEach(em::remove);
return jobCount;
}
@Override
public MCRJob getJob(Class<? extends MCRJobAction> action, Map<String, String> params, List<MCRJobStatus> status) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRJob> q = buildQuery(cb, action, params, status, CriteriaQuery::select);
TypedQuery<MCRJob> tq = em.createQuery(q);
try {
return tq.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (NonUniqueResultException e) {
throw new IllegalArgumentException("More than one job found for action " + action + " and params " + params,
e);
}
}
@Override
public List<MCRJob> getNextJobs(Class<? extends MCRJobAction> action, Integer amount) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MCRJob> oq = buildQuery(cb, action, Collections.emptyMap(), Stream.of(MCRJobStatus.NEW).toList(),
(iq, root) -> {
iq.select(root);
iq.distinct(true);
});
TypedQuery<MCRJob> query = em.createQuery(oq);
if (amount != null) {
query.setMaxResults(amount);
}
return query
.getResultList()
.stream()
.peek(em::detach)
.toList();
}
@Override
public int getRemainingJobCount(Class<? extends MCRJobAction> action) {
return getJobCount(action, Collections.emptyMap(), Stream.of(MCRJobStatus.NEW).toList());
}
@Override
public boolean updateJob(MCRJob job) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.merge(job);
return true;
}
@Override
public boolean addJob(MCRJob job) {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
em.persist(job);
return true;
}
@Override
public List<? extends Class<? extends MCRJobAction>> getActions() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<Object> query = em.createNamedQuery("mcrjob.classes", Object.class);
List<Object> resultList = query.getResultList();
return resultList.stream().map(clazz -> (Class<? extends MCRJobAction>) clazz).toList();
}
}
| 8,822 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJob.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJob.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.Convert;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.MapKeyColumn;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
/**
* Container class handled by hibernate to store and retrieve job information.
*
* @author René Adler
*/
@Entity
@NamedQueries({
@NamedQuery(name = "mcrjob.classes",
query = "select DISTINCT(o.action) from MCRJob o") })
@Table(name = "MCRJob")
public class MCRJob implements Cloneable {
private Long id;
private Class<? extends MCRJobAction> action;
private MCRJobStatus status;
private Date added;
private Date start;
private Date finished;
private Integer tries;
private String exception;
private Map<String, String> parameters;
/**
* The maximum length of the exception message, which is stored in the database.
*/
public static final int EXCEPTION_MAX_LENGTH = 9999;
/**
* Creates an empty job.
*/
protected MCRJob() {
}
/**
* Creates an empty job for the given action class.
* @param actionClass the action class
*/
public MCRJob(Class<? extends MCRJobAction> actionClass) {
action = actionClass;
}
/**
* Returns the job Id.
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
/**
* Set the job Id.
*
* @param id - the job id
*/
protected void setId(Long id) {
this.id = id;
}
/**
* Returns the action class ({@link MCRJobAction}).
*/
@Column(name = "action", nullable = false)
@Convert(converter = MCRJobActionConverter.class)
public Class<? extends MCRJobAction> getAction() {
return action;
}
/**
* Set the action class ({@link MCRJobAction}).
*
* @param actionClass - the action class to set
*/
public void setAction(Class<? extends MCRJobAction> actionClass) {
this.action = actionClass;
}
/**
* Returns the current state ({@link MCRJobStatus}) of the job.
*/
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
public MCRJobStatus getStatus() {
return status;
}
/**
* Set the state ({@link MCRJobStatus}) of the job.
*
* @param status - the job status
*/
public void setStatus(MCRJobStatus status) {
this.status = status;
}
/**
* Returns the adding date of job.
*/
@Column(name = "added")
public Date getAdded() {
return added;
}
/**
* Set the adding date.
* @param added the date when the job was added to the queue
*/
public void setAdded(Date added) {
this.added = added;
}
/**
* Returns the starting date of execution.
*/
@Column(name = "start")
public Date getStart() {
return start;
}
/**
* Set the job starting date.
*
* @param start - the starting date
*/
public void setStart(Date start) {
this.start = start;
}
/**
* Returns the finishing date of execution.
*/
@Column(name = "finished")
public Date getFinished() {
return finished;
}
/**
* Set the finishing date of execution.
*
* @param finished - the finishing date
*/
public void setFinished(Date finished) {
this.finished = finished;
}
/**
* Returns the number of retries.
*/
@Column(name = "tries")
public Integer getTries() {
return tries;
}
/**
* Set the number of retries.
* @param retries the number of retries
*/
public void setTries(Integer retries) {
this.tries = retries;
}
/**
* Returns the exception message. Which was thrown during last execution.
* @return the exception message or null if no exception was thrown
*/
@Column(name = "exception", length = EXCEPTION_MAX_LENGTH)
public String getException() {
return exception;
}
/**
* Set the exception message. Which was thrown during last execution.
* @param exception the exception message
*/
public void setException(String exception) {
this.exception = exception;
}
/**
* Returns all set parameters of the job.
*/
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "MCRJobParameter", joinColumns = @JoinColumn(name = "jobID"))
@MapKeyColumn(name = "paramKey", length = 128)
@Column(name = "paramValue")
public Map<String, String> getParameters() {
return parameters;
}
/**
* Set all job parameters.
*
* @param parameters - the job parameters
*/
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
/**
* Returns a single parameter by its name.
*
* @param key - the parameter name.
* @return the value of the parameter.
*/
@Transient
public String getParameter(String key) {
if (parameters == null) {
return null;
}
return parameters.get(key);
}
/**
* Set a single parameter.
*
* @param key - the parameter name
* @param value - the parameter value
*/
public void setParameter(String key, String value) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put(key, value);
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public MCRJob clone() {
MCRJob clone = new MCRJob();
clone.setAction(getAction());
clone.setAdded(getAdded());
clone.setFinished(getFinished());
clone.setId(getId());
clone.setStart(getStart());
clone.setStatus(getStatus());
clone.setTries(getTries());
clone.setException(getException());
Map<String, String> map = new HashMap<>(getParameters());
clone.setParameters(map);
return clone;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new MessageFormat("MCRJob [id:{0}, action:{1}, status:{2}, added:{3}, parameters:{4}]", Locale.ROOT)
.format(
new Object[] { getId(), getAction().getName(), getStatus(), getAdded(), getParameters() });
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MCRJob mcrJob = (MCRJob) o;
return Objects.equals(getId(), mcrJob.getId()) && getAction().equals(mcrJob.getAction())
&& getStatus() == mcrJob.getStatus()
&& Objects.equals(getAdded(), mcrJob.getAdded()) && Objects.equals(getStart(), mcrJob.getStart())
&& Objects.equals(getFinished(), mcrJob.getFinished()) && Objects.equals(getTries(), mcrJob.getTries())
&& Objects.equals(getException(), mcrJob.getException())
&& Objects.equals(getParameters(), mcrJob.getParameters());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getAction(), getStatus(), getAdded(), getStart(), getFinished(), getTries(),
getException(), getParameters());
}
}
| 8,879 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueCommands.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueCommands.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.frontend.cli.annotation.MCRCommand;
import org.mycore.frontend.cli.annotation.MCRCommandGroup;
import jakarta.persistence.EntityManager;
/**
* Provides commands to manage the job queue.
* @author Sebastian Hofmann
*/
@MCRCommandGroup(name = "Job Queue Commands")
public class MCRJobQueueCommands {
private static final Logger LOGGER = LogManager.getLogger();
static MCRJobDAOJPAImpl dao = new MCRJobDAOJPAImpl();
/**
* Lists all jobs with status MAX_TRIES.
*/
@MCRCommand(
syntax = "list max try jobs",
help = "List all jobs with status MAX_TRIES",
order = 10)
public static void listMaxTryJobs() {
List<MCRJob> jobs = dao.getJobs(null, null, List.of(MCRJobStatus.MAX_TRIES), null, null);
jobs.forEach(job -> {
LOGGER.info("{}: {} {} {} {} {}", job.getId(), job.getAction(), job.getStatus(), job.getTries(),
job.getAdded(), job.getStart());
job.getParameters().forEach((key, value) -> {
LOGGER.info("{}: {}={}", job.getId(), key, value);
});
LOGGER.info("Failed with Exception {}", job.getException());
});
}
/**
* Resets all jobs with status MAX_TRIES to status NEW.
*/
@MCRCommand(
syntax = "reset max try jobs",
help = "Reset all jobs with status MAX_TRIES to status NEW",
order = 20)
public static void resetMaxTryJobs() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
int count = em
.createQuery(
"UPDATE MCRJob SET status = :status, tries = 0, exception = null WHERE status = :maxTriesStatus")
.setParameter("status", MCRJobStatus.NEW)
.setParameter("maxTriesStatus", MCRJobStatus.MAX_TRIES)
.executeUpdate();
LOGGER.info("Reset {} jobs", count);
}
/**
* Resets all jobs with status MAX_TRIES and action {0} to status NEW.
* @param action the action to reset
*/
@MCRCommand(
syntax = "reset max try jobs with action {0}",
help = "Reset all jobs with status MAX_TRIES and action {0} to status NEW",
order = 30)
public static void resetMaxTryJobsWithAction(String action) {
if (action == null || action.isEmpty()) {
LOGGER.error("Action is required!");
return;
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
int count = em.createQuery(
"UPDATE MCRJob SET status = :status, tries = 0, exception = null WHERE status = :maxTriesStatus " +
"AND action = :action")
.setParameter("status", MCRJobStatus.NEW)
.setParameter("maxTriesStatus", MCRJobStatus.MAX_TRIES)
.setParameter("action", action)
.executeUpdate();
LOGGER.info("Reset {} jobs", count);
}
/**
* Resets all jobs with status MAX_TRIES and id {0} to status NEW.
* @param id the id to reset
*/
@MCRCommand(
syntax = "reset max try jobs with id {0}",
help = "reset all jobs with status MAX_TRIES and id {0} to status NEW",
order = 40)
public static void resetMaxTryJobsWithId(String id) {
if (id == null || id.isEmpty()) {
LOGGER.error("Id is required!");
return;
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
int count = em.createQuery(
"UPDATE MCRJob SET status = :status, tries = 0, exception = null WHERE status = :maxTriesStatus " +
"AND id = :id")
.setParameter("status", MCRJobStatus.NEW)
.setParameter("maxTriesStatus", MCRJobStatus.MAX_TRIES)
.setParameter("id", id)
.executeUpdate();
LOGGER.info("Reset {} jobs", count);
}
}
| 4,825 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueuePermission.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueuePermission.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import static org.mycore.access.MCRAccessManager.PERMISSION_READ;
import static org.mycore.access.MCRAccessManager.PERMISSION_WRITE;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessManager;
import org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
/**
* The MCRJobQueuePermission class checks if the user is allowed to access the job queue rest api.
* @author René Adler (eagle)
*/
public class MCRJobQueuePermission implements MCRResourceAccessChecker {
/**
* the string representation of the permission to list all job queues
*/
public static final String PERMISSION_LIST = "list-jobqueues";
private static final Logger LOGGER = LogManager.getLogger(MCRJobQueuePermission.class);
/* (non-Javadoc)
* @see org.mycore.frontend.jersey.filter.access.MCRResourceAccessChecker#isPermitted(com.sun.jersey.spi.container.ContainerRequest)
*/
@Override
public boolean isPermitted(ContainerRequestContext request) {
String queueName = request.getUriInfo().getPathSegments().size() > 1
? request.getUriInfo().getPathSegments().get(1).getPath()
: null;
try {
if (queueName == null || queueName.isEmpty()) {
return MCRAccessManager.checkPermission(PERMISSION_LIST);
}
String permissionType = request.getMethod().matches("(?i)(POST|PUT|DELETE)") ? PERMISSION_WRITE
: PERMISSION_READ;
if (!MCRAccessManager.checkPermission(queueName, permissionType)) {
LOGGER.info("Permission \"{}\" denied for queue \"{}\".", permissionType, queueName);
return false;
}
return true;
} catch (Exception exc) {
throw new WebApplicationException(exc,
Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("Unable to check permission for request " + request.getUriInfo().getRequestUri()
+ " containing entity value " + queueName)
.build());
}
}
}
| 3,092 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueEventListener.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobQueueEventListener.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.EventListener;
/**
* Listener interface for events related to the {@link MCRJobQueue}.
* @author Sebastian Hofmann
*/
public interface MCRJobQueueEventListener extends EventListener {
/**
* Called when a job is added to the queue. If a job is rejected, this method is not called.
* @param job the job that was added
*/
void onJobAdded(MCRJob job);
}
| 1,163 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobThreadStarter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobThreadStarter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.backend.jpa.MCREntityManagerProvider;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import org.mycore.common.MCRSystemUserInformation;
import org.mycore.common.events.MCRShutdownHandler;
import org.mycore.common.events.MCRShutdownHandler.Closeable;
import org.mycore.common.processing.MCRProcessableCollection;
import org.mycore.common.processing.MCRProcessableDefaultCollection;
import org.mycore.common.processing.MCRProcessableRegistry;
import org.mycore.util.concurrent.processing.MCRProcessableExecutor;
import org.mycore.util.concurrent.processing.MCRProcessableFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.PersistenceException;
import jakarta.persistence.RollbackException;
/**
* Pulls {@link MCRJob}s from Database and starts {@link MCRJobRunnable}s.
*
* @author René Adler
* @author Sebastian Hofmann
*/
public class MCRJobThreadStarter implements Runnable, Closeable {
private static final long ONE_MINUTE_IN_MS = TimeUnit.MINUTES.toMillis(1);
private static final Logger LOGGER = LogManager.getLogger(MCRJobThreadStarter.class);
private final MCRJobQueue jobQueue;
private final ThreadPoolExecutor jobExecutor;
private final Class<? extends MCRJobAction> action;
private volatile boolean running = true;
private final MCRProcessableDefaultCollection processableCollection;
private final LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
private final ReentrantLock runLock;
private final ListenerNotifier listener;
private MCRProcessableExecutor processableExecutor;
private final AtomicInteger activeThreads = new AtomicInteger();
private final int maxJobThreadCount;
private final MCRJobConfig config;
MCRJobThreadStarter(Class<? extends MCRJobAction> action, MCRJobConfig config, MCRJobQueue jobQueue) {
this.config = config;
MCRShutdownHandler.getInstance().addCloseable(this);
this.action = action;
runLock = new ReentrantLock();
this.jobQueue = jobQueue;
// listen for new jobs
listener = new ListenerNotifier();
jobQueue.addListener(listener);
maxJobThreadCount = config.maxJobThreadCount(action).orElseGet(config::maxJobThreadCount);
jobExecutor = new ActiveCountingThreadPoolExecutor(maxJobThreadCount, workQueue,
new JobThreadFactory(getSimpleActionName()), activeThreads);
MCRProcessableRegistry registry = MCRProcessableRegistry.getSingleInstance();
processableCollection = new MCRProcessableDefaultCollection(getName());
registry.register(processableCollection);
}
/**
* Starts local threads ({@link MCRJobRunnable}) and gives {@link MCRJob} instances to them.
* Use property <code>"MCR.QueuedJob.JobThreads"</code> to specify how many concurrent threads should be running.
* <code>"MCR.QueuedJob.activated"</code> can be used activate or deactivate general {@link MCRJob} running.
*/
@Override
public void run() {
boolean activated = config.activated(action).orElseGet(config::activated);
LOGGER.info("JobQueue {} is {}", action.getName(), activated ? "activated" : "deactivated");
if (!activated) {
return;
}
Thread.currentThread().setName(getName());
//get this MCRSession a speaking name
MCRSessionMgr.unlock();
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
mcrSession.setUserInformation(MCRSystemUserInformation.getSystemUserInstance());
running = true;
processableExecutor = MCRProcessableFactory.newPool(jobExecutor, processableCollection);
processableCollection.setProperty("running", running);
LOGGER.info("JobManager for {} with {} thread(s) is started", action.getName(), getMaxJobThreadCount());
while (running) {
try {
while (hasFreeJobThreads()) {
if (!scheduleNextJob()) {
break;
}
}
synchronized (listener) {
listener.wait(ONE_MINUTE_IN_MS);
}
} catch (PersistenceException e) {
LOGGER.warn("We have an database error, sleep and run later.", e);
try {
Thread.sleep(ONE_MINUTE_IN_MS);
} catch (InterruptedException ie) {
LOGGER.error("Waiting for database was interrupted.", ie);
}
} catch (Exception e) {
LOGGER.error("Keep running while catching exceptions.", e);
}
}
processableCollection.setProperty("running", running);
LOGGER.info("{} thread finished", getName());
MCRSessionMgr.releaseCurrentSession();
}
/**
* @return true if a job was scheduled and there could be more jobs
*/
private boolean scheduleNextJob() {
runLock.lock();
try {
if (!running) {
return false;
}
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
EntityTransaction transaction = em.getTransaction();
MCRJob job = null;
MCRJobAction action = null;
try {
transaction.begin();
job = jobQueue.poll();
processableCollection.setProperty("queue size", jobQueue.size());
if (job != null) {
action = toMCRJobAction(job);
if (action != null && !action.isActivated()) {
job.setStatus(MCRJobStatus.NEW);
job.setStart(null);
}
}
transaction.commit();
} catch (RollbackException e) {
LOGGER.error("Error while getting next job.", e);
try {
transaction.rollback();
} catch (RuntimeException re) {
LOGGER.warn("Could not rollback transaction.", re);
}
} finally {
em.close();
}
if (job != null && action != null && action.isActivated() && !jobExecutor.isShutdown()) {
LOGGER.info("Creating:{}", job);
processableExecutor.submit(new MCRJobRunnable(job, config, List.of(listener), action));
return true;
}
} finally {
runLock.unlock();
}
return false;
}
private boolean hasFreeJobThreads() {
return activeThreads.get() < getMaxJobThreadCount();
}
private int getMaxJobThreadCount() {
return maxJobThreadCount;
}
/**
* stops transmitting {@link MCRJob} to {@link MCRJobRunnable} and prepares shutdown.
*/
public void prepareClose() {
LOGGER.info("Closing manager thread");
//signal manager thread to stop now
running = false;
//Wake up, Neo!
synchronized (listener) {
LOGGER.debug("Wake up queue");
listener.notifyAll();
}
runLock.lock();
try {
if (processableExecutor != null) {
LOGGER.debug("Shutdown executor jobs.");
processableExecutor.getExecutor().shutdown();
try {
LOGGER.debug("Await termination of executor jobs.");
processableExecutor.getExecutor().awaitTermination(60, TimeUnit.SECONDS);
LOGGER.debug("All jobs finished.");
} catch (InterruptedException e) {
LOGGER.debug("Could not wait 60 seconds...", e);
}
}
} finally {
runLock.unlock();
}
}
/**
* Shuts down this thread and every local threads spawned by {@link #run()}.
*/
@Override
public void close() {
if (processableExecutor != null && !processableExecutor.getExecutor().isShutdown()) {
LOGGER.info("We are in a hurry, closing service right now");
this.jobExecutor.shutdownNow();
try {
this.jobExecutor.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.debug("Could not wait 60 seconds...", e);
}
}
}
@Override
public int getPriority() {
return MCRShutdownHandler.Closeable.DEFAULT_PRIORITY - 1;
}
private String getSimpleActionName() {
return action.getSimpleName();
}
/**
* Returns the name of this job manager.
*
* @return the name
*/
public String getName() {
return getSimpleActionName() + " Manager";
}
/**
* Returns the processable collection assigned to this job manager.
*
* @return the processable collection
*/
public MCRProcessableCollection getProcessableCollection() {
return processableCollection;
}
private static MCRJobAction toMCRJobAction(MCRJob job) {
try {
Constructor<? extends MCRJobAction> actionConstructor = job.getAction().getConstructor(MCRJob.class);
return actionConstructor.newInstance(job);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
/**
* Notifies waiting threads when a job is set to error, success or processing. When a job is added to the queue, the
* Thread is notified after the session is committed.
*/
private static final class ListenerNotifier implements MCRJobQueueEventListener, MCRJobStatusListener {
@Override
public void onJobAdded(MCRJob job) {
// a job was added to the queue, but the transaction is not yet committed, so we have to wait for it.
MCRSessionMgr.getCurrentSession().onCommit(() -> {
synchronized (this) {
this.notifyAll();
}
});
}
@Override
public void onError(MCRJob job, Exception e) {
synchronized (this) {
this.notifyAll();
}
}
@Override
public void onSuccess(MCRJob job) {
synchronized (this) {
this.notifyAll();
}
}
@Override
public void onProcessing(MCRJob job) {
synchronized (this) {
this.notifyAll();
}
}
}
/**
* A {@link ThreadFactory} that creates threads with a given name prefix.
*/
private static final class JobThreadFactory implements ThreadFactory {
private final String actionName;
private AtomicInteger tNum = new AtomicInteger(0);
JobThreadFactory(String simpleActionName) {
this.actionName = simpleActionName;
}
@Override
public Thread newThread(Runnable r) {
return new Thread(r, actionName + "Worker#" + tNum.incrementAndGet());
}
}
/**
* A {@link ThreadPoolExecutor} that counts the number of active threads. (without iterating over the thread pool)
*/
private static final class ActiveCountingThreadPoolExecutor extends ThreadPoolExecutor {
private final AtomicInteger activeThreads;
ActiveCountingThreadPoolExecutor(int maxJobThreadCount,
LinkedBlockingQueue<Runnable> workQueue,
JobThreadFactory jobThreadFactory,
AtomicInteger activeThreads) {
super(maxJobThreadCount, maxJobThreadCount, 1, TimeUnit.DAYS, workQueue, jobThreadFactory);
this.activeThreads = activeThreads;
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
activeThreads.decrementAndGet();
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
activeThreads.incrementAndGet();
}
}
}
| 13,408 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobDAO.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/MCRJobDAO.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob;
import java.util.List;
import java.util.Map;
/**
* DAO interface for the {@link MCRJob} class.
* @author Sebastian Hofmann
*/
public interface MCRJobDAO {
/**
* Retrieves jobs from some storage, matching the given parameters.
* The jobs are ordered by their creation date, ascending.
* @param action the action to filter for or null
* @param params the parameters to filter for or null
* @param status the status to filter for or null
* @param maxResults the maximum number of results to return or null
* @param offset the offset to start from or null
* @return the requested jobs
*/
List<MCRJob> getJobs(Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> status,
Integer maxResults,
Integer offset);
/**
* Retrieves the count of jobs from some storage, matching the given parameters.
* @param action the action to filter for or null
* @param params the parameters to filter for or null
* @param status the status to filter for or null
* @return the requested jobs
*/
int getJobCount(Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> status);
/**
* Removes jobs from some storage, matching the given parameters.
* @param action the action to filter for or null
* @param params the parameters to filter for or null
* @param status the status to filter for or null
* @return the number of removed jobs
*/
int removeJobs(Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> status);
/**
* Returns a job matching the given parameter.
* @param action the action to filter for or null
* @param params the parameters to filter for or null
* @param status the status to filter for or null
* @return the requested job or null
* @throws IllegalArgumentException if more than one job matches the given parameters
*/
MCRJob getJob(Class<? extends MCRJobAction> action,
Map<String, String> params,
List<MCRJobStatus> status);
/**
* Returns the next jobs to execute.
* @param action the action to execute or null
* @param amount the amount of jobs to return
* @return the next jobs to execute
*/
List<MCRJob> getNextJobs(Class<? extends MCRJobAction> action, Integer amount);
/**
* Returns the number of jobs which need to be executed.
* @param action the action to execute
* @return the number of jobs which need to be executed
*/
int getRemainingJobCount(Class<? extends MCRJobAction> action);
/**
* Updates the given job in the storage.
* @param job the job to update
* @return true if the job was updated, false otherwise
*/
boolean updateJob(MCRJob job);
/**
* Adds the given job to the storage.
* @param job the job to add
* @return true if the job was added, false otherwise
*/
boolean addJob(MCRJob job);
/**
* Returns the actions which are present in the storage.
* @return the actions which are present in the storage
*/
List<? extends Class<? extends MCRJobAction>> getActions();
}
| 4,054 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRConfiguration2JobConfig.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/config2/MCRConfiguration2JobConfig.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob.config2;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRClassTools;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.services.queuedjob.MCRJobAction;
import org.mycore.services.queuedjob.MCRJobConfig;
import org.mycore.services.queuedjob.MCRJobStatusListener;
/**
* Reads the configuration for the job queue from mycore.properties using the {@link MCRConfiguration2} class.
* @author Sebastian Hofmann
*/
public class MCRConfiguration2JobConfig implements MCRJobConfig {
private static final String CONFIG_MAX_TRY = "MaxTry";
private static final String CONFIG_TIME_TILL_RESET = "TimeTillReset";
private static final String CONFIG_JOB_THREADS = "JobThreads";
private static final String CONFIG_ACTIVATED = "activated";
private static final String CONFIG_PREFIX = "MCR.QueuedJob.";
private static final Logger LOGGER = LogManager.getLogger();
private static String getActionConfigPrefix(Class<? extends MCRJobAction> action) {
return CONFIG_PREFIX + action.getSimpleName() + ".";
}
@Override
public Optional<Duration> timeTillReset(Class<? extends MCRJobAction> action) {
return MCRConfiguration2.getInt(getActionConfigPrefix(action) + CONFIG_TIME_TILL_RESET)
.map(Duration::ofMinutes);
}
@Override
public Optional<Integer> maxTryCount(Class<? extends MCRJobAction> action) {
return MCRConfiguration2.getInt(getActionConfigPrefix(action) + CONFIG_MAX_TRY);
}
@Override
public Optional<Integer> maxJobThreadCount(Class<? extends MCRJobAction> action) {
return MCRConfiguration2.getInt(getActionConfigPrefix(action) + CONFIG_JOB_THREADS);
}
@Override
public Optional<Boolean> activated(Class<? extends MCRJobAction> action) {
return MCRConfiguration2.getBoolean(getActionConfigPrefix(action) + CONFIG_ACTIVATED);
}
@Override
public Integer maxJobThreadCount() {
String property = CONFIG_PREFIX + CONFIG_JOB_THREADS;
return MCRConfiguration2.getInt(property)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(property));
}
@Override
public Duration timeTillReset() {
String property = CONFIG_PREFIX + CONFIG_TIME_TILL_RESET;
return MCRConfiguration2.getInt(property)
.map(Duration::ofMinutes)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(property));
}
@Override
public Integer maxTryCount() {
String property = CONFIG_PREFIX + CONFIG_MAX_TRY;
return MCRConfiguration2.getInt(property)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(property));
}
@Override
public Boolean activated() {
String property = MCRConfiguration2JobConfig.CONFIG_PREFIX + MCRConfiguration2JobConfig.CONFIG_ACTIVATED;
return MCRConfiguration2.getBoolean(property)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(property));
}
@Override
public List<MCRJobStatusListener> jobStatusListeners(Class<? extends MCRJobAction> action) {
return MCRConfiguration2.getString("MCR.QueuedJob." + action.getSimpleName() + ".Listeners")
.stream()
.flatMap(MCRConfiguration2::splitValue)
.map(className -> {
try {
return (MCRJobStatusListener) MCRClassTools.forName(className)
.getDeclaredConstructor().newInstance();
} catch (Exception e) {
LOGGER.error("Could not load class {}", className, e);
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
}
| 4,742 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRStaticContentGeneratorJobAction.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/staticcontent/MCRStaticContentGeneratorJobAction.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob.staticcontent;
import java.util.concurrent.ExecutionException;
import org.mycore.datamodel.metadata.MCRMetadataManager;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.datamodel.metadata.MCRObjectID;
import org.mycore.services.queuedjob.MCRJob;
import org.mycore.services.queuedjob.MCRJobAction;
import org.mycore.services.staticcontent.MCRObjectStaticContentGenerator;
public class MCRStaticContentGeneratorJobAction extends MCRJobAction {
public static final String CONFIG_ID_PARAMETER = "configID";
public static final String OBJECT_ID_PARAMETER = "objectID";
/**
* The constructor of the job action with specific {@link MCRJob}.
*
* @param job the job holding the parameters for the action
*/
public MCRStaticContentGeneratorJobAction(MCRJob job) {
super(job);
}
@Override
public boolean isActivated() {
return true;
}
@Override
public String name() {
return "Static Content - " + getConfigID();
}
private String getConfigID() {
return this.job.getParameters().get(CONFIG_ID_PARAMETER);
}
private MCRObjectID getObjectID() {
String objectIDStr = this.job.getParameters().get(OBJECT_ID_PARAMETER);
return MCRObjectID.getInstance(objectIDStr);
}
@Override
public void execute() throws ExecutionException {
try {
MCRObject object = MCRMetadataManager.retrieveMCRObject(getObjectID());
MCRObjectStaticContentGenerator generator = new MCRObjectStaticContentGenerator(getConfigID());
generator.generate(object);
} catch (Exception e) {
throw new ExecutionException(e);
}
}
@Override
public void rollback() {
// do nothing
}
}
| 2,551 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobStaticContentGenerator.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/staticcontent/MCRJobStaticContentGenerator.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob.staticcontent;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.datamodel.metadata.MCRObject;
import org.mycore.services.queuedjob.MCRJob;
import org.mycore.services.queuedjob.MCRJobQueueManager;
import org.mycore.services.queuedjob.MCRJobStatus;
import org.mycore.services.staticcontent.MCRObjectStaticContentGenerator;
public class MCRJobStaticContentGenerator extends MCRObjectStaticContentGenerator {
private static final Logger LOGGER = LogManager.getLogger();
public MCRJobStaticContentGenerator(String configID) {
super(configID);
}
@Override
public void generate(MCRObject object) throws IOException {
HashMap<String, String> parameters = new HashMap<>();
parameters.put(MCRStaticContentGeneratorJobAction.CONFIG_ID_PARAMETER, configID);
parameters.put(MCRStaticContentGeneratorJobAction.OBJECT_ID_PARAMETER, object.getId().toString());
MCRJobQueueManager jobQueueManager = MCRJobQueueManager.getInstance();
List<MCRJob> jobs = jobQueueManager
.getJobDAO()
.getJobs(MCRStaticContentGeneratorJobAction.class, parameters,
List.of(MCRJobStatus.NEW, MCRJobStatus.ERROR, MCRJobStatus.PROCESSING), null, null);
if (jobs.isEmpty()) {
MCRJob job = new MCRJob(MCRStaticContentGeneratorJobAction.class);
job.setParameters(parameters);
jobQueueManager.getJobQueue(MCRStaticContentGeneratorJobAction.class).add(job);
} else {
LOGGER.info("There is already a generator job for the object {} and the config {}. Skipping generation.",
object.getId(), configID);
}
}
}
| 2,565 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueFeature.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/MCRJobQueueFeature.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob.rest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.feature.MCRJerseyDefaultFeature;
import org.mycore.restapi.MCREnableTransactionFilter;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.FeatureContext;
import jakarta.ws.rs.ext.Provider;
/**
* Jersey configuration for JobQueue Endpoint
*
* @author Sebastian Hofmann
*
* @see MCRJerseyDefaultFeature
*
*/
@Provider
public class MCRJobQueueFeature extends MCRJerseyDefaultFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
Class<?> resourceClass = resourceInfo.getResourceClass();
Method resourceMethod = resourceInfo.getResourceMethod();
if (requiresTransaction(resourceClass, resourceMethod)) {
context.register(MCREnableTransactionFilter.class);
}
super.configure(resourceInfo, context);
}
/**
* Checks if the class/method is annotated by {@link MCRRequireTransaction}.
*
* @param resourceClass the class to check
* @param resourceMethod the method to check
* @return true if one ore both is annotated and requires transaction
*/
protected boolean requiresTransaction(Class<?> resourceClass, Method resourceMethod) {
return resourceClass.getAnnotation(MCRRequireTransaction.class) != null
|| resourceMethod.getAnnotation(MCRRequireTransaction.class) != null;
}
@Override
protected List<String> getPackages() {
return MCRConfiguration2.getString("MCR.JobQueue.API.Resource.Packages").map(MCRConfiguration2::splitValue)
.orElse(Stream.empty())
.collect(Collectors.toList());
}
@Override
protected void registerSessionHookFilter(FeatureContext context) {
// don't register transaction filter, is already implemented by MCRSessionFilter
}
@Override
protected void registerTransactionFilter(FeatureContext context) {
// don't register transaction filter, is already implemented by MCRSessionFilter
}
@Override
protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) {
super.registerAccessFilter(context, resourceClass, resourceMethod);
}
}
| 3,244 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueApp.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/MCRJobQueueApp.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob.rest;
import org.apache.logging.log4j.LogManager;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.jersey.access.MCRRequestScopeACLFilter;
import org.mycore.restapi.MCRCORSResponseFilter;
import org.mycore.restapi.MCRIgnoreClientAbortInterceptor;
import org.mycore.restapi.MCRSessionFilter;
import org.mycore.restapi.MCRTransactionFilter;
import jakarta.ws.rs.ApplicationPath;
/**
* @author Sebastian Hofmann
*/
@ApplicationPath("/api/jobqueue")
public class MCRJobQueueApp extends ResourceConfig {
/**
* Creates the Jersey application for the MyCoRe JobQueue-API
*/
public MCRJobQueueApp() {
super();
initAppName();
property(ServerProperties.APPLICATION_NAME, getApplicationName());
packages(getRestPackages());
property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, true);
register(MCRSessionFilter.class);
register(MCRTransactionFilter.class);
register(MCRJobQueueFeature.class);
register(MCRCORSResponseFilter.class);
register(MCRRequestScopeACLFilter.class);
register(MCRIgnoreClientAbortInterceptor.class);
}
/**
* Sets the application name for the Jersey application
*/
protected void initAppName() {
setApplicationName("MyCoRe JobQueue-API " + getVersion());
LogManager.getLogger().info("Initiialize {}", getApplicationName());
}
/**
* @return the version of the JobQueue-API
*/
protected String getVersion() {
return "1.0";
}
/**
* @return the packages to scan for REST resources
*/
protected String[] getRestPackages() {
return MCRConfiguration2.getOrThrow("MCR.JobQueue.API.Resource.Packages", MCRConfiguration2::splitValue)
.toArray(String[]::new);
}
}
| 2,700 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRJobQueueResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-jobqueue/src/main/java/org/mycore/services/queuedjob/rest/resources/MCRJobQueueResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.services.queuedjob.rest.resources;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import org.mycore.common.MCRClassTools;
import org.mycore.frontend.jersey.filter.access.MCRRestrictedAccess;
import org.mycore.restapi.annotations.MCRAccessControlExposeHeaders;
import org.mycore.restapi.annotations.MCRRequireTransaction;
import org.mycore.services.queuedjob.MCRJob;
import org.mycore.services.queuedjob.MCRJobAction;
import org.mycore.services.queuedjob.MCRJobDAO;
import org.mycore.services.queuedjob.MCRJobQueue;
import org.mycore.services.queuedjob.MCRJobQueueManager;
import org.mycore.services.queuedjob.MCRJobQueuePermission;
import org.mycore.services.queuedjob.MCRJobStatus;
import jakarta.inject.Singleton;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlValue;
/**
* REST resource for job queues. Requires {@link MCRJobQueuePermission} to access.
* @author René Adler (eagle)
*/
@Path("/")
@Singleton
public class MCRJobQueueResource {
private static final String X_TOTAL_COUNT_HEADER = "X-Total-Count";
/**
* REST resource to receive all job queues.
* @return a list of all job queues as JSON or XML
*/
@GET()
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@MCRRestrictedAccess(MCRJobQueuePermission.class)
@MCRRequireTransaction()
public Response listJSON() {
Queues queuesEntity = new Queues();
queuesEntity.addAll(
MCRJobQueueManager.getInstance().getJobQueues().stream()
.map(MCRJobQueue::getAction)
.map(Class::getName)
.map(Queue::new)
.collect(Collectors.toList()));
return Response
.ok()
.status(Response.Status.OK)
.entity(queuesEntity)
.build();
}
/**
* REST resource for a specific job queue.
* @param name the name of the job queue
* @param status a filter for status of the jobs to return (optional)
* @param parameters a filter for parameters of the jobs to return (optional)
* @param offset the start index of the jobs to return (optional)
* @param limit the maximum number of jobs to return (optional)
* @return response with the jobs as JSON or XML
*/
@GET()
@Path("{name:.+}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@MCRRestrictedAccess(MCRJobQueuePermission.class)
@MCRAccessControlExposeHeaders(X_TOTAL_COUNT_HEADER)
@MCRRequireTransaction()
public Response queueJSON(@PathParam("name") String name,
@QueryParam("status") List<MCRJobStatus> status,
@QueryParam("parameter") List<String> parameters,
@QueryParam("offset") Integer offset,
@QueryParam("limit") Integer limit) {
HashMap<String, String> parameterMap = new HashMap<>();
parameters.forEach(p -> {
String[] split = p.split(":");
if (split.length == 2) {
parameterMap.put(URLDecoder.decode(split[0], StandardCharsets.UTF_8),
URLDecoder.decode(split[1], StandardCharsets.UTF_8));
}
});
Queue queue = new Queue(name);
MCRJobDAO dao = MCRJobQueueManager.getInstance()
.getJobDAO();
Class<? extends MCRJobAction> action = null;
try {
action = MCRClassTools.forName(name);
} catch (ClassNotFoundException e) {
throw new NotFoundException(e);
}
int count = dao.getJobCount(action, parameterMap, status);
queue.jobs = dao
.getJobs(action, parameterMap, status, limit, offset)
.stream()
.map(Job::new)
.collect(Collectors.toList());
return Response
.ok()
.status(Response.Status.OK)
.header(X_TOTAL_COUNT_HEADER, count)
.entity(queue)
.build();
}
@XmlRootElement(name = "queues")
static class Queues {
@XmlElement(name = "queue")
List<Queue> queues;
void add(Queue queue) {
if (queues == null) {
queues = new ArrayList<>();
}
queues.add(queue);
}
void addAll(List<Queue> queues) {
if (this.queues == null) {
this.queues = new ArrayList<>();
}
this.queues.addAll(queues);
}
}
@XmlRootElement(name = "queue")
static class Queue {
@XmlAttribute
String name;
@XmlElement(name = "job")
List<Job> jobs;
Queue() {
}
Queue(String name) {
this.name = name;
}
}
@XmlRootElement(name = "job")
static class Job {
@XmlAttribute
long id;
@XmlAttribute
String status;
@XmlElement(name = "date")
List<TypedDate> dates;
@XmlElement(name = "parameter")
List<Parameter> parameters;
@XmlElement(name = "exception")
String exception;
@XmlElement(name = "tries")
Integer tries;
Job() {
}
Job(MCRJob job) {
this.id = job.getId();
// convert like jersey does, so url parameter looks same
this.status = job.getStatus().toString().toUpperCase(Locale.ROOT);
List<TypedDate> dates = new ArrayList<>();
if (job.getAdded() != null) {
dates.add(new TypedDate("added", job.getAdded()));
}
if (job.getStart() != null) {
dates.add(new TypedDate("start", job.getStart()));
}
if (job.getFinished() != null) {
dates.add(new TypedDate("finished", job.getFinished()));
}
if (job.getException() != null) {
this.exception = job.getException();
}
if (job.getTries() != null) {
this.tries = job.getTries();
}
this.parameters = job.getParameters().entrySet().stream().map(e -> new Parameter(e.getKey(), e.getValue()))
.collect(Collectors.toList());
if (!dates.isEmpty()) {
this.dates = dates;
}
}
}
@XmlRootElement(name = "date")
static class TypedDate {
@XmlAttribute
String type;
@XmlValue
Date date;
TypedDate() {
}
TypedDate(String type, Date date) {
this.type = type;
this.date = date;
}
}
@XmlRootElement(name = "parameter")
static class Parameter {
@XmlAttribute
String name;
@XmlValue
String value;
Parameter() {
}
Parameter(String name, String value) {
this.name = name;
this.value = value;
}
}
}
| 8,194 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageUtilTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/test/java/org/mycore/iiif/image/MCRIIIFImageUtilTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image;
import org.junit.Assert;
import org.junit.Test;
public class MCRIIIFImageUtilTest {
@Test
public void encodeImageIdentifier() {
//examples from https://iiif.io/api/image/2.1/#uri-encoding-and-decoding
Assert.assertEquals("id1", MCRIIIFImageUtil.encodeImageIdentifier("id1"));
Assert.assertEquals("bb157hs6068", MCRIIIFImageUtil.encodeImageIdentifier("bb157hs6068"));
Assert.assertEquals("ark:%2F12025%2F654xz321", MCRIIIFImageUtil.encodeImageIdentifier("ark:/12025/654xz321"));
Assert.assertEquals("urn:foo:a123,456", MCRIIIFImageUtil.encodeImageIdentifier("urn:foo:a123,456"));
Assert.assertEquals("http:%2F%2Fexample.com%2F%3F54%23a",
MCRIIIFImageUtil.encodeImageIdentifier("http://example.com/?54#a"));
Assert.assertEquals("Mot%C3%B6rhead", MCRIIIFImageUtil.encodeImageIdentifier("Motörhead"));
Assert.assertEquals("mycore_derivate_00000001:%2Ftest.tiff",
MCRIIIFImageUtil.encodeImageIdentifier("mycore_derivate_00000001:/test.tiff"));
}
}
| 1,806 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFScaleParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/test/java/org/mycore/iiif/image/parser/MCRIIIFScaleParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.parser;
import java.util.Hashtable;
import java.util.Map;
import org.junit.Assert;
import org.mycore.iiif.image.model.MCRIIIFImageTargetSize;
public class MCRIIIFScaleParserTest {
public static final int IMAGE_WIDTH = 500;
public static final int IMAGE_HEIGHT = 400;
@org.junit.Test
public void testParseTargetScale() {
Map<String, MCRIIIFImageTargetSize> testValues = new Hashtable<>();
testValues.put("!1100,800", new MCRIIIFImageTargetSize(1000, 800));
testValues.put("!1000,900", new MCRIIIFImageTargetSize(1000, 800));
testValues.put("200,200", new MCRIIIFImageTargetSize(200, 200));
testValues.put(",200", new MCRIIIFImageTargetSize(250, 200));
testValues.put(",800", new MCRIIIFImageTargetSize(1000, 800));
testValues.put("1000,", new MCRIIIFImageTargetSize(1000, 800));
testValues.put("pct:200", new MCRIIIFImageTargetSize(1000, 800));
testValues.put("pct:50", new MCRIIIFImageTargetSize(250, 200));
testValues.forEach((scale, expectedResult) -> Assert.assertEquals(expectedResult,
new MCRIIIFScaleParser(scale, IMAGE_WIDTH, IMAGE_HEIGHT).parseTargetScale()));
}
}
| 1,950 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFRotationParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/test/java/org/mycore/iiif/image/parser/MCRIIIFRotationParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.parser;
import java.util.Hashtable;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.mycore.iiif.image.model.MCRIIIFImageTargetRotation;
public class MCRIIIFRotationParserTest {
@Test
public void testParse() {
Map<String, MCRIIIFImageTargetRotation> testValues = new Hashtable<>();
testValues.put("0", new MCRIIIFImageTargetRotation(false, 0));
testValues.put("!0", new MCRIIIFImageTargetRotation(true, 0));
testValues.put("90", new MCRIIIFImageTargetRotation(false, 90));
testValues.put("!90", new MCRIIIFImageTargetRotation(true, 90));
testValues.put("180", new MCRIIIFImageTargetRotation(false, 180));
testValues.put("!180", new MCRIIIFImageTargetRotation(true, 180));
testValues.put("270", new MCRIIIFImageTargetRotation(false, 270));
testValues.put("!270", new MCRIIIFImageTargetRotation(true, 270));
testValues.forEach((rotationString, expectedResult) -> Assert
.assertEquals(new MCRIIIFRotationParser(rotationString).parse(), expectedResult));
}
}
| 1,854 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFRegionParserTest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/test/java/org/mycore/iiif/image/parser/MCRIIIFRegionParserTest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.parser;
import java.util.Hashtable;
import java.util.Map;
import org.junit.Assert;
import org.mycore.iiif.image.model.MCRIIIFImageSourceRegion;
public class MCRIIIFRegionParserTest {
public static final int IMAGE_WIDTH = 500;
public static final int IMAGE_HEIGHT = 400;
@org.junit.Test
public void testParseImageRegion() {
Map<String, MCRIIIFImageSourceRegion> validCoords = new Hashtable<>();
validCoords.put("0,0,100,100", new MCRIIIFImageSourceRegion(0, 0, 100, 100));
validCoords.put("100,100,200,200", new MCRIIIFImageSourceRegion(100, 100, 300, 300));
validCoords.put("0,0,500,400", new MCRIIIFImageSourceRegion(0, 0, 499, 399));
validCoords.put("0,0,1,400", new MCRIIIFImageSourceRegion(0, 0, 1, 399));
validCoords.put("pct:10,10,90,90", new MCRIIIFImageSourceRegion(50, 40, 499, 399));
validCoords.put("pct:0,0,100,100", new MCRIIIFImageSourceRegion(0, 0, 499, 399));
for (Map.Entry<String, MCRIIIFImageSourceRegion> entry : validCoords.entrySet()) {
MCRIIIFImageSourceRegion result = new MCRIIIFRegionParser(entry.getKey(), IMAGE_WIDTH, IMAGE_HEIGHT)
.parseImageRegion();
Assert.assertEquals(entry.getValue(), result);
}
}
}
| 2,032 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFApp.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/common/MCRIIIFApp.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.common;
import org.apache.logging.log4j.LogManager;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.restapi.MCRJerseyRestApp;
import jakarta.ws.rs.ApplicationPath;
/**
* @author Sebastian Hofmann
*/
@ApplicationPath("/api/iiif")
public class MCRIIIFApp extends MCRJerseyRestApp {
public MCRIIIFApp() {
super();
register(MCRIIIFBaseURLFilter.class);
}
@Override
protected void initAppName() {
setApplicationName("MyCoRe IIIF-API " + getVersion());
LogManager.getLogger().info("Initiialize {}", getApplicationName());
}
@Override
protected String getVersion() {
return "2.0";
}
@Override
protected String[] getRestPackages() {
return MCRConfiguration2.getOrThrow("MCR.IIIF.API.Resource.Packages", MCRConfiguration2::splitValue)
.toArray(String[]::new);
}
}
| 1,640 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFBaseURLFilter.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/common/MCRIIIFBaseURLFilter.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.common;
import static org.mycore.frontend.MCRFrontendUtil.BASE_URL_ATTRIBUTE;
import org.mycore.common.MCRSession;
import org.mycore.common.MCRSessionMgr;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.core.Context;
public class MCRIIIFBaseURLFilter implements ContainerRequestFilter {
@Context
private HttpServletRequest httpRequest;
@Override
public void filter(ContainerRequestContext requestContext) {
// set BASE_URL_ATTRIBUTE to MCRSession
if (httpRequest.getAttribute(BASE_URL_ATTRIBUTE) != null) {
final MCRSession currentSession = MCRSessionMgr.getCurrentSession();
if (currentSession != null) {
currentSession.put(BASE_URL_ATTRIBUTE, httpRequest.getAttribute(BASE_URL_ATTRIBUTE));
}
}
}
}
| 1,685 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFMediaTypeHelper.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/common/MCRIIIFMediaTypeHelper.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.common;
import jakarta.ws.rs.core.MediaType;
/**
* @author Thomas Scheffler (yagee)
*/
public class MCRIIIFMediaTypeHelper {
public static final String APPLICATION_LD_JSON = "application/ld+json";
public static final MediaType APPLICATION_LD_JSON_TYPE = new MediaType("application", "ld+json");
}
| 1,062 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/MCRIIIFImageUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image;
import static org.mycore.iiif.image.resources.MCRIIIFImageResource.IIIF_IMAGE_API_2_LEVEL2;
import java.net.URI;
import java.net.URISyntaxException;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.iiif.image.impl.MCRIIIFImageImpl;
import org.mycore.iiif.image.model.MCRIIIFImageProfile;
public class MCRIIIFImageUtil {
public static void completeProfile(MCRIIIFImageImpl impl, MCRIIIFImageProfile profile) {
profile.setId(getProfileLink(impl));
}
/**
* Encodes image identidier so it can be used in an URI
* @see <a href="https://iiif.io/api/image/2.1/#uri-encoding-and-decoding">URI encoding of image identifier</a>
*/
public static String encodeImageIdentifier(String imageIdentifier) {
try {
//add '/' before path for URI to handle it as a path, removed in return statement
final URI uri = new URI(null, null, '/' + imageIdentifier, null, null);
return uri.toASCIIString().substring(1).replace("/", "%2F");
} catch (URISyntaxException e) {
//99.99% this won't happen
throw new MCRException("Could not encode image identifier: " + imageIdentifier, e);
}
}
public static String buildCanonicalURL(MCRIIIFImageImpl impl, String identifier) {
return "<" + getIIIFURL(impl) + encodeImageIdentifier(identifier)
+ "/full/full/0/color.jpg>;rel=\"canonical\"";
}
public static String buildProfileURL() {
return "<" + IIIF_IMAGE_API_2_LEVEL2 + ">;rel=\"profile\"";
}
public static String getIIIFURL(MCRIIIFImageImpl impl) {
StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());
sb.append("api/iiif/image/v2/");
String defaultImpl = MCRConfiguration2.getString("MCR.IIIFImage.Default").orElse("");
if (!defaultImpl.equals(impl.getImplName())) {
sb.append(impl.getImplName()).append('/');
}
return sb.toString();
}
public static String getProfileLink(MCRIIIFImageImpl impl) {
return getIIIFURL(impl) + "profile.json";
}
public static MCRIIIFImageImpl getImpl(String impl) {
return MCRIIIFImageImpl.getInstance(impl);
}
}
| 3,069 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFRegionParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/parser/MCRIIIFRegionParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.parser;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
import org.mycore.iiif.image.model.MCRIIIFImageSourceRegion;
public class MCRIIIFRegionParser {
public static final String PERCENT_PREFIX = "pct:";
private final int w;
private final int h;
private final String sourceRegion;
private boolean completeValid = true;
public MCRIIIFRegionParser(String sourceRegion, int w, int h) {
this.sourceRegion = sourceRegion.toLowerCase(Locale.ENGLISH);
this.w = w;
this.h = h;
if (w < 0 || h < 0) {
throw new IllegalArgumentException("w or h are zero!");
}
if (isFull()) {
return;
}
if (isSquare()) {
return;
}
if (parseNumbers().size() != 4) {
completeValid = false;
throw new IllegalArgumentException("sourceRegion must have 4 numbers!");
}
}
public MCRIIIFImageSourceRegion parseImageRegion() throws NumberFormatException {
if (isPercent()) {
return parsePercentImageRegion();
} else if (isFull()) {
return new MCRIIIFImageSourceRegion(0, 0, w - 1, h - 1);
} else if (isSquare()) {
final int shorterDimension = Math.min(w, h);
final int x1 = (int) Math.floor(w / 2.0 - shorterDimension / 2.0);
final int y1 = (int) Math.floor(h / 2.0 - shorterDimension / 2.0);
return new MCRIIIFImageSourceRegion(x1, y1, x1 + shorterDimension, y1 + shorterDimension);
}
return parseAbsoluteImageRegion();
}
private MCRIIIFImageSourceRegion parsePercentImageRegion() {
List<Double> doubles = parseNumbers();
double x = Math.floor(doubles.get(0) * (w / 100.0));
double y = Math.floor(doubles.get(1) * (h / 100.0));
double x2 = Math.ceil(x + (doubles.get(2) * (w / 100.0)));
double y2 = Math.ceil(y + (doubles.get(3) * (w / 100.0)));
return parseImageRegion((int) x, (int) y, (int) x2, (int) y2);
}
private MCRIIIFImageSourceRegion parseAbsoluteImageRegion() {
List<Double> doubles = parseNumbers();
double x1 = doubles.get(0);
double y1 = doubles.get(1);
double x2 = doubles.get(2) + x1;
double y2 = doubles.get(3) + y1;
return parseImageRegion((int) Math.round(x1), (int) Math.round(y1), (int) Math.round(x2), (int) Math.round(y2));
}
private MCRIIIFImageSourceRegion parseImageRegion(int x1, int y1, int x2, int y2) {
if (x1 >= w || y1 >= h) {
completeValid = false;
throw new IllegalArgumentException(
"x[" + x1 + "] or y[" + y1 + "] cant be bigger then or equal image size[" + w + "x" + h + "]!");
}
if (!(y1 < y2 && x1 < x2 && x1 >= 0 && y1 >= 0 && x2 <= w && y2 <= h)) {
completeValid = false;
}
// negative values become 0
int nx1 = Math.max(0, x1);
int ny1 = Math.max(0, y1);
// end values bigger then image become as big as image
int nx2 = Math.min(w - 1, x2);
int ny2 = Math.min(h - 1, y2);
return new MCRIIIFImageSourceRegion(nx1, ny1, nx2, ny2);
}
private boolean isPercent() {
return this.sourceRegion.startsWith(PERCENT_PREFIX);
}
private boolean isFull() {
return Objects.equals(sourceRegion, "full");
}
private boolean isSquare() {
return Objects.equals(sourceRegion, "square");
}
private List<Double> parseNumbers() {
return Arrays
.stream((isPercent() ? this.sourceRegion.substring(PERCENT_PREFIX.length()) : this.sourceRegion).split(","))
.map(Double::parseDouble)
.collect(Collectors.toList());
}
public boolean isCompleteValid() {
return completeValid;
}
}
| 4,701 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFScaleParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/parser/MCRIIIFScaleParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.parser;
import java.util.Objects;
import org.mycore.iiif.image.model.MCRIIIFImageTargetSize;
public class MCRIIIFScaleParser {
private String targetScale;
private int sourceRegionWidth;
private int sourceRegionHeight;
public MCRIIIFScaleParser(String targetScale, int w, int h) {
this.targetScale = targetScale;
this.sourceRegionWidth = w;
this.sourceRegionHeight = h;
}
private boolean isFull() {
return Objects.equals(targetScale, "full") || Objects.equals(targetScale, "max");
}
private boolean isPercent() {
return targetScale.startsWith("pct:");
}
private boolean isBestFit() {
return targetScale.startsWith("!");
}
public MCRIIIFImageTargetSize parseTargetScale() {
if (isFull()) {
return new MCRIIIFImageTargetSize(sourceRegionWidth, sourceRegionHeight);
}
if (isPercent()) {
return parsePercentValue();
}
StringBuilder wBuilder = new StringBuilder();
StringBuilder hBuilder = new StringBuilder();
getWidthAndHeightStrings(wBuilder, hBuilder);
String w = wBuilder.toString();
String h = hBuilder.toString();
try {
if (w.length() == 0) {
return scaleToHeight(Integer.parseInt(h));
} else if (h.length() == 0) {
return scaleToWidth(Integer.parseInt(w));
} else if (isBestFit()) {
return bestFit(Integer.parseInt(w), Integer.parseInt(h));
} else {
return scale(Integer.parseInt(w), Integer.parseInt(h));
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(h + " or " + w + " ist not a valid scale value!", e);
}
}
private MCRIIIFImageTargetSize scale(int w, int h) {
if (w <= 0) {
throw new IllegalArgumentException("width to scale must be positive! [" + w + "]");
}
if (h <= 0) {
throw new IllegalArgumentException("height to scale must be positive! [" + h + "]");
}
return new MCRIIIFImageTargetSize(w, h);
}
private MCRIIIFImageTargetSize bestFit(int w, int h) {
if (w <= 0) {
throw new IllegalArgumentException("width to scale must be positive! [" + w + "]");
}
if (h <= 0) {
throw new IllegalArgumentException("height to scale must be positive! [" + h + "]");
}
double ratio = Math.min(((double) w) / this.sourceRegionWidth, ((double) h) / this.sourceRegionHeight);
return new MCRIIIFImageTargetSize((int) Math.round(this.sourceRegionWidth * ratio),
(int) Math.round(this.sourceRegionHeight * ratio));
}
private MCRIIIFImageTargetSize scaleToWidth(Integer w) {
if (w <= 0) {
throw new IllegalArgumentException("width to scale must be positive! [" + w + "]");
}
double ratio = ((double) this.sourceRegionHeight) / this.sourceRegionWidth;
return new MCRIIIFImageTargetSize(w, (int) Math.ceil(ratio * w));
}
private MCRIIIFImageTargetSize scaleToHeight(Integer h) {
if (h <= 0) {
throw new IllegalArgumentException("height to scale must be positive! [" + h + "]");
}
double ratio = ((double) this.sourceRegionWidth) / this.sourceRegionHeight;
return new MCRIIIFImageTargetSize((int) Math.ceil(ratio * h), h);
}
private MCRIIIFImageTargetSize parsePercentValue() {
String rightValue = this.targetScale.substring("pct:".length());
double percentValue;
try {
percentValue = Double.parseDouble(rightValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(rightValue + " is not a valid scale!", e);
}
if (percentValue <= 0) {
throw new IllegalArgumentException("Scale has to be positive! [" + percentValue + "]");
}
return new MCRIIIFImageTargetSize((int) Math.ceil(percentValue / 100 * sourceRegionWidth),
(int) Math.ceil(percentValue / 100 * sourceRegionHeight));
}
private void getWidthAndHeightStrings(StringBuilder wBuilder, StringBuilder hBuilder) {
char[] chars = this.targetScale.toCharArray();
boolean writeW = true;
boolean first = true;
for (char currentChar : chars) {
switch (currentChar) {
case ',' -> {
first = false;
if (!writeW) {
throw new IllegalArgumentException("second , found in scale!");
}
writeW = false;
}
case '!' -> {
if (!first) {
throw new IllegalArgumentException("! should be located only in the first position of scale!");
}
first = false;
}
default -> {
first = false;
if (writeW) {
wBuilder.append(currentChar);
} else {
hBuilder.append(currentChar);
}
}
}
}
}
}
| 6,054 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFRotationParser.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/parser/MCRIIIFRotationParser.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.parser;
import org.mycore.iiif.image.model.MCRIIIFImageTargetRotation;
public class MCRIIIFRotationParser {
private final String rotation;
public MCRIIIFRotationParser(String rotation) {
this.rotation = rotation;
}
public MCRIIIFImageTargetRotation parse() {
boolean mirror = this.rotation.startsWith("!");
String rotationNumberString = mirror ? this.rotation.substring(1) : this.rotation;
double rotationNumber;
try {
rotationNumber = Double.parseDouble(rotationNumberString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(rotationNumberString + " cannot parsed to a rotation value!");
}
if (rotationNumber < 0 || rotationNumber > 360) {
throw new IllegalArgumentException(rotationNumber + " is not a valid rotation value!");
}
return new MCRIIIFImageTargetRotation(mirror, rotationNumber);
}
}
| 1,722 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/impl/MCRIIIFImageImpl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.impl;
import java.awt.image.BufferedImage;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.mycore.access.MCRAccessException;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.iiif.image.model.MCRIIIFImageInformation;
import org.mycore.iiif.image.model.MCRIIIFImageProfile;
import org.mycore.iiif.image.model.MCRIIIFImageQuality;
import org.mycore.iiif.image.model.MCRIIIFImageSourceRegion;
import org.mycore.iiif.image.model.MCRIIIFImageTargetRotation;
import org.mycore.iiif.image.model.MCRIIIFImageTargetSize;
public abstract class MCRIIIFImageImpl {
private static final String MCR_IIIF_IMAGE_CONFIG_PREFIX = "MCR.IIIFImage.";
private static final Map<String, MCRIIIFImageImpl> IMPLHOLDER = new HashMap<>();
private final String implName;
public MCRIIIFImageImpl(final String implName) {
this.implName = implName;
}
public static synchronized MCRIIIFImageImpl getInstance(String implNameParameter) {
String implName = (implNameParameter == null || implNameParameter.isBlank())
? MCRConfiguration2.getStringOrThrow("MCR.IIIFImage.Default")
: implNameParameter;
if (IMPLHOLDER.containsKey(implName)) {
return IMPLHOLDER.get(implName);
}
String classPropertyName = MCR_IIIF_IMAGE_CONFIG_PREFIX + implName;
Class<? extends MCRIIIFImageImpl> classObject = MCRConfiguration2.<MCRIIIFImageImpl>getClass(classPropertyName)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(classPropertyName));
try {
Constructor<? extends MCRIIIFImageImpl> constructor = classObject.getConstructor(String.class);
MCRIIIFImageImpl imageImpl = constructor.newInstance(implName);
IMPLHOLDER.put(implName, imageImpl);
return imageImpl;
} catch (NoSuchMethodException e) {
throw new MCRConfigurationException(
"Configurated class (" + classObject.getName() + ") needs a string constructor: " + classPropertyName);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new MCRException(e);
}
}
public String getImplName() {
return implName;
}
protected final Map<String, String> getProperties() {
return MCRConfiguration2.getSubPropertiesMap(getConfigPrefix());
}
protected String getConfigPrefix() {
return MCR_IIIF_IMAGE_CONFIG_PREFIX + implName + ".";
}
public abstract BufferedImage provide(String identifier,
MCRIIIFImageSourceRegion region,
MCRIIIFImageTargetSize targetSize,
MCRIIIFImageTargetRotation rotation,
MCRIIIFImageQuality imageQuality,
String format)
throws MCRIIIFImageNotFoundException, MCRIIIFImageProvidingException, MCRIIIFUnsupportedFormatException,
MCRAccessException;
public abstract MCRIIIFImageInformation getInformation(String identifier)
throws MCRIIIFImageNotFoundException, MCRIIIFImageProvidingException, MCRAccessException;
public abstract MCRIIIFImageProfile getProfile();
}
| 4,100 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFUnsupportedFormatException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/impl/MCRIIIFUnsupportedFormatException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.impl;
public class MCRIIIFUnsupportedFormatException extends Exception {
private static final long serialVersionUID = 1L;
public MCRIIIFUnsupportedFormatException(String unsupportedFormat) {
super("The format " + unsupportedFormat + " is not supported!");
}
}
| 1,040 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageNotFoundException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/impl/MCRIIIFImageNotFoundException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.impl;
public class MCRIIIFImageNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
private String identifier;
public MCRIIIFImageNotFoundException(String identifier) {
super("Invalid image-identifier " + identifier + "!");
this.identifier = identifier;
}
public String getIdentifier() {
return identifier;
}
}
| 1,155 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageProvidingException.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/impl/MCRIIIFImageProvidingException.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.impl;
public class MCRIIIFImageProvidingException extends Exception {
private static final long serialVersionUID = 1L;
public MCRIIIFImageProvidingException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public MCRIIIFImageProvidingException(Throwable cause) {
super(cause);
}
public MCRIIIFImageProvidingException(String message, Throwable cause) {
super(message, cause);
}
public MCRIIIFImageProvidingException(String message) {
super(message);
}
public MCRIIIFImageProvidingException() {
}
}
| 1,450 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/resources/MCRIIIFImageResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.resources;
import static org.mycore.iiif.image.MCRIIIFImageUtil.buildCanonicalURL;
import static org.mycore.iiif.image.MCRIIIFImageUtil.buildProfileURL;
import static org.mycore.iiif.image.MCRIIIFImageUtil.completeProfile;
import static org.mycore.iiif.image.MCRIIIFImageUtil.encodeImageIdentifier;
import static org.mycore.iiif.image.MCRIIIFImageUtil.getIIIFURL;
import static org.mycore.iiif.image.MCRIIIFImageUtil.getImpl;
import java.awt.image.BufferedImage;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.access.MCRAccessException;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.iiif.common.MCRIIIFMediaTypeHelper;
import org.mycore.iiif.image.impl.MCRIIIFImageImpl;
import org.mycore.iiif.image.impl.MCRIIIFImageNotFoundException;
import org.mycore.iiif.image.impl.MCRIIIFImageProvidingException;
import org.mycore.iiif.image.impl.MCRIIIFUnsupportedFormatException;
import org.mycore.iiif.image.model.MCRIIIFImageInformation;
import org.mycore.iiif.image.model.MCRIIIFImageProfile;
import org.mycore.iiif.image.model.MCRIIIFImageQuality;
import org.mycore.iiif.image.model.MCRIIIFImageSourceRegion;
import org.mycore.iiif.image.model.MCRIIIFImageTargetRotation;
import org.mycore.iiif.image.model.MCRIIIFImageTargetSize;
import org.mycore.iiif.image.parser.MCRIIIFRegionParser;
import org.mycore.iiif.image.parser.MCRIIIFRotationParser;
import org.mycore.iiif.image.parser.MCRIIIFScaleParser;
import org.mycore.iiif.model.MCRIIIFBase;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Request;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
@Path("/image/v2{noop: /?}{impl: ([a-zA-Z0-9]+)?}")
public class MCRIIIFImageResource {
public static final String IIIF_IMAGE_API_2_LEVEL2 = "http://iiif.io/api/image/2/level2.json";
public static final String IMPL_PARAM = "impl";
public static final String IDENTIFIER_PARAM = "identifier";
private static final Logger LOGGER = LogManager.getLogger();
@Context
Request request;
Optional<Response> getCachedResponse(long lastModified) {
return Optional.ofNullable(request)
.map(r -> r.evaluatePreconditions(new Date(lastModified)))
.map(Response.ResponseBuilder::build);
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/info.json")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getInfo(@PathParam(IMPL_PARAM) String implString, @PathParam(IDENTIFIER_PARAM) String identifier) {
try {
MCRIIIFImageImpl impl = getImpl(implString);
MCRIIIFImageInformation information = impl.getInformation(identifier);
Optional<Response> cachedResponse = getCachedResponse(information.lastModified);
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
MCRIIIFImageProfile profile = getProfile(impl);
information.profile.add(IIIF_IMAGE_API_2_LEVEL2);
information.profile.add(profile);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Link", buildCanonicalURL(impl, identifier))
.header("Profile", buildProfileURL())
.lastModified(new Date(information.lastModified))
.entity(gson.toJson(information))
.build();
} catch (MCRIIIFImageNotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (MCRAccessException e) {
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
} catch (MCRIIIFImageProvidingException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@GET
@Path("{" + IDENTIFIER_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getInfoRedirect(@PathParam(IMPL_PARAM) String impl,
@PathParam(IDENTIFIER_PARAM) String identifier) {
try {
String uriString = getIIIFURL(getImpl(impl)) + encodeImageIdentifier(identifier) + "/info.json";
return Response.temporaryRedirect(new URI(uriString)).build();
} catch (URISyntaxException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}
@GET
@Path("{" + IDENTIFIER_PARAM + "}/{region}/{size}/{rotation}/{quality}.{format}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getImage(@PathParam(IMPL_PARAM) String implStr, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam("region") String region,
@PathParam("size") String size,
@PathParam("rotation") String rotation,
@PathParam("quality") String quality,
@PathParam("format") String format) {
try {
MCRIIIFImageImpl impl = getImpl(implStr);
MCRIIIFImageInformation information = impl.getInformation(identifier);
Optional<Response> cachedResponse = getCachedResponse(information.lastModified);
if (cachedResponse.isPresent()) {
return cachedResponse.get();
}
MCRIIIFRegionParser rp = new MCRIIIFRegionParser(region, information.width, information.height);
MCRIIIFImageSourceRegion sourceRegion = rp.parseImageRegion();
MCRIIIFScaleParser sp = new MCRIIIFScaleParser(size, sourceRegion.x2() - sourceRegion.x1(),
sourceRegion.y2() - sourceRegion.y1());
MCRIIIFImageTargetSize targetSize = sp.parseTargetScale();
MCRIIIFRotationParser rotationParser = new MCRIIIFRotationParser(rotation);
MCRIIIFImageTargetRotation parsedRotation = rotationParser.parse();
MCRIIIFImageQuality imageQuality = MCRIIIFImageQuality.fromString(quality);
BufferedImage provide = impl
.provide(identifier, sourceRegion, targetSize, parsedRotation, imageQuality, format);
Response.Status status = rp.isCompleteValid() ? Response.Status.OK : Response.Status.BAD_REQUEST;
Response.ResponseBuilder responseBuilder = Response.status(status);
return responseBuilder
.header("Access-Control-Allow-Origin", "*")
.header("Link", buildCanonicalURL(impl, identifier))
.header("Profile", buildProfileURL())
.type("image/" + format)
.lastModified(new Date(information.lastModified))
.entity((StreamingOutput) outputStream -> ImageIO.write(provide, format, outputStream)).build();
} catch (MCRIIIFImageNotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (IllegalArgumentException | MCRIIIFUnsupportedFormatException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (MCRAccessException e) {
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
} catch (Exception e) {
LOGGER.error(() -> "Error while getting Image " + identifier + " from " + implStr + " with region: " +
region + ", size: " + size + ", rotation: " + rotation + ", quality: " + quality + ", format: " +
format, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@GET
@Path("profile.json")
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 7, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 7, unit = TimeUnit.DAYS))
public Response getDereferencedProfile(@PathParam(IMPL_PARAM) String implStr) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
MCRIIIFImageProfile profile = getProfile(getImpl(implStr));
profile.setContext(MCRIIIFBase.API_IMAGE_2);
return Response.ok().entity(gson.toJson(profile)).build();
}
public MCRIIIFImageProfile getProfile(MCRIIIFImageImpl impl) {
MCRIIIFImageProfile profile = impl.getProfile();
completeProfile(impl, profile);
return profile;
}
}
| 9,975 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageTargetRotation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageTargetRotation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
public record MCRIIIFImageTargetRotation(boolean mirrored, double degrees) {
}
| 844 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFFeatures.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFFeatures.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
public enum MCRIIIFFeatures {
baseUriRedirect("baseUriRedirect"),
canonicalLinkHeader("canonicalLinkHeader"),
cors("cors"),
jsonldMediaType(
"jsonldMediaType"),
mirroring("mirroring"),
profileLinkHeader("profileLinkHeader"),
regionByPct(
"regionByPct"),
regionByPx("regionByPx"),
rotationArbitrary("rotationArbitrary"),
rotationBy90s(
"rotationBy90s"),
sizeAboveFull("sizeAboveFull"),
sizeByWhListed("sizeByWhListed"),
sizeByForcedWh(
"sizeByForcedWh"),
sizeByH(
"sizeByH"),
sizeByPct("sizeByPct"),
sizeByW("sizeByW"),
sizeByWh("sizeByWh");
private final String featureName;
MCRIIIFFeatures(String featureName) {
this.featureName = featureName;
}
@Override
public String toString() {
return featureName;
}
}
| 1,624 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageInformation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageInformation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
import java.util.ArrayList;
import java.util.List;
import org.mycore.iiif.model.MCRIIIFBase;
public class MCRIIIFImageInformation extends MCRIIIFBase {
/**
* Required!
* Defines the protocol. Should be: <a href="http://iiif.io/api/image">http://iiif.io/api/image/2/context.json</a>
*/
public String protocol;
/**
* Required!
* width of image in pixels
*/
public int width;
/**
* Required!
* height of image in pixels
*/
public int height;
/**
* Required for caching.
*/
public transient long lastModified;
/**
* Required!
* A array of profiles, first entry is always a <i>compliance level URI</i> like
* <a href="http://iiif.io/api/image/2/level2.json">http://iiif.io/api/image/2/level2.json</a>.
*/
public List<Object> profile;
/**
* Optional!
*/
public List<MCRIIIFImageTileInformation> tiles;
public MCRIIIFImageInformation(String context, String id, String protocol, int width, int height,
long lastModified) {
super(id, null, context);
this.protocol = protocol;
this.width = width;
this.height = height;
this.tiles = new ArrayList<>();
this.profile = new ArrayList<>();
this.lastModified = lastModified;
}
}
| 2,092 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageQuality.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageQuality.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
import java.util.Locale;
public enum MCRIIIFImageQuality {
color, gray, bitonal;
public static MCRIIIFImageQuality fromString(String str) {
return switch (str.toLowerCase(Locale.ENGLISH)) {
case "color", "default", "native" -> //for backwards compatibility with IIIF Image API 1.0
color;
case "gray", "grey" -> //for backwards compatibility with IIIF Image API 1.0
gray;
case "bitonal" -> bitonal;
default -> throw new IllegalArgumentException(str + " is no valid ImageQuality!");
};
}
}
| 1,363 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageSourceRegion.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageSourceRegion.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
public record MCRIIIFImageSourceRegion(int x1, int y1, int x2, int y2) {
}
| 840 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageProfile.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageProfile.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
import java.util.HashSet;
import java.util.Set;
import org.mycore.iiif.model.MCRIIIFBase;
public class MCRIIIFImageProfile extends MCRIIIFBase {
public static final String IIIF_PROFILE_2_0 = "http://iiif.io/api/image/2/profiles/level2.json";
public static final String IIIF_IMAGE_PROFILE = "iiif:ImageProfile";
public Set<MCRIIIFFeatures> supports = new HashSet<>();
public Set<String> formats = new HashSet<>();
public Set<String> qualities = new HashSet<>();
public MCRIIIFImageProfile() {
super(IIIF_IMAGE_PROFILE, API_IMAGE_2);
supports.add(MCRIIIFFeatures.baseUriRedirect);
supports.add(MCRIIIFFeatures.canonicalLinkHeader);
supports.add(MCRIIIFFeatures.cors);
supports.add(MCRIIIFFeatures.jsonldMediaType);
supports.add(MCRIIIFFeatures.profileLinkHeader);
supports.add(MCRIIIFFeatures.profileLinkHeader);
}
}
| 1,673 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageTileInformation.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageTileInformation.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public record MCRIIIFImageTileInformation(int width, int height, List<Integer> scaleFactors) {
public static List<Integer> scaleFactorsAsPowersOfTwo(int n) {
return IntStream.range(0, n)
.map(i -> (int) Math.pow(2, i))
.boxed()
.collect(Collectors.toUnmodifiableList());
}
}
| 1,189 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFImageTargetSize.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/image/model/MCRIIIFImageTargetSize.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.image.model;
public record MCRIIIFImageTargetSize(int width, int height) {
}
| 829 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFPresentationManifestQuickAccess.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/MCRIIIFPresentationManifestQuickAccess.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.mycore.iiif.presentation.model.additional.MCRIIIFAnnotationBase;
import org.mycore.iiif.presentation.model.basic.MCRIIIFCanvas;
import org.mycore.iiif.presentation.model.basic.MCRIIIFManifest;
import org.mycore.iiif.presentation.model.basic.MCRIIIFRange;
import org.mycore.iiif.presentation.model.basic.MCRIIIFSequence;
public class MCRIIIFPresentationManifestQuickAccess {
private final MCRIIIFManifest manifest;
private final Map<String, MCRIIIFSequence> idSequenceMap = new ConcurrentHashMap<>();
private final Map<String, MCRIIIFCanvas> idCanvasMap = new ConcurrentHashMap<>();
private final Map<String, MCRIIIFAnnotationBase> idAnnotationMap = new ConcurrentHashMap<>();
private final Map<String, MCRIIIFRange> idRangeMap = new ConcurrentHashMap<>();
public MCRIIIFPresentationManifestQuickAccess(final MCRIIIFManifest manifest) {
this.manifest = manifest;
this.manifest.sequences.forEach(seq -> {
seq.canvases.forEach(canvas -> {
idCanvasMap.put(canvas.getId(), canvas);
canvas.images.forEach(annotation -> idAnnotationMap.put(annotation.getId(), annotation));
});
idSequenceMap.put(seq.getId(), seq);
});
this.manifest.structures.forEach(range -> idRangeMap.put(range.getId(), range));
}
public MCRIIIFSequence getSequence(String id) {
return idSequenceMap.get(id);
}
public MCRIIIFCanvas getCanvas(String id) {
return idCanvasMap.get(id);
}
public MCRIIIFAnnotationBase getAnnotationBase(String id) {
return idAnnotationMap.get(id);
}
public MCRIIIFRange getRange(String id) {
return idRangeMap.get(id);
}
public MCRIIIFManifest getManifest() {
return manifest;
}
}
| 2,646 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFPresentationUtil.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/MCRIIIFPresentationUtil.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.stream.Collectors;
import org.mycore.frontend.MCRFrontendUtil;
import org.mycore.iiif.model.MCRIIIFBase;
import org.mycore.iiif.presentation.model.additional.MCRIIIFAnnotation;
import org.mycore.iiif.presentation.model.attributes.MCRDCMIType;
import org.mycore.iiif.presentation.model.basic.MCRIIIFCanvas;
import org.mycore.iiif.presentation.model.basic.MCRIIIFManifest;
import org.mycore.iiif.presentation.model.basic.MCRIIIFRange;
import org.mycore.iiif.presentation.model.basic.MCRIIIFSequence;
public class MCRIIIFPresentationUtil {
/**
* The ids ({@link MCRIIIFBase#getId()}) are all local e.g. a canvas id is maybe abcdf.tiff then this methods
* replaces the id with a URI.
* -> http://my.repository.com/iiif/presentation/$impl/$identifier/canvas/abcdf.tiff
* Works recursive
* @param base where to start with replacing
*/
public static void correctIDs(MCRIIIFBase base, String impl, String identifier) {
switch (base.getType()) {
case MCRIIIFCanvas.TYPE -> {
base.setId(getImplBaseURL(impl, identifier) + "canvas/" + encodeUTF8(base.getId()));
if (base instanceof MCRIIIFCanvas canvas) {
canvas.images.forEach(annotation -> correctIDs(annotation, impl, identifier));
}
}
case MCRIIIFAnnotation.TYPE -> {
base.setId(getImplBaseURL(impl, identifier) + "annotation/" + encodeUTF8(base.getId()));
if (base instanceof MCRIIIFAnnotation iiifAnnotation) {
iiifAnnotation.refresh();
correctIDs(iiifAnnotation.getResource(), impl, identifier);
}
}
case MCRIIIFSequence.TYPE -> {
base.setId(getImplBaseURL(impl, identifier) + "sequence/" + encodeUTF8(base.getId()));
if (base instanceof MCRIIIFSequence sequence) {
sequence.canvases.forEach(canvas -> correctIDs(canvas, impl, identifier));
}
}
case MCRIIIFRange.TYPE -> {
base.setId(getImplBaseURL(impl, identifier) + "range/" + encodeUTF8(base.getId()));
if (base instanceof MCRIIIFRange range) {
range.canvases = range.canvases.stream()
.map(c -> getImplBaseURL(impl, identifier) + "canvas/" + encodeUTF8(c))
.collect(Collectors.toList());
range.ranges = range.ranges.stream()
.map(r -> getImplBaseURL(impl, identifier) + "range/" + encodeUTF8(r))
.collect(Collectors.toList());
}
}
case MCRIIIFManifest.TYPE -> {
base.setId(getImplBaseURL(impl, identifier) + "manifest");
if (base instanceof MCRIIIFManifest manifest) {
manifest.sequences.forEach(seq -> correctIDs(seq, impl, identifier));
manifest.structures.forEach(seq -> correctIDs(seq, impl, identifier));
}
}
default -> {
if (base.getType().equals(MCRDCMIType.Image.toString())) {
return;
}
base.setId(getImplBaseURL(impl, identifier) + "res/" + base.getId());
}
}
}
private static String getImplBaseURL(String impl, String identifier) {
String impAndSlash = Objects.equals(impl, "") ? "" : impl + "/";
return MCRFrontendUtil.getBaseURL() + "api/iiif/presentation/v2/" + impAndSlash + identifier + "/";
}
private static String encodeUTF8(String c) {
return URLEncoder.encode(c, StandardCharsets.UTF_8);
}
}
| 4,608 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFPresentationImpl.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/impl/MCRIIIFPresentationImpl.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.impl;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.mycore.common.MCRException;
import org.mycore.common.config.MCRConfiguration2;
import org.mycore.common.config.MCRConfigurationException;
import org.mycore.iiif.presentation.model.basic.MCRIIIFManifest;
public abstract class MCRIIIFPresentationImpl {
private static final String MCR_IIIF_PRESENTATION_CONFIG_PREFIX = "MCR.IIIFPresentation.";
private static final Map<String, MCRIIIFPresentationImpl> IMPLHOLDER = new HashMap<>();
private final String implName;
public MCRIIIFPresentationImpl(final String implName) {
this.implName = implName;
}
public static synchronized MCRIIIFPresentationImpl getInstance(String implNameParameter) {
String implName = (implNameParameter == null || implNameParameter.isBlank())
? MCRConfiguration2.getStringOrThrow("MCR.IIIFPresentation.Default")
: implNameParameter;
if (IMPLHOLDER.containsKey(implName)) {
return IMPLHOLDER.get(implName);
}
String classPropertyName = MCR_IIIF_PRESENTATION_CONFIG_PREFIX + implName;
Class<? extends MCRIIIFPresentationImpl> classObject = MCRConfiguration2.<MCRIIIFPresentationImpl>getClass(
classPropertyName)
.orElseThrow(() -> MCRConfiguration2.createConfigurationException(classPropertyName));
try {
Constructor<? extends MCRIIIFPresentationImpl> constructor = classObject.getConstructor(String.class);
MCRIIIFPresentationImpl presentationImpl = constructor.newInstance(implName);
IMPLHOLDER.put(implName, presentationImpl);
return presentationImpl;
} catch (NoSuchMethodException e) {
throw new MCRConfigurationException(
"Configurated class (" + classObject.getName() + ") needs a string constructor: " + classPropertyName);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new MCRException(e);
}
}
public String getImplName() {
return implName;
}
protected final Map<String, String> getProperties() {
return MCRConfiguration2.getSubPropertiesMap(getConfigPrefix());
}
private String getConfigPrefix() {
return MCR_IIIF_PRESENTATION_CONFIG_PREFIX + implName + ".";
}
/**
* For consistency and security reasons it may become necessary to
* to cleanup the identifier, which is an otherwise unchecked URL path parameter.
*
* Subclasses may override.
*
* @param identifier - the IIIF manifest identifier, which should be normalized
* @return the normalized identifier
*/
public String normalizeIdentifier(String identifier) {
return identifier;
}
public abstract MCRIIIFManifest getManifest(String id);
}
| 3,729 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFPresentationResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/resources/MCRIIIFPresentationResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.resources;
import static org.mycore.iiif.presentation.MCRIIIFPresentationUtil.correctIDs;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mycore.common.MCRCache;
import org.mycore.frontend.jersey.MCRCacheControl;
import org.mycore.iiif.common.MCRIIIFMediaTypeHelper;
import org.mycore.iiif.presentation.MCRIIIFPresentationManifestQuickAccess;
import org.mycore.iiif.presentation.impl.MCRIIIFPresentationImpl;
import org.mycore.iiif.presentation.model.basic.MCRIIIFManifest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;
@Path("/presentation/v2{noop: /?}{impl: ([a-zA-Z0-9]+)?}")
public class MCRIIIFPresentationResource {
private static final Logger LOGGER = LogManager.getLogger();
private static final MCRCache<String, MCRIIIFPresentationManifestQuickAccess> CACHE = new MCRCache<>(1000,
MCRIIIFPresentationResource.class.getName());
private static final String IMPL_PARAM = "impl";
private static final String NAME_PARAM = "name";
private static final String IDENTIFIER_PARAM = "identifier";
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("collection/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getCollection(@PathParam(IMPL_PARAM) String impl, @PathParam(NAME_PARAM) String name) {
return null;
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/manifest")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getManifest(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@HeaderParam("Cache-Control") String cacheControl) {
String normalizedID = MCRIIIFPresentationImpl.getInstance(impl).normalizeIdentifier(identifier);
MCRIIIFPresentationManifestQuickAccess quickAccess = getManifestQuickAccess(impl, normalizedID,
cacheHeaderAsList(cacheControl).contains("no-cache"));
String manifestAsJSON = getGson().toJson(quickAccess.getManifest());
return addHeaders(Response.ok()).entity(manifestAsJSON).build();
}
protected MCRIIIFPresentationManifestQuickAccess getManifestQuickAccess(String impl, String identifier) {
return getManifestQuickAccess(impl, identifier, false);
}
protected MCRIIIFPresentationManifestQuickAccess getManifestQuickAccess(String impl, String identifier,
boolean noCache) {
MCRIIIFPresentationManifestQuickAccess quickAccess = CACHE
.getIfUpToDate(impl + identifier, TimeUnit.HOURS.toMillis(1));
if (quickAccess == null || noCache) {
long startTime = new Date().getTime();
MCRIIIFManifest manifest = MCRIIIFPresentationImpl.getInstance(impl).getManifest(identifier);
long endTime = new Date().getTime();
long timeNeeded = endTime - startTime;
LOGGER.info("Manifest {}:{} generation needed: {}ms", impl, identifier, timeNeeded);
quickAccess = new MCRIIIFPresentationManifestQuickAccess(manifest);
CACHE.put(impl + identifier, quickAccess);
correctIDs(manifest, impl, identifier);
} else {
LOGGER.info("Manifest {}:{} served from cache", impl, identifier);
}
return quickAccess;
}
protected Response.ResponseBuilder addHeaders(Response.ResponseBuilder builder) {
return builder
.header("Link",
"<http://iiif.io/api/presentation/2/context.json>\n;rel=\"http://www.w3.org/ns/json-ld#context\";type=\""
+ MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON + "\"")
.header("Access-Control-Allow-Origin", "*");
}
protected Gson getGson() {
return new GsonBuilder()
.setPrettyPrinting()
.create();
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/sequence/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getSequence(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam(NAME_PARAM) String name, @HeaderParam("Cache-Control") String cacheControl) {
String normalizedID = MCRIIIFPresentationImpl.getInstance(impl).normalizeIdentifier(identifier);
MCRIIIFPresentationManifestQuickAccess quickAccess = getManifestQuickAccess(impl, normalizedID,
cacheHeaderAsList(cacheControl).contains("no-cache"));
String sequenceAsJSON = getGson().toJson(quickAccess.getSequence(name));
return addHeaders(Response.ok()).entity(sequenceAsJSON).build();
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/canvas/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response getCanvas(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam(NAME_PARAM) String name, @HeaderParam("Cache-Control") String cacheControl) {
String normalizedID = MCRIIIFPresentationImpl.getInstance(impl).normalizeIdentifier(identifier);
MCRIIIFPresentationManifestQuickAccess quickAccess = getManifestQuickAccess(impl, normalizedID,
cacheHeaderAsList(cacheControl).contains("no-cache"));
String canvasAsJSON = getGson().toJson(quickAccess.getCanvas(name));
return addHeaders(Response.ok()).entity(canvasAsJSON).build();
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/annotation/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getAnnotation(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam(NAME_PARAM) String name, @HeaderParam("Cache-Control") String cacheControl) {
String normalizedID = MCRIIIFPresentationImpl.getInstance(impl).normalizeIdentifier(identifier);
MCRIIIFPresentationManifestQuickAccess quickAccess = getManifestQuickAccess(impl, normalizedID,
cacheHeaderAsList(cacheControl).contains("no-cache"));
String annotationAsJSON = getGson().toJson(quickAccess.getAnnotationBase(name));
return addHeaders(Response.ok()).entity(annotationAsJSON).build();
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/list/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getAnnotationList(@PathParam(IMPL_PARAM) String impl,
@PathParam(IDENTIFIER_PARAM) String identifier, @PathParam(NAME_PARAM) String name,
@HeaderParam("Cache-Control") String cacheControl) {
String normalizedID = MCRIIIFPresentationImpl.getInstance(impl).normalizeIdentifier(identifier);
return getAnnotation(impl, normalizedID, name, cacheControl);
}
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/range/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS))
public Response getRange(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam(NAME_PARAM) String name, @HeaderParam("Cache-Control") String cacheControl) {
String normalizedID = MCRIIIFPresentationImpl.getInstance(impl).normalizeIdentifier(identifier);
MCRIIIFPresentationManifestQuickAccess quickAccess = getManifestQuickAccess(impl, normalizedID,
cacheHeaderAsList(cacheControl).contains("no-cache"));
String rangeAsJSON = getGson().toJson(quickAccess.getRange(name));
return addHeaders(Response.ok()).entity(rangeAsJSON).build();
}
// layers and resources are not supported currently
@GET
@Produces(MCRIIIFMediaTypeHelper.APPLICATION_LD_JSON)
@Path("{" + IDENTIFIER_PARAM + "}/layer/{" + NAME_PARAM + "}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response getLayer(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam(NAME_PARAM) String name) {
return null;
}
@GET
@Path("{" + IDENTIFIER_PARAM + "}/res/{" + NAME_PARAM + "}[.]{format}")
@MCRCacheControl(maxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.DAYS),
sMaxAge = @MCRCacheControl.Age(time = 1, unit = TimeUnit.HOURS))
public Response getContent(@PathParam(IMPL_PARAM) String impl, @PathParam(IDENTIFIER_PARAM) String identifier,
@PathParam(NAME_PARAM) String name, @PathParam("format") String format) {
return null;
}
private List<String> cacheHeaderAsList(String cacheHeader) {
if (cacheHeader == null) {
return Collections.emptyList();
}
return Arrays.asList(cacheHeader.toLowerCase(Locale.ROOT).trim().split("\\s*,\\s*"));
}
}
| 10,930 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFPresentationBase.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/MCRIIIFPresentationBase.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model;
import java.util.List;
import org.mycore.iiif.model.MCRIIIFBase;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFLDURI;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFResource;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFService;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFViewingHint;
public class MCRIIIFPresentationBase extends MCRIIIFBase {
public List<MCRIIIFLDURI> seeAlso = null;
private String attribution = null;
private MCRIIIFResource logo = null;
private MCRIIIFLDURI licence = null;
private MCRIIIFViewingHint viewingHint = null;
private MCRIIIFResource related = null;
private MCRIIIFService service = null;
public MCRIIIFPresentationBase(String id, String type, String context) {
super(id, type, context);
}
public MCRIIIFPresentationBase(String type, String context) {
super(type, context);
}
public MCRIIIFPresentationBase(String context) {
super(context);
}
public MCRIIIFPresentationBase() {
}
public String getAttribution() {
return attribution;
}
public void setAttribution(String attribution) {
this.attribution = attribution;
}
public MCRIIIFResource getLogo() {
return logo;
}
public void setLogo(MCRIIIFResource logo) {
this.logo = logo;
}
public MCRIIIFLDURI getLicence() {
return licence;
}
public void setLicence(MCRIIIFLDURI licence) {
this.licence = licence;
}
public MCRIIIFViewingHint getViewingHint() {
return viewingHint;
}
public void setViewingHint(MCRIIIFViewingHint viewingHint) {
this.viewingHint = viewingHint;
}
public MCRIIIFResource getRelated() {
return related;
}
public void setRelated(MCRIIIFResource related) {
this.related = related;
}
public MCRIIIFService getService() {
return service;
}
public void setService(MCRIIIFService service) {
this.service = service;
}
}
| 2,848 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFReference.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/basic/MCRIIIFReference.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.basic;
import org.mycore.iiif.model.MCRIIIFBase;
public class MCRIIIFReference extends MCRIIIFBase {
public MCRIIIFReference(String id, String type) {
super(id, type, API_PRESENTATION_2);
}
public MCRIIIFReference(MCRIIIFCanvas canvas) {
super(canvas.getId(), canvas.getType(), canvas.getContext());
}
public MCRIIIFReference(MCRIIIFRange range) {
super(range.getId(), range.getType(), range.getContext());
}
}
| 1,234 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFManifest.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/basic/MCRIIIFManifest.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.basic;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.mycore.iiif.presentation.model.MCRIIIFPresentationBase;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFResource;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFViewingDirection;
public class MCRIIIFManifest extends MCRIIIFPresentationBase {
public static final String TYPE = "sc:Manifest";
public List<MCRIIIFSequence> sequences = new ArrayList<>();
public List<MCRIIIFMetadata> metadata = new ArrayList<>();
public List<MCRIIIFRange> structures = new ArrayList<>();
private String label = null;
private String description = null;
private MCRIIIFResource thumbnail = null;
private MCRIIIFViewingDirection viewingDirection = null;
private String within = null;
private Date navDate;
public MCRIIIFManifest() {
super(TYPE, API_PRESENTATION_2);
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public MCRIIIFResource getThumbnail() {
return thumbnail;
}
public void setThumbnail(MCRIIIFResource thumbnail) {
this.thumbnail = thumbnail;
}
public MCRIIIFViewingDirection getViewingDirection() {
return viewingDirection;
}
public void setViewingDirection(MCRIIIFViewingDirection viewingDirection) {
this.viewingDirection = viewingDirection;
}
public String getWithin() {
return within;
}
public void setWithin(String within) {
this.within = within;
}
public Date getNavDate() {
return navDate;
}
public void setNavDate(Date navDate) {
this.navDate = navDate;
}
}
| 2,783 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFSequence.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/basic/MCRIIIFSequence.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.basic;
import java.util.List;
import org.mycore.iiif.presentation.model.MCRIIIFPresentationBase;
import org.mycore.iiif.presentation.model.additional.MCRIIIFAnnotationBase;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFViewingDirection;
public class MCRIIIFSequence extends MCRIIIFPresentationBase {
public static final String TYPE = "sc:Sequence";
public List<MCRIIIFCanvas> canvases;
public List<MCRIIIFMetadata> metadata;
protected MCRIIIFReference startCanvas;
private transient MCRIIIFCanvas origStartCanvas;
private String description;
private String label;
private MCRIIIFAnnotationBase thumbnail = null;
private MCRIIIFViewingDirection viewingDirection = null;
public MCRIIIFSequence(String id) {
super(id, TYPE, API_PRESENTATION_2);
}
public MCRIIIFCanvas getStartCanvas() {
return origStartCanvas;
}
public void setStartCanvas(MCRIIIFCanvas startCanvas) {
this.origStartCanvas = startCanvas;
this.startCanvas = new MCRIIIFReference(startCanvas);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public MCRIIIFAnnotationBase getThumbnail() {
return thumbnail;
}
public void setThumbnail(MCRIIIFAnnotationBase thumbnail) {
this.thumbnail = thumbnail;
}
public MCRIIIFViewingDirection getViewingDirection() {
return viewingDirection;
}
public void setViewingDirection(MCRIIIFViewingDirection viewingDirection) {
this.viewingDirection = viewingDirection;
}
}
| 2,656 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFRange.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/basic/MCRIIIFRange.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.basic;
import java.util.ArrayList;
import java.util.List;
import org.mycore.iiif.presentation.model.MCRIIIFPresentationBase;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata;
public class MCRIIIFRange extends MCRIIIFPresentationBase {
public static final String TYPE = "sc:Range";
public List<MCRIIIFMetadata> metadata = new ArrayList<>();
// ranges and canvases should be removed!
public List<String> ranges = new ArrayList<>();// = new ArrayList<>();
public List<String> canvases = new ArrayList<>();
private String label;
public MCRIIIFRange(String id) {
super();
setId(id);
setType(TYPE);
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
| 1,589 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFCanvas.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/basic/MCRIIIFCanvas.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.basic;
import java.util.ArrayList;
import java.util.List;
import org.mycore.iiif.presentation.model.MCRIIIFPresentationBase;
import org.mycore.iiif.presentation.model.additional.MCRIIIFAnnotationBase;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata;
import org.mycore.iiif.presentation.model.attributes.MCRIIIFResource;
public class MCRIIIFCanvas extends MCRIIIFPresentationBase {
public static final String TYPE = "sc:Canvas";
public List<MCRIIIFAnnotationBase> images = new ArrayList<>();
public List<MCRIIIFMetadata> metadata = new ArrayList<>();
private String label;
private String description = null;
private MCRIIIFResource thumbnail = null;
private int height;
private int width;
public MCRIIIFCanvas(String id, String label, int width, int height) {
super(id, TYPE, API_PRESENTATION_2);
this.label = label;
this.width = width;
this.height = height;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public String getLabel() {
return label;
}
public String getDescription() {
return description;
}
public MCRIIIFResource getThumbnail() {
return thumbnail;
}
}
| 2,062 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRDCMIType.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRDCMIType.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
/**
* @see <a href="http://dublincore.org/documents/dcmi-type-vocabulary/#dcmitype-Dataset">dcmitype-Dataset</a>
*/
public enum MCRDCMIType {
/**
* An aggregation of resources.
* A collection is described as a group; its parts may also be separately described.
*/
Collection("dctypes:Collection"),
/**
* Data encoded in a defined structure.
* Examples include lists, tables, and databases. A dataset may be useful for direct machine processing.
*/
Dataset("dctypes:Dataset"),
/**
* A non-persistent, time-based occurrence.
* Metadata for an event provides descriptive information that is the basis for discovery of the purpose, location,
* duration, and responsible agents associated with an event. Examples include an exhibition, webcast, conference,
* workshop, open day, performance, battle, trial, wedding, tea party, conflagration.
*/
Event("dctypes:Event"),
/**
* A visual representation other than text.
* Examples include images and photographs of physical objects, paintings, prints, drawings, other images and
* graphics, animations and moving pictures, film, diagrams, maps, musical notation. Note that Image may include
* both electronic and physical representations.
*/
Image("dctypes:Image"),
/**
* A resource requiring interaction from the user to be understood, executed, or experienced.
* Examples include forms on Web pages, applets, multimedia learning objects, chat services, or virtual reality
* environments.
*/
InteractiveResource("dctypes:InteractiveResource"),
/**
* A series of visual representations imparting an impression of motion when shown in succession.
* Examples include animations, movies, television programs, videos, zoetropes, or visual output from a simulation.
* Instances of the type Moving Image must also be describable as instances of the broader type Image.
*/
MovingImage("dctypes:MovingImage"),
/**
* An inanimate, three-dimensional object or substance.
* Note that digital representations of, or surrogates for, these objects should use Image, Text or one of the other
* types.
*/
PhysicalObject("dctypes:PhysicalObject"),
/**
* A system that provides one or more functions.
* Examples include a photocopying service, a banking service, an authentication service, interlibrary loans, a
* Z39.50 or Web server.
*/
Service("dctypes:Service"),
/**
* A computer program in source or compiled form.
* Examples include a C source file, MS-Windows .exe executable, or Perl script.
*/
Software("dctypes:Software"),
/**
* A resource primarily intended to be heard.
* Examples include a music playback file format, an audio compact disc, and recorded speech or sounds.
*/
Sound("dctypes:Sound"),
/**
* A static visual representation.
* Examples include paintings, drawings, graphic designs, plans and maps. Recommended best practice is to assign the
* type Text to images of textual materials. Instances of the type Still Image must also be describable as instances
* of the broader type Image.
*/
StillImage("dctypes:StillImage"),
/**
* A resource consisting primarily of words for reading.
* Examples include books, letters, dissertations, poems, newspapers, articles, archives of mailing lists. Note that
* facsimiles or images of texts are still of the genre Text.
*/
Text("dctypes:Text");
private final String stringExpr;
MCRDCMIType(String stringExpr) {
this.stringExpr = stringExpr;
}
@Override
public String toString() {
return this.stringExpr;
}
}
| 4,555 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFViewingDirection.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFViewingDirection.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
import com.google.gson.annotations.SerializedName;
/**
* The direction that canvases of the resource should be presented when rendered for the user to navigate and/or read.
* @see <a href="http://iiif.io/api/presentation/2.0/#technical-properties">IIIF-Documentation</a>
*/
public enum MCRIIIFViewingDirection {
/**
* The object is read from left to right, and is the default if not specified.
*/
@SerializedName("left-to-right")
left_to_right(),
/**
* The object is read from right to left.
*/
@SerializedName("right-to-left")
right_to_left(),
/**
* The object is read from the top to the bottom.
*/
@SerializedName("top-to-bottom")
top_to_bottom(),
/**
* The object is read from the bottom to the top.
*/
@SerializedName("bottom-to-top")
bottom_to_top()
}
| 1,637 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFService.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFService.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
import org.mycore.iiif.model.MCRIIIFBase;
/**
* A link to a service that makes more functionality available for the resource, such as from an image to the base URI
* of an associated IIIF Image API service. The service resource should have additional information associated with it
* in order to allow the client to determine how to make appropriate use of it, such as a profile link to a service
* description. It may also have relevant information copied from the service itself. This duplication is permitted in
* order to increase the performance of rendering the object without necessitating additional HTTP requests.
*
* @see <a href="http://iiif.io/api/presentation/2.0/#linking-properties">IIIF-Documentation</a>
*/
public class MCRIIIFService extends MCRIIIFBase {
/**
* This can be a String or also @link {@link org.mycore.iiif.image.model.MCRIIIFImageProfile}
**/
public String profile;
public MCRIIIFService(String id, String context) {
super(id, null, context);
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
}
| 1,956 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFResource.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFResource.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
public class MCRIIIFResource extends MCRIIIFLDURI {
protected MCRIIIFService service;
private int width;
private int height;
public MCRIIIFResource(String uri, MCRDCMIType type, String format) {
super(uri, type.toString(), format);
}
public MCRIIIFResource(String uri, MCRDCMIType type) {
super(uri, type.toString(), null);
}
public void setService(MCRIIIFService service) {
this.service = service;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
| 1,519 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFLDURI.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFLDURI.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
import org.mycore.iiif.model.MCRIIIFBase;
public class MCRIIIFLDURI extends MCRIIIFBase {
private String format = null;
public MCRIIIFLDURI(String uri, String type, String format) {
super(uri, type, MCRIIIFBase.API_PRESENTATION_2);
this.format = format;
}
public MCRIIIFLDURI(String uri, String type) {
super(uri, type, MCRIIIFBase.API_PRESENTATION_2);
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
| 1,330 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFMetadataValue.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFMetadataValue.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
import com.google.gson.annotations.SerializedName;
public class MCRIIIFMetadataValue {
@SerializedName("@value")
private String value;
@SerializedName("@language")
private String language;
public MCRIIIFMetadataValue(String value, String language) {
this.value = value;
this.language = language;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
| 1,418 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFMetadata.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFMetadata.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
import java.util.Optional;
public class MCRIIIFMetadata {
private String label;
private Object value;
public MCRIIIFMetadata(String label, String value) {
this.label = label;
this.value = value;
}
public MCRIIIFMetadata(String label, MCRIIIFMetadataValue value) {
this.label = label;
this.value = value;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Optional<MCRIIIFMetadataValue> getValue() {
if (this.value instanceof MCRIIIFMetadataValue metadataValue) {
return Optional.of(metadataValue);
}
return Optional.empty();
}
public Optional<String> getStringValue() {
if (this.value instanceof String s) {
return Optional.of(s);
}
return Optional.empty();
}
}
| 1,691 | Java | .java | MyCoRe-Org/mycore | 33 | 14 | 19 | 2016-10-07T06:02:02Z | 2024-05-08T18:38:30Z |
MCRIIIFViewingHint.java | /FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-iiif/src/main/java/org/mycore/iiif/presentation/model/attributes/MCRIIIFViewingHint.java | /*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyCoRe is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.iiif.presentation.model.attributes;
import com.google.gson.annotations.SerializedName;
/**
* A hint to the client as to the most appropriate method of displaying the resource.
*
* @see <a href="http://iiif.io/api/presentation/2.0/#technical-properties">IIIF-Documentation</a>
*/
public enum MCRIIIFViewingHint {
/**
* "The canvases referenced from the resource are all individual sheets, and should not be presented in a
* page-turning interface. Examples include a set of views of a 3 dimensional object, or a set of the front sides of
* photographs in a collection."
*/
@SerializedName("individuals")
individuals,
/**
* "The canvases represent pages in a bound volume, and should be presented in a page-turning interface if one
* is available. The first canvas is a single view (the first recto) and thus the second canvas represents the back
* of the object in the first canvas."
*/
@SerializedName("paged")
paged,
/**
* "
* Valid only for collections. Collections with this hint consist of multiple manifests that each form part of a
* logical whole. Clients might render the collection as a table of contents, rather than with thumbnails. Examples
* include multi-volume books or a set of journal issues or other serials. "
*/
@SerializedName("multi-part")
multi_part,
/**
* "Each canvas is the complete view of one side of a long scroll or roll and an appropriate rendering might
* only
* display part of the canvas at any given time rather than the entire object. "
*/
@SerializedName("continuous")
continuous,
/**
* "Canvases with this hint must not be presented in a page turning interface, and must be skipped over when
* determining the page sequence. This viewing hint must be ignored if the current sequence or manifest does not
* have the ‘paged’ viewing hint."
*/
@SerializedName("non-paged")
non_paged,
/**
* "Only valid on a range. A range which has this viewingHint is the top-most node in a hierarchy of ranges
* that
* represents a structure to be rendered by the client to assist in navigation. For example, a table of contents
* within a paged object, major sections of a 3d object, the textual areas within a single scroll, and so forth.
* Other ranges that are descendants of the “top” range are the entries to be rendered in the navigation structure.
* There may be multiple ranges marked with this hint. If so, the client should display a choice of multiple
* structures to navigate through."
*/
@SerializedName("top")
top,
/**
* "Canvases with this hint, in a sequence or manifest with the “paged” viewing hint, must be displayed by
* themselves, as they depict both parts of the opening. If all of the canvases are like this, then page turning is
* not possible, so simply use “individuals” instead."
*/
@SerializedName("facing-pages")
facing_pages
}
| 3,871 | 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.