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
PlayerFreezer.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/PlayerFreezer.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import eu.matejkormuth.pexel.PexelCore.Pexel; /** * Utility class that help freezing of players. * * @author Mato Kormuth * */ public class PlayerFreezer implements Listener { /** * List of frozen textures. <br/> * FIXME: Remove 'dead' disconnected player objects. */ private final List<Player> frozen_movement = new ArrayList<Player>(); private final List<Player> frozen_rotation = new ArrayList<Player>(); public PlayerFreezer() { Bukkit.getPluginManager().registerEvents(this, Pexel.getCore()); } /** * Freezes (disables movement) the player. * * @param player * player to freeze */ public void freeze(final Player player) { this.freeze(player, false); } public void freeze(final Player player, final boolean rotation) { this.frozen_movement.add(player); if (rotation) this.frozen_rotation.add(player); } /** * Unfreezes (enables movement) the player. * * @param player * player to unfreeze */ public void unfreeze(final Player player) { this.frozen_movement.remove(player); this.frozen_rotation.remove(player); } @EventHandler private void onPlayerMove(final PlayerMoveEvent event) { if (this.frozen_movement.contains(event.getPlayer())) event.setTo(event.getFrom()); } }
2,546
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
EndRoundMusic.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/EndRoundMusic.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import net.minecraft.server.v1_8_R1.PacketPlayOutNamedSoundEffect; import org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer; import org.bukkit.entity.Player; /** * Class used for playing endround music. * * @author Mato Kormuth * */ public class EndRoundMusic { private final List<String> musicTracks = new ArrayList<String>(); private final Random random = new Random(); private String randomMusic() { return this.musicTracks.get(this.random.nextInt(this.musicTracks.size())); } public void playMusic(final Player player) { String soundName = this.randomMusic(); PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect( soundName, player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), Float.MAX_VALUE, 1); ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); } public void playMusic(final Collection<Player> players) { String soundName = this.randomMusic(); for (Player player : players) { PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect( soundName, player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), Float.MAX_VALUE, 1); ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); } } }
2,433
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Voting.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/Voting.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.Pexel; /** * Class used for voting. */ public abstract class Voting { /** * Amount of ticks in one second. */ private static final long ONE_SECOND = 20L; private List<Player> voters; private final Map<Player, Vote> votes = new HashMap<Player, Vote>(); private final String voteSubject; private long lastInteraction = Long.MAX_VALUE; private long timeout = 20 * 5; private boolean canVoteOnlyOnce = true; private int taskId = 0; public Voting(final String voteSubject) { this.voteSubject = voteSubject; } /** * Starts this vote. * * @param voters * players that should be able to vote * @param invoker * player that invoked the vote */ public void invoke(final List<Player> voters, final Player invoker) { this.voters = voters; this.taskId = Pexel.getScheduler().scheduleSyncRepeatingTask(new Runnable() { @Override public void run() { Voting.this.timeout(); } }, 0L, Voting.ONE_SECOND); this.startVote(invoker); this.lastInteraction = System.currentTimeMillis(); } /** * Called when voting should timeout. */ protected void timeout() { if (this.lastInteraction + this.timeout < System.currentTimeMillis()) { Pexel.getScheduler().cancelTask(this.taskId); this.onVoteFailed(); } } /** * Sends message to all voters. */ private void startVote(final Player invoker) { this.broadcast("Player " + invoker.getName() + " started the vote for " + this.voteSubject + "."); } public void broadcast(final String message) { for (Player p : this.voters) p.sendMessage(ChatColor.GOLD + "[VOTE] " + message); } /** * Votes positively for specified player. * * @param voter * player that votes for subject */ public void vote(final Player voter, final Vote vote) { if (!this.voters.contains(voter)) throw new RuntimeException("Invalid voter! Specified voter can't vote."); if (this.votes.containsKey(voter) && this.canVoteOnlyOnce) throw new RuntimeException("Invalid vote! One player can vote only once!"); this.votes.put(voter, vote); this.broadcastState(); this.processEnd(); this.lastInteraction = System.currentTimeMillis(); } /** * Check for voting end. */ private void processEnd() { int yesVotes = 0; for (Vote value : this.votes.values()) if (value == Vote.YES) yesVotes++; if (yesVotes == this.voters.size()) this.onVoteSucceeded(); else if (yesVotes > (this.voters.size() / 2)) this.onVoteSucceeded(); else this.onVoteFailed(); } /** * Broadcast vote state to all players. */ private void broadcastState() { int yesVotes = 0; for (Vote value : this.votes.values()) if (value == Vote.YES) yesVotes++; this.broadcast(yesVotes + "/" + this.voters.size() + " players voted for " + this.voteSubject + "!"); } // Abstract functions /** * Called when vote failed. */ public abstract void onVoteFailed(); /** * Called when vote succeeded. */ public abstract void onVoteSucceeded(); // Getters and setters public long getTimeout() { return this.timeout; } public void setTimeout(final long timeout) { this.timeout = timeout; } public boolean canVoteOnlyOnce() { return this.canVoteOnlyOnce; } public void setCanVoteOnlyOnce(final boolean canVoteOnlyOnce) { this.canVoteOnlyOnce = canVoteOnlyOnce; } }
5,195
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
AsyncWorker.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/AsyncWorker.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import eu.matejkormuth.pexel.PexelCore.core.Log; /** * Async worker for things like network stuff, etc... * * @author Mato Kormuth * */ public class AsyncWorker implements Runnable { /** * Tasks that should be done. */ private final Queue<Runnable> tasks = new ArrayBlockingQueue<Runnable>(50); /** * List of worker threads. */ private final List<Thread> workers = new ArrayList<Thread>(4); private boolean enabled = false; private final int workersCount; /** * Creates new object with specified amount of wokrker threads. * * @param workersCount * count of workers */ public AsyncWorker(final int workersCount) { Log.partEnable("AyncWorker"); this.workersCount = workersCount; } public void start() { this.enabled = true; for (int i = 0; i < this.workersCount; i++) { Log.info("Setting up worker #" + (i + 1) + "..."); this.workers.add(new Thread(this)); this.workers.get(this.workers.size() - 1).setName("AsyncWorker-" + (i + 1)); this.workers.get(this.workers.size() - 1).start(); } } /** * Adds specified task to list. Taks should be executed not later then 200 ms. * * @param runnable * taks to be executed from other thread. */ public void addTask(final Runnable runnable) { this.tasks.add(runnable); } /** * Shutdowns the workers and the logic. */ public void shutdown() { Log.partDisable("AsyncWorker"); this.enabled = false; } @Override public void run() { while (this.enabled) { Runnable r = this.tasks.poll(); if (r != null) try { r.run(); } catch (Exception ex) { Log.warn("[AsyncWorker] Task generated: " + ex.getMessage()); } else try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } Log.info(Thread.currentThread().getName() + " died."); } }
3,294
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ServerLocation.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/ServerLocation.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import org.apache.commons.lang.Validate; /** * Location on server. Used for unknown pruposes. * * @author Mato Kormuth * */ public class ServerLocation { /** * Name of the location. */ private final String locationName; /** * Type of the location. */ private final ServerLocationType locationType; /** * Creates new instance of ServerLocation. * * @param locationName * @param locationType */ public ServerLocation(final String locationName, final ServerLocationType locationType) { Validate.notNull(locationName); Validate.notNull(locationType); this.locationName = locationName; this.locationType = locationType; } /** * Returns name of server location. * * @return the name */ public String getName() { return this.locationName; } /** * Returns type of location. * * @return type */ public ServerLocationType getType() { return this.locationType; } @Override public String toString() { return this.locationType.toString() + ": " + this.locationName; } }
2,098
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ParametrizedRunnable.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/ParametrizedRunnable.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import eu.matejkormuth.pexel.PexelCore.actions.JavaArbitraryAction; /** * Parametrized runnable. Well, i don't know if this works properly... * * @author Mato Kormuth * */ public abstract class ParametrizedRunnable implements Runnable { private final Object[] args; public ParametrizedRunnable(final Object... args) { this.args = args; } /** * In {@link JavaArbitraryAction} <code>args[0]</code> is player, who executed the action. * * @param args */ public abstract void run(final Object... args); @Override public void run() { this.run(this.args); } }
1,518
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
SerializableVector.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/SerializableVector.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import org.bukkit.util.Vector; /** * Vector that is serializable. * * @author Mato Kormuth * */ @XmlAccessorType(XmlAccessType.FIELD) public class SerializableVector extends Vector implements Serializable { private static final long serialVersionUID = -5438305359697297397L; @XmlAttribute(name = "x") protected double x; @XmlAttribute(name = "y") protected double y; @XmlAttribute(name = "z") protected double z; public SerializableVector(final Vector vector) { super(vector.getX(), vector.getY(), vector.getZ()); } public SerializableVector(final int x, final int y, final int z) { super(x, y, z); } public SerializableVector(final double x, final double y, final double z) { super(x, y, z); } public SerializableVector(final float x, final float y, final float z) { super(x, y, z); } }
1,983
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Countdown.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/Countdown.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import eu.matejkormuth.pexel.PexelCore.Pexel; /** * Class used for countdown. * * @author Mato Kormuth * */ public class Countdown { private int timeLeft = 0; private int timeLenght = 0; private int taskId = 0; private Runnable onEnd; private Runnable onTick; private String tag = null; /** * Creates new countdown with specified time left. * * @param seconds * time lieft in seconds */ public Countdown(final int seconds) { this.timeLenght = seconds; this.timeLeft = seconds; } /** * Creates new countdown with specified time left. * * @param seconds * time lieft in seconds * @param tag * tag of countdown */ public Countdown(final int seconds, final String tag) { this.timeLenght = seconds; this.timeLeft = seconds; this.tag = tag; } /** * Starts the countdown. */ public void start() { this.taskId = Pexel.getScheduler().scheduleSyncRepeatingTask(new Runnable() { @Override public void run() { Countdown.this.tick(); } }, 0L, 20L); } private void tick() { this.timeLeft--; if (this.onTick != null) this.onTick.run(); if (this.timeLeft < 1) { Pexel.getScheduler().cancelTask(this.taskId); if (this.onEnd != null) this.onEnd.run(); } } /** * Pauses countdown. Resume with {@link Countdown#start()}. */ public void pause() { Pexel.getScheduler().cancelTask(this.taskId); } /** * Resets time left to default value. */ public void reset() { this.timeLeft = this.timeLenght; } /** * Sets runnable that will be executed when countdown reach zero. * * @param onEnd * runnable */ public void setOnEnd(final Runnable onEnd) { this.onEnd = onEnd; } /** * Sets runnable that will be executed each second. * * @param onTick * runnable */ public void setOnTick(final Runnable onTick) { this.onTick = onTick; } /** * Returns tag of this countdown. * * @return tag */ public String getTag() { return this.tag; } /** * Returns time left in countdown in seconds. * * @return time left in seconds */ public int getTimeLeft() { return this.timeLeft; } /** * Returns lenght of countdown. * * @return lenght */ public int getLenght() { return this.timeLenght; } }
3,682
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
NMS.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/NMS.java
package eu.matejkormuth.pexel.PexelCore.util; import net.minecraft.server.v1_8_R1.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.entity.LivingEntity; /** * Helper na pracu s NMS kodom. * * @author Matej Kormuth * */ public class NMS { /** * Verzia serveru. */ public static final String VERSION = Bukkit.getServer() .getClass() .getPackage() .getName() .replaceAll("org.bukkit.craftbukkit.", "") .replaceAll(".CraftServer", ""); /** * Nazov balicku NMS. */ public static final String PACKAGE_MC = "net.minecraft.server." + VERSION + "."; /** * Nazov balicku CB. */ public static final String PACKAGE_CB = "org.bukkit.craftbukkit." + VERSION + "."; /** * @param entity * @param movX * @param movY * @param movZ */ public static void relMoveEntity(final LivingEntity entity, final double movX, final double movY, final double movZ) { if (entity instanceof EntityLiving) { ((EntityLiving) entity).move(movX, movY, movZ); } } /** * @param movX * @return */ public static int fixedPointNumInteger(final double i) { if (i >= 134217728) System.out.println("Can't cast double bigger then 134217728 to fixed point number using int32."); return (int) (i * 32); } /** * @param i * @return */ public static byte fixedPointNumByte(final double i) { if (i >= 8) System.out.println("Can't cast double bigger then 8 to fixed point number using byte."); return (byte) (i * 32); } /** * Osporti entitu, ak je entita EntityInsentient tak, ze jej zmaze goalSelector golas a targetSelector goals, cize * AI. * * FIXME!!!!! * * @param e */ public static void makeIdiot(final org.bukkit.entity.LivingEntity e) { //EntityInsentient ei = (EntityInsentient) e; /* * try { Field gsa = net.minecraft.server.v1_7_R3.PathfinderGoalSelector.class.getDeclaredField("c"); * gsa.setAccessible(true); gsa.set(this.goalSelector, new UnsafeList()); gsa.set(this.targetSelector, new * UnsafeList()); * * Field gsb = net.minecraft.server.v1_7_R3.PathfinderGoalSelector.class.getDeclaredField("b"); * gsb.setAccessible(true); gsb.set(this.goalSelector, new UnsafeList()); gsb.set(this.targetSelector, new * UnsafeList()); * * } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); * } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { * e.printStackTrace(); } */ } }
3,103
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ReflectionUtil.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/ReflectionUtil.java
package eu.matejkormuth.pexel.PexelCore.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.bukkit.Bukkit; /** * <b>ReflectionUtils</b> * <p> * This class provides useful methods which makes dealing with reflection much easier, especially when working with * Bukkit * <p> * You are welcome to use it, modify it and redistribute it under the following conditions: * <ul> * <li>Don't claim this class as your own * <li>Don't remove this disclaimer * </ul> * <p> * <i>It would be nice if you provide credit to me if you use this class in a published project</i> * * @author DarkBlade12 * @version 1.1 */ public final class ReflectionUtil { // Prevent accidental construction private ReflectionUtil() { } /** * Returns the constructor of a given class with the given parameter types * * @param clazz * Target class * @param parameterTypes * Parameter types of the desired constructor * @return The constructor of the target class with the specified parameter types * @throws NoSuchMethodException * If the desired constructor with the specified parameter types cannot be found * @see DataType * @see DataType#getPrimitive(Class[]) * @see DataType#compare(Class[], Class[]) */ public static Constructor<?> getConstructor(final Class<?> clazz, final Class<?>... parameterTypes) throws NoSuchMethodException { Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); for (Constructor<?> constructor : clazz.getConstructors()) { if (!DataType.compare( DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) { continue; } return constructor; } throw new NoSuchMethodException( "There is no such constructor in this class with the specified parameter types"); } /** * Returns the constructor of a desired class with the given parameter types * * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param parameterTypes * Parameter types of the desired constructor * @return The constructor of the desired target class with the specified parameter types * @throws NoSuchMethodException * If the desired constructor with the specified parameter types cannot be found * @throws ClassNotFoundException * ClassNotFoundException If the desired target class with the specified name and package cannot be * found * @see #getClass(String, PackageType) * @see #getConstructor(Class, Class...) */ public static Constructor<?> getConstructor(final String className, final PackageType packageType, final Class<?>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { return getConstructor(packageType.getClass(className), parameterTypes); } /** * Returns an instance of a class with the given arguments * * @param clazz * Target class * @param arguments * Arguments which are used to construct an object of the target class * @return The instance of the target class with the specified arguments * @throws InstantiationException * If you cannot create an instance of the target class due to certain circumstances * @throws IllegalAccessException * If the desired constructor cannot be accessed due to certain circumstances * @throws IllegalArgumentException * If the types of the arguments do not match the parameter types of the constructor (this should not * occur since it searches for a constructor with the types of the arguments) * @throws InvocationTargetException * If the desired constructor cannot be invoked * @throws NoSuchMethodException * If the desired constructor with the specified arguments cannot be found */ public static Object instantiateObject(final Class<?> clazz, final Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance( arguments); } /** * Returns an instance of a desired class with the given arguments * * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param arguments * Arguments which are used to construct an object of the desired target class * @return The instance of the desired target class with the specified arguments * @throws InstantiationException * If you cannot create an instance of the desired target class due to certain circumstances * @throws IllegalAccessException * If the desired constructor cannot be accessed due to certain circumstances * @throws IllegalArgumentException * If the types of the arguments do not match the parameter types of the constructor (this should not * occur since it searches for a constructor with the types of the arguments) * @throws InvocationTargetException * If the desired constructor cannot be invoked * @throws NoSuchMethodException * If the desired constructor with the specified arguments cannot be found * @throws ClassNotFoundException * If the desired target class with the specified name and package cannot be found * @see #getClass(String, PackageType) * @see #instantiateObject(Class, Object...) */ public static Object instantiateObject(final String className, final PackageType packageType, final Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { return instantiateObject(packageType.getClass(className), arguments); } /** * Returns a method of a class with the given parameter types * * @param clazz * Target class * @param methodName * Name of the desired method * @param parameterTypes * Parameter types of the desired method * @return The method of the target class with the specified name and parameter types * @throws NoSuchMethodException * If the desired method of the target class with the specified name and parameter types cannot be found * @see DataType#getPrimitive(Class[]) * @see DataType#compare(Class[], Class[]) */ public static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>... parameterTypes) throws NoSuchMethodException { Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); for (Method method : clazz.getMethods()) { if (!method.getName().equals(methodName) || !DataType.compare( DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) { continue; } return method; } throw new NoSuchMethodException( "There is no such method in this class with the specified name and parameter types"); } /** * Returns a method of a desired class with the given parameter types * * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param methodName * Name of the desired method * @param parameterTypes * Parameter types of the desired method * @return The method of the desired target class with the specified name and parameter types * @throws NoSuchMethodException * If the desired method of the desired target class with the specified name and parameter types cannot * be found * @throws ClassNotFoundException * If the desired target class with the specified name and package cannot be found * @see #getClass(String, PackageType) * @see #getMethod(Class, String, Class...) */ public static Method getMethod(final String className, final PackageType packageType, final String methodName, final Class<?>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { return getMethod(packageType.getClass(className), methodName, parameterTypes); } /** * Invokes a method on an object with the given arguments * * @param instance * Target object * @param methodName * Name of the desired method * @param arguments * Arguments which are used to invoke the desired method * @return The result of invoking the desired method on the target object * @throws IllegalAccessException * If the desired method cannot be accessed due to certain circumstances * @throws IllegalArgumentException * If the types of the arguments do not match the parameter types of the method (this should not occur * since it searches for a method with the types of the arguments) * @throws InvocationTargetException * If the desired method cannot be invoked on the target object * @throws NoSuchMethodException * If the desired method of the class of the target object with the specified name and arguments cannot * be found * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ public static Object invokeMethod(final Object instance, final String methodName, final Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); } /** * Invokes a method of the target class on an object with the given arguments * * @param instance * Target object * @param clazz * Target class * @param methodName * Name of the desired method * @param arguments * Arguments which are used to invoke the desired method * @return The result of invoking the desired method on the target object * @throws IllegalAccessException * If the desired method cannot be accessed due to certain circumstances * @throws IllegalArgumentException * If the types of the arguments do not match the parameter types of the method (this should not occur * since it searches for a method with the types of the arguments) * @throws InvocationTargetException * If the desired method cannot be invoked on the target object * @throws NoSuchMethodException * If the desired method of the target class with the specified name and arguments cannot be found * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ public static Object invokeMethod(final Object instance, final Class<?> clazz, final String methodName, final Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke( instance, arguments); } /** * Invokes a method of a desired class on an object with the given arguments * * @param instance * Target object * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param methodName * Name of the desired method * @param arguments * Arguments which are used to invoke the desired method * @return The result of invoking the desired method on the target object * @throws IllegalAccessException * If the desired method cannot be accessed due to certain circumstances * @throws IllegalArgumentException * If the types of the arguments do not match the parameter types of the method (this should not occur * since it searches for a method with the types of the arguments) * @throws InvocationTargetException * If the desired method cannot be invoked on the target object * @throws NoSuchMethodException * If the desired method of the desired target class with the specified name and arguments cannot be * found * @throws ClassNotFoundException * If the desired target class with the specified name and package cannot be found * @see #getClass(String, PackageType) * @see #invokeMethod(Object, Class, String, Object...) */ public static Object invokeMethod(final Object instance, final String className, final PackageType packageType, final String methodName, final Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { return invokeMethod(instance, packageType.getClass(className), methodName, arguments); } /** * Returns a field of the target class with the given name * * @param clazz * Target class * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @return The field of the target class with the specified name * @throws NoSuchFieldException * If the desired field of the given class cannot be found * @throws SecurityException * If the desired field cannot be made accessible */ public static Field getField(final Class<?> clazz, final boolean declared, final String fieldName) throws NoSuchFieldException, SecurityException { Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); field.setAccessible(true); return field; } /** * Returns a field of a desired class with the given name * * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @return The field of the desired target class with the specified name * @throws NoSuchFieldException * If the desired field of the desired class cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @throws ClassNotFoundException * If the desired target class with the specified name and package cannot be found * @see #getField(Class, boolean, String) */ public static Field getField(final String className, final PackageType packageType, final boolean declared, final String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { return getField(packageType.getClass(className), declared, fieldName); } /** * Returns the value of a field of the given class of an object * * @param instance * Target object * @param clazz * Target class * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @return The value of field of the target object * @throws IllegalArgumentException * If the target object does not feature the desired field * @throws IllegalAccessException * If the desired field cannot be accessed * @throws NoSuchFieldException * If the desired field of the target class cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ public static Object getValue(final Object instance, final Class<?> clazz, final boolean declared, final String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getField(clazz, declared, fieldName).get(instance); } /** * Returns the value of a field of a desired class of an object * * @param instance * Target object * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @return The value of field of the target object * @throws IllegalArgumentException * If the target object does not feature the desired field * @throws IllegalAccessException * If the desired field cannot be accessed * @throws NoSuchFieldException * If the desired field of the desired class cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @throws ClassNotFoundException * If the desired target class with the specified name and package cannot be found * @see #getValue(Object, Class, boolean, String) */ public static Object getValue(final Object instance, final String className, final PackageType packageType, final boolean declared, final String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { return getValue(instance, packageType.getClass(className), declared, fieldName); } /** * Returns the value of a field with the given name of an object * * @param instance * Target object * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @return The value of field of the target object * @throws IllegalArgumentException * If the target object does not feature the desired field (should not occur since it searches for a * field with the given name in the class of the object) * @throws IllegalAccessException * If the desired field cannot be accessed * @throws NoSuchFieldException * If the desired field of the target object cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @see #getValue(Object, Class, boolean, String) */ public static Object getValue(final Object instance, final boolean declared, final String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getValue(instance, instance.getClass(), declared, fieldName); } /** * Sets the value of a field of the given class of an object * * @param instance * Target object * @param clazz * Target class * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @param value * New value * @throws IllegalArgumentException * If the type of the value does not match the type of the desired field * @throws IllegalAccessException * If the desired field cannot be accessed * @throws NoSuchFieldException * If the desired field of the target class cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ public static void setValue(final Object instance, final Class<?> clazz, final boolean declared, final String fieldName, final Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { getField(clazz, declared, fieldName).set(instance, value); } /** * Sets the value of a field of a desired class of an object * * @param instance * Target object * @param className * Name of the desired target class * @param packageType * Package where the desired target class is located * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @param value * New value * @throws IllegalArgumentException * If the type of the value does not match the type of the desired field * @throws IllegalAccessException * If the desired field cannot be accessed * @throws NoSuchFieldException * If the desired field of the desired class cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @throws ClassNotFoundException * If the desired target class with the specified name and package cannot be found * @see #setValue(Object, Class, boolean, String, Object) */ public static void setValue(final Object instance, final String className, final PackageType packageType, final boolean declared, final String fieldName, final Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { setValue(instance, packageType.getClass(className), declared, fieldName, value); } /** * Sets the value of a field with the given name of an object * * @param instance * Target object * @param declared * Whether the desired field is declared or not * @param fieldName * Name of the desired field * @param value * New value * @throws IllegalArgumentException * If the type of the value does not match the type of the desired field * @throws IllegalAccessException * If the desired field cannot be accessed * @throws NoSuchFieldException * If the desired field of the target object cannot be found * @throws SecurityException * If the desired field cannot be made accessible * @see #setValue(Object, Class, boolean, String, Object) */ public static void setValue(final Object instance, final boolean declared, final String fieldName, final Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { setValue(instance, instance.getClass(), declared, fieldName, value); } /** * Represents an enumeration of dynamic packages of NMS and CraftBukkit * <p> * This class is part of the <b>ReflectionUtils</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.0 */ public enum PackageType { MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()), CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()), CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"), CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"), CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"), CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"), CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"), CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"), CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"), CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"), CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"), CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"), CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"), CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"), CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"), CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"), CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"), CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"), CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"), CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util"); private final String path; /** * Construct a new package type * * @param path * Path of the package */ private PackageType(final String path) { this.path = path; } /** * Construct a new package type * * @param parent * Parent package of the package * @param path * Path of the package */ private PackageType(final PackageType parent, final String path) { this(parent + "." + path); } /** * Returns the path of this package type * * @return The path */ public String getPath() { return this.path; } /** * Returns the class with the given name * * @param className * Name of the desired class * @return The class with the specified name * @throws ClassNotFoundException * If the desired class with the specified name and package cannot be found */ public Class<?> getClass(final String className) throws ClassNotFoundException { return Class.forName(this + "." + className); } // Override for convenience @Override public String toString() { return this.path; } /** * Returns the version of your server * * @return The server version */ public static String getServerVersion() { return Bukkit.getServer().getClass().getPackage().getName().substring(23); } } /** * Represents an enumeration of Java data types with corresponding classes * <p> * This class is part of the <b>ReflectionUtils</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.0 */ public enum DataType { BYTE(byte.class, Byte.class), SHORT(short.class, Short.class), INTEGER(int.class, Integer.class), LONG(long.class, Long.class), CHARACTER(char.class, Character.class), FLOAT(float.class, Float.class), DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); private static final Map<Class<?>, DataType> CLASS_MAP = new HashMap<Class<?>, DataType>(); private final Class<?> primitive; private final Class<?> reference; // Initialize map for quick class lookup static { for (DataType type : values()) { CLASS_MAP.put(type.primitive, type); CLASS_MAP.put(type.reference, type); } } /** * Construct a new data type * * @param primitive * Primitive class of this data type * @param reference * Reference class of this data type */ private DataType(final Class<?> primitive, final Class<?> reference) { this.primitive = primitive; this.reference = reference; } /** * Returns the primitive class of this data type * * @return The primitive class */ public Class<?> getPrimitive() { return this.primitive; } /** * Returns the reference class of this data type * * @return The reference class */ public Class<?> getReference() { return this.reference; } /** * Returns the data type with the given primitive/reference class * * @param clazz * Primitive/Reference class of the data type * @return The data type */ public static DataType fromClass(final Class<?> clazz) { return CLASS_MAP.get(clazz); } /** * Returns the primitive class of the data type with the given reference class * * @param clazz * Reference class of the data type * @return The primitive class */ public static Class<?> getPrimitive(final Class<?> clazz) { DataType type = fromClass(clazz); return type == null ? clazz : type.getPrimitive(); } /** * Returns the reference class of the data type with the given primitive class * * @param clazz * Primitive class of the data type * @return The reference class */ public static Class<?> getReference(final Class<?> clazz) { DataType type = fromClass(clazz); return type == null ? clazz : type.getReference(); } /** * Returns the primitive class array of the given class array * * @param classes * Given class array * @return The primitive class array */ public static Class<?>[] getPrimitive(final Class<?>[] classes) { int length = classes == null ? 0 : classes.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getPrimitive(classes[index]); } return types; } /** * Returns the reference class array of the given class array * * @param classes * Given class array * @return The reference class array */ public static Class<?>[] getReference(final Class<?>[] classes) { int length = classes == null ? 0 : classes.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getReference(classes[index]); } return types; } /** * Returns the primitive class array of the given object array * * @param object * Given object array * @return The primitive class array */ public static Class<?>[] getPrimitive(final Object[] objects) { int length = objects == null ? 0 : objects.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getPrimitive(objects[index].getClass()); } return types; } /** * Returns the reference class array of the given object array * * @param object * Given object array * @return The reference class array */ public static Class<?>[] getReference(final Object[] objects) { int length = objects == null ? 0 : objects.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getReference(objects[index].getClass()); } return types; } /** * Compares two class arrays on equivalence * * @param primary * Primary class array * @param secondary * Class array which is compared to the primary array * @return Whether these arrays are equal or not */ public static boolean compare(final Class<?>[] primary, final Class<?>[] secondary) { if (primary == null || secondary == null || primary.length != secondary.length) { return false; } for (int index = 0; index < primary.length; index++) { Class<?> primaryClass = primary[index]; Class<?> secondaryClass = secondary[index]; if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) { continue; } return false; } return true; } } }
34,337
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
InventoryUtils.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/InventoryUtils.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class InventoryUtils { /** * Returns whether inventory (inventory slots, not crafting nor armor slost) is empty. * * @param inv * inventory * @return true if inventory is empty */ public static boolean isEmpty(final Inventory inv) { for (ItemStack is : inv.getContents()) { if (is != null) { return false; } } return true; } }
1,375
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
TimeBomb.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/TimeBomb.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import org.apache.commons.lang.Validate; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.EntityType; public class TimeBomb { private final Block signBlock; private final Block tntBlock; private int timeLeft = 60; private final BukkitTimer timer; public TimeBomb(final Block tntblock, final Block sign, final int timeLeft) { this.timer = new BukkitTimer(20, new Runnable() { @Override public void run() { TimeBomb.this.tick(); } }); this.timer.start(); Validate.notNull(tntblock); Validate.notNull(sign); this.signBlock = sign; this.tntBlock = tntblock; this.timeLeft = timeLeft; Sign s = (Sign) this.signBlock.getState(); s.setLine(0, "===================="); s.setLine(2, "===================="); s.update(); } protected void tick() { this.timeLeft--; this.update(this.timeLeft); } public void update(final int timeLeft) { Sign s = (Sign) this.signBlock.getState(); if (this.timeLeft < 10) { s.setLine(1, ChatColor.RED + "00:" + Formatter.formatTimeLeft(this.timeLeft) + "." + ChatColor.MAGIC + "00"); } else { s.setLine(1, "00:" + Formatter.formatTimeLeft(this.timeLeft) + "." + ChatColor.MAGIC + "00"); } s.update(); if (this.timeLeft <= 0) { this.timer.stop(); this.tntBlock.setType(Material.AIR); this.signBlock.setType(Material.AIR); this.tntBlock.getLocation().getWorld().spawnEntity( this.tntBlock.getLocation(), EntityType.PRIMED_TNT); } } }
2,805
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PacketHelper.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/PacketHelper.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import net.minecraft.server.v1_8_R1.Packet; import org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer; import org.bukkit.entity.Player; /** * Pomocna trieda pouzivana na posielanie pakiet. * */ public class PacketHelper { /** * Posle paketu packet hracovi player. * * @param player * @param packet */ public static void send(final Player player, final Packet packet) { ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); } }
1,368
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ServerLocationType.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/ServerLocationType.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; /** * Different types of server locations. * * @author Mato Kormuth * */ public enum ServerLocationType { /** * Player is in lobby. */ LOBBY, /** * Player is in minigame lobby. */ MINIGAME_LOBBY, /** * Player is in minigame (palying). */ MINIGAME, /** * Player is in quickjoin session. */ QUICKJOIN, /** * Player location unknown. */ UNKNOWN }
1,313
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
BlockPattern.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/BlockPattern.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import org.bukkit.Location; import org.bukkit.material.MaterialData; /** * Class used for detecting block patterns. */ public class BlockPattern { private final MaterialData[][][] pattern; private int anchorX; private int anchorY; private int anchorZ; /** * Creates new instance of BlockPattern with specified MaterialData pattern in x, y, z coordinate order. * * @param pattern * pattern of material data in order [x][y][z] */ public BlockPattern(final MaterialData[][][] pattern) { this.pattern = pattern; } /** * Sets relative locaton of anchor block. * * @param x * x-coordinate * @param y * y-coordinate * @param z * z-coordinate */ public void setAnchor(final int x, final int y, final int z) { this.anchorX = x; this.anchorY = y; this.anchorZ = z; } /** * Checks for match on specified lcoation. * * @param location * location of nachor block * @return <b>true</b> if match found, <b>false</b> otherwise */ public boolean match(final Location location) { for (int x = 0; x < this.pattern.length; x++) { for (int y = 0; y < this.pattern[0].length; y++) { for (int z = 0; z < this.pattern[0][0].length; z++) { int absX = location.getBlockX() - this.anchorX + x; int absY = location.getBlockY() - this.anchorY + y; int absZ = location.getBlockZ() - this.anchorZ + z; if (this.pattern[x][y][z] != null) { if (!location.getWorld().getBlockAt(absX, absY, absZ).equals( this.pattern[x][y][z])) { return false; } } } } } return true; } }
2,889
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
NetworkCCFormatter.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/NetworkCCFormatter.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.arenas.AdvancedArena; import eu.matejkormuth.pexel.PexelCore.chat.ChatManager; /** * Formats and send messages to network (global) chat channel. */ public class NetworkCCFormatter { private static final String SEPARATOR = "|"; public static final int MSG_TYPE_ARENA_CONSTRUCTOR = 0; public static final int MSG_TYPE_ARENA_CD_START = 1; public static final int MSG_TYPE_ARENA_CD_STOP = 2; public static final int MSG_TYPE_ARENA_PLAYERJOIN = 3; public static final int MSG_TYPE_ARENA_PLAYERLEAVE = 4; public static final int MSG_TYPE_ARENA_PLAYERCOUNT = 5; public static final int MSG_TYPE_ARENA_STATE = 6; public static final void sendArenaMsg(final int type, final AdvancedArena arena, final String msg) { ChatManager.CHANNEL_NETWORK.broadcastMessage("ARENA-" + type + NetworkCCFormatter.SEPARATOR + NetworkCCFormatter.formatArena(arena) + NetworkCCFormatter.SEPARATOR + msg); } private static String formatArena(final AdvancedArena arena) { return arena.getName(); } /** * Sends message to network chat channel. * * @param type * type of message - one of MSG_TYPE_* constants from {@link NetworkCCFormatter} * @param arena * arena that executed this send * @param msg * message to send */ public static final void send(final int type, final AdvancedArena arena, final String msg) { NetworkCCFormatter.sendArenaMsg(type, arena, msg); } public static void sendConstructor(final AdvancedArena advancedMinigameArena) { NetworkCCFormatter.sendArenaMsg(MSG_TYPE_ARENA_CONSTRUCTOR, advancedMinigameArena, "Construct"); } public static void sendCDstart(final AdvancedArena advancedMinigameArena) { NetworkCCFormatter.sendArenaMsg(MSG_TYPE_ARENA_CD_START, advancedMinigameArena, Long.toString(System.currentTimeMillis())); } public static void sendCDstop(final AdvancedArena advancedMinigameArena) { NetworkCCFormatter.sendArenaMsg(MSG_TYPE_ARENA_CD_STOP, advancedMinigameArena, Long.toString(System.currentTimeMillis())); } public static void sendPlayerJoin(final AdvancedArena advancedMinigameArena, final Player player) { NetworkCCFormatter.sendArenaMsg(MSG_TYPE_ARENA_PLAYERJOIN, advancedMinigameArena, player.getUniqueId().toString() + "/" + player.getName()); NetworkCCFormatter.send(MSG_TYPE_ARENA_PLAYERCOUNT, advancedMinigameArena, Integer.toString(advancedMinigameArena.getPlayerCount())); } public static void sendPlayerLeft(final AdvancedArena advancedMinigameArena, final Player player) { NetworkCCFormatter.sendArenaMsg(MSG_TYPE_ARENA_PLAYERLEAVE, advancedMinigameArena, player.getUniqueId().toString() + "/" + player.getName()); NetworkCCFormatter.send(MSG_TYPE_ARENA_PLAYERCOUNT, advancedMinigameArena, Integer.toString(advancedMinigameArena.getPlayerCount())); } }
4,209
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
SerializableLocation.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/SerializableLocation.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import org.bukkit.Bukkit; import org.bukkit.Location; /** * Location that is serializable. * * @author Mato Kormuth * */ @XmlAccessorType(XmlAccessType.FIELD) public class SerializableLocation implements Serializable { private static final long serialVersionUID = -7108270886650549653L; @XmlAttribute(name = "x") protected double X; @XmlAttribute(name = "y") protected double Y; @XmlAttribute(name = "z") protected double Z; @XmlAttribute(name = "yaw") protected float yaw; @XmlAttribute(name = "pitch") protected float pitch; @XmlAttribute(name = "world") protected String worldName; private transient Location location; public SerializableLocation(final double x, final double y, final double z, final float yaw, final float pitch, final String worldName) { this.X = x; this.Y = y; this.Z = z; this.yaw = yaw; this.pitch = pitch; this.worldName = worldName; } public SerializableLocation(final Location location) { this.location = location; this.X = location.getX(); this.Y = location.getY(); this.Z = location.getZ(); this.yaw = location.getYaw(); this.pitch = location.getPitch(); this.worldName = location.getWorld().getName(); } public static final SerializableLocation fromLocation(final Location location) { return new SerializableLocation(location); } public Location getLocation() { if (this.location == null) this.create(); return this.location; } private void create() { this.location = new Location(Bukkit.getWorld(this.worldName), this.X, this.Y, this.Z, this.yaw, this.pitch); } }
2,917
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
SoundUtility.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/SoundUtility.java
/** * SoundEffects.java part of mertexfun. by M * * (C) M 26.3.2014 19:17:35 */ package eu.matejkormuth.pexel.PexelCore.util; import net.minecraft.server.v1_8_R1.PacketPlayOutNamedSoundEffect; import org.bukkit.craftbukkit.v1_8_R1.entity.CraftPlayer; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; /** * Trieda, ktora spracovava prehravanie vlastnych zvukovych efektov. * * @author Matej Kormuth * */ public class SoundUtility { //Zvuky. public static final String MUSIC_LOBBY = "music_lobby"; /** * Prehra vlastsny zvuk podla mena. * * @param p * @param soundName * @param volume * @param pitch * @param worldwide */ public static void playCustomSound(final Player p, final String soundName, final float volume, final float pitch, final boolean worldwide) { System.out.println("CustomSound: " + p.getName() + ", " + soundName + ", " + volume + ", " + pitch + ", " + worldwide); if (worldwide) { PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect( soundName, p.getLocation().getX(), p.getLocation().getY(), p.getLocation().getZ(), Float.MAX_VALUE, pitch); ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); } else { PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect( soundName, p.getLocation().getX(), p.getLocation().getY(), p.getLocation().getZ(), volume, pitch); ((CraftPlayer) p).getHandle().playerConnection.sendPacket(packet); } } /** * Prehra vlastny zvuk vsetkym hracom v okoli * * @param player_loc * @param soundName * @param volume * @param pitch */ public static void playCustomSound(final Player player_loc, final String soundName, final float volume, final float pitch) { PacketPlayOutNamedSoundEffect packet2 = new PacketPlayOutNamedSoundEffect( soundName, player_loc.getLocation().getX(), player_loc.getLocation() .getY(), player_loc.getLocation().getZ(), volume, pitch); ((CraftPlayer) player_loc).getHandle().playerConnection.sendPacket(packet2); for (Entity e : player_loc.getNearbyEntities(100, 100, 100)) { if (e instanceof Player) { if (player_loc.getLocation().distanceSquared(e.getLocation()) < 10000) { PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect( soundName, e.getLocation().getX(), e.getLocation().getY(), e.getLocation().getZ(), 1 - (float) (player_loc.getLocation().distanceSquared( e.getLocation()) / 10000) * volume, pitch); ((CraftPlayer) e).getHandle().playerConnection.sendPacket(packet); } } } } /** * @param bj * @param soundName * @param volume * @param pitch */ public static void playCustomSound(final Entity bj, final String soundName, final float volume, final float pitch) { for (Entity e : bj.getNearbyEntities(100, 100, 100)) { if (e instanceof Player) { if (bj.getLocation().distanceSquared(e.getLocation()) < 10000) { PacketPlayOutNamedSoundEffect packet = new PacketPlayOutNamedSoundEffect( soundName, e.getLocation().getX(), e.getLocation().getY(), e.getLocation().getZ(), 1 - (float) (bj.getLocation().distanceSquared( e.getLocation()) / 10000) * volume, pitch); ((CraftPlayer) e).getHandle().playerConnection.sendPacket(packet); } } } } }
4,054
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
AFKChecker.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/AFKChecker.java
package eu.matejkormuth.pexel.PexelCore.util; import java.util.HashMap; import java.util.Map; import org.bukkit.Location; import org.bukkit.entity.Player; import eu.matejkormuth.pexel.PexelCore.core.PlayerHolder; /** * Class that is used for checking when is player AFK. */ public class AFKChecker { private final int time; private final BukkitTimer timer; private final PlayerHolder playerHolder; private final Map<Player, AFKEntry> entries = new HashMap<Player, AFKEntry>(); public AFKChecker(final int seconds, final PlayerHolder playerHolder) { this.time = seconds; this.playerHolder = playerHolder; this.timer = new BukkitTimer(20, new Runnable() { @Override public void run() { AFKChecker.this.check(); } }); this.timer.start(); } protected void check() { long checkTime = System.currentTimeMillis(); for (Player p : this.playerHolder.getPlayers()) { AFKEntry entry = this.entries.get(p); // Check for kicks if (System.currentTimeMillis() > entry.lastMovementTime + this.time) { p.kickPlayer("You were kicked, because you were AFK. If it was during a competitive match, you migth be penalized."); this.entries.remove(p); continue; } else if (!p.isOnline()) { this.entries.remove(p); } // Update last movement if (!entry.lastLoc.equals(p.getLocation())) { entry.lastLoc = p.getLocation(); entry.lastMovementTime = checkTime; } } } public void start() { this.timer.start(); } public void reset() { this.entries.clear(); this.timer.stop(); } public class AFKEntry { public Location lastLoc; public long lastMovementTime; } }
2,051
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ReflectionHandler.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/ReflectionHandler.java
package eu.matejkormuth.pexel.PexelCore.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.bukkit.Bukkit; /** * ReflectionHandler v1.0 * * This class makes dealing with reflection much easier, especially when working with Bukkit * * You are welcome to use it, modify it and redistribute it under the following conditions: 1. Don't claim this class as * your own 2. Don't remove this text * * (Would be nice if you provide credit to me) * * @author DarkBlade12 */ public final class ReflectionHandler { private ReflectionHandler() { } public static Class<?> getClass(final String name, final PackageType type) throws Exception { return Class.forName(type + "." + name); } public static Class<?> getClass(final String name, final SubPackageType type) throws Exception { return Class.forName(type + "." + name); } public static Constructor<?> getConstructor(final Class<?> clazz, final Class<?>... parameterTypes) { Class<?>[] p = DataType.convertToPrimitive(parameterTypes); for (Constructor<?> c : clazz.getConstructors()) if (DataType.equalsArray(DataType.convertToPrimitive(c.getParameterTypes()), p)) return c; return null; } public static Constructor<?> getConstructor(final String className, final PackageType type, final Class<?>... parameterTypes) throws Exception { return getConstructor(getClass(className, type), parameterTypes); } public static Constructor<?> getConstructor(final String className, final SubPackageType type, final Class<?>... parameterTypes) throws Exception { return getConstructor(getClass(className, type), parameterTypes); } public static Object newInstance(final Class<?> clazz, final Object... args) throws Exception { return getConstructor(clazz, DataType.convertToPrimitive(args)).newInstance(args); } public static Object newInstance(final String className, final PackageType type, final Object... args) throws Exception { return newInstance(getClass(className, type), args); } public static Object newInstance(final String className, final SubPackageType type, final Object... args) throws Exception { return newInstance(getClass(className, type), args); } public static Method getMethod(final Class<?> clazz, final String name, final Class<?>... parameterTypes) { Class<?>[] p = DataType.convertToPrimitive(parameterTypes); for (Method m : clazz.getMethods()) if (m.getName().equals(name) && DataType.equalsArray( DataType.convertToPrimitive(m.getParameterTypes()), p)) return m; return null; } public static Method getMethod(final String className, final PackageType type, final String name, final Class<?>... parameterTypes) throws Exception { return getMethod(getClass(className, type), name, parameterTypes); } public static Method getMethod(final String className, final SubPackageType type, final String name, final Class<?>... parameterTypes) throws Exception { return getMethod(getClass(className, type), name, parameterTypes); } public static Object invokeMethod(final String name, final Object instance, final Object... args) throws Exception { return getMethod(instance.getClass(), name, DataType.convertToPrimitive(args)).invoke( instance, args); } public static Object invokeMethod(final Class<?> clazz, final String name, final Object instance, final Object... args) throws Exception { return getMethod(clazz, name, DataType.convertToPrimitive(args)).invoke( instance, args); } public static Object invokeMethod(final String className, final PackageType type, final String name, final Object instance, final Object... args) throws Exception { return invokeMethod(getClass(className, type), name, instance, args); } public static Object invokeMethod(final String className, final SubPackageType type, final String name, final Object instance, final Object... args) throws Exception { return invokeMethod(getClass(className, type), name, instance, args); } public static Field getField(final Class<?> clazz, final String name) throws Exception { Field f = clazz.getField(name); f.setAccessible(true); return f; } public static Field getField(final String className, final PackageType type, final String name) throws Exception { return getField(getClass(className, type), name); } public static Field getField(final String className, final SubPackageType type, final String name) throws Exception { return getField(getClass(className, type), name); } public static Field getDeclaredField(final Class<?> clazz, final String name) throws Exception { Field f = clazz.getDeclaredField(name); f.setAccessible(true); return f; } public static Field getDeclaredField(final String className, final PackageType type, final String name) throws Exception { return getDeclaredField(getClass(className, type), name); } public static Field getDeclaredField(final String className, final SubPackageType type, final String name) throws Exception { return getDeclaredField(getClass(className, type), name); } public static Object getValue(final Object instance, final String fieldName) throws Exception { return getField(instance.getClass(), fieldName).get(instance); } public static Object getValue(final Class<?> clazz, final Object instance, final String fieldName) throws Exception { return getField(clazz, fieldName).get(instance); } public static Object getValue(final String className, final PackageType type, final Object instance, final String fieldName) throws Exception { return getValue(getClass(className, type), instance, fieldName); } public static Object getValue(final String className, final SubPackageType type, final Object instance, final String fieldName) throws Exception { return getValue(getClass(className, type), instance, fieldName); } public static Object getDeclaredValue(final Object instance, final String fieldName) throws Exception { return getDeclaredField(instance.getClass(), fieldName).get(instance); } public static Object getDeclaredValue(final Class<?> clazz, final Object instance, final String fieldName) throws Exception { return getDeclaredField(clazz, fieldName).get(instance); } public static Object getDeclaredValue(final String className, final PackageType type, final Object instance, final String fieldName) throws Exception { return getDeclaredValue(getClass(className, type), instance, fieldName); } public static Object getDeclaredValue(final String className, final SubPackageType type, final Object instance, final String fieldName) throws Exception { return getDeclaredValue(getClass(className, type), instance, fieldName); } public static void setValue(final Object instance, final String fieldName, final Object fieldValue) throws Exception { Field f = getField(instance.getClass(), fieldName); f.set(instance, fieldValue); } public static void setValue(final Object instance, final FieldPair pair) throws Exception { setValue(instance, pair.getName(), pair.getValue()); } public static void setValue(final Class<?> clazz, final Object instance, final String fieldName, final Object fieldValue) throws Exception { Field f = getField(clazz, fieldName); f.set(instance, fieldValue); } public static void setValue(final Class<?> clazz, final Object instance, final FieldPair pair) throws Exception { setValue(clazz, instance, pair.getName(), pair.getValue()); } public static void setValue(final String className, final PackageType type, final Object instance, final String fieldName, final Object fieldValue) throws Exception { setValue(getClass(className, type), instance, fieldName, fieldValue); } public static void setValue(final String className, final PackageType type, final Object instance, final FieldPair pair) throws Exception { setValue(className, type, instance, pair.getName(), pair.getValue()); } public static void setValue(final String className, final SubPackageType type, final Object instance, final String fieldName, final Object fieldValue) throws Exception { setValue(getClass(className, type), instance, fieldName, fieldValue); } public static void setValue(final String className, final SubPackageType type, final Object instance, final FieldPair pair) throws Exception { setValue(className, type, instance, pair.getName(), pair.getValue()); } public static void setValues(final Object instance, final FieldPair... pairs) throws Exception { for (FieldPair pair : pairs) setValue(instance, pair); } public static void setValues(final Class<?> clazz, final Object instance, final FieldPair... pairs) throws Exception { for (FieldPair pair : pairs) setValue(clazz, instance, pair); } public static void setValues(final String className, final PackageType type, final Object instance, final FieldPair... pairs) throws Exception { setValues(getClass(className, type), instance, pairs); } public static void setValues(final String className, final SubPackageType type, final Object instance, final FieldPair... pairs) throws Exception { setValues(getClass(className, type), instance, pairs); } public static void setDeclaredValue(final Object instance, final String fieldName, final Object fieldValue) throws Exception { Field f = getDeclaredField(instance.getClass(), fieldName); f.set(instance, fieldValue); } public static void setDeclaredValue(final Object instance, final FieldPair pair) throws Exception { setDeclaredValue(instance, pair.getName(), pair.getValue()); } public static void setDeclaredValue(final Class<?> clazz, final Object instance, final String fieldName, final Object fieldValue) throws Exception { Field f = getDeclaredField(clazz, fieldName); f.set(instance, fieldValue); } public static void setDeclaredValue(final Class<?> clazz, final Object instance, final FieldPair pair) throws Exception { setDeclaredValue(clazz, instance, pair.getName(), pair.getValue()); } public static void setDeclaredValue(final String className, final PackageType type, final Object instance, final String fieldName, final Object fieldValue) throws Exception { setDeclaredValue(getClass(className, type), instance, fieldName, fieldValue); } public static void setDeclaredValue(final String className, final PackageType type, final Object instance, final FieldPair pair) throws Exception { setDeclaredValue(className, type, instance, pair.getName(), pair.getValue()); } public static void setDeclaredValue(final String className, final SubPackageType type, final Object instance, final String fieldName, final Object fieldValue) throws Exception { setDeclaredValue(getClass(className, type), instance, fieldName, fieldValue); } public static void setDeclaredValue(final String className, final SubPackageType type, final Object instance, final FieldPair pair) throws Exception { setDeclaredValue(className, type, instance, pair.getName(), pair.getValue()); } public static void setDeclaredValues(final Object instance, final FieldPair... pairs) throws Exception { for (FieldPair pair : pairs) setDeclaredValue(instance, pair); } public static void setDeclaredValues(final Class<?> clazz, final Object instance, final FieldPair... pairs) throws Exception { for (FieldPair pair : pairs) setDeclaredValue(clazz, instance, pair); } public static void setDeclaredValues(final String className, final PackageType type, final Object instance, final FieldPair... pairs) throws Exception { setDeclaredValues(getClass(className, type), instance, pairs); } public static void setDeclaredValues(final String className, final SubPackageType type, final Object instance, final FieldPair... pairs) throws Exception { setDeclaredValues(getClass(className, type), instance, pairs); } /** * This class is part of the ReflectionHandler and follows the same usage conditions * * @author DarkBlade12 */ public enum DataType { BYTE(byte.class, Byte.class), SHORT(short.class, Short.class), INTEGER(int.class, Integer.class), LONG(long.class, Long.class), CHARACTER(char.class, Character.class), FLOAT(float.class, Float.class), DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); private static final Map<Class<?>, DataType> CLASS_MAP = new HashMap<Class<?>, DataType>(); private final Class<?> primitive; private final Class<?> reference; static { for (DataType t : values()) { CLASS_MAP.put(t.primitive, t); CLASS_MAP.put(t.reference, t); } } private DataType(final Class<?> primitive, final Class<?> reference) { this.primitive = primitive; this.reference = reference; } public Class<?> getPrimitive() { return this.primitive; } public Class<?> getReference() { return this.reference; } public static DataType fromClass(final Class<?> c) { return CLASS_MAP.get(c); } public static Class<?> getPrimitive(final Class<?> c) { DataType t = fromClass(c); return t == null ? c : t.getPrimitive(); } public static Class<?> getReference(final Class<?> c) { DataType t = fromClass(c); return t == null ? c : t.getReference(); } public static Class<?>[] convertToPrimitive(final Class<?>[] classes) { int length = classes == null ? 0 : classes.length; Class<?>[] types = new Class<?>[length]; for (int i = 0; i < length; i++) types[i] = getPrimitive(classes[i]); return types; } public static Class<?>[] convertToPrimitive(final Object[] objects) { int length = objects == null ? 0 : objects.length; Class<?>[] types = new Class<?>[length]; for (int i = 0; i < length; i++) types[i] = getPrimitive(objects[i].getClass()); return types; } public static boolean equalsArray(final Class<?>[] a1, final Class<?>[] a2) { if (a1 == null || a2 == null || a1.length != a2.length) return false; for (int i = 0; i < a1.length; i++) if (!a1[i].equals(a2[i]) && !a1[i].isAssignableFrom(a2[i])) return false; return true; } } /** * This class is part of the ReflectionHandler and follows the same usage conditions * * @author DarkBlade12 */ public final class FieldPair { private final String name; private final Object value; public FieldPair(final String name, final Object value) { this.name = name; this.value = value; } public String getName() { return this.name; } public Object getValue() { return this.value; } } /** * This class is part of the ReflectionHandler and follows the same usage conditions * * @author DarkBlade12 */ public enum PackageType { MINECRAFT_SERVER("net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().substring(23)), CRAFTBUKKIT(Bukkit.getServer().getClass().getPackage().getName()); private final String name; private PackageType(final String name) { this.name = name; } public String getName() { return this.name; } @Override public String toString() { return this.name; } } /** * This class is part of the ReflectionHandler and follows the same usage conditions * * @author DarkBlade12 */ public enum SubPackageType { BLOCK, CHUNKIO, COMMAND, CONVERSATIONS, ENCHANTMENS, ENTITY, EVENT, GENERATOR, HELP, INVENTORY, MAP, METADATA, POTION, PROJECTILES, SCHEDULER, SCOREBOARD, UPDATER, UTIL; private final String name; private SubPackageType() { this.name = PackageType.CRAFTBUKKIT + "." + this.name().toLowerCase(); } public String getName() { return this.name; } @Override public String toString() { return this.name; } } /** * This class is part of the ReflectionHandler and follows the same usage conditions * * @author DarkBlade12 */ public enum PacketType { HANDSHAKING_IN_SET_PROTOCOL("PacketHandshakingInSetProtocol"), LOGIN_IN_ENCRYPTION_BEGIN("PacketLoginInEncryptionBegin"), LOGIN_IN_START("PacketLoginInStart"), LOGIN_OUT_DISCONNECT("PacketLoginOutDisconnect"), LOGIN_OUT_ENCRYPTION_BEGIN("PacketLoginOutEncryptionBegin"), LOGIN_OUT_SUCCESS("PacketLoginOutSuccess"), PLAY_IN_ABILITIES("PacketPlayInAbilities"), PLAY_IN_ARM_ANIMATION("PacketPlayInArmAnimation"), PLAY_IN_BLOCK_DIG("PacketPlayInBlockDig"), PLAY_IN_BLOCK_PLACE("PacketPlayInBlockPlace"), PLAY_IN_CHAT("PacketPlayInChat"), PLAY_IN_CLIENT_COMMAND("PacketPlayInClientCommand"), PLAY_IN_CLOSE_WINDOW("PacketPlayInCloseWindow"), PLAY_IN_CUSTOM_PAYLOAD("PacketPlayInCustomPayload"), PLAY_IN_ENCHANT_ITEM("PacketPlayInEnchantItem"), PLAY_IN_ENTITY_ACTION("PacketPlayInEntityAction"), PLAY_IN_FLYING("PacketPlayInFlying"), PLAY_IN_HELD_ITEM_SLOT("PacketPlayInHeldItemSlot"), PLAY_IN_KEEP_ALIVE("PacketPlayInKeepAlive"), PLAY_IN_LOOK("PacketPlayInLook"), PLAY_IN_POSITION("PacketPlayInPosition"), PLAY_IN_POSITION_LOOK("PacketPlayInPositionLook"), PLAY_IN_SET_CREATIVE_SLOT("PacketPlayInSetCreativeSlot "), PLAY_IN_SETTINGS("PacketPlayInSettings"), PLAY_IN_STEER_VEHICLE("PacketPlayInSteerVehicle"), PLAY_IN_TAB_COMPLETE("PacketPlayInTabComplete"), PLAY_IN_TRANSACTION("PacketPlayInTransaction"), PLAY_IN_UPDATE_SIGN("PacketPlayInUpdateSign"), PLAY_IN_USE_ENTITY("PacketPlayInUseEntity"), PLAY_IN_WINDOW_CLICK("PacketPlayInWindowClick"), PLAY_OUT_ABILITIES("PacketPlayOutAbilities"), PLAY_OUT_ANIMATION("PacketPlayOutAnimation"), PLAY_OUT_ATTACH_ENTITY("PacketPlayOutAttachEntity"), PLAY_OUT_BED("PacketPlayOutBed"), PLAY_OUT_BLOCK_ACTION("PacketPlayOutBlockAction"), PLAY_OUT_BLOCK_BREAK_ANIMATION("PacketPlayOutBlockBreakAnimation"), PLAY_OUT_BLOCK_CHANGE("PacketPlayOutBlockChange"), PLAY_OUT_CHAT("PacketPlayOutChat"), PLAY_OUT_CLOSE_WINDOW("PacketPlayOutCloseWindow"), PLAY_OUT_COLLECT("PacketPlayOutCollect"), PLAY_OUT_CRAFT_PROGRESS_BAR("PacketPlayOutCraftProgressBar"), PLAY_OUT_CUSTOM_PAYLOAD("PacketPlayOutCustomPayload"), PLAY_OUT_ENTITY("PacketPlayOutEntity"), PLAY_OUT_ENTITY_DESTROY("PacketPlayOutEntityDestroy"), PLAY_OUT_ENTITY_EFFECT("PacketPlayOutEntityEffect"), PLAY_OUT_ENTITY_EQUIPMENT("PacketPlayOutEntityEquipment"), PLAY_OUT_ENTITY_HEAD_ROTATION("PacketPlayOutEntityHeadRotation"), PLAY_OUT_ENTITY_LOOK("PacketPlayOutEntityLook"), PLAY_OUT_ENTITY_METADATA("PacketPlayOutEntityMetadata"), PLAY_OUT_ENTITY_STATUS("PacketPlayOutEntityStatus"), PLAY_OUT_ENTITY_TELEPORT("PacketPlayOutEntityTeleport"), PLAY_OUT_ENTITY_VELOCITY("PacketPlayOutEntityVelocity"), PLAY_OUT_EXPERIENCE("PacketPlayOutExperience"), PLAY_OUT_EXPLOSION("PacketPlayOutExplosion"), PLAY_OUT_GAME_STATE_CHANGE("PacketPlayOutGameStateChange"), PLAY_OUT_HELD_ITEM_SLOT("PacketPlayOutHeldItemSlot"), PLAY_OUT_KEEP_ALIVE("PacketPlayOutKeepAlive"), PLAY_OUT_KICK_DISCONNECT("PacketPlayOutKickDisconnect"), PLAY_OUT_LOGIN("PacketPlayOutLogin"), PLAY_OUT_MAP("PacketPlayOutMap"), PLAY_OUT_MAP_CHUNK("PacketPlayOutMapChunk"), PLAY_OUT_MAP_CHUNK_BULK("PacketPlayOutMapChunkBulk"), PLAY_OUT_MULTI_BLOCK_CHANGE("PacketPlayOutMultiBlockChange"), PLAY_OUT_NAMED_ENTITY_SPAWN("PacketPlayOutNamedEntitySpawn"), PLAY_OUT_NAMED_SOUND_EFFECT("PacketPlayOutNamedSoundEffect"), PLAY_OUT_OPEN_SIGN_EDITOR("PacketPlayOutOpenSignEditor"), PLAY_OUT_OPEN_WINDOW("PacketPlayOutOpenWindow"), PLAY_OUT_PLAYER_INFO("PacketPlayOutPlayerInfo"), PLAY_OUT_POSITION("PacketPlayOutPosition"), PLAY_OUT_REL_ENTITY_MOVE("PacketPlayOutRelEntityMove"), PLAY_OUT_REL_ENTITY_MOVE_LOOK("PacketPlayOutRelEntityMoveLook"), PLAY_OUT_REMOVE_ENTITY_EFFECT("PacketPlayOutRemoveEntityEffect"), PLAY_OUT_RESPAWN("PacketPlayOutRespawn"), PLAY_OUT_SCOREBOARD_DISPLAY_OBJECTIVE("PacketPlayOutScoreboardDisplayObjective"), PLAY_OUT_SCOREBOARD_OBJECTIVE("PacketPlayOutScoreboardObjective"), PLAY_OUT_SCOREBOARD_SCORE("PacketPlayOutScoreboardScore"), PLAY_OUT_SCOREBOARD_TEAM("PacketPlayOutScoreboardTeam"), PLAY_OUT_SET_SLOT("PacketPlayOutSetSlot"), PLAY_OUT_SPAWN_ENTITY("PacketPlayOutSpawnEntity"), PLAY_OUT_SPAWN_ENTITY_EXPERIENCE_ORB("PacketPlayOutSpawnEntityExperienceOrb"), PLAY_OUT_SPAWN_ENTITY_LIVING("PacketPlayOutSpawnEntityLiving"), PLAY_OUT_SPAWN_ENTITY_PAINTING("PacketPlayOutSpawnEntityPainting"), PLAY_OUT_SPAWN_ENTITY_WEATHER("PacketPlayOutSpawnEntityWeather"), PLAY_OUT_SPAWN_POSITION("PacketPlayOutSpawnPosition"), PLAY_OUT_STATISTIC("PacketPlayOutStatistic"), PLAY_OUT_TAB_COMPLETE("PacketPlayOutTabComplete"), PLAY_OUT_TILE_ENTITY_DATA("PacketPlayOutTileEntityData"), PLAY_OUT_TRANSACTION("PacketPlayOutTransaction"), PLAY_OUT_UPDATE_ATTRIBUTES("PacketPlayOutUpdateAttributes"), PLAY_OUT_UPDATE_HEALTH("PacketPlayOutUpdateHealth"), PLAY_OUT_UPDATE_SIGN("PacketPlayOutUpdateSign"), PLAY_OUT_UPDATE_TIME("PacketPlayOutUpdateTime"), PLAY_OUT_WINDOW_ITEMS("PacketPlayOutWindowItems"), PLAY_OUT_WORLD_EVENT("PacketPlayOutWorldEvent"), PLAY_OUT_WORLD_PARTICLES("PacketPlayOutWorldParticles"), STATUS_IN_PING("PacketStatusInPing"), STATUS_IN_START("PacketStatusInStart"), STATUS_OUT_PONG("PacketStatusOutPong"), STATUS_OUT_SERVER_INFO("PacketStatusOutServerInfo"); private final String name; private Class<?> packet; private PacketType(final String name) { this.name = name; } public String getName() { return this.name(); } public Class<?> getPacket() throws Exception { return this.packet == null ? this.packet = ReflectionHandler.getClass( this.name, PackageType.MINECRAFT_SERVER) : this.packet; } } }
25,295
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Formatter.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/Formatter.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; /** * Class that formats some things. */ public class Formatter { /** * Returns formatter time in format mm:ss from provided time left. * * @param secondsLeft * seconds to format * @return formatted time */ public static String formatTimeLeft(final int secondsLeft) { int minutes = secondsLeft / 60; int seconds = secondsLeft % 60; return String.format("%02d:%02d", minutes, seconds); } }
1,341
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
BukkitTimer.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/BukkitTimer.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import eu.matejkormuth.pexel.PexelCore.Pexel; /** * Timer implemented over bukkit tasks. */ public class BukkitTimer { private final int interval; private int taskId; private final Runnable onTick; public BukkitTimer(final int interval, final Runnable onTick) { this.interval = interval; this.onTick = onTick; } public boolean isRunning() { return this.taskId == 0; } public void start() { this.taskId = Pexel.getScheduler().scheduleSyncRepeatingTask(this.onTick, 0L, this.interval); } public void stop() { Pexel.getScheduler().cancelTask(this.taskId); this.taskId = 0; } }
1,593
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ParticleEffect2.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/ParticleEffect2.java
package eu.matejkormuth.pexel.PexelCore.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import eu.matejkormuth.pexel.PexelCore.util.ReflectionUtil.PackageType; /** * <b>ParticleEffect Library</b> * <p> * This library was created by @DarkBlade12 and allows you to display all Minecraft particle effects on a Bukkit server * <p> * You are welcome to use it, modify it and redistribute it under the following conditions: * <ul> * <li>Don't claim this class as your own * <li>Don't remove this disclaimer * </ul> * <p> * Special thanks: * <ul> * <li>@microgeek (original idea, names and packet parameters) * <li>@ShadyPotato (1.8 names, ids and packet parameters) * <li>@RingOfStorms (specific particle direction) * </ul> * <p> * <i>It would be nice if you provide credit to me if you use this class in a published project</i> * * @author DarkBlade12 * @version 1.6 */ public enum ParticleEffect2 { /** * A particle effect which is displayed by exploding tnt and creepers: * <ul> * <li>It looks like a white cloud * <li>The speed value influences the velocity at which the particle flies off * </ul> */ EXPLOSION_NORMAL("explode", 0, -1), /** * A particle effect which is displayed by exploding ghast fireballs and wither skulls: * <ul> * <li>It looks like a gray ball which is fading away * <li>The speed value slightly influences the size of this particle effect * </ul> */ EXPLOSION_LARGE("largeexplode", 1, -1), /** * A particle effect which is displayed by exploding tnt and creepers: * <ul> * <li>It looks like a crowd of gray balls which are fading away * <li>The speed value has no influence on this particle effect * </ul> */ EXPLOSION_HUGE("hugeexplosion", 2, -1), /** * A particle effect which is displayed by launching fireworks: * <ul> * <li>It looks like a white star which is sparkling * <li>The speed value influences the velocity at which the particle flies off * </ul> */ FIREWORKS_SPARK("fireworksSpark", 3, -1), /** * A particle effect which is displayed by swimming entities and arrows in water: * <ul> * <li>It looks like a bubble * <li>The speed value influences the velocity at which the particle flies off * </ul> */ WATER_BUBBLE("bubble", 4, -1, false, true), /** * A particle effect which is displayed by swimming entities and shaking wolves: * <ul> * <li>It looks like a blue drop * <li>The speed value has no influence on this particle effect * </ul> */ WATER_SPLASH("splash", 5, -1), /** * A particle effect which is displayed on water when fishing: * <ul> * <li>It looks like a blue droplet * <li>The speed value influences the velocity at which the particle flies off * </ul> */ WATER_WAKE("wake", 6, 7), /** * A particle effect which is displayed by water: * <ul> * <li>It looks like a tiny blue square * <li>The speed value has no influence on this particle effect * </ul> */ SUSPENDED("suspended", 7, -1, false, true), /** * A particle effect which is displayed by air when close to bedrock and the in the void: * <ul> * <li>It looks like a tiny gray square * <li>The speed value has no influence on this particle effect * </ul> */ SUSPENDED_DEPTH("depthSuspend", 8, -1), /** * A particle effect which is displayed when landing a critical hit and by arrows: * <ul> * <li>It looks like a light brown cross * <li>The speed value influences the velocity at which the particle flies off * </ul> */ CRIT("crit", 9, -1), /** * A particle effect which is displayed when landing a hit with an enchanted weapon: * <ul> * <li>It looks like a cyan star * <li>The speed value influences the velocity at which the particle flies off * </ul> */ CRIT_MAGIC("magicCrit", 10, -1), /** * A particle effect which is displayed by primed tnt, torches, droppers, dispensers, end portals, brewing stands * and monster spawners: * <ul> * <li>It looks like a little gray cloud * <li>The speed value influences the velocity at which the particle flies off * </ul> */ SMOKE_NORMAL("smoke", 11, -1), /** * A particle effect which is displayed by fire, minecarts with furnace and blazes: * <ul> * <li>It looks like a large gray cloud * <li>The speed value influences the velocity at which the particle flies off * </ul> */ SMOKE_LARGE("largesmoke", 12, -1), /** * A particle effect which is displayed when splash potions or bottles o' enchanting hit something: * <ul> * <li>It looks like a white swirl * <li>The speed value causes the particle to only move upwards when set to 0 * </ul> */ SPELL("spell", 13, -1), /** * A particle effect which is displayed when instant splash potions hit something: * <ul> * <li>It looks like a white cross * <li>The speed value causes the particle to only move upwards when set to 0 * </ul> */ SPELL_INSTANT("instantSpell", 14, -1), /** * A particle effect which is displayed by entities with active potion effects: * <ul> * <li>It looks like a colored swirl * <li>The speed value causes the particle to be colored black when set to 0 * <li>The particle color gets lighter when increasing the speed and darker when decreasing the speed * </ul> */ SPELL_MOB("mobSpell", 15, -1), /** * A particle effect which is displayed by entities with active potion effects applied through a beacon: * <ul> * <li>It looks like a transparent colored swirl * <li>The speed value causes the particle to be always colored black when set to 0 * <li>The particle color gets lighter when increasing the speed and darker when decreasing the speed * </ul> */ SPELL_MOB_AMBIENT("mobSpellAmbient", 16, -1), /** * A particle effect which is displayed by witches: * <ul> * <li>It looks like a purple cross * <li>The speed value causes the particle to only move upwards when set to 0 * </ul> */ SPELL_WITCH("witchMagic", 17, -1), /** * A particle effect which is displayed by blocks beneath a water source: * <ul> * <li>It looks like a blue drip * <li>The speed value has no influence on this particle effect * </ul> */ DRIP_WATER("dripWater", 18, -1), /** * A particle effect which is displayed by blocks beneath a lava source: * <ul> * <li>It looks like an orange drip * <li>The speed value has no influence on this particle effect * </ul> */ DRIP_LAVA("dripLava", 19, -1), /** * A particle effect which is displayed when attacking a villager in a village: * <ul> * <li>It looks like a cracked gray heart * <li>The speed value has no influence on this particle effect * </ul> */ VILLAGER_ANGRY("angryVillager", 20, -1), /** * A particle effect which is displayed when using bone meal and trading with a villager in a village: * <ul> * <li>It looks like a green star * <li>The speed value has no influence on this particle effect * </ul> */ VILLAGER_HAPPY("happyVillager", 21, -1), /** * A particle effect which is displayed by mycelium: * <ul> * <li>It looks like a tiny gray square * <li>The speed value has no influence on this particle effect * </ul> */ TOWN_AURA("townaura", 22, -1), /** * A particle effect which is displayed by note blocks: * <ul> * <li>It looks like a colored note * <li>The speed value causes the particle to be colored green when set to 0 * </ul> */ NOTE("note", 23, -1), /** * A particle effect which is displayed by nether portals, endermen, ender pearls, eyes of ender, ender chests and * dragon eggs: * <ul> * <li>It looks like a purple cloud * <li>The speed value influences the spread of this particle effect * </ul> */ PORTAL("portal", 24, -1), /** * A particle effect which is displayed by enchantment tables which are nearby bookshelves: * <ul> * <li>It looks like a cryptic white letter * <li>The speed value influences the spread of this particle effect * </ul> */ ENCHANTMENT_TABLE("enchantmenttable", 25, -1), /** * A particle effect which is displayed by torches, active furnaces, magma cubes and monster spawners: * <ul> * <li>It looks like a tiny flame * <li>The speed value influences the velocity at which the particle flies off * </ul> */ FLAME("flame", 26, -1), /** * A particle effect which is displayed by lava: * <ul> * <li>It looks like a spark * <li>The speed value has no influence on this particle effect * </ul> */ LAVA("lava", 27, -1), /** * A particle effect which is currently unused: * <ul> * <li>It looks like a transparent gray square * <li>The speed value has no influence on this particle effect * </ul> */ FOOTSTEP("footstep", 28, -1), /** * A particle effect which is displayed when a mob dies: * <ul> * <li>It looks like a large white cloud * <li>The speed value influences the velocity at which the particle flies off * </ul> */ CLOUD("cloud", 29, -1), /** * A particle effect which is displayed by redstone ore, powered redstone, redstone torches and redstone repeaters: * <ul> * <li>It looks like a tiny colored cloud * <li>The speed value causes the particle to be colored red when set to 0 * </ul> */ REDSTONE("reddust", 30, -1), /** * A particle effect which is displayed when snowballs hit a block: * <ul> * <li>It looks like a little piece with the snowball texture * <li>The speed value has no influence on this particle effect * </ul> */ SNOWBALL("snowballpoof", 31, -1), /** * A particle effect which is currently unused: * <ul> * <li>It looks like a tiny white cloud * <li>The speed value influences the velocity at which the particle flies off * </ul> */ SNOW_SHOVEL("snowshovel", 32, -1), /** * A particle effect which is displayed by slimes: * <ul> * <li>It looks like a tiny part of the slimeball icon * <li>The speed value has no influence on this particle effect * </ul> */ SLIME("slime", 33, -1), /** * A particle effect which is displayed when breeding and taming animals: * <ul> * <li>It looks like a red heart * <li>The speed value has no influence on this particle effect * </ul> */ HEART("heart", 34, -1), /** * A particle effect which is displayed by barriers: * <ul> * <li>It looks like a red box with a slash through it * <li>The speed value has no influence on this particle effect * </ul> */ BARRIER("barrier", 35, 8), /** * A particle effect which is displayed when breaking a tool or eggs hit a block: * <ul> * <li>It looks like a little piece with an item texture * </ul> */ ITEM_CRACK("iconcrack", 36, -1, true), /** * A particle effect which is displayed when breaking blocks or sprinting: * <ul> * <li>It looks like a little piece with a block texture * <li>The speed value has no influence on this particle effect * </ul> */ BLOCK_CRACK("blockcrack", 37, -1, true), /** * A particle effect which is displayed when falling: * <ul> * <li>It looks like a little piece with a block texture * </ul> */ BLOCK_DUST("blockdust", 38, 7, true), /** * A particle effect which is displayed when rain hits the ground: * <ul> * <li>It looks like a blue droplet * <li>The speed value has no influence on this particle effect * </ul> */ WATER_DROP("droplet", 39, 8), /** * A particle effect which is currently unused: * <ul> * <li>It has no visual effect * </ul> */ ITEM_TAKE("take", 40, 8), /** * A particle effect which is displayed by elder guardians: * <ul> * <li>It looks like the shape of the elder guardian * <li>The speed value has no influence on this particle effect * </ul> */ MOB_APPEARANCE("mobappearance", 41, 8); private static final Map<String, ParticleEffect2> NAME_MAP = new HashMap<String, ParticleEffect2>(); private static final Map<Integer, ParticleEffect2> ID_MAP = new HashMap<Integer, ParticleEffect2>(); private final String name; private final int id; private final int requiredVersion; private final boolean requiresData; private final boolean requiresWater; // Initialize map for quick name and id lookup static { for (ParticleEffect2 effect : values()) { NAME_MAP.put(effect.name, effect); ID_MAP.put(effect.id, effect); } } /** * Construct a new particle effect * * @param name * Name of this particle effect * @param id * Id of this particle effect * @param requiredVersion * Version which is required (1.x) * @param requiresData * Indicates whether additional data is required for this particle effect * @param requiresWater * Indicates whether water is required for this particle effect to display properly */ private ParticleEffect2(final String name, final int id, final int requiredVersion, final boolean requiresData, final boolean requiresWater) { this.name = name; this.id = id; this.requiredVersion = requiredVersion; this.requiresData = requiresData; this.requiresWater = requiresWater; } /** * Construct a new particle effect with {@link #requiresWater} set to <code>false</code> * * @param name * Name of this particle effect * @param id * Id of this particle effect * @param requiredVersion * Version which is required (1.x) * @param requiresData * Indicates whether additional data is required for this particle effect * @see #ParticleEffect(String, int, boolean, boolean) */ private ParticleEffect2(final String name, final int id, final int requiredVersion, final boolean requiresData) { this(name, id, requiredVersion, requiresData, false); } /** * Construct a new particle effect with {@link #requiresData} and {@link #requiresWater} set to <code>false</code> * * @param name * Name of this particle effect * @param id * Id of this particle effect * @param requiredVersion * Version which is required (1.x) * @param requiresData * Indicates whether additional data is required for this particle effect * @see #ParticleEffect(String, int, boolean) */ private ParticleEffect2(final String name, final int id, final int requiredVersion) { this(name, id, requiredVersion, false); } /** * Returns the name of this particle effect * * @return The name */ public String getName() { return this.name; } /** * Returns the id of this particle effect * * @return The id */ public int getId() { return this.id; } /** * Returns the required version for this particle effect (1.x) * * @return The required version */ public int getRequiredVersion() { return this.requiredVersion; } /** * Determine if additional data is required for this particle effect * * @return Whether additional data is required or not */ public boolean getRequiresData() { return this.requiresData; } /** * Determine if water is required for this particle effect to display properly * * @return Whether water is required or not */ public boolean getRequiresWater() { return this.requiresWater; } /** * Determine if this particle effect is supported by your current server version * * @return Whether the particle effect is supported or not */ public boolean isSupported() { if (this.requiredVersion == -1) { return true; } return ParticlePacket.getVersion() >= this.requiredVersion; } /** * Returns the particle effect with the given name * * @param name * Name of the particle effect * @return The particle effect */ public static ParticleEffect2 fromName(final String name) { for (Entry<String, ParticleEffect2> entry : NAME_MAP.entrySet()) { if (!entry.getKey().equalsIgnoreCase(name)) { continue; } return entry.getValue(); } return null; } /** * Returns the particle effect with the given id * * @param id * Id of the particle effect * @return The particle effect */ public static ParticleEffect2 fromId(final int id) { for (Entry<Integer, ParticleEffect2> entry : ID_MAP.entrySet()) { if (entry.getKey() != id) { continue; } return entry.getValue(); } return null; } /** * Determine if water is at a certain location * * @param location * Location to check * @return Whether water is at this location or not */ private static boolean isWater(final Location location) { Material material = location.getBlock().getType(); return material == Material.WATER || material == Material.STATIONARY_WATER; } /** * Determine if the distance between @param location and one of the players exceeds 256 * * @param location * Location to check * @return Whether the distance exceeds 256 or not */ private static boolean isLongDistance(final Location location, final List<Player> players) { for (Player player : players) { if (player.getLocation().distanceSquared(location) < 65536) { continue; } return true; } return false; } /** * Determine if the data type for a particle effect is correct * * @param effect * Particle effect * @param data * Particle data * @return Whether the data type is correct or not */ private static boolean isDataCorrect(final ParticleEffect2 effect, final ParticleData data) { return ((effect == BLOCK_CRACK || effect == BLOCK_DUST) && data instanceof BlockData) || effect == ITEM_CRACK && data instanceof ItemData; } /** * Displays a particle effect which is only visible for all players within a certain range in the world of @param * center * * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param center * Center location of the effect * @param range * Range of the visibility * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect requires additional data * @throws IllegalArgumentException * If the particle effect requires water and none is at the center location * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ public void display(final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (this.requiresData) { throw new ParticleDataException( "This particle effect requires additional data"); } if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException( "There is no water at the center location"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, null).sendTo(center, range); } /** * Displays a particle effect which is only visible for the specified players * * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect requires additional data * @throws IllegalArgumentException * If the particle effect requires water and none is at the center location * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ public void display(final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final List<Player> players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (this.requiresData) { throw new ParticleDataException( "This particle effect requires additional data"); } if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException( "There is no water at the center location"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players); } /** * Displays a particle effect which is only visible for the specified players * * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect requires additional data * @throws IllegalArgumentException * If the particle effect requires water and none is at the center location * @see #display(float, float, float, float, int, Location, List) */ public void display(final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { this.display(offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); } /** * Displays a single particle which flies into a determined direction and is only visible for all players within a * certain range in the world of @param center * * @param direction * Direction of the particle * @param speed * Display speed of the particle * @param center * Center location of the effect * @param range * Range of the visibility * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect requires additional data * @throws IllegalArgumentException * If the particle effect requires water and none is at the center location * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ public void display(final Vector direction, final float speed, final Location center, final double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (this.requiresData) { throw new ParticleDataException( "This particle effect requires additional data"); } if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException( "There is no water at the center location"); } new ParticlePacket(this, direction, speed, range > 256, null).sendTo(center, range); } /** * Displays a single particle which flies into a determined direction and is only visible for the specified players * * @param direction * Direction of the particle * @param speed * Display speed of the particle * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect requires additional data * @throws IllegalArgumentException * If the particle effect requires water and none is at the center location * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ public void display(final Vector direction, final float speed, final Location center, final List<Player> players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (this.requiresData) { throw new ParticleDataException( "This particle effect requires additional data"); } if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException( "There is no water at the center location"); } new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo( center, players); } /** * Displays a single particle which flies into a determined direction and is only visible for the specified players * * @param direction * Direction of the particle * @param speed * Display speed of the particle * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect requires additional data * @throws IllegalArgumentException * If the particle effect requires water and none is at the center location * @see #display(Vector, float, Location, List) */ public void display(final Vector direction, final float speed, final Location center, final Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { this.display(direction, speed, center, Arrays.asList(players)); } /** * Displays a particle effect which requires additional data and is only visible for all players within a certain * range in the world of @param center * * @param data * Data of the effect * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param center * Center location of the effect * @param range * Range of the visibility * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect does not require additional data or if the data type is incorrect * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ public void display(final ParticleData data, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final double range) throws ParticleVersionException, ParticleDataException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (!this.requiresData) { throw new ParticleDataException( "This particle effect does not require additional data"); } if (!isDataCorrect(this, data)) { throw new ParticleDataException( "The particle data type is incorrect"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); } /** * Displays a particle effect which requires additional data and is only visible for the specified players * * @param data * Data of the effect * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect does not require additional data or if the data type is incorrect * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ public void display(final ParticleData data, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final List<Player> players) throws ParticleVersionException, ParticleDataException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (!this.requiresData) { throw new ParticleDataException( "This particle effect does not require additional data"); } if (!isDataCorrect(this, data)) { throw new ParticleDataException( "The particle data type is incorrect"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players); } /** * Displays a particle effect which requires additional data and is only visible for the specified players * * @param data * Data of the effect * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect does not require additional data or if the data type is incorrect * @see #display(ParticleData, float, float, float, float, int, Location, List) */ public void display(final ParticleData data, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final Player... players) throws ParticleVersionException, ParticleDataException { this.display(data, offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); } /** * Displays a single particle which requires additional data that flies into a determined direction and is only * visible for all players within a certain range in the world of @param center * * @param data * Data of the effect * @param direction * Direction of the particle * @param speed * Display speed of the particles * @param center * Center location of the effect * @param range * Range of the visibility * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect does not require additional data or if the data type is incorrect * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ public void display(final ParticleData data, final Vector direction, final float speed, final Location center, final double range) throws ParticleVersionException, ParticleDataException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (!this.requiresData) { throw new ParticleDataException( "This particle effect does not require additional data"); } if (!isDataCorrect(this, data)) { throw new ParticleDataException( "The particle data type is incorrect"); } new ParticlePacket(this, direction, speed, range > 256, data).sendTo(center, range); } /** * Displays a single particle which requires additional data that flies into a determined direction and is only * visible for the specified players * * @param data * Data of the effect * @param direction * Direction of the particle * @param speed * Display speed of the particles * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect does not require additional data or if the data type is incorrect * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ public void display(final ParticleData data, final Vector direction, final float speed, final Location center, final List<Player> players) throws ParticleVersionException, ParticleDataException { if (!this.isSupported()) { throw new ParticleVersionException( "This particle effect is not supported by your server version"); } if (!this.requiresData) { throw new ParticleDataException( "This particle effect does not require additional data"); } if (!isDataCorrect(this, data)) { throw new ParticleDataException( "The particle data type is incorrect"); } new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo( center, players); } /** * Displays a single particle which requires additional data that flies into a determined direction and is only * visible for the specified players * * @param data * Data of the effect * @param direction * Direction of the particle * @param speed * Display speed of the particles * @param center * Center location of the effect * @param players * Receivers of the effect * @throws ParticleVersionException * If the particle effect is not supported by the server version * @throws ParticleDataException * If the particle effect does not require additional data or if the data type is incorrect * @see #display(ParticleData, Vector, float, Location, List) */ public void display(final ParticleData data, final Vector direction, final float speed, final Location center, final Player... players) throws ParticleVersionException, ParticleDataException { this.display(data, direction, speed, center, Arrays.asList(players)); } /** * Represents the particle data for effects like {@link ParticleEffect2#ITEM_CRACK}, * {@link ParticleEffect2#BLOCK_CRACK} and {@link ParticleEffect2#BLOCK_DUST} * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.6 */ public static abstract class ParticleData { private final Material material; private final byte data; private final int[] packetData; /** * Construct a new particle data * * @param material * Material of the item/block * @param data * Data value of the item/block */ @SuppressWarnings("deprecation") public ParticleData(final Material material, final byte data) { this.material = material; this.data = data; this.packetData = new int[] { material.getId(), data }; } /** * Returns the material of this data * * @return The material */ public Material getMaterial() { return this.material; } /** * Returns the data value of this data * * @return The data value */ public byte getData() { return this.data; } /** * Returns the data as an int array for packet construction * * @return The data for the packet */ public int[] getPacketData() { return this.packetData; } /** * Returns the data as a string for pre 1.8 versions * * @return The data string for the packet */ public String getPacketDataString() { return "_" + this.packetData[0] + "_" + this.packetData[1]; } } /** * Represents the item data for the {@link ParticleEffect2#ITEM_CRACK} effect * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.6 */ public static final class ItemData extends ParticleData { /** * Construct a new item data * * @param material * Material of the item * @param data * Data value of the item * @see ParticleData#ParticleData(Material, byte) */ public ItemData(final Material material, final byte data) { super(material, data); } } /** * Represents the block data for the {@link ParticleEffect2#BLOCK_CRACK} and {@link ParticleEffect2#BLOCK_DUST} * effects * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.6 */ public static final class BlockData extends ParticleData { /** * Construct a new block data * * @param material * Material of the block * @param data * Data value of the block * @throws IllegalArgumentException * If the material is not a block * @see ParticleData#ParticleData(Material, byte) */ public BlockData(final Material material, final byte data) throws IllegalArgumentException { super(material, data); if (!material.isBlock()) { throw new IllegalArgumentException( "The material is not a block"); } } } /** * Represents a runtime exception that is thrown either if the displayed particle effect requires data and has none * or vice-versa or if the data type is wrong * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.6 */ private static final class ParticleDataException extends RuntimeException { private static final long serialVersionUID = 3203085387160737484L; /** * Construct a new particle data exception * * @param message * Message that will be logged * @param cause * Cause of the exception */ public ParticleDataException(final String message) { super(message); } } /** * Represents a runtime exception that is thrown if the displayed particle effect requires a newer version * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.6 */ private static final class ParticleVersionException extends RuntimeException { private static final long serialVersionUID = 3203085387160737484L; /** * Construct a new particle version exception * * @param message * Message that will be logged * @param cause * Cause of the exception */ public ParticleVersionException(final String message) { super(message); } } /** * Represents a particle effect packet with all attributes which is used for sending packets to the players * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.5 */ public static final class ParticlePacket { private static int version; private static Class<?> enumParticle; private static Constructor<?> packetConstructor; private static Method getHandle; private static Field playerConnection; private static Method sendPacket; private static boolean initialized; private final ParticleEffect2 effect; private final float offsetX; private final float offsetY; private final float offsetZ; private final float speed; private final int amount; private final boolean longDistance; private final ParticleData data; private Object packet; /** * Construct a new particle packet * * @param effect * Particle effect * @param offsetX * Maximum distance particles can fly away from the center on the x-axis * @param offsetY * Maximum distance particles can fly away from the center on the y-axis * @param offsetZ * Maximum distance particles can fly away from the center on the z-axis * @param speed * Display speed of the particles * @param amount * Amount of particles * @param longDistance * Indicates whether the maximum distance is increased from 256 to 65536 * @param data * Data of the effect * @throws IllegalArgumentException * If the speed is lower than 0 or the amount is lower than 1 * @see #initialize() */ public ParticlePacket(final ParticleEffect2 effect, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final boolean longDistance, final ParticleData data) throws IllegalArgumentException { initialize(); if (speed < 0) { throw new IllegalArgumentException( "The speed is lower than 0"); } if (amount < 1) { throw new IllegalArgumentException( "The amount is lower than 1"); } this.effect = effect; this.offsetX = offsetX; this.offsetY = offsetY; this.offsetZ = offsetZ; this.speed = speed; this.amount = amount; this.longDistance = longDistance; this.data = data; } /** * Construct a new particle packet of a single particle flying into a determined direction * * @param effect * Particle effect * @param direction * Direction of the particle * @param speed * Display speed of the particle * @param longDistance * Indicates whether the maximum distance is increased from 256 to 65536 * @param data * Data of the effect * @throws IllegalArgumentException * If the speed is lower than 0 * @see #initialize() */ public ParticlePacket(final ParticleEffect2 effect, final Vector direction, final float speed, final boolean longDistance, final ParticleData data) throws IllegalArgumentException { initialize(); if (speed < 0) { throw new IllegalArgumentException( "The speed is lower than 0"); } this.effect = effect; this.offsetX = (float) direction.getX(); this.offsetY = (float) direction.getY(); this.offsetZ = (float) direction.getZ(); this.speed = speed; this.amount = 0; this.longDistance = longDistance; this.data = data; } /** * Initializes {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} * and sets {@link #initialized} to <code>true</code> if it succeeds * <p> * <b>Note:</b> These fields only have to be initialized once, so it will return if {@link #initialized} is * already set to <code>true</code> * * @throws VersionIncompatibleException * if your bukkit version is not supported by this library */ public static void initialize() throws VersionIncompatibleException { if (initialized) { return; } try { version = Integer.parseInt(Character.toString(PackageType.getServerVersion() .charAt(3))); if (version > 7) { enumParticle = PackageType.MINECRAFT_SERVER.getClass("EnumParticle"); } Class<?> packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); packetConstructor = ReflectionUtil.getConstructor(packetClass); getHandle = ReflectionUtil.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); playerConnection = ReflectionUtil.getField("EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection"); sendPacket = ReflectionUtil.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); } catch (Exception exception) { throw new VersionIncompatibleException( "Your current bukkit version seems to be incompatible with this library", exception); } initialized = true; } /** * Returns the version of your server (1.x) * * @return The version number */ public static int getVersion() { return version; } /** * Determine if {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and * {@link #sendPacket} are initialized * * @return Whether these fields are initialized or not * @see #initialize() */ public static boolean isInitialized() { return initialized; } /** * Sends the packet to a single player and caches it * * @param center * Center location of the effect * @param player * Receiver of the packet * @throws PacketInstantiationException * if instantion fails due to an unknown error * @throws PacketSendingException * if sending fails due to an unknown error */ public void sendTo(final Location center, final Player player) throws PacketInstantiationException, PacketSendingException { if (this.packet == null) { try { this.packet = packetConstructor.newInstance(); Object id; if (version < 8) { id = this.effect.getName() + (this.data == null ? "" : this.data.getPacketDataString()); } else { id = enumParticle.getEnumConstants()[this.effect.getId()]; } ReflectionUtil.setValue(this.packet, true, "a", id); ReflectionUtil.setValue(this.packet, true, "b", (float) center.getX()); ReflectionUtil.setValue(this.packet, true, "c", (float) center.getY()); ReflectionUtil.setValue(this.packet, true, "d", (float) center.getZ()); ReflectionUtil.setValue(this.packet, true, "e", this.offsetX); ReflectionUtil.setValue(this.packet, true, "f", this.offsetY); ReflectionUtil.setValue(this.packet, true, "g", this.offsetZ); ReflectionUtil.setValue(this.packet, true, "h", this.speed); ReflectionUtil.setValue(this.packet, true, "i", this.amount); if (version > 7) { ReflectionUtil.setValue(this.packet, true, "j", this.longDistance); ReflectionUtil.setValue( this.packet, true, "k", this.data == null ? new int[0] : this.data.getPacketData()); } } catch (Exception exception) { throw new PacketInstantiationException( "Packet instantiation failed", exception); } } try { sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), this.packet); } catch (Exception exception) { throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception); } } /** * Sends the packet to all players in the list * * @param center * Center location of the effect * @param players * Receivers of the packet * @throws IllegalArgumentException * If the player list is empty * @see #sendTo(Location center, Player player) */ public void sendTo(final Location center, final List<Player> players) throws IllegalArgumentException { if (players.isEmpty()) { throw new IllegalArgumentException( "The player list is empty"); } for (Player player : players) { this.sendTo(center, player); } } /** * Sends the packet to all players in a certain range * * @param center * Center location of the effect * @param range * Range in which players will receive the packet (Maximum range for particles is usually 16, but it * can differ for some types) * @throws IllegalArgumentException * If the range is lower than 1 * @see #sendTo(Location center, Player player) */ @SuppressWarnings("deprecation") public void sendTo(final Location center, final double range) throws IllegalArgumentException { if (range < 1) { throw new IllegalArgumentException( "The range is lower than 1"); } String worldName = center.getWorld().getName(); double squared = range * range; for (Player player : Bukkit.getOnlinePlayers()) { if (!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) { continue; } this.sendTo(center, player); } } /** * Represents a runtime exception that is thrown if a bukkit version is not compatible with this library * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.5 */ private static final class VersionIncompatibleException extends RuntimeException { private static final long serialVersionUID = 3203085387160737484L; /** * Construct a new version incompatible exception * * @param message * Message that will be logged * @param cause * Cause of the exception */ public VersionIncompatibleException(final String message, final Throwable cause) { super(message, cause); } } /** * Represents a runtime exception that is thrown if packet instantiation fails * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.4 */ private static final class PacketInstantiationException extends RuntimeException { private static final long serialVersionUID = 3203085387160737484L; /** * Construct a new packet instantiation exception * * @param message * Message that will be logged * @param cause * Cause of the exception */ public PacketInstantiationException(final String message, final Throwable cause) { super(message, cause); } } /** * Represents a runtime exception that is thrown if packet sending fails * <p> * This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.4 */ private static final class PacketSendingException extends RuntimeException { private static final long serialVersionUID = 3203085387160737484L; /** * Construct a new packet sending exception * * @param message * Message that will be logged * @param cause * Cause of the exception */ public PacketSendingException(final String message, final Throwable cause) { super(message, cause); } } } }
60,113
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
CacheHelper.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/CacheHelper.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; import eu.matejkormuth.pexel.PexelCore.core.Log; import eu.matejkormuth.pexel.PexelCore.core.Paths; /** * Class used for caching data. */ public class CacheHelper { private Map<String, Object> cache = new HashMap<>(); private final String name; private boolean nr = false; public CacheHelper(final String name) { this.name = name; try { this.load(); } catch (ClassNotFoundException | IOException e) { this.nr = true; Log.severe("Cache broken!"); e.printStackTrace(); } } public boolean needsRebuild() { return this.nr; } @SuppressWarnings("unchecked") private void load() throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File( Paths.cache(this.name)))); Object object = ois.readObject(); ois.close(); if (object instanceof HashMap<?, ?>) this.cache = (HashMap<String, Object>) object; else throw new RuntimeException("Broken cache file! Can't read data!"); } public String getName() { return this.name; } public int getSize() { return (int) new File(Paths.cache(this.name)).length(); } public void clear() { this.cache.clear(); } public void put(final String key, final Object value) { this.cache.put(key, value); } @SuppressWarnings("unchecked") public <T> T getTyped(final String key) { return (T) this.cache.get(key); } public Object get(final String key) { return this.cache.get(key); } public void commit() throws FileNotFoundException, IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File( Paths.cache(this.name)))); oos.writeObject(this.cache); oos.close(); } }
3,187
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Watcher.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/Watcher.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; public class Watcher<T> { private T lastState; private Runnable onChanged; public void check(final T value) { if (this.changed(value)) { this.lastState = value; this.onChanged.run(); } } public boolean changed(final T value) { return this.lastState == value; } public void setOnChanged(final Runnable onChanged) { this.onChanged = onChanged; } }
1,328
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MovingObject.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/MovingObject.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import org.bukkit.Location; import org.bukkit.util.Vector; /** * Class that represents moving object. */ public abstract class MovingObject { protected Location location; /** * Moves object by specified amount. * * @param amount * amount */ public void move(final Location amount) { this.move(amount.toVector()); } /** * Moves object by specified amount. * * @param amount * amount */ public void move(final Vector amount) { this.move(amount.getX(), amount.getY(), amount.getZ()); } /** * Moves object by specified amount. * * @param x * motX * @param y * motY * @param z * motZ */ public void move(final double x, final double y, final double z) { this.location.add(x, y, z); } /** * Sets object's location. * * @param location * location to set */ protected void setLocation(final Location location) { this.location = location; } /** * Returns object current location. * * @return current location */ public Location getLocation() { return this.location; } }
2,176
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Vote.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/Vote.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; /** * Class that specifies what player voted. */ public enum Vote { YES, NO; }
961
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Lang.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/util/Lang.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Class used for translations. Taken from project STARVING. * * @see Lang#getTranslation(String); * */ public class Lang { /** * Default language */ private static final String DEFAULT_LANGUAGE = "en"; /** * Map containing all translations in formate {lang}_{phrase} = translatedPhrase; */ private static Map<String, String> translations = Collections.synchronizedMap(new HashMap<String, String>()); /** * Singleton instance. */ private volatile static Lang instance; /** * Konstruktor na singleton. */ private Lang() { } /** * Loads the translations to memory. */ public static void loadTranslations(final String dataFolder) { System.out.println("[Translations] Nacitavam preklady..."); //Get the files with translations. File folder = new File(dataFolder + "/lang/"); File[] listOfFiles = folder.listFiles(); //For each file for (File file : listOfFiles) { //If its a lang file. if (file.isFile() && file.getName().endsWith("lang")) { if (file.getName().contains(".")) { System.out.println("[Translations] Found translation " + file.getName()); //Read the file. String translationLang = file.getName().split("\\.")[0]; //Reader BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { //Real line, split by = and put into translations map. String[] translation = line.split("="); translations.put(translationLang + "_" + translation[0], translation[1]); } //Close the reader. reader.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } } } } /** * Returns translated phrase by specified phrase code and default language. * * @param phrase * code (user-specified) * @return translated phrase or phrase code if the translation was not found */ public static String getTranslation(final String phrase) { synchronized (Lang.translations) { if (Lang.translations.containsKey(DEFAULT_LANGUAGE + "_" + phrase)) { return Lang.translations.get(DEFAULT_LANGUAGE + "_" + phrase); } else { return DEFAULT_LANGUAGE + "_" + phrase; } } } /** * Returns translated phrase by specified phrase code and default language. * * @param phrase * code (user-specified) * @param vars * map of variabiles to replace (key is variabile, value is replacement * @return translated phrase or phrase code if the translation was not found */ public static String getTranslation(final String phrase, final Map<String, String> vars) { String translation = ""; synchronized (Lang.translations) { //Get translation translation = Lang.translations.get(DEFAULT_LANGUAGE + "_" + phrase); } //Replace variabiles for (String variabile : vars.keySet()) { translation = translation.replace("{" + variabile + "}", vars.get(variabile)); } return translation; } /** * Returns translated phrase by specified phrase code and language. * * @param phrase * code (user-specified) * @param language * language code (ISO 3166-1 Alpha-2 standard, two-letter code) * @return translated phrase or phrase code if the translation was not found */ public static String getTranslation(final String phrase, final String language) { synchronized (Lang.translations) { if (Lang.translations.containsKey(language + "_" + phrase)) { return Lang.translations.get(language + "_" + phrase); } else { return language + "_" + phrase; } } } /** * Returns translated phrase by specified phrase code and language. * * @param phrase * code (user-specified) * @param language * language code (ISO 3166-1 Alpha-2 standard, two-letter code) * @param vars * map of variabiles to replace (key is variabile, value is replacement * @return translated phrase */ public static String getTranslation(final String phrase, final String language, final Map<String, String> vars) { String translation = ""; synchronized (Lang.translations) { //Get translation translation = Lang.translations.get(language + "_" + phrase); } //Replace variabiles for (String variabile : vars.keySet()) { translation = translation.replace("{" + variabile + "}", vars.get(variabile)); } return translation; } /** * Returns country code which is used as language code by IP address. * * @return language code (SO 3166-1 Alpha-2 standard, two-letter code) */ public static String getLang() { return "en"; } /** * Returns the instance of Lang. * * @return */ public static Lang getInstance() { if (Lang.instance != null) return Lang.instance; else return Lang.instance = new Lang(); } }
7,113
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ProtectedArea.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/ProtectedArea.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; import java.util.HashMap; import java.util.Map; import java.util.UUID; import eu.matejkormuth.pexel.PexelCore.core.Region; /** * Used for handling protected areas. * * @author Mato Kormuth * */ public class ProtectedArea { /** * Map of default values for flags. */ public static final Map<AreaFlag, Boolean> defaultFlags = new HashMap<AreaFlag, Boolean>(); //Initialization of static values. static { ProtectedArea.defaultFlags.put(AreaFlag.BLOCK_BREAK, false); ProtectedArea.defaultFlags.put(AreaFlag.BLOCK_PLACE, false); ProtectedArea.defaultFlags.put(AreaFlag.PLAYER_GETDAMAGE, false); ProtectedArea.defaultFlags.put(AreaFlag.PLAYER_DODAMAGE, false); ProtectedArea.defaultFlags.put(AreaFlag.PLAYER_DROPITEM, false); ProtectedArea.defaultFlags.put(AreaFlag.PLAYER_STARVATION, false); ProtectedArea.defaultFlags.put(AreaFlag.AREA_CHAT_GOODBYE, true); ProtectedArea.defaultFlags.put(AreaFlag.AREA_CHAT_PERMISSIONDENIED, true); ProtectedArea.defaultFlags.put(AreaFlag.AREA_CHAT_WELCOME, true); } /** * Area region */ protected Region region; /** * Global area flags. */ protected final Map<AreaFlag, Boolean> globalFlags = new HashMap<AreaFlag, Boolean>(); /** * Player area flags. */ protected final Map<UUID, HashMap<AreaFlag, Boolean>> playerFlags = new HashMap<UUID, HashMap<AreaFlag, Boolean>>(); /** * Owner of area. */ protected AreaOwner owner; /** * Name of area. */ protected final String areaName; /** * Creates new area with specified name. * * @param name */ public ProtectedArea(final String name, final Region region) { this.areaName = name; this.region = region; } /** * Returns value of global flag. If not specified uses parent's flag (default). * * @param flag */ public boolean getGlobalFlag(final AreaFlag flag) { if (this.globalFlags.get(flag) == null) if (ProtectedArea.defaultFlags.get(flag) == null) return false; else return ProtectedArea.defaultFlags.get(flag); else return this.globalFlags.get(flag); } /** * Returns value of player flag. If not specified uses parent's flag (global). * * @param flag * @param player */ public boolean getPlayerFlag(final AreaFlag flag, final UUID player) { if (this.playerFlags.containsKey(player)) if (this.playerFlags.get(player).get(flag) == null) if (this.globalFlags.get(flag) == null) if (ProtectedArea.defaultFlags.get(flag) == null) return false; else return ProtectedArea.defaultFlags.get(flag); else return this.globalFlags.get(flag); else return this.playerFlags.get(player).get(flag); else { if (this.globalFlags.get(flag) == null) if (ProtectedArea.defaultFlags.get(flag) == null) return false; else return ProtectedArea.defaultFlags.get(flag); else return this.globalFlags.get(flag); } } /** * Sets global flag. * * @param flag * flag to set * @param value * value to set */ public void setGlobalFlag(final AreaFlag flag, final boolean value) { this.globalFlags.put(flag, value); } /** * Sets player flag. * * @param flag * @param value * @param player */ public void setPlayerFlag(final AreaFlag flag, final boolean value, final UUID player) { if (this.playerFlags.containsKey(player)) this.playerFlags.get(player).put(flag, value); else { this.playerFlags.put(player, new HashMap<AreaFlag, Boolean>()); this.playerFlags.get(player).put(flag, value); } } /** * Returns area region. * * @return region */ public Region getRegion() { return this.region; } /** * Returns area name. * * @return name of area */ public String getName() { return this.areaName; } /** * Returns area owner. * * @return owner of area */ public AreaOwner getOwner() { return this.owner; } }
5,628
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
AreaFlag.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/AreaFlag.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; /** * All flags avaiable for areas. * * @author Mato Kormuth * */ public enum AreaFlag { /** * Block break event. */ BLOCK_BREAK, /** * Block place event. */ BLOCK_PLACE, /** * Player doing damage. */ PLAYER_DODAMAGE, /** * Player dropping item/s. */ PLAYER_DROPITEM, /** * Player getting damage. */ PLAYER_GETDAMAGE, /** * Starvation of player. */ PLAYER_STARVATION, /** * Permission for receiving "Permission denied" message. */ AREA_CHAT_PERMISSIONDENIED, /** * Permission for receiving area welcome message. */ AREA_CHAT_WELCOME, /** * Permission for receiving arena goodbye message. */ AREA_CHAT_GOODBYE }
1,653
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PlayerAreaOwner.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/PlayerAreaOwner.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; import org.bukkit.entity.Player; /** * Player area owner. * * @author Mato Kormuth * */ public class PlayerAreaOwner implements AreaOwner { /** * Player who is owner. */ private final Player owner; /** * Initializes new instance of area owner with specified player. * * @param player */ public PlayerAreaOwner(final Player player) { this.owner = player; } @Override public String getName() { return this.owner.getName(); } }
1,395
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
AreaOwner.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/AreaOwner.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; /** * Owner of the area. * * @author Mato Kormuth * */ public interface AreaOwner { /** * Returns name of owner. * * @return the name of owner */ public String getName(); }
1,082
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ServerAreaOwner.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/ServerAreaOwner.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; /** * Server area owner. * * @author Mato Kormuth * */ public class ServerAreaOwner implements AreaOwner { @Override public String getName() { return "Server"; } }
1,064
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Lobby.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/Lobby.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import eu.matejkormuth.pexel.PexelCore.Pexel; import eu.matejkormuth.pexel.PexelCore.core.Region; import eu.matejkormuth.pexel.PexelCore.core.Updatable; import eu.matejkormuth.pexel.PexelCore.core.UpdatedParts; /** * Lobby is protected area with some special functions. * * @author Mato Kormuth * */ public class Lobby extends ProtectedArea implements Updatable { /** * Creates new lobby object with specified name and region. * * @param name * name of lobby * @param region * region of lobby */ public Lobby(final String name, final Region region) { super(name, region); this.setGlobalFlag(AreaFlag.BLOCK_BREAK, false); this.setGlobalFlag(AreaFlag.BLOCK_PLACE, false); this.setGlobalFlag(AreaFlag.PLAYER_GETDAMAGE, false); //Wierd call, isn't it? this.updateStart(); } /** * Location of lobby spawn. */ private Location lobbySpawn; private int taskId = 0; /** * How often should lobby check for players. */ private long checkInterval = 20; //40 ticks = 2 second. /** * The minimal Y coordinate value, after the lobby will teleport players to its spawn. */ private int thresholdY = 50; /** * Returns lobby spawn. * * @return spawn */ public Location getSpawn() { return this.lobbySpawn; } /** * Sets lobby spawn. * * @param location */ public void setSpawn(final Location location) { this.lobbySpawn = location; } /** * Updates players. Adds potion effects and teleports them if needed. */ private void updatePlayers() { for (Player player : this.getRegion().getPlayersXZ()) { //Lobby potion enhantsments. player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20 * 30, 2)); player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20 * 30, 1)); //In-void lobby teleport. if (player.getLocation().getY() < this.thresholdY) player.teleport(this.lobbySpawn); } } @Override public void updateStart() { UpdatedParts.registerPart(this); this.taskId = Pexel.getScheduler().scheduleSyncRepeatingTask(new Runnable() { @Override public void run() { Lobby.this.updatePlayers(); } }, 0, this.checkInterval); } @Override public void updateStop() { Pexel.getScheduler().cancelTask(this.taskId); } /** * @return the thresholdY */ public int getThresholdY() { return this.thresholdY; } /** * @return the checkInterval */ public long getCheckInterval() { return this.checkInterval; } /** * @param checkInterval * the checkInterval to set */ public void setCheckInterval(final long checkInterval) { this.checkInterval = checkInterval; } /** * @param thresholdY * the thresholdY to set */ public void setThresholdY(final int thresholdY) { this.thresholdY = thresholdY; } }
4,314
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Areas.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/areas/Areas.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.areas; import org.bukkit.Location; import eu.matejkormuth.pexel.PexelCore.core.StorageEngine; /** * Class for work with areas. * * @author Mato Kormuth * */ public class Areas { /** * Tries to find arena by specified lcoation, if not found, returns null. * * @param location * location to search for area * @return area that was find at specified location */ public static final ProtectedArea findArea(final Location location) { for (ProtectedArea area : StorageEngine.getAreas().values()) if (area.getRegion().intersects(location)) return area; return null; } /** * Returns area by name. * * @param name * name of area * @return protected area by name */ public static final ProtectedArea getArea(final String name) { return StorageEngine.getAreas().get(name); } }
1,806
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MinigameCategory.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/minigame/MinigameCategory.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.minigame; /** * All categories of minigames. * * @author Mato Kormuth * */ public enum MinigameCategory { /** * Aracade minigame (ex. Tnt Tag). */ ARCADE, /** * Minigame that is about to survive (ex. Survival Games). */ SURVIVAL, /** * Mingiame that is ready for tournaments (ex. Kingdom Wars, Annihilation). Minigames in this category have enabled * negative points for leaving match before match ends. */ TOURNAMENT; }
1,353
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Minigame.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/minigame/Minigame.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on- package eu.matejkormuth.pexel.PexelCore.minigame; import java.util.List; import org.bukkit.Location; import eu.matejkormuth.pexel.PexelCore.bans.Bannable; /** * Interface for minigame. * * @author Mato Kormuth * */ public interface Minigame extends Bannable { /** * Returns display name of minigame. * * @return display name */ public String getDisplayName(); /** * Returns code safe name of minigame. <b>Must return name that is all lowercase and contains only characters a-z * and number 0-9, should not be longer than 20 characters (better keep name on about 12 characters)</b>. * * @return code safe name */ public String getName(); /** * Returns minigame category. * * @return minigame categorry */ public MinigameCategory getCategory(); /** * Returns minigame types. * * @return all minigame types. */ public List<MinigameType> getTypes(); /** * Returns the minigame lobby location. * * @return location of minigame's lobby */ public Location getLobbyLocation(); }
1,978
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MinigameType.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelCore/minigame/MinigameType.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelCore.minigame; import java.util.Arrays; import java.util.List; /** * All minigame types / tags. * * @author Mato Kormuth * */ public enum MinigameType { TNT, CREEPER, PVP; public static final List<MinigameType> makeTypes(final MinigameType... types) { return Arrays.asList(types); } }
1,187
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Request.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/Request.java
package eu.matejkormuth.pexel.PexelNetworking; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * Class that represents request. * * @author Mato Kormuth * */ public class Request { private final long requestId; private final AbstractPacket requestContent; private ResponeEventHandler onRespone; public Request(final AbstractPacket content) { this.requestId = Request.nextId(); this.requestContent = content; } public Request(final AbstractPacket content, final long requestId) { this.requestId = requestId; this.requestContent = content; } protected void onRespone(final Respone respone) { this.onRespone.onRespone(this, respone); } public void setOnRespone(final ResponeEventHandler handler) { this.onRespone = handler; } public long getRequestId() { return this.requestId; } public AbstractPacket getContent() { return this.requestContent; } public static final long nextId() { if (Request.lastId.containsKey(Server.THIS_SERVER.hashCode())) { return ((long) Server.THIS_SERVER.hashCode() << 32) | (Request.lastId.get(Server.THIS_SERVER.hashCode()).getAndIncrement() & 0xFFFFFFFL); } else { Request.lastId.put(Server.THIS_SERVER.hashCode(), new AtomicInteger()); return nextId(); } } public static final long nextId(final int clientUID) { if (Request.lastId.containsKey(clientUID)) { return ((long) clientUID << 32) | (Request.lastId.get(clientUID).getAndIncrement() & 0xFFFFFFFL); } else { Request.lastId.put(clientUID, new AtomicInteger()); return nextId(); } } private static Map<Integer, AtomicInteger> lastId = new HashMap<Integer, AtomicInteger>(); }
2,015
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PacketHandler.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/PacketHandler.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.io.DataInputStream; import java.io.IOException; import org.apache.commons.lang.NullArgumentException; import eu.matejkormuth.pexel.PexelNetworking.packets.CrossServerTeleportPacket; /** * packet handler. * * @author Mato Kormuth * */ public class PacketHandler { private final DataInputStream inputStream; private boolean serverInstance = false; public PacketHandler(final DataInputStream inputStream, final boolean serverInstance) { this.inputStream = inputStream; this.serverInstance = serverInstance; } private void processPacket(final AbstractPacket packet) { if (packet != null) if (this.serverInstance) packet.handleServer(); else packet.handleClient(); else throw new NullArgumentException("packet"); } public boolean isConnected() { return false; } public void handlePacket() throws IOException { //Packet header. PacketType packetType = PacketType.fromShort(this.inputStream.readShort()); //Handle packet by type. this.processPacket(this.getPacket(packetType)); } private AbstractPacket getPacket(final PacketType packetType) throws IOException { switch (packetType) { case CrossServerTeleportPacket: return CrossServerTeleportPacket.read(this.inputStream); default: return null; } } public void sendPacket(final PexelPacket packet, final PexelServerClient client) throws IOException { //Write packet header client.getOutputStream().writeShort( PacketType.fromClass(packet.getClass()).getId()); //Write packet body packet.write(client.getOutputStream()); } }
2,735
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Server.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/Server.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import eu.matejkormuth.pexel.PexelCore.bans.Bannable; /** * Class specifing pexel compactibile server. * * @author Mato Kormuth * */ public class Server implements Bannable { public static final Server THIS_SERVER = new Server(null, "$#__THIS__#$"); private final PexelServerClient client; private final String name; private final String bungeeName; /** * Creates new server with same name and bungeename. * * @param client * @param name */ public Server(final PexelServerClient client, final String name) { this.client = client; this.name = name; this.bungeeName = name; } /** * Creates a new server with different name and bungeename. * * @param client * @param name * @param bungeeName */ public Server(final PexelServerClient client, final String name, final String bungeeName) { this.client = client; this.name = name; this.bungeeName = bungeeName; } public boolean isLocalServer() { return this.name.equals("$#__THIS__#$"); } public PexelServerClient getClient() { return this.client; } public String getName() { return this.name; } public boolean isConnectedToMaster() { return this.client.isConnected(); } public String getBungeeName() { return this.bungeeName; } @Override public int hashCode() { return this.bungeeName.hashCode(); } @Override public String getBannableName() { return this.name; } @Override public String getBannableID() { return "SRV-" + this.bungeeName; } }
2,646
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Demo.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/Demo.java
package eu.matejkormuth.pexel.PexelNetworking; import org.bukkit.Bukkit; import eu.matejkormuth.pexel.PexelNetworking.packets.CrossServerChatMessage; public class Demo { public void a() { Request request = new Request(new CrossServerChatMessage("test")); request.setOnRespone(new ResponeEventHandler() { @Override public void onRespone(final Request requset, final Respone respone) { Bukkit.broadcastMessage("onRespone: " + ((CrossServerChatMessage) respone.getContent()).message); } }); } }
603
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
Respone.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/Respone.java
package eu.matejkormuth.pexel.PexelNetworking; /** * Class that represents respone. * * @author Mato Kormuth * */ public class Respone { private final long requestId; private final AbstractPacket responeContent; public Respone(final long requestId, final AbstractPacket responeContent) { this.requestId = requestId; this.responeContent = responeContent; } public long getRequestId() { return this.requestId; } public AbstractPacket getContent() { return this.responeContent; } }
576
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ServerRequestType.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/ServerRequestType.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.util.HashMap; import java.util.Map; /** * Enum specificating <i>pexel protocol</i>. * * @author Mato Kormuth * */ public enum ServerRequestType { ONLINEPLAYERS_LIST(0), MINIGAMES_LIST(1), ARENAS_LIST(2), ARENA_DISABLE(3), ARENA_ENABLE(4), ARENA_GETPLAYERS(5), ARENA_GETFIELDS(6), ARENA_GETINFO(7), BASIC_SERVERINFO(8), PLAYER_INFO(9), ARENA_INFO_BASIC(10), ARENA_INFO_REFLECTION(11); private int id; private ServerRequestType(final int id) { this.id = (short) id; } public int getId() { return this.id; } private static Map<Integer, ServerRequestType> mapping = new HashMap<Integer, ServerRequestType>(); static { for (ServerRequestType type : ServerRequestType.values()) ServerRequestType.mapping.put(type.getId(), type); } public static ServerRequestType fromInt(final int typeId) { return ServerRequestType.mapping.get(typeId); } }
1,905
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
AbstractPacket.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/AbstractPacket.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.io.DataInputStream; import java.io.IOException; public abstract class AbstractPacket implements PexelPacket { public short packetId; public abstract void handleClient(); public static AbstractPacket read(final DataInputStream stream) throws IOException { return null; } public abstract void handleServer(); }
1,238
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PexelPacket.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/PexelPacket.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.io.DataOutputStream; import java.io.IOException; /** * Packet for pexel server protocol. * * @author Mato Kormuth * */ public interface PexelPacket { public void write(DataOutputStream stream) throws IOException; }
1,112
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PexelMasterServer.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/PexelMasterServer.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import eu.matejkormuth.pexel.PexelCore.core.Log; /** * Master server. * * @author Mato Kormuth * */ public class PexelMasterServer implements Runnable { private ServerSocket socket; private final List<PexelServerClient> clients = new ArrayList<PexelServerClient>(); public PexelMasterServer(final int port) { Log.partEnable("PMS"); try { this.socket = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); this.socket = null; } } public void listen() { new Thread(this).start(); } public void close() { Log.partDisable("PMS"); try { this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { Thread.currentThread().setName("PexelMasterServer-ListenThread"); while (!this.socket.isClosed()) { try { final Socket client = this.socket.accept(); //Login final String serverName = ""; new Thread(new Runnable() { @Override public void run() { Log.info("PMS Client " + serverName + " passed login! Comunicating with him now."); Thread.currentThread().setName( "PexelMasterServer-ClientThread-" + serverName); PexelServerClient psc = new PexelServerClient(client); PexelMasterServer.this.clients.add(psc); PexelMasterServer.this.processClient(new Server(psc, serverName)); } }).start(); } catch (IOException e) { e.printStackTrace(); } } } public void processClient(final Server server) { while (!this.socket.isClosed()) { try { server.getClient().getHandler().handlePacket(); } catch (IOException e) { e.printStackTrace(); } } this.clients.remove(server.getClient()); } /** * @param crossServerChatMessage */ public void broadcast(final PexelPacket packet) { for (PexelServerClient client : this.clients) client.sendPacket(packet); } }
3,546
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PacketType.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/PacketType.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.util.HashMap; import java.util.Map; import eu.matejkormuth.pexel.PexelNetworking.packets.CrossServerTeleportPacket; /** * @author Mato Kormuth * */ public enum PacketType { CrossServerTeleportPacket(30, CrossServerTeleportPacket.class); private short id; private Class<? extends PexelPacket> clazz; private PacketType(final int id, final Class<? extends PexelPacket> clazz) { this.id = (short) id; this.clazz = clazz; } public short getId() { return this.id; } private Class<? extends PexelPacket> getClazz() { return this.clazz; } public static PacketType fromShort(final short id) { return PacketType.mappingShort.get(id); } public static PacketType fromClass(final Class<? extends PexelPacket> clazz) { return PacketType.mappingClass.get(clazz); } private static final Map<Short, PacketType> mappingShort = new HashMap<Short, PacketType>(); private static final Map<Class<? extends PexelPacket>, PacketType> mappingClass = new HashMap<Class<? extends PexelPacket>, PacketType>(); static { for (PacketType type : PacketType.values()) if (PacketType.mappingShort.containsKey(type.getId())) throw new RuntimeException( "Wrong mapping in PacketType! Can't store more than one type for one ID."); else PacketType.mappingShort.put(type.getId(), type); for (PacketType type : PacketType.values()) if (PacketType.mappingClass.containsKey(type.getClass())) throw new RuntimeException( "Wrong mapping in PacketType! Can't store more than one type for one CLASS."); else PacketType.mappingClass.put(type.getClazz(), type); } }
2,831
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ResponeEventHandler.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/ResponeEventHandler.java
package eu.matejkormuth.pexel.PexelNetworking; /** * Respone event handler. */ public interface ResponeEventHandler { /** * Called from network thread when respone arrives on client machine. * * @param requset * request that involved this action * @param respone * respone to the request */ public void onRespone(Request requset, Respone respone); }
419
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PexelServerClient.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/PexelServerClient.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; /** * Class used for comunicating with pexel compactibile servers. * * @author Mato Kormuth * */ public class PexelServerClient { private Socket clientSocket; private PacketHandler handler; private final boolean serverInstance; public PexelServerClient(final String masterIp, final int masterPort) { try { this.clientSocket = new Socket(); this.clientSocket.connect(new InetSocketAddress( InetAddress.getByName(masterIp), masterPort)); this.login(); } catch (IOException e) { e.printStackTrace(); } this.serverInstance = false; } private void login() { //TODO: Login to master //Read loop. new Thread(new Runnable() { @Override public void run() { Thread.currentThread().setName("PexelServerClient-ReadThread"); PexelServerClient.this.readCycle(); } }).start(); } protected void readCycle() { try { this.handler = new PacketHandler(new DataInputStream( this.clientSocket.getInputStream()), false); } catch (IOException e1) { e1.printStackTrace(); } while (!this.clientSocket.isClosed()) { try { this.handler.handlePacket(); } catch (IOException e) { e.printStackTrace(); } } } public PexelServerClient(final Socket socket) { this.clientSocket = socket; try { this.handler = new PacketHandler( new DataInputStream(socket.getInputStream()), true); } catch (IOException e) { e.printStackTrace(); } this.serverInstance = true; } public boolean isServerInstance() { return this.serverInstance; } public InetAddress getAddress() { return this.clientSocket.getInetAddress(); } public void sendPacket(final PexelPacket packet) { try { this.handler.sendPacket(packet, this); } catch (IOException e) { e.printStackTrace(); } } public boolean isConnected() { return !this.clientSocket.isClosed(); } public PacketHandler getHandler() { return this.handler; } public DataOutputStream getOutputStream() { try { return new DataOutputStream(this.clientSocket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); return null; } } }
3,725
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
CrossServerTeleportPacket.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/packets/CrossServerTeleportPacket.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking.packets; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import eu.matejkormuth.pexel.PexelNetworking.AbstractPacket; public class CrossServerTeleportPacket extends AbstractPacket { public UUID player; public Location loc; public CrossServerTeleportPacket(final UUID player, final Location location) { this.player = player; this.loc = location; } private CrossServerTeleportPacket() { } @Override public void write(final DataOutputStream stream) throws IOException { stream.writeUTF(this.player.toString()); stream.writeDouble(this.loc.getX()); stream.writeDouble(this.loc.getY()); stream.writeDouble(this.loc.getZ()); stream.writeFloat(this.loc.getYaw()); stream.writeFloat(this.loc.getPitch()); stream.writeUTF(this.loc.getWorld().getName()); } public static CrossServerTeleportPacket read(final DataInputStream stream) throws IOException { CrossServerTeleportPacket packet = new CrossServerTeleportPacket(); packet.player = UUID.fromString(stream.readUTF()); double x = stream.readDouble(); double y = stream.readDouble(); double z = stream.readDouble(); float yaw = stream.readFloat(); float pitch = stream.readFloat(); String worldName = stream.readUTF(); packet.loc = new Location(Bukkit.getWorld(worldName), x, y, z, yaw, pitch); return packet; } @Override public void handleClient() { //Add to teleport queue, expire in 30 seconds. } @Override public void handleServer() { //No handling on master server. } }
2,732
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
CrossServerChatMessage.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/packets/CrossServerChatMessage.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking.packets; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.bukkit.Bukkit; import eu.matejkormuth.pexel.PexelCore.Pexel; import eu.matejkormuth.pexel.PexelNetworking.AbstractPacket; public class CrossServerChatMessage extends AbstractPacket { public String message; public CrossServerChatMessage(final String message) { super(); this.message = message; } @Override public void write(final DataOutputStream stream) throws IOException { stream.writeUTF(this.message); } public static CrossServerChatMessage read(final DataInputStream stream) throws IOException { CrossServerChatMessage packet = new CrossServerChatMessage(""); packet.message = stream.readUTF(); return packet; } @Override public void handleClient() { Bukkit.broadcastMessage(this.message); } @Override public void handleServer() { Pexel.getCore().pexelserver.broadcast(this); } }
1,948
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ForwardPacket.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/pexel/PexelNetworking/packets/ForwardPacket.java
// @formatter:off /* * Pexel Project - Minecraft minigame server platform. * Copyright (C) 2014 Matej Kormuth <http://www.matejkormuth.eu> * * This file is part of Pexel. * * Pexel is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Pexel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. * */ // @formatter:on package eu.matejkormuth.pexel.PexelNetworking.packets; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import eu.matejkormuth.pexel.PexelNetworking.AbstractPacket; public class ForwardPacket extends AbstractPacket { public AbstractPacket packet; public String serverName; @Override public void write(final DataOutputStream stream) throws IOException { } public static ForwardPacket read(final DataInputStream stream) throws IOException { ForwardPacket packet = new ForwardPacket(); return packet; } @Override public void handleClient() { //No handling. } @Override public void handleServer() { //Forward to specified client. } }
1,646
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
ParametrizedRunnable.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/util/ParametrizedRunnable.java
package eu.matejkormuth.util; /** * Parametrized runnable. */ public interface ParametrizedRunnable { /** * Runs action with specified parameters. * * @param params * parameters */ public void run(Object... params); }
266
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
AnnotationNotPresentException.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/util/AnnotationNotPresentException.java
package eu.matejkormuth.util; public class AnnotationNotPresentException extends RuntimeException { private static final long serialVersionUID = 1L; public AnnotationNotPresentException() { super(); } public AnnotationNotPresentException(final String message) { super(message); } public AnnotationNotPresentException(final Throwable throwable) { super(throwable); } public AnnotationNotPresentException(final String message, final Throwable throwable) { super(message, throwable); } }
574
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
PrimitiveParser.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/util/PrimitiveParser.java
package eu.matejkormuth.util; public final class PrimitiveParser { public static final Object parseAsObject(final String string, final PrimitiveType asType) { switch (asType) { case BOOLEAN: return PrimitiveParser.parseBoolean(string); case BYTE: return PrimitiveParser.parseByte(string); case DOUBLE: return PrimitiveParser.parseDouble(string); case FLOAT: return PrimitiveParser.parseFloat(string); case INTEGER: return PrimitiveParser.parseInteger(string); case LONG: return PrimitiveParser.parseLong(string); case SHORT: return PrimitiveParser.parseShort(string); default: return null; } } @SuppressWarnings("unchecked") public static final <T> T parse(final String string, final PrimitiveType asType) { switch (asType) { case BOOLEAN: return (T) (Boolean) PrimitiveParser.parseBoolean(string); case BYTE: return (T) (Byte) PrimitiveParser.parseByte(string); case DOUBLE: return (T) (Double) PrimitiveParser.parseDouble(string); case FLOAT: return (T) (Float) PrimitiveParser.parseFloat(string); case INTEGER: return (T) (Integer) PrimitiveParser.parseInteger(string); case LONG: return (T) (Long) PrimitiveParser.parseLong(string); case SHORT: return (T) (Short) PrimitiveParser.parseShort(string); default: return null; } } public static final double parseDouble(final String string) { return Double.parseDouble(string); } public static final float parseFloat(final String string) { return Float.parseFloat(string); } public static final byte parseByte(final String string) { return Byte.parseByte(string); } public static final boolean parseBoolean(final String string) { return Boolean.parseBoolean(string); } public static final int parseInteger(final String string) { return Integer.parseInt(string); } public static final short parseShort(final String string) { return Short.parseShort(string); } public static final long parseLong(final String string) { return Long.parseLong(string); } public static enum PrimitiveType { FLOAT, DOUBLE, BYTE, SHORT, INTEGER, LONG, BOOLEAN; } }
2,724
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
EventHandler.java
/FileExtraction/Java_unseen/dobrakmato_PexelCore/src/eu/matejkormuth/util/EventHandler.java
package eu.matejkormuth.util; /** * Generic event handler. * * @param <T> * event args type. */ public interface EventHandler<T> { /** * Called when event happens. Handles the event. * * @param instance * event args. */ public void handle(T instance); }
316
Java
.java
dobrakmato/PexelCore
12
5
0
2014-08-28T19:30:48Z
2015-02-06T15:49:16Z
MCRGoogleSitemapServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-indexing/src/main/java/org/mycore/frontend/indexbrowser/MCRGoogleSitemapServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.indexbrowser; import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRFileContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.xml.MCRXMLParserFactory; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; /** * This class builds a google sitemap containing links to all documents. The * web.xml file should contain a mapping to /sitemap.xml * * @author Frank Lützenkirchen * @author Jens Kupferschmidt * @author Thomas Scheffler (yagee) */ public final class MCRGoogleSitemapServlet extends MCRServlet { private static final long serialVersionUID = 1L; /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRGoogleSitemapServlet.class.getName()); /** * This method implement the doGetPost method of MCRServlet. It build a XML * file for the Google search engine. * * @param job * a MCRServletJob instance */ public void doGetPost(MCRServletJob job) throws Exception { File baseDir = MCRFrontendUtil .getWebAppBaseDir(getServletContext()) .orElseGet(() -> new File(MCRConfiguration2.getStringOrThrow("MCR.WebApplication.basedir"))); MCRGoogleSitemapCommon common = new MCRGoogleSitemapCommon(MCRFrontendUtil.getBaseURL(job.getRequest()), baseDir); int number = common.checkSitemapFile(); LOGGER.debug("Build Google number of URL files {}.", Integer.toString(number)); Document jdom = null; // check if sitemap_google.xml exist String fnsm = common.getFileName(1, true); LOGGER.debug("Build Google check file {}", fnsm); File fi = new File(fnsm); if (fi.isFile()) { jdom = MCRXMLParserFactory.getNonValidatingParser().parseXML(new MCRFileContent(fi)); if (jdom == null) { if (number == 1) { jdom = common.buildSingleSitemap(); } else { jdom = common.buildSitemapIndex(number); } } //send XML output getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(jdom)); return; } // remove old files common.removeSitemapFiles(); // build new return and URL files if (number == 1) { jdom = common.buildSingleSitemap(); } else { for (int i = 0; i < number; i++) { String fn = common.getFileName(i + 2, true); File xml = new File(fn); jdom = common.buildPartSitemap(i); LOGGER.info("Write Google sitemap file {}.", fn); new MCRJDOMContent(jdom).sendTo(xml); } jdom = common.buildSitemapIndex(number); } // send XML output getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(jdom)); } }
3,946
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGoogleSitemapCommon.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-indexing/src/main/java/org/mycore/frontend/indexbrowser/MCRGoogleSitemapCommon.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.indexbrowser; import java.io.File; import java.io.IOException; import java.nio.file.NotDirectoryException; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.TimeZone; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.common.MCRObjectIDDate; import org.mycore.datamodel.ifs2.MCRObjectIDDateImpl; import org.mycore.solr.MCRSolrClientFactory; /** * This class implements all common methods to create the sitemap data. * <br> * used properties: * <br> * <ul> * <li>MCR.baseurl - the application base URL</li> * <li>MCR.WebApplication.basedir - the directory where the web application is stored</li> * <li>MCR.GoogleSitemap.Directory - the directory where the sitemap should be stored relative to * MCR.WebApplication.basedir (it could be empty)</li> * <li>MCR.GoogleSitemap.Types - a list of MCRObject types, they should be included</li> * <li>MCR.GoogleSitemap.Freq - the frequency of harvesting, 'monthly' is default<li> * <li>MCR.GoogleSitemap.Style - a style extension for the URL in form of ?XSL.Style={style}, default is empty</li> * <li>MCR.GoogleSitemap.ObjectPath - the path to get the MCRObject in the sitemap URL, 'receive/' is default</li> * <li>MCR.GoogleSitemap.NumberOfURLs - the number of URLs in one sitemap file, 10000 is default</li> * </ul> * * see <a href="http://www.sitemaps.org/de/protocol.html">http://www.sitemaps.org/de/protocol.html</a> * * @author Frank Lützenkirchen * @author Jens Kupferschmidt * @author Thomas Scheffler (yagee) * */ public final class MCRGoogleSitemapCommon { /** Zone information **/ private static final Locale SITEMAP_LOCALE = Locale.ROOT; private static final TimeZone SITEMAP_TIMEZONE = TimeZone.getTimeZone("UTC"); /** The namespaces */ private static final Namespace NS = Namespace.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9"); private static final String XSI_URL = "http://www.w3.org/2001/XMLSchema-instance"; private static final Namespace XSI_NAMESPACE = Namespace.getNamespace("xsi", XSI_URL); private static final String SITEINDEX_SCHEMA = "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd"; private static final String SITEMAP_SCHEMA = "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"; /** The directory path to store sitemaps relative to MCR.WebApplication.basedir */ private static final String CDIR = MCRConfiguration2.getString("MCR.GoogleSitemap.Directory").orElse(""); /** The frequence of crawle by Google */ private static final String FREQ = MCRConfiguration2.getString("MCR.GoogleSitemap.Freq").orElse("monthly"); /** The style for by Google link */ private static final String STYLE = MCRConfiguration2.getString("MCR.GoogleSitemap.Style").orElse(""); /** The url path for retrieving object metadata */ private static final String OBJECT_PATH = MCRConfiguration2.getString("MCR.GoogleSitemap.ObjectPath") .orElse("receive/"); /** The filter query for selecting objects to present in google sitemap */ private static final String SOLR_QUERY = MCRConfiguration2.getStringOrThrow("MCR.GoogleSitemap.SolrQuery"); /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRGoogleSitemapCommon.class.getName()); /** Number of URLs in one sitemap */ private int numberOfURLs = MCRConfiguration2.getInt("MCR.GoogleSitemap.NumberOfURLs").orElse(10000); /** number format for parts */ private static NumberFormat number_format = getNumberFormat(); /** date formatter */ private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", SITEMAP_LOCALE); /** The webapps directory path from configuration */ private final File webappBaseDir; /** The base URL */ private String baseurl = MCRConfiguration2.getString("MCR.baseurl").orElse(""); /** local data */ private List<MCRObjectIDDate> objidlist = null; public MCRGoogleSitemapCommon(File baseDir) throws NotDirectoryException { if (!Objects.requireNonNull(baseDir, "baseDir may not be null.").isDirectory()) { throw new NotDirectoryException(baseDir.getAbsolutePath()); } this.webappBaseDir = baseDir; LOGGER.info("Using webappbaseDir: {}", baseDir.getAbsolutePath()); objidlist = new ArrayList<>(); if ((numberOfURLs < 1) || (numberOfURLs > 50000)) { numberOfURLs = 50000; } if (CDIR.length() != 0) { File sitemapDirectory = new File(webappBaseDir, CDIR); if (!sitemapDirectory.exists()) { sitemapDirectory.mkdirs(); } } } public MCRGoogleSitemapCommon(String baseURL, File baseDir) throws NotDirectoryException { this(baseDir); this.baseurl = baseURL; } private static NumberFormat getNumberFormat() { NumberFormat nf = NumberFormat.getIntegerInstance(SITEMAP_LOCALE); nf.setMinimumFractionDigits(5); return nf; } /** * The method computes the number of sitemap files. If we have less than * <em>numberOfURLs</em> URLs and only one MyCoRe type the sitemap_google.xml * contained all URLs. Otherwise it split the sitemap in an sitemap_google.xml * index file and a lot of sitemap_google_xxxx.xml URL files. * * @return the number of files, one for a single sitemap_google.xml file, more than * one for the index and all parts. * */ protected int checkSitemapFile() throws IOException { int number = 0; QueryResponse response; SolrQuery query = new SolrQuery(); query.setQuery(SOLR_QUERY); query.setRows(Integer.MAX_VALUE); query.setParam("fl", "id,modified"); try { response = MCRSolrClientFactory.getMainSolrClient().query(query); objidlist = response.getResults().stream().map((document) -> { String id = (String) document.getFieldValue("id"); Date modified = (Date) document.getFieldValue("modified"); return new MCRObjectIDDateImpl(modified, id); }).collect(Collectors.toList()); } catch (SolrServerException e) { LOGGER.error(e); } number = objidlist.size() / numberOfURLs; if (objidlist.size() % numberOfURLs != 0) { number++; } return number; } /** * The method return the path to the sitemap_google.xml file. * * @param number * number of this file - '1' = sitemap_google.xml - '&gt; 1' sitemap_google_xxx.xml * @param withpath * true for the full path, false for the file name * @return a path to sitemap_google.xml */ protected String getFileName(int number, boolean withpath) { String fn = "sitemap_google.xml"; if (number > 1) { fn = "sitemap_google_" + number_format.format(number - 1) + ".xml"; } String localPath = fn; if (CDIR.length() != 0) { localPath = CDIR + File.separator + fn; } if (withpath) { return webappBaseDir + File.separator + localPath; } return localPath; } /** * The method build the sitemap_google.xml JDOM document over all items. * * @return The sitemap_google.xml as JDOM document */ protected Document buildSingleSitemap() { LOGGER.debug("Build Google URL sitemap_google.xml for whole items."); // build document frame Element urlset = new Element("urlset", NS); urlset.addNamespaceDeclaration(XSI_NAMESPACE); urlset.setAttribute("noNamespaceSchemaLocation", SITEMAP_SCHEMA, XSI_NAMESPACE); Document jdom = new Document(urlset); // build over all types for (MCRObjectIDDate objectIDDate : objidlist) { urlset.addContent(buildURLElement(objectIDDate)); } return jdom; } /** * The method call the database and build the sitemap_google.xml JDOM document. * * @param number * number of this file - '1' = sitemap_google.xml - '&gt; 1' sitemap_google_xxx.xml * @return The sitemap.xml as JDOM document */ protected Document buildPartSitemap(int number) { LOGGER.debug("Build Google URL sitemap list number {}", Integer.toString(number)); // build document frame Element urlset = new Element("urlset", NS); urlset.addNamespaceDeclaration(XSI_NAMESPACE); urlset.setAttribute("schemaLocation", SITEMAP_SCHEMA, XSI_NAMESPACE); Document jdom = new Document(urlset); // build over all types int start = numberOfURLs * (number); int stop = numberOfURLs * (number + 1); if (stop > objidlist.size()) { stop = objidlist.size(); } LOGGER.debug("Build Google URL in range from {} to {}.", Integer.toString(start), Integer.toString(stop - 1)); for (int i = start; i < stop; i++) { MCRObjectIDDate objectIDDate = objidlist.get(i); urlset.addContent(buildURLElement(objectIDDate)); } return jdom; } private Element buildURLElement(MCRObjectIDDate objectIDDate) { String mcrID = objectIDDate.getId(); StringBuilder sb = new StringBuilder(1024); sb.append(baseurl).append(OBJECT_PATH).append(mcrID); if ((STYLE != null) && (STYLE.trim().length() > 0)) { sb.append("?XSL.Style=").append(STYLE); } // build entry Element url = new Element("url", NS); url.addContent(new Element("loc", NS).addContent(sb.toString())); String datestr = formatter.format(objectIDDate.getLastModified()); url.addContent(new Element("lastmod", NS).addContent(datestr)); url.addContent(new Element("changefreq", NS).addContent(FREQ)); return url; } /** * The method build the index sitemap_google.xml JDOM document. * * @param number * number of indexed files (must greater than 1 * @return The index sitemap_google.xml as JDOM document */ protected Document buildSitemapIndex(int number) { LOGGER.debug("Build Google sitemap number {}", Integer.toString(number)); // build document frame Element index = new Element("sitemapindex", NS); index.addNamespaceDeclaration(XSI_NAMESPACE); index.setAttribute("schemaLocation", SITEINDEX_SCHEMA, XSI_NAMESPACE); Document jdom = new Document(index); // build over all files for (int i = 0; i < number; i++) { Element sitemap = new Element("sitemap", NS); index.addContent(sitemap); sitemap.addContent(new Element("loc", NS).addContent((baseurl + getFileName(i + 2, false)).trim())); String datestr = formatter.format((new GregorianCalendar(SITEMAP_TIMEZONE, SITEMAP_LOCALE)).getTime()); sitemap.addContent(new Element("lastmod", NS).addContent(datestr.trim())); } return jdom; } /** * This method remove all sitemap files from the webapps directory. */ protected void removeSitemapFiles() { File dir = new File(webappBaseDir, CDIR); File[] li = dir.listFiles(); if (li != null) { for (File fi : li) { if (fi.getName().startsWith("sitemap_google")) { LOGGER.debug("Remove file {}", fi.getName()); fi.delete(); } } } } }
13,042
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGoogleSitemapCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-indexing/src/main/java/org/mycore/frontend/indexbrowser/MCRGoogleSitemapCommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.frontend.indexbrowser; import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRJDOMContent; import org.mycore.frontend.cli.MCRAbstractCommands; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; /** * This class builds a google sitemap containing links to all documents and * store them to the webapps directory. This can be configured with property * variable MCR.GoogleSitemap.Directory. The web.xml file should contain a * mapping to /sitemap.xml * * @author Frank Lützenkirchen * @author Jens Kupferschmidt * @author Thomas Scheffler (yagee) */ @MCRCommandGroup(name = "Google Sitemap Commands") public final class MCRGoogleSitemapCommands extends MCRAbstractCommands { /** The logger */ private static Logger LOGGER = LogManager.getLogger(MCRGoogleSitemapCommands.class.getName()); /** * The build and store method. */ @MCRCommand(syntax = "build google sitemap", help = "Creates the google sitemap(s) in webapps directory.", order = 10) public static void buildSitemap() throws Exception { // check time LOGGER.debug("Build Google sitemap start."); final long start = System.currentTimeMillis(); // init File webappBaseDir = new File(MCRConfiguration2.getStringOrThrow("MCR.WebApplication.basedir")); MCRGoogleSitemapCommon common = new MCRGoogleSitemapCommon(webappBaseDir); // remove old files common.removeSitemapFiles(); // compute number of files int number = common.checkSitemapFile(); LOGGER.debug("Build Google number of URL files {}.", Integer.toString(number)); if (number == 1) { String fn = common.getFileName(1, true); File xml = new File(fn); Document jdom = common.buildSingleSitemap(); LOGGER.info("Write Google sitemap file {}.", fn); new MCRJDOMContent(jdom).sendTo(xml); } else { String fn = common.getFileName(1, true); File xml = new File(fn); Document jdom = common.buildSitemapIndex(number); LOGGER.info("Write Google sitemap file {}.", fn); new MCRJDOMContent(jdom).sendTo(xml); for (int i = 0; i < number; i++) { fn = common.getFileName(i + 2, true); xml = new File(fn); jdom = common.buildPartSitemap(i); LOGGER.info("Write Google sitemap file {}.", fn); new MCRJDOMContent(jdom).sendTo(xml); } } // check time LOGGER.debug("Google sitemap request took {}ms.", System.currentTimeMillis() - start); } }
3,623
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MetsEditorTestBase.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/webtest/MetsEditorTestBase.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.webtest; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.mycore.common.selenium.MCRSeleniumTestBase; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class MetsEditorTestBase extends MCRSeleniumTestBase { public static final String BASE_URL = System.getProperty("BaseUrl", "http://localhost:9301"); private static final int MAXIMAL_TIME_TO_WAIT_FOR_A_ELEMENT = 10; private static final int ONE_SECOND_IN_MILLISECONDS = 1000; @Before public void setUp() { this.getDriver().get(BASE_URL + "/classes/META-INF/resources/module/mets/example/mets-editor.html"); } @After public void tearDown() { this.takeScreenshot(); } protected void waitForElement(By byTextIgnoreCSS) throws InterruptedException { int maxWait = MAXIMAL_TIME_TO_WAIT_FOR_A_ELEMENT; WebDriver webDriver = this.getDriver(); List<WebElement> elements = new ArrayList<>(); while (elements.isEmpty() && maxWait-- > 0) { elements = webDriver.findElements(byTextIgnoreCSS); Thread.sleep(ONE_SECOND_IN_MILLISECONDS); } if (elements.isEmpty()) { throw new AssertionError("The element to wait for was not found!"); } } }
2,115
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
PaginationIT.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/webtest/PaginationIT.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.webtest; import org.junit.Assert; import org.junit.Test; import org.mycore.common.selenium.drivers.MCRWebdriverWrapper; import org.mycore.common.selenium.util.MCRBy; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; /** * @author Sebastian Röher (basti890) * */ public class PaginationIT extends MetsEditorTestBase { private static final String TEST_STRING = "test123"; @Test public void setPagination() { WebDriver webDriver = getDriver(); WebElement row = webDriver.findElement(MCRBy.partialText("perthes_1855_0001.jpg")).findElement( By.xpath("ancestor::tr")); row.findElement(By.xpath("//button[@title=\"???editPagination???\"]")).click(); row.findElement(By.xpath("//input")).sendKeys(TEST_STRING); row.findElement(By.xpath("//button[@title=\"???paginationChange???\"]")).click(); Assert.assertNotNull(row.findElement(MCRBy.partialText(TEST_STRING))); } @Test public void abortPagination() { MCRWebdriverWrapper webDriver = getDriver(); WebElement row = webDriver.waitAndFindElement(MCRBy.partialText("perthes_1855_0001.jpg")).findElement( By.xpath("ancestor::tr")); row.findElement(By.xpath("//button[@title=\"???editPagination???\"]")).click(); row.findElement(By.xpath("//input")).sendKeys(TEST_STRING); row.findElement(By.xpath("//button[@title=\"???paginationAbort???\"]")).click(); Assert.assertTrue("Pagination should not be set!", row.findElements(MCRBy.partialText(TEST_STRING)).isEmpty()); } @Test public void autoPaginationAll() throws InterruptedException { MCRWebdriverWrapper webDriver = getDriver(); webDriver.waitAndFindElement(By.xpath("//button[@title=\"autoPagination\"]")).click(); // wait for the Pagination-Dialog waitForElement(MCRBy.partialText("???paginationValue???")); webDriver.waitAndFindElement(MCRBy.partialText("undefined(1)")); webDriver.waitAndFindElement(MCRBy.partialText("undefined(34)")); webDriver.waitAndFindElement(By.xpath("//input[@type=\"text\"]")).sendKeys("1v"); Select select = new Select(webDriver.findElement(By.tagName("select"))); select.selectByVisibleText("???rectoVerso_lowercase???"); webDriver.waitAndFindElement(By.xpath("//button[contains(text(),\"???paginationChange???\")]")).click(); Assert.assertNotNull(webDriver.waitAndFindElement(MCRBy.partialText("1v"))); Assert.assertNotNull(webDriver.waitAndFindElement(MCRBy.partialText("18r"))); } /* @Test public void deletePaginationFew() throws InterruptedException { WebDriver webDriver = getDriver(); autoPaginationFew(); WebElement row = webDriver.findElement(MCRBy.partialText("1v")).findElement(By.xpath("ancestor::tr")); row.findElement(By.xpath("//button[@title=\"???removePagination???\"]")).click(); if (!webDriver.findElements(MCRBy.partialText("1v")).isEmpty()) throw new AssertionError("Pagination has not been removed!"); }*/ /* @Test public void revertChange() throws InterruptedException { WebDriver webDriver = getDriver(); deletePaginationFew(); webDriver.findElement(By.xpath("//button[@title=\"???undo???\"]")).click(); webDriver.findElement(MCRBy.partialText("1v")); } */ // TODO find a way to drag&drop the elements to test the sortation by hand // @Test // public void sortPagination() throws InterruptedException { // WebDriver webDriver = getDriver(); // autoPaginationAll(); // WebElement row1 = webDriver.findElement(MyBy.byTextIgnoreCSS("perthes_1855_0001.jpg")).findElement( // By.xpath("ancestor::td")); // Actions move = new Actions(webDriver); // WebElement rowToMove = webDriver.findElement(By.xpath("//tr[@ng-repeat-end][5]/td")); // move.doubleClick(row1).clickAndHold(row1).moveToElement(rowToMove).release(row1).perform(); // Thread.sleep(100000); // } }
4,965
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAltoHighlightResourceTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/resource/MCRAltoHighlightResourceTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.resource; import static org.junit.Assert.assertEquals; import org.junit.Test; public class MCRAltoHighlightResourceTest { @Test public void buildQuery() { MCRAltoHighlightResource r = new MCRAltoHighlightResource(); assertEquals("alto_content:Jena", r.buildQuery("Jena")); assertEquals("alto_content:Jena alto_content:Stadt", r.buildQuery("Jena Stadt")); assertEquals("alto_content:\"Jena Stadt\"", r.buildQuery("\"Jena Stadt\"")); assertEquals("alto_content:Berlin alto_content:\"Jena Stadt\" alto_content:Hamburg", r.buildQuery("Berlin \"Jena Stadt\" Hamburg")); assertEquals("alto_content:\"Berlin Hamburg\" alto_content:\"Jena Stadt\"", r.buildQuery("\"Berlin Hamburg\" \"Jena Stadt\"")); assertEquals("alto_content:Berlin alto_content:\"Jena Stadt\" alto_content:Hamburg", r.buildQuery("Berlin \"Jena Stadt\" Hamburg")); } }
1,696
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsModelHelperTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/MCRMetsModelHelperTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mycore.common.MCRTestCase; @RunWith(Parameterized.class) public class MCRMetsModelHelperTest extends MCRTestCase { private final String path; private final Optional<String> expected; public MCRMetsModelHelperTest(String path, Optional<String> expected) { this.path = path; this.expected = expected; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { "bild.jpg", Optional.of(MCRMetsModelHelper.MASTER_USE) }, { "alto/datei1.xml", Optional.of(MCRMetsModelHelper.ALTO_USE) }, { "tei/transcription/page1.xml", Optional.of(MCRMetsModelHelper.TRANSCRIPTION_USE) }, { "tei/transcription/page2.xml", Optional.of(MCRMetsModelHelper.TRANSCRIPTION_USE) }, { "tei/translation/page1.xml", Optional.empty() }, { "tei/text.xml", Optional.of(MCRMetsModelHelper.MASTER_USE) }, { "tei/translation.de/page1.xml", Optional.of(MCRMetsModelHelper.TRANSLATION_USE + ".DE") }, { "tei/translation.en/page2.xml", Optional.of(MCRMetsModelHelper.TRANSLATION_USE + ".EN") }, { "tei/translation.kr/page2.xml", Optional.empty() }, }); } @Test public void getUseForHref() { Assert.assertEquals(expected, MCRMetsModelHelper.getUseForHref(path)); } @Override protected Map<String, String> getTestProperties() { final Map<String, String> testProperties = super.getTestProperties(); testProperties.put(MCRMetsModelHelper.ALLOWED_TRANSLATION_PROPERTY, "de,en"); return testProperties; } }
2,641
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSGeneratorFactoryTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/MCRMETSGeneratorFactoryTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.mycore.common.config.MCRConfiguration2; public class MCRMETSGeneratorFactoryTest { @Test public void getGenerator() { // prepare config MCRConfiguration2.set("MCR.Component.MetsMods.Generator", TestGenerator.class.getName()); // check getGenerator MCRMETSGenerator generator = MCRMETSGeneratorFactory.create(null); assertTrue(generator instanceof TestGenerator); } public static class TestGenerator implements MCRMETSGenerator { @Override public Mets generate() { return new Mets(); } } }
1,426
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRJSONSimpleModelConverterTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/converter/MCRJSONSimpleModelConverterTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.converter; import java.io.IOException; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mycore.mets.model.simple.MCRMetsLink; import org.mycore.mets.model.simple.MCRMetsSection; import org.mycore.mets.model.simple.MCRMetsSimpleModel; public class MCRJSONSimpleModelConverterTest { private String json; @Before public void buildJson() throws IOException { json = MCRMetsTestUtil.readJsonFile("text-json-1.json"); } @Test public void testToSimpleModel() { MCRMetsSimpleModel metsSimpleModel = MCRJSONSimpleModelConverter.toSimpleModel(json); MCRMetsSimpleModel compareSimpleModel = MCRMetsTestUtil.buildMetsSimpleModel(); MCRMetsSection s1RootSection = metsSimpleModel.getRootSection(); MCRMetsSection s2RootSection = compareSimpleModel.getRootSection(); Assert.assertEquals("labels of root must be the same", s1RootSection.getLabel(), s2RootSection.getLabel()); Assert.assertEquals("types of root must be the same", s1RootSection.getType(), s2RootSection.getType()); Assert.assertEquals("page count must be the same", metsSimpleModel.getMetsPageList().size(), compareSimpleModel.getMetsPageList().size()); List<MCRMetsLink> s1SectionPageLinkList = metsSimpleModel.getSectionPageLinkList(); List<MCRMetsLink> s2SectionPageLinkList = compareSimpleModel.getSectionPageLinkList(); for (int n = 0; n < 3; n++) { Assert.assertEquals("from of " + n + " link must be the same", s1SectionPageLinkList.get(n).getFrom().getLabel(), s2SectionPageLinkList.get(n).getFrom().getLabel()); Assert.assertEquals("to of " + n + " link must be the same", s1SectionPageLinkList.get(n).getTo().getOrderLabel(), s2SectionPageLinkList.get(n).getTo().getOrderLabel()); } } }
2,682
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSimpleModelJSONConverterTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/converter/MCRSimpleModelJSONConverterTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.converter; import org.junit.Before; import org.junit.Test; import org.mycore.mets.model.simple.MCRMetsSimpleModel; public class MCRSimpleModelJSONConverterTest { private MCRMetsSimpleModel metsSimpleModel; @Before public void buildModel() { metsSimpleModel = MCRMetsTestUtil.buildMetsSimpleModel(); } @Test public void testToJSON() { MCRSimpleModelJSONConverter.toJSON(metsSimpleModel); } }
1,197
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsTestUtil.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/converter/MCRMetsTestUtil.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.converter; import static java.util.stream.Collectors.toList; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.mycore.mets.model.MCRMetsModelHelper; import org.mycore.mets.model.simple.MCRMetsFile; import org.mycore.mets.model.simple.MCRMetsLink; import org.mycore.mets.model.simple.MCRMetsPage; import org.mycore.mets.model.simple.MCRMetsSection; import org.mycore.mets.model.simple.MCRMetsSimpleModel; public class MCRMetsTestUtil { private static Properties PROPERTIES = new Properties(); public static String readJsonFile(String path) throws IOException { InputStream resourceAsStream = MCRMetsTestUtil.class.getClassLoader().getResourceAsStream("json/" + path); List<String> stringList = IOUtils.readLines(resourceAsStream, StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); stringList.forEach(sb::append); return sb.toString(); } public static Document readXMLFile(String path) throws JDOMException, IOException { InputStream resourceAsStream = MCRMetsTestUtil.class.getClassLoader().getResourceAsStream("xml/" + path); SAXBuilder builder = new SAXBuilder(); return builder.build(resourceAsStream); } public static Properties getProperties() { if (PROPERTIES.isEmpty()) { try { PROPERTIES.load(MCRMetsTestUtil.class.getClassLoader().getResourceAsStream("mets.properties")); } catch (IOException e) { throw new RuntimeException("could not load application properties!", e); } } return PROPERTIES; } public static <T> T instantiate(final String className, final Class<T> type) { try { return type.cast(Class.forName(className).getDeclaredConstructor().newInstance()); } catch (final ReflectiveOperationException e) { throw new IllegalStateException(e); } } @SafeVarargs public static <T> boolean comparer(Comparator<T> comparator, T object, T... withList) { return Arrays.stream(withList).noneMatch(with -> comparator.compare(object, with) != 0); } @SafeVarargs public static <T, R> List<R> bulk(BulkOperation<T, R> op, T... on) { return Arrays.asList(on).stream().map(op::doOperation).collect(toList()); } public interface BulkOperation<T, R> { R doOperation(T input); } public static MCRMetsSimpleModel buildMetsSimpleModel() { MCRMetsSimpleModel metsSimpleModel = new MCRMetsSimpleModel(); builSimpleModelSections(metsSimpleModel); buildSimpleModelPages(metsSimpleModel); buildSimpleModelLinkList(metsSimpleModel); return metsSimpleModel; } private static void buildSimpleModelLinkList(MCRMetsSimpleModel metsSimpleModel) { List<MCRMetsLink> linkList = metsSimpleModel.sectionPageLinkList; MCRMetsSection rootSection = metsSimpleModel.getRootSection(); List<MCRMetsPage> pageList = metsSimpleModel.getMetsPageList(); linkList.add(new MCRMetsLink(rootSection, pageList.get(0))); linkList.add(new MCRMetsLink(rootSection.getMetsSectionList().get(0), pageList.get(1))); linkList.add(new MCRMetsLink(rootSection.getMetsSectionList().get(1), pageList.get(2))); } private static void buildSimpleModelPages(MCRMetsSimpleModel metsSimpleModel) { MCRMetsPage metsPage1 = new MCRMetsPage("1_P", "1", "URN:special-urn1"); metsPage1.getFileList().add(new MCRMetsFile("1_M", "1.jpg", "image/jpeg", MCRMetsModelHelper.MASTER_USE)); metsPage1.getFileList().add(new MCRMetsFile("1_A", "1.xml", "text/xml", MCRMetsModelHelper.ALTO_USE)); MCRMetsPage metsPage2 = new MCRMetsPage("2_P", "2", "URN:special-urn2"); metsPage2.getFileList().add(new MCRMetsFile("2_M", "2.jpg", "image/jpeg", MCRMetsModelHelper.MASTER_USE)); metsPage2.getFileList().add(new MCRMetsFile("2_A", "2.xml", "text/xml", MCRMetsModelHelper.ALTO_USE)); MCRMetsPage metsPage3 = new MCRMetsPage("3_P", "3", "URN:special-urn3"); metsPage3.getFileList().add(new MCRMetsFile("3_M", "3.jpg", "image/jpeg", MCRMetsModelHelper.MASTER_USE)); metsPage3.getFileList().add(new MCRMetsFile("3_A", "3.xml", "text/xml", MCRMetsModelHelper.ALTO_USE)); metsSimpleModel.getMetsPageList().add(metsPage1); metsSimpleModel.getMetsPageList().add(metsPage2); metsSimpleModel.getMetsPageList().add(metsPage3); } private static void builSimpleModelSections(MCRMetsSimpleModel metsSimpleModel) { MCRMetsSection rootSection = new MCRMetsSection("root", "testRootType", "testRootLabel", null); metsSimpleModel.setRootSection(rootSection); MCRMetsSection subSection1 = new MCRMetsSection("sub1", "subSection", "subSection1Label", rootSection); MCRMetsSection subSection2 = new MCRMetsSection("sub2", "subSection", "subSection2Label", rootSection); rootSection.addSection(subSection1); rootSection.addSection(subSection2); } }
6,107
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRXMLSimpleModelConverterTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/converter/MCRXMLSimpleModelConverterTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.converter; import java.util.Iterator; import java.util.List; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.junit.Assert; import org.junit.Before; import org.mycore.mets.model.MCRMetsModelHelper; import org.mycore.mets.model.simple.MCRMetsFile; import org.mycore.mets.model.simple.MCRMetsSection; import org.mycore.mets.model.simple.MCRMetsSimpleModel; public class MCRXMLSimpleModelConverterTest { public static final Logger LOGGER = LogManager.getLogger(MCRXMLSimpleModelConverterTest.class); public static final String FILE_NAME_MATCH_PATTERN = "file%d.jpg"; public static final String ROOT_SECTION_LABEL = "ArchNachl_derivate_00000011"; public static final String ROOT_SECTION_FIRST_CHILD_LABEL = "intro"; public static final String ROOT_SECTION_SECOND_CHILD_LABEL = "begin"; public static final String ROOT_SECTION_THIRD_CHILD_LABEL = "middle"; public static final String SECTION_ASSERT_MESSAGE_PATTERN = "The %s child of rootSection should have %s as %s!"; public static final String CHAPTER_TYPE = "chapter"; public static final String COVER_FRONT_TYPE = "- cover_front"; public static final String CONTAINED_WORK_TYPE = "contained_work"; public static final String ALL_FILE_MIMETYPE = "image/jpeg"; private MCRMetsSimpleModel metsSimpleModel; @Before public void readMetsSimpleModel() throws Exception { Document document = MCRMetsTestUtil.readXMLFile("test-mets-1.xml"); metsSimpleModel = MCRXMLSimpleModelConverter.fromXML(document); } @org.junit.Test public void testFromXMLMetsFiles() { Iterator<MCRMetsFile> hrefIterator = metsSimpleModel.getMetsPageList() .stream() .map((p) -> { Optional<MCRMetsFile> first = p.getFileList().stream().findFirst(); return first.get(); }).iterator(); int i = 0; while (hrefIterator.hasNext()) { i++; MCRMetsFile mcrMetsFile = hrefIterator.next(); String expectedFileName = String.format(FILE_NAME_MATCH_PATTERN, i); String message = String.format("href %s should match %s", mcrMetsFile.getHref(), expectedFileName); Assert.assertEquals(message, mcrMetsFile.getHref(), expectedFileName); message = String.format("MimeType %s should match %s", mcrMetsFile.getMimeType(), ALL_FILE_MIMETYPE); Assert.assertEquals(message, mcrMetsFile.getMimeType(), ALL_FILE_MIMETYPE); message = String.format("File-Use %s should match %s", mcrMetsFile.getUse(), MCRMetsModelHelper.MASTER_USE); Assert.assertEquals(message, mcrMetsFile.getUse(), MCRMetsModelHelper.MASTER_USE); } } @org.junit.Test public void testFromXMLMetsSection() { MCRMetsSection rootSection = metsSimpleModel.getRootSection(); Assert.assertEquals("The rootSection label should be " + ROOT_SECTION_LABEL, rootSection.getLabel(), ROOT_SECTION_LABEL); Assert.assertEquals("log_ArchNachl_derivate_00000011", rootSection.getId()); List<MCRMetsSection> metsSectionList = rootSection.getMetsSectionList(); String message = String.format(SECTION_ASSERT_MESSAGE_PATTERN, "first", ROOT_SECTION_FIRST_CHILD_LABEL, "label"); Assert.assertEquals(message, metsSectionList.get(0).getLabel(), ROOT_SECTION_FIRST_CHILD_LABEL); message = String.format(SECTION_ASSERT_MESSAGE_PATTERN, "first", COVER_FRONT_TYPE, "type"); Assert.assertEquals(message, metsSectionList.get(0).getType(), COVER_FRONT_TYPE); message = String.format(SECTION_ASSERT_MESSAGE_PATTERN, "second", ROOT_SECTION_FIRST_CHILD_LABEL, "label"); Assert.assertEquals(message, metsSectionList.get(1).getLabel(), ROOT_SECTION_SECOND_CHILD_LABEL); message = String.format(SECTION_ASSERT_MESSAGE_PATTERN, "second", CONTAINED_WORK_TYPE, "type"); Assert.assertEquals(message, metsSectionList.get(1).getType(), CONTAINED_WORK_TYPE); message = String.format(SECTION_ASSERT_MESSAGE_PATTERN, "third", ROOT_SECTION_THIRD_CHILD_LABEL, "label"); Assert.assertEquals(message, metsSectionList.get(2).getLabel(), ROOT_SECTION_THIRD_CHILD_LABEL); message = String.format(SECTION_ASSERT_MESSAGE_PATTERN, "third", CHAPTER_TYPE, "type"); Assert.assertEquals(message, metsSectionList.get(2).getType(), CHAPTER_TYPE); } }
5,293
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSimpleModelXMLConverterTest.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/test/java/org/mycore/mets/model/converter/MCRSimpleModelXMLConverterTest.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.converter; import java.util.Arrays; import java.util.Collections; import org.jdom2.Document; import org.jdom2.Namespace; import org.jdom2.filter.Filters; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.xpath.XPathFactory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mycore.mets.model.simple.MCRMetsSimpleModel; public class MCRSimpleModelXMLConverterTest { private static final String PATHS_TO_CHECK = "count(//mets:structLink/mets:smLink)=3;" + "count(//mets:structMap[@TYPE='LOGICAL']/mets:div[@LABEL='testRootLabel'])=1;" + "count(//mets:structMap[@TYPE='LOGICAL']/mets:div[@LABEL='testRootLabel']/mets:div[@LABEL='subSection1Label'])=1;" + "count(//mets:structMap[@TYPE='LOGICAL']/mets:div[@LABEL='testRootLabel']/mets:div[@LABEL='subSection2Label'])=1;" + "count(//mets:fileGrp[@USE='MASTER']/mets:file)=3;" + "count(//mets:fileGrp[@USE='ALTO']/mets:file)=3;" + "count(//mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']/mets:div[@TYPE='page'])=3;" + "count(//mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']/mets:div[@TYPE='page']/mets:fptr)=6;" + "count(//mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']/mets:div[@TYPE='page' and " + "contains(@CONTENTIDS, 'URN:special-urn')])=3;"; private MCRMetsSimpleModel metsSimpleModel; @Before public void createModel() { metsSimpleModel = MCRMetsTestUtil.buildMetsSimpleModel(); } @Test public void testToXML() { Document document = MCRSimpleModelXMLConverter.toXML(metsSimpleModel); XPathFactory xPathFactory = XPathFactory.instance(); String documentAsString = new XMLOutputter(Format.getPrettyFormat()).outputString(document); Arrays.asList(PATHS_TO_CHECK.split(";")).stream() .map((String xpath) -> xPathFactory.compile(xpath, Filters.fboolean(), Collections.emptyMap(), Namespace.getNamespace("mets", "http://www.loc.gov/METS/"))) .forEachOrdered(xPath -> { Boolean evaluate = xPath.evaluateFirst(document); Assert.assertTrue( String.format("The xpath : %s is not true! %s %s", xPath, System.lineSeparator(), documentAsString), evaluate); }); } }
3,159
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRSolrAltoExtractor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/solr/MCRSolrAltoExtractor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.solr; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.apache.logging.log4j.LogManager; import org.apache.solr.common.SolrInputDocument; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.filter.Filters; import org.jdom2.input.SAXBuilder; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.solr.index.file.MCRSolrFileIndexAccumulator; /** * Extract content and word coordinates of ALTO XML and adds it to the alto_words and alto_content field. * * @author Matthias Eichner */ public class MCRSolrAltoExtractor implements MCRSolrFileIndexAccumulator { @Override public void accumulate(SolrInputDocument document, Path filePath, BasicFileAttributes attributes) throws IOException { String parentPath = MCRPath.toMCRPath(filePath).getParent().getOwnerRelativePath(); if (!parentPath.startsWith("/alto")) { return; } try (InputStream is = Files.newInputStream(filePath)) { SAXBuilder builder = new SAXBuilder(); Document altoDocument = builder.build(is); extract(altoDocument.getRootElement(), document); } catch (JDOMException e) { LogManager.getLogger().error("Unable to parse {}", filePath, e); } } private void extract(Element root, SolrInputDocument document) { StringBuilder altoContent = new StringBuilder(); String exp = "alto:Layout/alto:Page/alto:PrintSpace//alto:String"; Namespace namespace = root.getNamespace(); Namespace altoNS = Namespace.getNamespace("alto", namespace.getURI()); XPathExpression<Element> stringExp = XPathFactory.instance().compile(exp, Filters.element(), null, altoNS); for (Element stringElement : stringExp.evaluate(root)) { String content = stringElement.getAttributeValue("CONTENT"); String hpos = stringElement.getAttributeValue("HPOS"); String vpos = stringElement.getAttributeValue("VPOS"); String width = stringElement.getAttributeValue("WIDTH"); String height = stringElement.getAttributeValue("HEIGHT"); if (hpos == null || vpos == null || width == null || height == null) { continue; } String regEx = "\\.0"; String altoWord = String.join("|", content, hpos.replaceAll(regEx, ""), vpos.replaceAll(regEx, ""), width.replaceAll(regEx, ""), height.replaceAll(regEx, "")); altoContent.append(content).append(' '); document.addField("alto_words", altoWord); } document.addField("alto_content", altoContent.toString().trim()); } }
3,684
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsFileIndexAccumulator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/solr/MCRMetsFileIndexAccumulator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.solr; import static org.mycore.common.MCRConstants.XPATH_FACTORY; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.common.SolrInputDocument; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.filter.Filters; import org.jdom2.input.SAXBuilder; import org.mycore.common.MCRConstants; import org.mycore.common.config.MCRConfiguration2; import org.mycore.solr.index.file.MCRSolrFileIndexAccumulator; /** * Class indexes label attributes in mets files. * * By default, the labels are indexed in solr field <code>mets_label</code>. Configure your own by providing a proper * name in property <code>MCR.Solr.Mets.Label.Field</code>. * * @author shermann (Silvio Hermann) * */ public class MCRMetsFileIndexAccumulator implements MCRSolrFileIndexAccumulator { protected static Logger LOGGER = LogManager.getLogger(MCRMetsFileIndexAccumulator.class); @Override public void accumulate(SolrInputDocument solrInputDocument, Path path, BasicFileAttributes basicFileAttributes) throws IOException { if (!MCRConfiguration2.getString("MCR.Mets.Filename").get().equals(path.getFileName().toString())) { return; } try (InputStream is = Files.newInputStream(path)) { Document mets = new SAXBuilder().build(is); List<Attribute> attributeList = XPATH_FACTORY .compile("/mets:mets/mets:structMap[@TYPE='LOGICAL']//*/@LABEL", Filters.attribute(), null, MCRConstants.METS_NAMESPACE) .evaluate(mets); // collect all label attributes for (Attribute a : attributeList) { solrInputDocument.addField( MCRConfiguration2.getString("MCR.Solr.Mets.Label.Field").orElse("mets_label"), a.getValue()); } } catch (JDOMException e) { throw new IOException(e); } } }
2,947
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRGoobiMetsPostUploadProcessor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/tools/MCRGoobiMetsPostUploadProcessor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.tools; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Supplier; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRStreamContent; import org.mycore.common.content.transformer.MCRXSLTransformer; import org.mycore.frontend.fileupload.MCRPostUploadFileProcessor; public class MCRGoobiMetsPostUploadProcessor extends MCRPostUploadFileProcessor { private final MCRXSLTransformer goobiMetsTransformer; public MCRGoobiMetsPostUploadProcessor() { goobiMetsTransformer = MCRXSLTransformer.getInstance("xsl/goobi-mycore-mets.xsl"); } @Override public boolean isProcessable(String path) { return path.endsWith("mets.xml"); } @Override public Path processFile(String path, Path tempFile, Supplier<Path> tempFileSupplier) throws IOException { try (InputStream in = Files.newInputStream(tempFile)) { MCRStreamContent streamContent = new MCRStreamContent(in); MCRContent transform = goobiMetsTransformer.transform(streamContent); Path result = tempFileSupplier.get(); try (OutputStream out = Files.newOutputStream(result)) { out.write(transform.asByteArray()); return result; } } } }
2,144
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsLock.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsLock.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.tools; import java.util.Hashtable; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.datamodel.metadata.MCRObjectID; /** * * Used to lock the mets editor for a specific Derivate * * @author Sebastian Hofmann (mcrshofm) */ public class MCRMetsLock { private static Hashtable<MCRObjectID, String> metsAccessSessionTable = new Hashtable<>(); private static final Logger LOGGER = LogManager.getLogger(MCRMetsLock.class); /** * Checks if a Derivate is locked * @param derivateIdString the derivate id * @return true if the derivate is locked */ public static synchronized boolean isLocked(String derivateIdString) { MCRObjectID derivateId = MCRObjectID.getInstance(derivateIdString); if (MCRMetsLock.metsAccessSessionTable.containsKey(derivateId)) { String lastAccessID = MCRMetsLock.metsAccessSessionTable.get(derivateId); MCRSession lastSession = MCRSessionMgr.getSession(lastAccessID); LOGGER.debug("{} is locked : {}", derivateIdString, lastSession != null); return lastSession != null; } else { LOGGER.debug("{} is not locked", derivateIdString); return false; } } /** * Locks a Derivate with the current SessionId * @param derivateIdString the Derivate to lock * @return True if the derivate is locked. False if the derivate could not be locked. */ public static synchronized boolean doLock(String derivateIdString) { MCRObjectID derivateId = MCRObjectID.getInstance(derivateIdString); if (isLocked(derivateIdString) && MCRMetsLock.metsAccessSessionTable.get(derivateId) != MCRSessionMgr.getCurrentSessionID()) { LOGGER.info("Could not lock {}, because its already locked.", derivateIdString); return false; } else { LOGGER.info("{} is now locked", derivateIdString); MCRMetsLock.metsAccessSessionTable.put(derivateId, MCRSessionMgr.getCurrentSessionID()); return true; } } /** * Unlocks a Derivate wich was locked with the current SessionId * @param derivateIdString the id of the derivate * @throws MCRException if the session-id of locker is different from current session-id */ public static synchronized void doUnlock(String derivateIdString) throws MCRException { MCRObjectID derivateId = MCRObjectID.getInstance(derivateIdString); if (isLocked(derivateIdString)) { String sessionId = MCRMetsLock.metsAccessSessionTable.get(MCRObjectID.getInstance(derivateIdString)); if (MCRSessionMgr.getCurrentSessionID().equals(sessionId)) { LOGGER.info("{} is not locked anymore", derivateIdString); MCRMetsLock.metsAccessSessionTable.remove(derivateId); } else { LOGGER.error("could not unlock {} because session id is different", derivateIdString); String message = String.format(Locale.ENGLISH, "Could not unlock %s, because the session wich locked it was : ''%s'' " + "and current sesssion is ''%s''", derivateIdString, sessionId, MCRSessionMgr.getCurrentSessionID()); throw new MCRException(message); } } } }
4,297
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsResolver.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsResolver.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.tools; import java.nio.file.Files; import java.util.Collection; 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.Document; import org.jdom2.Element; import org.jdom2.Namespace; import org.jdom2.transform.JDOMSource; import org.mycore.access.MCRAccessManager; import org.mycore.common.content.MCRPathContent; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.mets.model.MCRMETSGeneratorFactory; /** * returns a structured METS document for any valid MyCoRe ID (object or * derivate). May return empty &lt;mets:mets/&gt; if no derivate is present. No * metadata is attached. * * @author Thomas Scheffler (yagee) */ public class MCRMetsResolver implements URIResolver { private static final Logger LOGGER = LogManager.getLogger(MCRMetsResolver.class); @Override public Source resolve(String href, String base) throws TransformerException { String id = href.substring(href.indexOf(":") + 1); LOGGER.debug("Reading METS for ID {}", id); MCRObjectID objId = MCRObjectID.getInstance(id); if (!objId.getTypeId().equals("derivate")) { String derivateID = getDerivateFromObject(id); if (derivateID == null) { return new JDOMSource(new Element("mets", Namespace.getNamespace("mets", "http://www.loc.gov/METS/"))); } id = derivateID; } MCRPath metsPath = MCRPath.getPath(id, "/mets.xml"); try { if (Files.exists(metsPath)) { //TODO: generate new METS Output //ignoreNodes.add(metsFile); return new MCRPathContent(metsPath).getSource(); } Document mets = MCRMETSGeneratorFactory.create(MCRPath.getPath(id, "/")).generate().asDocument(); return new JDOMSource(mets); } catch (Exception e) { throw new TransformerException(e); } } private String getDerivateFromObject(String id) { Collection<String> derivates = MCRLinkTableManager.instance().getDestinationOf(id, "derivate"); for (String derID : derivates) { if (MCRAccessManager.checkDerivateDisplayPermission(derID)) { return derID; } } return null; } }
3,290
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsSave.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/tools/MCRMetsSave.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.tools; import java.io.IOException; import java.io.OutputStream; import java.net.URISyntaxException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.filter.Filters; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.common.MCRPersistenceException; import org.mycore.common.MCRStreamUtils; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRPathContent; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.datamodel.common.MCRMarkManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRContentTypes; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.mets.model.MCRMetsModelHelper; import org.mycore.mets.model.Mets; import org.mycore.mets.model.files.FLocat; import org.mycore.mets.model.files.File; import org.mycore.mets.model.files.FileGrp; import org.mycore.mets.model.struct.Fptr; import org.mycore.mets.model.struct.LOCTYPE; import org.mycore.mets.model.struct.LogicalDiv; import org.mycore.mets.model.struct.LogicalStructMap; import org.mycore.mets.model.struct.PhysicalDiv; import org.mycore.mets.model.struct.PhysicalStructMap; import org.mycore.mets.model.struct.PhysicalSubDiv; import org.mycore.mets.model.struct.SmLink; import org.mycore.mets.model.struct.StructLink; import org.xml.sax.SAXException; /** * Class is responsible for saving a mets document to a derivate. It also can * handle addition and removing files from a derivate. * * @author shermann * Sebastian Hofmann * * TODO: Complete rework needed */ public class MCRMetsSave { public static final String ALTO_FOLDER_PREFIX = "alto/"; public static final String TEI_FOLDER_PREFIX = "tei/"; public static final String TRANSLATION_FOLDER_PREFIX = "translation."; public static final String TRANSCRIPTION_FOLDER_PREFIX = "transcription"; public static final String UNKNOWN_FILEGROUP = "UNKNOWN"; private static final Logger LOGGER = LogManager.getLogger(MCRMetsSave.class); /** * Saves the content of the given document to file and then adds the file to * the derivate with the given id. The name of the file depends on property * 'MCR.Mets.Filename'. If this property has not been set 'mets.xml' is used * as a default filename. * * @return * true if the given document was successfully saved, otherwise false */ public static synchronized boolean saveMets(Document document, MCRObjectID derivateId) { return saveMets(document, derivateId, true, true); } /** * Saves the content of the given document to file, if no mets present and then adds the file to * the derivate with the given id. The name of the file depends on property * 'MCR.Mets.Filename'. If this property has not been set 'mets.xml' is used * as a default filename. * * @param overwrite * if true existing mets-file will be overwritten * @param validate * if true the document will be validated before its stored * @return * true if the given document was successfully saved, otherwise false */ public static synchronized boolean saveMets(Document document, MCRObjectID derivateId, boolean overwrite, boolean validate) { // add the file to the existing derivate in ifs MCRPath metsFile = getMetsFile(derivateId.toString()); if (metsFile == null) { metsFile = createMetsFile(derivateId.toString()); } else if (!overwrite) { return false; } if (validate && !Mets.isValid(document)) { LOGGER.warn("Storing mets.xml for {} failed cause the given document was invalid.", derivateId); return false; } try (OutputStream metsOut = Files.newOutputStream(metsFile)) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); xout.output(document, metsOut); LOGGER.info("Storing file content from \"{}\" to derivate \"{}\"", getMetsFileName(), derivateId); } catch (Exception e) { LOGGER.error(e); return false; } return true; } public static String getMetsFileName() { return MCRConfiguration2.getString("MCR.Mets.Filename").orElse("mets.xml"); } /** * Updates the mets.xml belonging to the given derivate. Adds the file to * the mets document (updates file sections and stuff within the mets.xml) * * @param file * a handle for the file to add to the mets.xml */ public static void updateMetsOnFileAdd(MCRPath file) throws Exception { MCRObjectID derivateID = MCRObjectID.getInstance(file.getOwner()); Document mets = getCurrentMets(derivateID.toString()); if (mets == null) { LOGGER.info("Derivate with id \"{}\" has no mets file. Nothing to do", derivateID); return; } mets = MCRMetsSave.updateOnFileAdd(mets, file); if (mets != null) { MCRMetsSave.saveMets(mets, derivateID); } } /** * Returns the mets.xml as JDOM document for the given derivate or null. * * @param derivateID the derivate identifier * @return the mets.xml as JDOM document */ private static Document getCurrentMets(String derivateID) throws JDOMException, IOException { MCRPath metsFile = getMetsFile(derivateID); return metsFile == null ? null : new MCRPathContent(metsFile).asXML(); } public static MCRPath getMetsFile(String derivateID) { MCRPath metsFile = createMetsFile(derivateID); return Files.exists(metsFile) ? metsFile : null; } public static MCRPath createMetsFile(String derivateID) { return MCRPath.getPath(derivateID, "/mets.xml"); } // TODO: should use mets-model api /** * Alters the mets file * * @param mets * the unmodified source * @param file * the file to add * @return the modified mets or null if an exception occures */ private static Document updateOnFileAdd(Document mets, MCRPath file) { try { // check for file existance (if a derivate with mets.xml is uploaded String relPath = MCRXMLFunctions.encodeURIPath(file.getOwnerRelativePath().substring(1), true); // Check if file already exists -> if yes do nothing String fileExistPathString = "mets:mets/mets:fileSec/mets:fileGrp/mets:file/mets:FLocat[@xlink:href='" + relPath + "']"; XPathExpression<Element> xpath = XPathFactory.instance().compile(fileExistPathString, Filters.element(), null, MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); if (xpath.evaluate(mets).size() > 0) { String msgTemplate = "The File : '%s' already exists in mets.xml"; LOGGER.warn(String.format(Locale.ROOT, msgTemplate, relPath)); return null; } else { String msgTemplate = "The File : '%s' does not exists in mets.xml"; LOGGER.warn(String.format(Locale.ROOT, msgTemplate, relPath)); } // add to file section String contentType = MCRContentTypes.probeContentType(file); LOGGER.warn("Content Type is : {}", contentType); String fileGrpUSE = getFileGroupUse(file); String fileId = new MessageFormat("{0}_{1}", Locale.ROOT) .format(new Object[] { fileGrpUSE.toLowerCase(Locale.ROOT), getFileBase(relPath) }); File fileAsMetsFile = new File(fileId, contentType); FLocat fLocat = new FLocat(LOCTYPE.URL, relPath); fileAsMetsFile.setFLocat(fLocat); Element fileSec = getFileGroup(mets, fileGrpUSE); fileSec.addContent(fileAsMetsFile.asElement()); if (fileGrpUSE.equals(MCRMetsModelHelper.MASTER_USE)) { updateOnImageFile(mets, fileId, relPath); } else { updateOnCustomFile(mets, fileId, relPath); } } catch (Exception ex) { LOGGER.error("Error occured while adding file {} to the existing mets file", file, ex); return null; } return mets; } private static void updateOnImageFile(Document mets, String fileId, String path) { LOGGER.debug("FILE is a image!"); //check if custom files are present and save the ids List<String> customFileGroups = getFileGroups(mets); // add to structMap physical PhysicalSubDiv div = new PhysicalSubDiv(PhysicalSubDiv.ID_PREFIX + fileId, PhysicalSubDiv.TYPE_PAGE); div.add(new Fptr(fileId)); customFileGroups.stream() .map(customFileGroup -> searchFileInGroup(mets, path, customFileGroup)) .filter(Objects::nonNull) .map(Fptr::new) .forEach(div::add); // actually alter the mets document Element structMapPhys = getPhysicalStructmap(mets); structMapPhys.addContent(div.asElement()); // add to structLink SmLink smLink = getDefaultSmLink(mets, div); Element structLink = getStructLink(mets); structLink.addContent(smLink.asElement()); } private static void updateOnCustomFile(Document mets, String fileId, String path) { LOGGER.debug("FILE is a custom file (ALTO/TEI)!"); String matchId = searchFileInGroup(mets, path, MCRMetsModelHelper.MASTER_USE); if (matchId == null) { // there is no file wich belongs to the alto xml so just return LOGGER.warn("no file found wich belongs to the custom xml : {}", path); return; } // check if there is a physical file Element physPageElement = getPhysicalFile(mets, matchId); if (physPageElement != null) { physPageElement.addContent(new Fptr(fileId).asElement()); LOGGER.warn("physical page found for file {}", matchId); } else { LOGGER.warn("no physical page found for file {}", matchId); } } private static Element getPhysicalFile(Document mets, String matchId) { XPathExpression<Element> xpath; String physicalFileExistsXpathString = String .format( Locale.ROOT, "mets:mets/mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']" + "/mets:div[mets:fptr/@FILEID='%s']", matchId); xpath = XPathFactory.instance().compile(physicalFileExistsXpathString, Filters.element(), null, MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); return xpath.evaluateFirst(mets); } private static List<String> getFileGroups(Document mets) { final XPathExpression<Attribute> xpath = XPathFactory.instance() .compile("mets:mets/mets:fileSec/mets:fileGrp/@USE", Filters.attribute(), null, MCRConstants.METS_NAMESPACE); return xpath.evaluate(mets).stream().map(Attribute::getValue).collect(Collectors.toList()); } private static Element getFileGroup(Document mets, String fileGrpUSE) { XPathExpression<Element> xpath;// alter the mets document String fileGroupXPathString = String.format(Locale.ROOT, "mets:mets/mets:fileSec/mets:fileGrp[@USE='%s']", fileGrpUSE); xpath = XPathFactory.instance().compile(fileGroupXPathString, Filters.element(), null, MCRConstants.METS_NAMESPACE); Element element = xpath.evaluateFirst(mets); if (element == null) { // section does not exist Element fileGroupElement = new FileGrp(fileGrpUSE).asElement(); String fileSectionPath = "mets:mets/mets:fileSec"; xpath = XPathFactory.instance().compile(fileSectionPath, Filters.element(), null, MCRConstants.METS_NAMESPACE); Element fileSectionElement = xpath.evaluateFirst(mets); if (fileSectionElement == null) { throw new MCRPersistenceException("There is no fileSection in mets.xml!"); } fileSectionElement.addContent(fileGroupElement); element = fileGroupElement; } return element; } /** * Build the default smLink. The PhysicalSubDiv is simply linked to the root chapter of the mets document. * * @param mets the mets document * @param div the PhysicalSubDiv which should be linked * @return the default smLink */ private static SmLink getDefaultSmLink(Document mets, PhysicalSubDiv div) { XPathExpression<Attribute> attributeXpath; attributeXpath = XPathFactory.instance().compile("mets:mets/mets:structMap[@TYPE='LOGICAL']/mets:div/@ID", Filters.attribute(), null, MCRConstants.METS_NAMESPACE); Attribute idAttribute = attributeXpath.evaluateFirst(mets); String rootID = idAttribute.getValue(); return new SmLink(rootID, div.getId()); } /** * Gets the StructLink of a mets document * * @param mets the mets document * @return the StructLink of a mets document */ private static Element getStructLink(Document mets) { XPathExpression<Element> xpath; xpath = XPathFactory.instance().compile("mets:mets/mets:structLink", Filters.element(), null, MCRConstants.METS_NAMESPACE); return xpath.evaluateFirst(mets); } /** * Gets the physicalStructMap of a mets document * * @param mets the mets document * @return the physicalStructmap of the mets document */ private static Element getPhysicalStructmap(Document mets) { XPathExpression<Element> xpath; xpath = XPathFactory.instance().compile( "mets:mets/mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']", Filters.element(), null, MCRConstants.METS_NAMESPACE); return xpath.evaluateFirst(mets); } /** * Decides in which file group the file should be inserted * * @param file the to check * @return the id of the filegGroup */ public static String getFileGroupUse(MCRPath file) { return MCRMetsModelHelper.getUseForHref(file.getOwnerRelativePath()).orElse(UNKNOWN_FILEGROUP); } /** * Searches a file in a group, which matches a filename. * * @param mets the mets file to search * @param path the path to the alto file (e.g. "alto/alto_file.xml" when searching in DEFAULT_FILE_GROUP_USE or * "image_file.jpg" when searchin in ALTO_FILE_GROUP_USE) * @return the id of the matching file or null if there is no matching file */ private static String searchFileInGroup(Document mets, String path, String searchFileGroup) { XPathExpression<Element> xpath;// first check all files in default file group String relatedFileExistPathString = String.format(Locale.ROOT, "mets:mets/mets:fileSec/mets:fileGrp[@USE='%s']/mets:file/mets:FLocat", searchFileGroup); xpath = XPathFactory.instance().compile(relatedFileExistPathString, Filters.element(), null, MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); List<Element> fileLocList = xpath.evaluate(mets); String matchId = null; // iterate over all files String cleanPath = getCleanPath(path); for (Element fileLoc : fileLocList) { Attribute hrefAttribute = fileLoc.getAttribute("href", MCRConstants.XLINK_NAMESPACE); String hrefAttributeValue = hrefAttribute.getValue(); String hrefPath = getCleanPath(removeExtension(hrefAttributeValue)); if (hrefPath.equals(removeExtension(cleanPath))) { matchId = ((Element) fileLoc.getParent()).getAttributeValue("ID"); break; } } return matchId; } private static String getCleanPath(String path) { String cleanPath = path; if (cleanPath.startsWith(ALTO_FOLDER_PREFIX)) { cleanPath = cleanPath.substring(ALTO_FOLDER_PREFIX.length()); } else if (cleanPath.startsWith(TEI_FOLDER_PREFIX)) { cleanPath = cleanPath.substring(TEI_FOLDER_PREFIX.length()); if (cleanPath.startsWith(TRANSLATION_FOLDER_PREFIX)) { // e.g. tei/TRANSLATION_FOLDER_PREFIXDE/folder/file.tif -> folder/file.tif cleanPath = cleanPath.substring(TRANSLATION_FOLDER_PREFIX.length()); cleanPath = cleanPath.substring(cleanPath.indexOf("/") + 1); } else if (cleanPath.startsWith(TRANSCRIPTION_FOLDER_PREFIX)) { cleanPath = cleanPath.substring(TRANSCRIPTION_FOLDER_PREFIX.length() + 1); } } return cleanPath; } private static String removeExtension(String fileName) { int dotPosition = fileName.lastIndexOf("."); return fileName.substring(0, dotPosition); } /** * Updates the mets.xml belonging to the given derivate. Removes the file * from the mets document (updates file sections and stuff within the * mets.xml) * * @param file * a handle for the file to add to the mets.xml */ public static void updateMetsOnFileDelete(MCRPath file) throws JDOMException, SAXException, IOException { MCRObjectID derivateID = MCRObjectID.getInstance(file.getOwner()); Document mets = getCurrentMets(derivateID.toString()); if (mets == null) { LOGGER.info("Derivate with id \"{}\" has no mets file. Nothing to do", derivateID); return; } mets = MCRMetsSave.updateOnFileDelete(mets, file); if (mets != null) { MCRMetsSave.saveMets(mets, derivateID); } } /** * Inserts the given URNs into the mets document. * * @param derivate The {@link MCRDerivate} which contains the mets file */ public static void updateMetsOnUrnGenerate(MCRDerivate derivate) { if (MCRMarkManager.instance().isMarkedForDeletion(derivate)) { return; } try { Map<String, String> urnFileMap = derivate.getUrnMap(); if (urnFileMap.size() > 0) { updateMetsOnUrnGenerate(derivate.getId(), urnFileMap); } else { LOGGER.debug("There are no URN to insert"); } } catch (Exception e) { LOGGER.error("Read derivate XML cause error", e); } } /** * Inserts the given URNs into the Mets document. * @param derivateID The {@link MCRObjectID} of the Derivate wich contains the METs file * @param fileUrnMap a {@link Map} which contains the file as key and the urn as as value */ public static void updateMetsOnUrnGenerate(MCRObjectID derivateID, Map<String, String> fileUrnMap) throws JDOMException, SAXException, IOException { Document mets = getCurrentMets(derivateID.toString()); if (mets == null) { LOGGER.info("Derivate with id \"{}\" has no mets file. Nothing to do", derivateID); return; } LOGGER.info("Update {} URNS in mets.xml", fileUrnMap.size()); Mets metsObject = new Mets(mets); updateURNsInMetsDocument(metsObject, fileUrnMap); saveMets(metsObject.asDocument(), derivateID); } /** * Inserts the given URNs into the {@link Mets} Object. * @param mets the {@link Mets} object were the URNs should be inserted. * @param fileUrnMap a {@link Map} wich contains the file as key and the urn as as value */ public static void updateURNsInMetsDocument(Mets mets, Map<String, String> fileUrnMap) { // put all files of the mets in a list List<FileGrp> fileGroups = mets.getFileSec().getFileGroups(); List<File> files = new ArrayList<>(); for (FileGrp fileGrp : fileGroups) { files.addAll(fileGrp.getFileList()); } // combine the filename and the id in a map Map<String, String> idFileMap = new HashMap<>(); for (File file : files) { idFileMap.put(file.getId(), file.getFLocat().getHref()); } List<PhysicalSubDiv> childs = ((PhysicalStructMap) mets.getStructMap(PhysicalStructMap.TYPE)).getDivContainer() .getChildren(); for (PhysicalSubDiv divChild : childs) { String idMets = divChild.getChildren().get(0).getFileId(); // check if there is a URN for the file String file = "/" + URLDecoder.decode(idFileMap.get(idMets), StandardCharsets.UTF_8); if (fileUrnMap.containsKey(file)) { divChild.setContentIds(fileUrnMap.get(file)); } } } private static Document updateOnFileDelete(Document mets, MCRPath file) { Mets modifiedMets; try { modifiedMets = new Mets(mets); String href = file.getOwnerRelativePath().substring(1); PhysicalStructMap physStructMap = (PhysicalStructMap) modifiedMets.getStructMap(PhysicalStructMap.TYPE); PhysicalDiv divContainer = physStructMap.getDivContainer(); // search the right group and remove the file from the group List<FileGrp> fileGroups = modifiedMets.getFileSec().getFileGroups(); for (FileGrp fileGrp : fileGroups) { if (fileGrp.contains(href)) { File fileToRemove = fileGrp.getFileByHref(href); fileGrp.removeFile(fileToRemove); ArrayList<PhysicalSubDiv> physicalSubDivsToRemove = new ArrayList<>(); // remove file from mets:mets/mets:structMap[@TYPE='PHYSICAL'] for (PhysicalSubDiv physicalSubDiv : divContainer.getChildren()) { ArrayList<Fptr> fptrsToRemove = new ArrayList<>(); for (Fptr fptr : physicalSubDiv.getChildren()) { if (fptr.getFileId().equals(fileToRemove.getId())) { if (fileGrp.getUse().equals(FileGrp.USE_MASTER)) { physicalSubDivsToRemove.add(physicalSubDiv); } else { fptrsToRemove.add(fptr); } } } for (Fptr fptrToRemove : fptrsToRemove) { LOGGER.warn(String.format(Locale.ROOT, "remove fptr \"%s\" from mets.xml of \"%s\"", fptrToRemove.getFileId(), file.getOwner())); physicalSubDiv.remove(fptrToRemove); } } for (PhysicalSubDiv physicalSubDivToRemove : physicalSubDivsToRemove) { //remove links in mets:structLink section List<SmLink> list = modifiedMets.getStructLink().getSmLinkByTo(physicalSubDivToRemove.getId()); LogicalStructMap logicalStructMap = (LogicalStructMap) modifiedMets .getStructMap(LogicalStructMap.TYPE); for (SmLink linkToRemove : list) { LOGGER.warn(String.format(Locale.ROOT, "remove smLink from \"%s\" to \"%s\"", linkToRemove.getFrom(), linkToRemove.getTo())); modifiedMets.getStructLink().removeSmLink(linkToRemove); // modify logical struct Map String logID = linkToRemove.getFrom(); // the deleted file was not directly assigned to a structure if (logicalStructMap.getDivContainer().getId().equals(logID)) { continue; } LogicalDiv logicalDiv = logicalStructMap.getDivContainer().getLogicalSubDiv( logID); if (logicalDiv == null) { LOGGER.error("Could not find {} with id {}", LogicalDiv.class.getSimpleName(), logID); LOGGER.error("Mets document remains unchanged"); return mets; } // there are still files for this logical sub div, nothing to do if (modifiedMets.getStructLink().getSmLinkByFrom(logicalDiv.getId()).size() > 0) { continue; } // the logical div has other divs included, nothing to do if (logicalDiv.getChildren().size() > 0) { continue; } /* * the log div might be in a hierarchy of divs, which may now be empty * (only containing empty directories), if so the parent of the log div * must be deleted * */ handleParents(logicalDiv, modifiedMets); logicalStructMap.getDivContainer().remove(logicalDiv); } divContainer.remove(physicalSubDivToRemove); } } } } catch (Exception ex) { LOGGER.error("Error occured while removing file {} from the existing mets file", file, ex); return null; } return modifiedMets.asDocument(); } private static void handleParents(LogicalDiv logDiv, Mets mets) { LogicalDiv parent = logDiv.getParent(); // there are files for the parent of the log div, thus nothing to do if (mets.getStructLink().getSmLinkByFrom(parent.getId()).size() > 0) { return; } //no files associated to the parent of the log div LogicalDiv logicalDiv = ((LogicalStructMap) mets.getStructMap(LogicalStructMap.TYPE)).getDivContainer(); if (parent.getParent() == logicalDiv) { //the parent the log div container itself, thus we quit here and remove the log div logicalDiv.remove(parent); } else { handleParents(parent, mets); } } /** * @return true if all files owned by the derivate appearing in the master file group or false otherwise */ public static boolean isComplete(Mets mets, MCRObjectID derivateId) { try { FileGrp fileGroup = mets.getFileSec().getFileGroup(FileGrp.USE_MASTER); MCRPath rootPath = MCRPath.getPath(derivateId.toString(), "/"); return isComplete(fileGroup, rootPath); } catch (Exception ex) { LOGGER.error("Error while validating mets", ex); return false; } } /** * @return true if all files in the {@link org.mycore.datamodel.ifs2.MCRDirectory} appears in the fileGroup */ public static boolean isComplete(final FileGrp fileGroup, MCRPath rootDir) { final AtomicBoolean complete = new AtomicBoolean(true); try { Files.walkFileTree(rootDir, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!file.getFileName().toString().equals(MCRMetsSave.getMetsFileName())) { MCRPath mcrPath = MCRPath.toMCRPath(file); String path; try { path = MCRXMLFunctions .encodeURIPath(mcrPath.getOwnerRelativePath().substring(1), true);//remove leading '/' } catch (URISyntaxException e) { throw new IOException(e); } if (!fileGroup.contains(path)) { LOGGER.warn("{} does not appear in {}!", path, mcrPath.getOwner()); complete.set(false); return FileVisitResult.TERMINATE; } } return super.visitFile(file, attrs); } }); } catch (Exception ex) { LOGGER.error("Error while validating mets", ex); return false; } return complete.get(); } /** * Call this method to update the mets.xml if files of the derivate have changed. Files will be added or removed * from the mets:fileSec and mets:StructMap[@type=PHYSICAL]. The mets:structLink part will be rebuild after. * * <p>This method takes care of the group assignment. For example: image files will be added to the MASTER * group and ALTO files to the ALTO group. It will also bundle files with the same name e.g. sample1.tiff and * alto/sample1.xml to the same physical struct map div.</p> * * <p><b>Important:</b> This method does not update the mets.xml in the derivate, its just updating the given mets * instance.</p> * * @param mets the mets to update * @param derivatePath path to the derivate -&gt; required for looking up new files * @throws IOException derivate couldn't be read */ public static void updateFiles(Mets mets, final MCRPath derivatePath) throws IOException { List<String> metsFiles = mets.getFileSec().getFileGroups().stream().flatMap(g -> g.getFileList().stream()) .map(File::getFLocat).map(FLocat::getHref).collect(Collectors.toList()); List<String> derivateFiles = Files.walk(derivatePath).filter(MCRStreamUtils.not(Files::isDirectory)) .map(MCRPath::toMCRPath).map(MCRPath::getOwnerRelativePath) .map(path -> path.substring(1)).filter(href -> !Objects.equals(href, "mets.xml")) .collect(Collectors.toList()); ArrayList<String> removedFiles = new ArrayList<>(metsFiles); removedFiles.removeAll(derivateFiles); ArrayList<String> addedFiles = new ArrayList<>(derivateFiles); Collections.sort(addedFiles); addedFiles.removeAll(metsFiles); StructLink structLink = mets.getStructLink(); PhysicalStructMap physicalStructMap = mets.getPhysicalStructMap(); List<String> unlinkedLogicalIds = new ArrayList<>(); // remove files PhysicalDiv physicalDiv = physicalStructMap.getDivContainer(); removedFiles.forEach(href -> { File file = null; // remove from fileSec for (FileGrp grp : mets.getFileSec().getFileGroups()) { file = grp.getFileByHref(href); if (file != null) { grp.removeFile(file); break; } } if (file == null) { return; } // remove from physical PhysicalSubDiv physicalSubDiv = physicalDiv.byFileId(file.getId()); physicalSubDiv.remove(physicalSubDiv.getFptr(file.getId())); if (physicalSubDiv.getChildren().isEmpty()) { physicalDiv.remove(physicalSubDiv); } // remove from struct link structLink.getSmLinkByTo(physicalSubDiv.getId()).forEach(smLink -> { structLink.removeSmLink(smLink); if (structLink.getSmLinkByFrom(smLink.getFrom()).isEmpty()) { unlinkedLogicalIds.add(smLink.getFrom()); } }); }); // fix unlinked logical divs if (!unlinkedLogicalIds.isEmpty()) { // get first physical div List<PhysicalSubDiv> physicalChildren = physicalStructMap.getDivContainer().getChildren(); String firstPhysicalID = physicalChildren.isEmpty() ? physicalStructMap.getDivContainer().getId() : physicalChildren.get(0).getId(); // a logical div is not linked anymore -> link with first physical div unlinkedLogicalIds.forEach(from -> structLink.addSmLink(new SmLink(from, firstPhysicalID))); } // get last logical div LogicalDiv divContainer = mets.getLogicalStructMap().getDivContainer(); List<LogicalDiv> descendants = divContainer.getDescendants(); LogicalDiv lastLogicalDiv = descendants.isEmpty() ? divContainer : descendants.get(descendants.size() - 1); // add files addedFiles.forEach(href -> { MCRPath filePath = (MCRPath) derivatePath.resolve(href); String fileBase = getFileBase(href); try { String fileGroupUse = MCRMetsSave.getFileGroupUse(filePath); // build file String mimeType = MCRContentTypes.probeContentType(filePath); String fileId = fileGroupUse.toLowerCase(Locale.ROOT) + "_" + fileBase; File file = new File(fileId, mimeType); file.setFLocat(new FLocat(LOCTYPE.URL, href)); // fileSec FileGrp fileGroup = mets.getFileSec().getFileGroup(fileGroupUse); if (fileGroup == null) { fileGroup = new FileGrp(fileGroupUse); mets.getFileSec().addFileGrp(fileGroup); } fileGroup.addFile(file); // structMap physical String existingFileID = mets.getFileSec().getFileGroups().stream() .filter(grp -> !grp.getUse().equals(fileGroupUse)) .flatMap(grp -> grp.getFileList().stream()).filter(brotherFile -> fileBase .equals(getFileBase(brotherFile.getFLocat().getHref()))) .map(File::getId).findAny() .orElse(null); PhysicalSubDiv physicalSubDiv; if (existingFileID != null) { // there is a file (e.g. img or alto) which the same file base -> add the file to this mets:div physicalSubDiv = physicalDiv.byFileId(existingFileID); physicalSubDiv.add(new Fptr(file.getId())); } else { // there is no mets:div with this file physicalSubDiv = new PhysicalSubDiv(PhysicalSubDiv.ID_PREFIX + fileBase, PhysicalSubDiv.TYPE_PAGE); physicalSubDiv.add(new Fptr(file.getId())); physicalDiv.add(physicalSubDiv); } // add to struct link structLink.addSmLink(new SmLink(lastLogicalDiv.getId(), physicalSubDiv.getId())); } catch (Exception exc) { LOGGER.error("Unable to add file {} to mets.xml of {}", href, derivatePath.getOwner(), exc); } }); } /** * Returns a list of files in the given path. This does not return directories! * * @param path the path to list * @param ignore paths which should be ignored * @return list of <code>MCRPath's</code> files * @throws IOException if an I/O error is thrown when accessing the starting file. */ public static List<MCRPath> listFiles(MCRPath path, Collection<MCRPath> ignore) throws IOException { return Files.walk(path) .filter(Files::isRegularFile) .map(MCRPath::toMCRPath) .filter(MCRStreamUtils.not(ignore::contains)) .sorted() .collect(Collectors.toList()); } /** * Builds new mets:fileGrp's based on the given paths using the mycore derivate convetions. * * <ul> * <li><b>root folder</b> -&gt; mets:fileGrp[@USE=MASTER]</li> * <li><b>alto/ folder</b> -&gt; mets:fileGrp[@USE=ALTO]</li> * <li><b>tei/translation folder</b> -&gt; mets:fileGrp[@USE=TRANSLATION</li> * <li><b>tei/transcription folder</b> -&gt; mets:fileGrp[@USE=TRANSCRIPTION</li> * </ul> * * @param paths the paths to check for the groups * @return a list of new created <code>FileGrp</code> objects */ public static List<FileGrp> buildFileGroups(List<MCRPath> paths) { return listFileUse(paths).stream() .map(FileGrp::new) .collect(Collectors.toList()); } /** * Returns a list of all <code>MCRMetsFileUse</code> in the given paths. * * @param paths paths to check * @return list of <code>MCRMetsFileUse</code> */ public static List<String> listFileUse(List<MCRPath> paths) { Set<String> fileUseSet = new HashSet<>(); for (MCRPath path : paths) { final Optional<String> use = MCRMetsModelHelper.getUseForHref(path.getOwnerRelativePath()); use.ifPresent(fileUseSet::add); } return new ArrayList<>(fileUseSet); } /** * Returns the name without any path information or file extension. Usable to create mets ID's. * * <ul> * <li>abc123.jpg -&gt; abc123</li> * <li>alto/abc123.xml -&gt; abc123</li> * </ul> * * @param href the href to get the file base name * @return the href shortcut */ public static String getFileBase(String href) { String fileName = Paths.get(href).getFileName().toString(); int endIndex = fileName.lastIndexOf("."); if (endIndex != -1) { fileName = fileName.substring(0, endIndex); } return MCRXMLFunctions.toNCNameSecondPart(fileName); } /** * Returns the name without any path information or file extension. Useable to create mets ID's. * * <ul> * <li>abc123.jpg -&gt; abc123</li> * <li>alto/abc123.xml -&gt; abc123</li> * </ul> * * @param path the href to get the file base name * @return the href shortcut */ public static String getFileBase(MCRPath path) { return getFileBase(path.getOwnerRelativePath().substring(1)); } /** * Returns the mets:file/@ID for the given path. * * @param path path to the file * @return mets:file ID */ public static String getFileId(MCRPath path) { String prefix = MCRMetsModelHelper.getUseForHref(path.getOwnerRelativePath()).orElse(UNKNOWN_FILEGROUP); String base = getFileBase(path); return prefix + "_" + base; } }
40,576
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDFGLinkServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/servlets/MCRDFGLinkServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.servlets; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.common.MCRPersistenceException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRPathContent; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.mets.model.MCRMETSGeneratorFactory; import org.mycore.mets.model.Mets; import org.mycore.mets.model.files.FLocat; import org.mycore.mets.model.files.File; import org.mycore.mets.model.files.FileGrp; import org.mycore.mets.model.struct.Fptr; import org.mycore.mets.model.struct.PhysicalDiv; import org.mycore.mets.model.struct.PhysicalStructMap; import org.mycore.mets.model.struct.PhysicalSubDiv; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * This servlet redirects to the DFG-viewer and * sets all parameters for specific images automatically if needed * * parameters: * deriv = the MyCoReID of the derivate (needed) * file = the Filename of the image that had to be shown in the DFG-Viewer (optional) * * @author Sebastian Röher (basti890) */ public class MCRDFGLinkServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRDFGLinkServlet.class); @Override protected void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); HttpServletResponse response = job.getResponse(); String filePath = request.getParameter("file") == null ? "" : request.getParameter("file"); String derivateID = request.getParameter("deriv") == null ? "" : request.getParameter("deriv"); if (Objects.equals(derivateID, "")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Derivate is not set"); } String encodedMetsURL = URLEncoder.encode(MCRServlet.getServletBaseURL() + "MCRMETSServlet/" + derivateID + "?XSL.Style=dfg", StandardCharsets.UTF_8); LOGGER.info(request.getPathInfo()); MCRPath rootPath = MCRPath.getPath(derivateID, "/"); if (!Files.isDirectory(rootPath)) { response.sendError(HttpServletResponse.SC_NOT_FOUND, String.format(Locale.ENGLISH, "Derivate %s does not exist.", derivateID)); return; } request.setAttribute("XSL.derivateID", derivateID); Collection<String> linkList = MCRLinkTableManager.instance().getSourceOf(derivateID); if (linkList.isEmpty()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format(Locale.ENGLISH, "Derivate %s is not linked with a MCRObject. Please contact an administrator.", derivateID)); return; } if (filePath.isEmpty()) { MCRDerivate derivate = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivateID)); filePath = derivate.getDerivate().getInternals().getMainDoc(); } MCRPath metsPath = (MCRPath) rootPath.resolve("mets.xml"); int imageNumber = -2; if (Files.exists(metsPath)) { imageNumber = getOrderNumber(new MCRPathContent(metsPath).asXML(), filePath); } else { MCRContent metsContent = getMetsSource(job, useExistingMets(request), derivateID); imageNumber = getOrderNumber(metsContent.asXML(), filePath); } switch (imageNumber) { case -1 -> response.sendError(HttpServletResponse.SC_CONFLICT, String.format(Locale.ENGLISH, "Image \"%s\" not found in the MCRDerivate. Please contact an administrator.", filePath)); case -2 -> response.sendRedirect("https://dfg-viewer.de/show/?tx_dlf[id]=" + encodedMetsURL); default -> response.sendRedirect( "https://dfg-viewer.de/show/?tx_dlf[id]=" + encodedMetsURL + "&set[image]=" + imageNumber); } } private static int getOrderNumber(Document metsDoc, String fileHref) { int orderNumber = -1; String fileID = null; try { Mets mets = new Mets(metsDoc); List<FileGrp> fileGroups = mets.getFileSec().getFileGroups(); for (FileGrp fileGrp : fileGroups) { List<File> fileList = fileGrp.getFileList(); for (File file : fileList) { FLocat fLocat = file.getFLocat(); if (fLocat.getHref().equals(MCRXMLFunctions.encodeURIPath(fileHref, true))) { fileID = file.getId(); } } } if (fileID != null) { PhysicalStructMap structMap = (PhysicalStructMap) mets.getStructMap(PhysicalStructMap.TYPE); PhysicalDiv rootDiv = structMap.getDivContainer(); List<PhysicalSubDiv> children = rootDiv.getChildren(); for (int index = 0; index < children.size(); index++) { PhysicalSubDiv physicalSubDiv = children.get(index); List<Fptr> fptrList = physicalSubDiv.getChildren(); for (Fptr fptr : fptrList) { if (fptr.getFileId().equals(fileID)) { orderNumber = index + 1; } } } } } catch (Exception e) { throw new MCRPersistenceException("could not parse mets.xml", e); } return orderNumber; } /** * Returns the mets document wrapped in a {@link MCRContent} object. * */ private static MCRContent getMetsSource(MCRServletJob job, boolean useExistingMets, String derivate) { MCRPath metsFile = MCRPath.getPath(derivate, "/mets.xml"); try { job.getRequest().setAttribute("XSL.derivateID", derivate); job.getRequest().setAttribute("XSL.objectID", MCRLinkTableManager.instance().getSourceOf(derivate).iterator().next()); } catch (Exception x) { LOGGER.warn("Unable to set \"XSL.objectID\" attribute to current request", x); } boolean metsExists = Files.exists(metsFile); if (metsExists && useExistingMets) { MCRContent content = new MCRPathContent(metsFile); content.setDocType("mets"); return content; } else { Document mets = MCRMETSGeneratorFactory.create(metsFile.getParent()).generate().asDocument(); return new MCRJDOMContent(mets); } } private boolean useExistingMets(HttpServletRequest request) { String useExistingMetsParam = request.getParameter("useExistingMets"); if (useExistingMetsParam == null) { return true; } return Boolean.parseBoolean(useExistingMetsParam); } }
8,285
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSServlet.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/servlets/MCRMETSServlet.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.servlets; import java.io.IOException; import java.nio.file.Files; import java.util.Collection; import java.util.Locale; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.common.MCRSession; import org.mycore.common.MCRSessionMgr; import org.mycore.common.MCRTransactionHelper; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRPathContent; import org.mycore.common.xml.MCRLayoutService; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.frontend.servlets.MCRServlet; import org.mycore.frontend.servlets.MCRServletJob; import org.mycore.mets.model.MCRMETSGeneratorFactory; import org.mycore.mets.tools.MCRMetsSave; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author Thomas Scheffler (yagee) */ public class MCRMETSServlet extends MCRServlet { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LogManager.getLogger(MCRMETSServlet.class); public static final boolean STORE_METS_ON_GENERATE = MCRConfiguration2 .getOrThrow("MCR.Mets.storeMetsOnGenerate", Boolean::parseBoolean); private boolean useExpire; private static int CACHE_TIME; @Override protected void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); HttpServletResponse response = job.getResponse(); LOGGER.info(request.getPathInfo()); String derivate = getOwnerID(request.getPathInfo()); MCRPath rootPath = MCRPath.getPath(derivate, "/"); if (!Files.isDirectory(rootPath)) { response.sendError(HttpServletResponse.SC_NOT_FOUND, String.format(Locale.ENGLISH, "Derivate %s does not exist.", derivate)); return; } request.setAttribute("XSL.derivateID", derivate); Collection<String> linkList = MCRLinkTableManager.instance().getSourceOf(derivate); if (linkList.isEmpty()) { MCRDerivate derivate2 = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivate)); MCRObjectID ownerID = derivate2.getOwnerID(); if (ownerID != null && ownerID.toString().length() != 0) { linkList.add(ownerID.toString()); } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format(Locale.ENGLISH, "Derivate %s is not linked with a MCRObject. Please contact an administrator.", derivate)); return; } } request.setAttribute("XSL.objectID", linkList.iterator().next()); response.setContentType("text/xml"); long lastModified = Files.getLastModifiedTime(rootPath).toMillis(); MCRFrontendUtil.writeCacheHeaders(response, CACHE_TIME, lastModified, useExpire); long start = System.currentTimeMillis(); MCRContent metsContent = getMetsSource(job, useExistingMets(request), derivate); MCRLayoutService.instance().doLayout(request, response, metsContent); LOGGER.info("Generation of code by {} took {} ms", this.getClass().getSimpleName(), System.currentTimeMillis() - start); } /** * Returns the mets document wrapped in a {@link MCRContent} object. */ static MCRContent getMetsSource(MCRServletJob job, boolean useExistingMets, String derivate) { MCRPath metsPath = MCRPath.getPath(derivate, "/mets.xml"); try { job.getRequest().setAttribute("XSL.derivateID", derivate); String objectid = MCRLinkTableManager.instance().getSourceOf(derivate).iterator().next(); if (objectid == null || objectid.length() == 0) { MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(derivate)); MCRObjectID ownerID = derObj.getOwnerID(); objectid = ownerID.toString(); } job.getRequest().setAttribute("XSL.objectID", objectid); } catch (Exception x) { LOGGER.warn("Unable to set \"XSL.objectID\" attribute to current request", x); } boolean metsExists = Files.exists(metsPath); if (metsExists && useExistingMets) { MCRContent content = new MCRPathContent(metsPath); content.setDocType("mets"); return content; } else { Document mets = MCRMETSGeneratorFactory.create(MCRPath.getPath(derivate, "/")).generate().asDocument(); if (!metsExists && STORE_METS_ON_GENERATE) { MCRMetsSave.saveMets(mets, MCRObjectID.getInstance(derivate)); } return new MCRJDOMContent(mets); } } /* * (non-Javadoc) * * @see org.mycore.frontend.servlets.MCRServlet#init() */ @Override public void init() throws ServletException { super.init(); String cacheParam = getInitParameter("cacheTime"); /* default is one day */ CACHE_TIME = cacheParam != null ? Integer.parseInt(cacheParam) : (60 * 60 * 24); useExpire = MCRConfiguration2.getBoolean("MCR.Component.MetsMods.Servlet.UseExpire").orElse(true); } private boolean useExistingMets(HttpServletRequest request) { String useExistingMetsParam = request.getParameter("useExistingMets"); if (useExistingMetsParam == null) { return true; } return Boolean.parseBoolean(useExistingMetsParam); } public static String getOwnerID(String pathInfo) { StringBuilder ownerID = new StringBuilder(pathInfo.length()); boolean running = true; for (int i = (pathInfo.charAt(0) == '/') ? 1 : 0; (i < pathInfo.length() && running); i++) { if (pathInfo.charAt(i) == '/') { running = false; } else { ownerID.append(pathInfo.charAt(i)); } } return ownerID.toString(); } /* * (non-Javadoc) * * @see * org.mycore.frontend.servlets.MCRServlet#getLastModified(jakarta.servlet * .http.HttpServletRequest) */ @Override protected long getLastModified(HttpServletRequest request) { String ownerID = getOwnerID(request.getPathInfo()); MCRSessionMgr.unlock(); MCRSession session = MCRSessionMgr.getCurrentSession(); MCRPath metsPath = MCRPath.getPath(ownerID, "/mets.xml"); try { MCRTransactionHelper.beginTransaction(); try { if (Files.exists(metsPath)) { return Files.getLastModifiedTime(metsPath).toMillis(); } else if (Files.isDirectory(metsPath.getParent())) { return Files.getLastModifiedTime(metsPath.getParent()).toMillis(); } } catch (IOException e) { LOGGER.warn("Error while retrieving last modified information from {}", metsPath, e); } return -1L; } finally { MCRTransactionHelper.commitTransaction(); MCRSessionMgr.releaseCurrentSession(); session.close(); // just created session for db transaction } } }
8,475
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsCommands.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/frontend/MCRMetsCommands.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.frontend; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.XMLOutputter; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRPathContent; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.cli.MCRAbstractCommands; import org.mycore.frontend.cli.MCRCommandUtils; import org.mycore.frontend.cli.MCRObjectCommands; import org.mycore.frontend.cli.annotation.MCRCommand; import org.mycore.frontend.cli.annotation.MCRCommandGroup; import org.mycore.mets.model.MCRMETSGeneratorFactory; import org.mycore.mets.model.converter.MCRSimpleModelXMLConverter; import org.mycore.mets.model.converter.MCRXMLSimpleModelConverter; import org.mycore.mets.model.simple.MCRMetsSimpleModel; import org.mycore.mets.tools.MCRMetsSave; import org.mycore.mets.validator.METSValidator; import org.mycore.mets.validator.validators.ValidationException; @MCRCommandGroup(name = "Mets Commands") public class MCRMetsCommands extends MCRAbstractCommands { private static final Logger LOGGER = LogManager.getLogger(MCRMetsCommands.class); public static ConcurrentLinkedQueue<String> invalidMetsQueue = new ConcurrentLinkedQueue<>(); @MCRCommand(syntax = "validate selected mets", help = "validates all mets.xml of selected derivates", order = 10) public static void validateSelectedMets() { List<String> selectedObjectIDs = MCRObjectCommands.getSelectedObjectIDs(); for (String objectID : selectedObjectIDs) { LOGGER.info("Validate mets.xml of {}", objectID); MCRPath metsFile = MCRPath.getPath(objectID, "/mets.xml"); if (Files.exists(metsFile)) { try { MCRContent content = new MCRPathContent(metsFile); InputStream metsIS = content.getInputStream(); METSValidator mv = new METSValidator(metsIS); List<ValidationException> validationExceptionList = mv.validate(); if (validationExceptionList.size() > 0) { invalidMetsQueue.add(objectID); } for (ValidationException validationException : validationExceptionList) { LOGGER.error(validationException.getMessage()); } } catch (IOException e) { LOGGER.error("Error while reading mets.xml of {}", objectID, e); } catch (JDOMException e) { LOGGER.error("Error while parsing mets.xml of {}", objectID, e); } } } } @MCRCommand(syntax = "try fix invalid mets", help = "This Command can be used to fix invalid mets files that was found in any validate selected mets runs.", order = 15) public static void fixInvalidMets() { while (true) { String selectedObjectID = invalidMetsQueue.poll(); if (selectedObjectID == null) { break; } LOGGER.info("Try to fix METS of {}", selectedObjectID); MCRPath metsFile = MCRPath.getPath(selectedObjectID, "/mets.xml"); SAXBuilder saxBuilder = new SAXBuilder(); Document metsDocument; try (InputStream metsInputStream = Files.newInputStream(metsFile)) { metsDocument = saxBuilder.build(metsInputStream); } catch (IOException | JDOMException e) { LOGGER.error(() -> "Cannot fix METS of " + selectedObjectID + ". Can not parse mets.xml!", e); return; } MCRMetsSimpleModel mcrMetsSimpleModel; try { mcrMetsSimpleModel = MCRXMLSimpleModelConverter.fromXML(metsDocument); } catch (Exception e) { LOGGER.error(() -> "Cannot fix METS of " + selectedObjectID + ". Can not convert to SimpleModel!", e); return; } Document newMets = MCRSimpleModelXMLConverter.toXML(mcrMetsSimpleModel); XMLOutputter xmlOutputter = new XMLOutputter(); try (OutputStream os = Files.newOutputStream(metsFile)) { xmlOutputter.output(newMets, os); } catch (IOException e) { LOGGER.error(() -> "Cannot fix METS of " + selectedObjectID + ". Can not write mets to derivate.", e); } } } @MCRCommand(syntax = "add mets files for derivate {0}", order = 20) public static void addMetsFileForDerivate(String derivateID) { MCRPath metsFile = MCRPath.getPath(derivateID, "/mets.xml"); if (!Files.exists(metsFile)) { try { LOGGER.debug("Start MCRMETSGenerator for derivate {}", derivateID); Document mets = MCRMETSGeneratorFactory.create(MCRPath.getPath(derivateID, "/")).generate() .asDocument(); MCRMetsSave.saveMets(mets, MCRObjectID.getInstance(derivateID)); LOGGER.debug("Stop MCRMETSGenerator for derivate {}", derivateID); } catch (Exception e) { LOGGER.error("Can't create mets file for derivate {}", derivateID); } } } @MCRCommand(syntax = "add mets files for project id {0}", order = 30) public static List<String> addMetsFileForProjectID(String projectID) { return MCRCommandUtils.getIdsForProjectAndType(projectID, "derivate") .map(id -> "add mets files for derivate " + id) .collect(Collectors.toList()); } }
6,696
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsMods2IIIFConverter.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/iiif/MCRMetsMods2IIIFConverter.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.iiif; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.mycore.access.MCRAccessException; import org.mycore.common.MCRConstants; import org.mycore.common.MCRException; import org.mycore.iiif.image.MCRIIIFImageUtil; 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.model.MCRIIIFImageInformation; import org.mycore.iiif.image.model.MCRIIIFImageProfile; import org.mycore.iiif.presentation.model.additional.MCRIIIFAnnotation; import org.mycore.iiif.presentation.model.attributes.MCRDCMIType; import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata; import org.mycore.iiif.presentation.model.attributes.MCRIIIFResource; import org.mycore.iiif.presentation.model.attributes.MCRIIIFService; import org.mycore.iiif.presentation.model.attributes.MCRIIIFViewingHint; 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; import org.mycore.mets.model.Mets; import org.mycore.mets.model.files.File; import org.mycore.mets.model.files.FileGrp; import org.mycore.mets.model.sections.DmdSec; import org.mycore.mets.model.struct.LogicalDiv; import org.mycore.mets.model.struct.LogicalStructMap; import org.mycore.mets.model.struct.MDTYPE; import org.mycore.mets.model.struct.MdWrap; import org.mycore.mets.model.struct.PhysicalDiv; import org.mycore.mets.model.struct.PhysicalStructMap; import org.mycore.mets.model.struct.PhysicalSubDiv; public class MCRMetsMods2IIIFConverter { private static final Logger LOGGER = LogManager.getLogger(); protected final Document metsDocument; protected final Mets mets; protected final String identifier; protected final FileGrp imageGrp; protected final Map<String, List<String>> logicalIdIdentifiersMap = new HashMap<>(); protected final Map<String, PhysicalSubDiv> identifierPhysicalMap = new ConcurrentHashMap<>(); protected final Map<PhysicalSubDiv, String> physicalIdentifierMap = new ConcurrentHashMap<>(); protected final Map<String, PhysicalSubDiv> idPhysicalMetsMap = new ConcurrentHashMap<>(); public MCRMetsMods2IIIFConverter(Document metsDocument, String identifier) { this.metsDocument = metsDocument; this.mets = new Mets(metsDocument); this.identifier = identifier; FileGrp imageGrp = mets.getFileSec().getFileGroup("MASTER"); if (imageGrp == null) { imageGrp = mets.getFileSec().getFileGroup("IVIEW"); } if (imageGrp == null) { imageGrp = mets.getFileSec().getFileGroup("MAX"); } if (imageGrp == null) { imageGrp = mets.getFileSec().getFileGroup("DEFAULT"); } if (imageGrp == null) { throw new MCRException("Could not find a image file group in mets!"); } this.imageGrp = imageGrp; this.mets.getPhysicalStructMap() .getDivContainer() .getChildren() .parallelStream() .forEach(physicalSubDiv -> { String id = getIIIFIdentifier(physicalSubDiv); identifierPhysicalMap.put(id, physicalSubDiv); physicalIdentifierMap.put(physicalSubDiv, id); idPhysicalMetsMap.put(physicalSubDiv.getId(), physicalSubDiv); }); mets.getStructLink().getSmLinks().forEach(smLink -> { String logicalId = smLink.getFrom(); List<String> identifiers; if (this.logicalIdIdentifiersMap.containsKey(logicalId)) { identifiers = this.logicalIdIdentifiersMap.get(logicalId); } else { identifiers = new ArrayList<>(); this.logicalIdIdentifiersMap.put(logicalId, identifiers); } identifiers.add(physicalIdentifierMap.get(idPhysicalMetsMap.get(smLink.getTo()))); }); } public MCRIIIFManifest convert() { MCRIIIFManifest manifest = new MCRIIIFManifest(); // root chapter ^= manifest metadata LogicalStructMap logicalStructMap = (LogicalStructMap) mets.getStructMap("LOGICAL"); LogicalDiv divContainer = logicalStructMap.getDivContainer(); List<MCRIIIFMetadata> metadata = extractMedataFromLogicalDiv(mets, divContainer); manifest.metadata = metadata; manifest.setId(this.identifier); PhysicalStructMap physicalStructMap = (PhysicalStructMap) mets.getStructMap("PHYSICAL"); PhysicalDiv physicalDivContainer = physicalStructMap.getDivContainer(); String id = physicalDivContainer.getId(); MCRIIIFSequence sequence = new MCRIIIFSequence(id); List<PhysicalSubDiv> children = physicalDivContainer.getChildren(); MCRIIIFImageImpl imageImpl = MCRIIIFImageImpl.getInstance(getImageImplName()); MCRIIIFImageProfile profile = imageImpl.getProfile(); profile.setId(MCRIIIFImageUtil.getProfileLink(imageImpl)); sequence.canvases = children.stream().map(physicalSubDiv -> { String order = physicalSubDiv.asElement().getAttributeValue("ORDER"); String orderLabel = physicalSubDiv.getOrderLabel(); String contentIds = physicalSubDiv.getContentIds(); String label = Stream.of(order, orderLabel, contentIds) .filter(o -> o != null && !o.isEmpty()) .collect(Collectors.joining(" - ")); label = (Objects.equals(label, "")) ? physicalSubDiv.getId() : label; String identifier = this.physicalIdentifierMap.get(physicalSubDiv); try { MCRIIIFImageInformation information = imageImpl.getInformation(new URI(identifier).getPath()); MCRIIIFCanvas canvas = new MCRIIIFCanvas(identifier, label, information.width, information.height); MCRIIIFAnnotation annotation = new MCRIIIFAnnotation(identifier, canvas); canvas.images.add(annotation); MCRIIIFResource resource = new MCRIIIFResource(information.getId(), MCRDCMIType.Image); resource.setWidth(information.width); resource.setHeight(information.height); MCRIIIFService service = new MCRIIIFService(information.getId(), profile.getContext()); service.profile = MCRIIIFImageProfile.IIIF_PROFILE_2_0; resource.setService(service); annotation.setResource(resource); return canvas; } catch (MCRIIIFImageNotFoundException | MCRIIIFImageProvidingException | URISyntaxException e) { throw new MCRException("Error while providing ImageInfo for " + identifier, e); } catch (MCRAccessException e) { LOGGER.warn("User has no access to {}", identifier); return null; } }).filter(Objects::nonNull) .collect(Collectors.toList()); manifest.sequences.add(sequence); List<MCRIIIFRange> complete = new ArrayList<>(); processDivContainer(complete, divContainer); manifest.structures.addAll(complete); manifest.setLabel( metadata.stream().filter(m -> m.getLabel().equals("title")).findFirst().get().getStringValue().get()); return manifest; } protected void processDivContainer(List<MCRIIIFRange> complete, LogicalDiv divContainer) { MCRIIIFRange range = new MCRIIIFRange(divContainer.getId()); if (divContainer.getParent() == null) { range.setViewingHint(MCRIIIFViewingHint.top); } complete.add(range); range.setLabel((divContainer.getLabel() != null) ? divContainer.getLabel() : divContainer.getType()); range.canvases.addAll(this.logicalIdIdentifiersMap.getOrDefault(divContainer.getId(), Collections.emptyList())); divContainer.getChildren() .forEach(div -> { processDivContainer(complete, div); range.ranges.add(div.getId()); }); range.metadata = extractMedataFromLogicalDiv(mets, divContainer); } protected String getImageImplName() { return "Iview"; } protected String getIIIFIdentifier(PhysicalSubDiv subDiv) { File file = subDiv.getChildren() .stream() .map(fptr -> imageGrp.getFileById(fptr.getFileId())) .filter(Objects::nonNull) .findAny().get(); String cleanHref = file.getFLocat().getHref(); cleanHref = cleanHref.substring(cleanHref.indexOf(this.identifier)); return cleanHref; } protected List<MCRIIIFMetadata> extractMedataFromLogicalDiv(Mets mets, LogicalDiv divContainer) { String dmdId = divContainer.getDmdId(); if (dmdId != null && !dmdId.isEmpty()) { DmdSec dmdSec = mets.getDmdSecById(dmdId); if (dmdSec != null) { MdWrap mdWrap = dmdSec.getMdWrap(); MDTYPE mdtype = mdWrap.getMdtype(); if (Objects.requireNonNull(mdtype) != MDTYPE.MODS) { LOGGER.info("No extractor found for mdType: {}", mdtype); return Collections.emptyList(); } MCRMetsIIIFModsMetadataExtractor extractor = new MCRMetsIIIFModsMetadataExtractor(); return extractor .extractModsMetadata(mdWrap.asElement().getChild("xmlData", MCRConstants.METS_NAMESPACE)); } } return Collections.emptyList(); } }
10,912
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsIIIFMetadataExtractor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/iiif/MCRMetsIIIFMetadataExtractor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.iiif; import java.util.List; import org.jdom2.Element; import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata; public interface MCRMetsIIIFMetadataExtractor { List<MCRIIIFMetadata> extractModsMetadata(Element modsElement); }
997
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsIIIFModsMetadataExtractor.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/iiif/MCRMetsIIIFModsMetadataExtractor.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.iiif; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.jdom2.Element; import org.jdom2.Text; import org.jdom2.filter.Filters; import org.jdom2.xpath.XPathExpression; import org.jdom2.xpath.XPathFactory; import org.mycore.common.MCRConstants; import org.mycore.iiif.presentation.model.attributes.MCRIIIFMetadata; public class MCRMetsIIIFModsMetadataExtractor implements MCRMetsIIIFMetadataExtractor { @Override public List<MCRIIIFMetadata> extractModsMetadata(Element xmlData) { Map<String, String> elementLabelMap = new HashMap<>(); elementLabelMap.put("title", "mods:mods/mods:titleInfo/mods:title/text()"); elementLabelMap.put("genre", "mods:mods/mods:genre/text()"); // TODO: add some more metadata return elementLabelMap.entrySet().stream().map(entry -> { XPathExpression<Text> pathExpression = XPathFactory.instance().compile(entry.getValue(), Filters.text(), null, MCRConstants.MODS_NAMESPACE); List<Text> texts = pathExpression.evaluate(xmlData); if (texts.size() == 0) { return null; } return new MCRIIIFMetadata(entry.getKey(), texts.stream().map(Text::getText).collect(Collectors.joining(", "))); }).filter(Objects::nonNull) .collect(Collectors.toList()); } }
2,203
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsIIIFPresentationImpl.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/iiif/MCRMetsIIIFPresentationImpl.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.iiif; import java.io.IOException; import java.nio.file.Files; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.content.MCRContent; import org.mycore.common.content.MCRJDOMContent; import org.mycore.common.content.MCRPathContent; import org.mycore.common.content.transformer.MCRContentTransformer; import org.mycore.common.content.transformer.MCRContentTransformerFactory; import org.mycore.common.content.transformer.MCRParameterizedTransformer; import org.mycore.common.xsl.MCRParameterCollector; import org.mycore.datamodel.common.MCRLinkTableManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.iiif.presentation.impl.MCRIIIFPresentationImpl; import org.mycore.iiif.presentation.model.basic.MCRIIIFManifest; import org.mycore.mets.model.MCRMETSGeneratorFactory; import org.mycore.mets.tools.MCRMetsSave; public class MCRMetsIIIFPresentationImpl extends MCRIIIFPresentationImpl { private static final String TRANSFORMER_ID_CONFIGURATION_KEY = "Transformer"; private static final Logger LOGGER = LogManager.getLogger(); public static final boolean STORE_METS_ON_GENERATE = MCRConfiguration2 .getOrThrow("MCR.Mets.storeMetsOnGenerate", Boolean::parseBoolean); public MCRMetsIIIFPresentationImpl(String implName) { super(implName); } @Override public MCRIIIFManifest getManifest(String id) { try { Document metsDocument = getMets(id); LOGGER.debug(() -> new XMLOutputter(Format.getPrettyFormat()).outputString(metsDocument)); return getConverter(id, metsDocument).convert(); } catch (IOException | JDOMException e) { throw new MCRException(e); } } protected MCRMetsMods2IIIFConverter getConverter(String id, Document metsDocument) { return new MCRMetsMods2IIIFConverter(metsDocument, id); } protected MCRContentTransformer getTransformer() { String transformerID = getProperties().get(TRANSFORMER_ID_CONFIGURATION_KEY); MCRContentTransformer transformer = MCRContentTransformerFactory.getTransformer(transformerID); if (transformer == null) { throw new MCRConfigurationException("Could not resolve transformer with id : " + transformerID); } return transformer; } public Document getMets(String id) throws IOException, JDOMException { String objectid = MCRLinkTableManager.instance().getSourceOf(id).iterator().next(); MCRContentTransformer transformer = getTransformer(); MCRParameterCollector parameter = new MCRParameterCollector(); if (objectid != null && objectid.length() != 0) { MCRDerivate derObj = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(id)); MCRObjectID ownerID = derObj.getOwnerID(); objectid = ownerID.toString(); parameter.setParameter("objectID", objectid); parameter.setParameter("derivateID", id); } final MCRPath metsPath = MCRPath.getPath(id, "mets.xml"); MCRContent source = Files.exists(metsPath) ? new MCRPathContent(metsPath) : generateMets(id); MCRContent content = transformer instanceof MCRParameterizedTransformer ? ((MCRParameterizedTransformer) transformer).transform(source, parameter) : transformer.transform(source); return content.asXML(); } private synchronized MCRJDOMContent generateMets(String id) { final Document document = MCRMETSGeneratorFactory.create(MCRPath.getPath(id, "/")).generate().asDocument(); if (STORE_METS_ON_GENERATE) { MCRMetsSave.saveMets(document, MCRObjectID.getInstance(id)); } return new MCRJDOMContent(document); } }
4,994
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRUpdateMetsOnDerivateChangeEventHandler.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/events/MCRUpdateMetsOnDerivateChangeEventHandler.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.events; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.events.MCREvent; import org.mycore.common.events.MCREventHandlerBase; import org.mycore.datamodel.common.MCRMarkManager; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.mets.tools.MCRMetsSave; /** * EventHandler updates the mets.xml after a file is added to an existing * derivate. * * @author shermann */ public class MCRUpdateMetsOnDerivateChangeEventHandler extends MCREventHandlerBase { private static final Logger LOGGER = LogManager.getLogger(MCRUpdateMetsOnDerivateChangeEventHandler.class); private String mets = MCRMetsSave.getMetsFileName(); /** * Checks if the mets.xml should be updated. * * @param evt the mcr event * @param file the file which was changed * @param attrs the file attributes * @return true if the mets shoud be updated, otherwise false */ protected boolean checkUpdateMets(MCREvent evt, Path file, BasicFileAttributes attrs) { // don't update if no MCRPath if (!(file instanceof MCRPath)) { return false; } // don't update if mets.xml is deleted Path fileName = file.getFileName(); if (fileName != null && fileName.toString().equals(mets)) { return false; } MCRPath mcrPath = MCRPath.toMCRPath(file); String derivateId = mcrPath.getOwner(); // don't update if mets.xml does not exist if (Files.notExists(MCRPath.getPath(derivateId, '/' + mets))) { return false; } // don't update if derivate or mycore object is marked for deletion MCRObjectID mcrDerivateId = MCRObjectID.getInstance(derivateId); MCRDerivate mcrDerivate = MCRMetadataManager.retrieveMCRDerivate(mcrDerivateId); return !MCRMarkManager.instance().isMarkedForDeletion(mcrDerivate); } /* (non-Javadoc) * @see org.mycore.common.events.MCREventHandlerBase * #handleFileDeleted(org.mycore.common.events.MCREvent, org.mycore.datamodel.ifs.MCRFile) */ @Override protected void handlePathDeleted(MCREvent evt, Path file, BasicFileAttributes attrs) { if (!checkUpdateMets(evt, file, attrs)) { return; } MCRPath mcrPath = MCRPath.toMCRPath(file); try { MCRMetsSave.updateMetsOnFileDelete(mcrPath); } catch (Exception e) { LOGGER.error("Error while updating mets file", e); } } @Override protected void handlePathCreated(MCREvent evt, Path file, BasicFileAttributes attrs) { if (!checkUpdateMets(evt, file, attrs)) { return; } MCRPath mcrPath = MCRPath.toMCRPath(file); try { MCRMetsSave.updateMetsOnFileAdd(mcrPath); } catch (Exception e) { LOGGER.error("Error while updating mets file", e); } } @Override protected void handleDerivateUpdated(MCREvent evt, MCRDerivate der) { MCRMetsSave.updateMetsOnUrnGenerate(der); } }
4,118
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MetsResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/resource/MetsResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.resource; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.apache.commons.io.IOUtils; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.XMLOutputter; import org.mycore.access.MCRAccessManager; import org.mycore.common.MCRClassTools; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.frontend.MCRFrontendUtil; import org.mycore.mets.model.MCRMETSGeneratorFactory; import org.mycore.mets.model.converter.MCRJSONSimpleModelConverter; import org.mycore.mets.model.converter.MCRSimpleModelJSONConverter; import org.mycore.mets.model.converter.MCRSimpleModelXMLConverter; import org.mycore.mets.model.converter.MCRXMLSimpleModelConverter; import org.mycore.mets.model.simple.MCRMetsSimpleModel; import org.mycore.mets.tools.MCRMetsLock; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; @Path("/mets") public class MetsResource { public static final String METS_XML_PATH = "/mets.xml"; @GET @Path("/editor/start/{derivateId}") @Produces(MediaType.TEXT_HTML) public String startEditor(@PathParam("derivateId") String derivateId) { MCRObjectID derivateIdObject = MCRObjectID.getInstance(derivateId); checkDerivateExists(derivateIdObject); checkDerivateAccess(derivateIdObject, MCRAccessManager.PERMISSION_WRITE); InputStream resourceAsStream = MCRClassTools.getClassLoader().getResourceAsStream("mets-editor.html"); try { StringWriter writer = new StringWriter(); IOUtils.copy(resourceAsStream, writer, StandardCharsets.UTF_8); String htmlTemplate = writer.toString(); // add additional javascript code String js = MCRConfiguration2.getString("MCR.Mets.Editor.additional.javascript").orElse(null); if (js != null && !js.isEmpty()) { htmlTemplate = htmlTemplate.replace("<link rel=\"additionalJS\" />", js); } // replace variables htmlTemplate = htmlTemplate.replaceAll("\\{baseURL\\}", MCRFrontendUtil.getBaseURL()) .replaceAll("\\{derivateID\\}", derivateId); return htmlTemplate; } catch (IOException e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/editor/islocked/{derivateId}") public String isLocked(@PathParam("derivateId") String derivateId) { checkDerivateAccess(MCRObjectID.getInstance(derivateId), MCRAccessManager.PERMISSION_READ); boolean isLocked = MCRMetsLock.isLocked(derivateId); return "{\"lock\": " + isLocked + " }"; } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/editor/lock/{derivateId}") public String lock(@PathParam("derivateId") String derivateId) { checkDerivateAccess(MCRObjectID.getInstance(derivateId), MCRAccessManager.PERMISSION_WRITE); boolean isLockSuccessfully = MCRMetsLock.doLock(derivateId); return "{\"success\": " + isLockSuccessfully + " }"; } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/editor/unlock/{derivateId}") public String unlock(@PathParam("derivateId") String derivateId) { checkDerivateAccess(MCRObjectID.getInstance(derivateId), MCRAccessManager.PERMISSION_WRITE); try { MCRMetsLock.doUnlock(derivateId); return "{\"success\": true }"; } catch (MCRException e) { return "{\"success\": false }"; } } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/crud/{derivateId}") public String get(@PathParam("derivateId") String derivateId) { MCRObjectID derivateIdObject = MCRObjectID.getInstance(derivateId); checkDerivateExists(derivateIdObject); checkDerivateAccess(derivateIdObject, MCRAccessManager.PERMISSION_READ); MCRPath rootPath = MCRPath.getPath(derivateId, "/"); if (!Files.isDirectory(rootPath)) { throw new WebApplicationException(Response.Status.NOT_FOUND); } MCRPath metsPath = MCRPath.getPath(derivateId, METS_XML_PATH); try { return MCRSimpleModelJSONConverter.toJSON(MCRXMLSimpleModelConverter.fromXML(getMetsDocument(metsPath))); } catch (Exception e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/crud/{derivateId}") public String save(@PathParam("derivateId") String derivateId, String data) { MCRObjectID derivateIdObject = MCRObjectID.getInstance(derivateId); checkDerivateExists(derivateIdObject); checkDerivateAccess(derivateIdObject, MCRAccessManager.PERMISSION_WRITE); MCRMetsSimpleModel model = MCRJSONSimpleModelConverter.toSimpleModel(data); Document document = MCRSimpleModelXMLConverter.toXML(model); XMLOutputter o = new XMLOutputter(); try (OutputStream out = Files.newOutputStream(MCRPath.getPath(derivateId, METS_XML_PATH), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { o.output(document, out); } catch (IOException e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } return "{ \"success\": true }"; } @DELETE @Path("/crud/{derivateId}") public String delete(@PathParam("derivateId") String derivateId) { MCRObjectID derivateIdObject = MCRObjectID.getInstance(derivateId); checkDerivateExists(derivateIdObject); checkDerivateAccess(derivateIdObject, MCRAccessManager.PERMISSION_DELETE); try { Files.delete(MCRPath.getPath(derivateId, METS_XML_PATH)); } catch (IOException e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } return "{ \"success\": true }"; } /** * A simple helper to receive existing or create new default mets document. * @param metsPath the path to the mets document * @return a document with the content of the mets.xml * @throws WebApplicationException if something went wrong while generating or parsing the mets */ private Document getMetsDocument(MCRPath metsPath) { if (!Files.exists(metsPath)) { try { return MCRMETSGeneratorFactory.create(metsPath.getParent()).generate().asDocument(); } catch (Exception e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } else { try (InputStream inputStream = Files.newInputStream(metsPath)) { SAXBuilder builder = new SAXBuilder(); return builder.build(inputStream); } catch (JDOMException | IOException e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } } } /** * A simple helper to detect if a user has a specific permission for a derivate. * * @param derivateIdObject the id Object of the derivate * @param permission the permission to check {@link MCRAccessManager#PERMISSION_DELETE} * | {@link MCRAccessManager#PERMISSION_READ} | {@link MCRAccessManager#PERMISSION_WRITE} * @throws WebApplicationException if the user doesnt have the permission */ private void checkDerivateAccess(MCRObjectID derivateIdObject, String permission) { if (!MCRAccessManager.checkPermission(derivateIdObject, permission)) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } /** * A simple helper to detect if a derivate exists. * * @param derivateIdObject the id object of the derivate * @throws WebApplicationException if the derivate does not exists */ private void checkDerivateExists(MCRObjectID derivateIdObject) { if (!MCRMetadataManager.exists(derivateIdObject)) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } }
9,659
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRAltoHighlightResource.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/resource/MCRAltoHighlightResource.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.resource; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.params.ModifiableSolrParams; import org.mycore.frontend.jersey.MCRJerseyUtil; import org.mycore.solr.MCRSolrClientFactory; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.core.Response; /** * <p>Solr resource for alto text highlighting.</p> * * <b>Example: rsc/alto/highlight/mycore_derivate_00000001?q="jena paradies"</b> * * <pre> * [ * { * "id": "mycore_derivate_00000001:/alto/alto_1.xml", * "hits": [ * { * "hl": "Es ist schön in <em>Jena</em> <em>Paradies</em>.", * "positions":[ * { * "content": "Jena", * "xpos": 1566, * "vpos": 1100, * "width": 105, * "height": 44 * }, * { * "content": "Paradies", * "xpos": 1671, * "vpos": 1100, * "width": 185, * "height": 47 * } * ] * }, * { * "hl": ..., * "positions": [ * ... * ] * } * ... * ] * }, * * { * "id": "alto/alto_2.xml", * ... * }, * * ... * * ] * </pre> */ @Path("/alto/highlight") public class MCRAltoHighlightResource { @GET @Path("{derivateId}") @Produces(MCRJerseyUtil.APPLICATION_JSON_UTF8) public Response query(@PathParam("derivateId") String derivateId, @QueryParam("q") String query) { ModifiableSolrParams p = new ModifiableSolrParams(); p.set("q", buildQuery(query)); p.add("fq", "derivateID:" + derivateId); p.set("fl", "id"); p.set("rows", Integer.MAX_VALUE - 1); p.set("hl", "on"); p.set("hl.method", "unified"); p.set("hl.fl", "alto_content,alto_words"); p.set("hl.snippets", Integer.MAX_VALUE - 1); p.set("hl.bs.type", "WORD"); p.set("hl.fragsize", 70); p.set("hl.maxAnalyzedChars", Integer.MAX_VALUE - 1); try { QueryResponse solrResponse = MCRSolrClientFactory.getMainSolrClient().query(p); JsonArray response = buildQueryResponse(solrResponse.getHighlighting()); return Response.ok().entity(new Gson().toJson(response)).build(); } catch (Exception exc) { throw new WebApplicationException("Unable to highlight '" + query + "' of derivate " + derivateId, exc, Response.Status.INTERNAL_SERVER_ERROR); } } protected String buildQuery(String query) { String fixedQuery = query.trim().replaceAll("\\s\\s", " "); List<String> words = new ArrayList<>(); StringBuilder currentWord = new StringBuilder(); boolean split = true; for (int i = 0; i < fixedQuery.length(); i++) { char c = fixedQuery.charAt(i); if (c == ' ' && split) { addWord(words, currentWord.toString()); currentWord = new StringBuilder(); } else if (c == '"') { split = !split; } else { currentWord.append(c); } } addWord(words, currentWord.toString()); return String.join(" ", words); } protected void addWord(List<String> words, String word) { if (word.isEmpty()) { return; } String field = "alto_content:"; words.add(word.contains(" ") ? field + "\"" + word + "\"" : field + word); } private JsonArray buildQueryResponse(Map<String, Map<String, List<String>>> highlighting) { JsonArray response = new JsonArray(); highlighting.forEach((id, fields) -> buildPageObject(id, fields).ifPresent(response::add)); return response; } private Optional<JsonObject> buildPageObject(String id, Map<String, List<String>> fields) { JsonObject page = new JsonObject(); JsonArray hits = new JsonArray(); page.addProperty("id", toMCRPathId(id)); page.add("hits", hits); List<String> altoContentList = fields.get("alto_content"); List<String> altoWords = fields.get("alto_words"); if (altoContentList.size() == 0 || altoWords.size() == 0) { return Optional.empty(); } int wordIndex = 0; for (String altoContent : altoContentList) { JsonObject hit = new JsonObject(); hit.addProperty("hl", altoContent); JsonArray positions = new JsonArray(); int wordCount = StringUtils.countMatches(altoContent, "<em>"); for (int i = wordIndex; i < wordIndex + wordCount; i++) { String altoWord = altoWords.get(i); if (!altoWord.equals("")) { JsonObject positionObject = buildPositionObject(altoWord); if (!positionObject.entrySet().isEmpty()) { positions.add(positionObject); } } else if (wordCount < altoWords.size()) { wordCount++; } } wordIndex += wordCount; hit.add("positions", positions); hits.add(hit); } return Optional.of(page); } private String toMCRPathId(String ifsId) { return ifsId.replaceFirst("ifs\\d?:/", ""); } private JsonObject buildPositionObject(String altoWord) { JsonObject positionObject = new JsonObject(); String plainWord = altoWord.replaceAll("<em>|</em>", ""); String[] split = plainWord.split("\\|"); if (split.length == 5) { positionObject.addProperty("content", split[0]); positionObject.addProperty("xpos", Integer.parseInt(split[1])); positionObject.addProperty("vpos", Integer.parseInt(split[2])); positionObject.addProperty("width", Integer.parseInt(split[3])); positionObject.addProperty("height", Integer.parseInt(split[4])); } return positionObject; } }
7,515
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsModelHelper.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRMetsModelHelper.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.config.MCRConfiguration2; public class MCRMetsModelHelper { public static final String TRANSLATION_USE = "TEI.TRANSLATION"; public static final String TRANSCRIPTION_USE = "TEI.TRANSCRIPTION"; public static final String ALTO_USE = "ALTO"; public static final String MASTER_USE = "MASTER"; protected static final String ALLOWED_TRANSLATION_PROPERTY = "MCR.METS.Allowed.Translation.Subfolder"; private static final Set<String> ALLOWED_TRANSLATION = MCRConfiguration2.getString(ALLOWED_TRANSLATION_PROPERTY) .map(folders -> folders.split(",")) .map(Arrays::asList) .map(HashSet::new) .map(Set.class::cast) .orElse(Collections.emptySet()); private static final Logger LOGGER = LogManager.getLogger(); public static Optional<String> getUseForHref(final String href) { final String hrefWithoutSlash = href.startsWith("/") ? href.substring(1) : href; final int lastFolderPosition = hrefWithoutSlash.lastIndexOf("/"); final String path = (lastFolderPosition == -1) ? "" : hrefWithoutSlash.substring(0, lastFolderPosition); if (path.startsWith("tei/")) { return handleTEI(hrefWithoutSlash, path); } else if (hrefWithoutSlash.startsWith("alto/")) { return Optional.of(ALTO_USE); } return Optional.of(MASTER_USE); } private static Optional<String> handleTEI(String hrefWithoutSlash, String path) { final String[] pathParts = path.split("/"); if (pathParts.length == 1) { LOGGER.warn("Could not detect the file group of " + hrefWithoutSlash); return Optional.empty(); } final String teiType = pathParts[1]; if (Objects.equals(teiType, "transcription")) { return Optional.of(TRANSCRIPTION_USE); } else if (teiType.startsWith("translation.")) { final String translation = teiType.split("[.]", 2)[1]; if (!ALLOWED_TRANSLATION.contains(translation)) { LOGGER.warn( "Can not detect file group because " + translation + " is not in list of allowed translations " + ALLOWED_TRANSLATION_PROPERTY); return Optional.empty(); } return Optional.of(TRANSLATION_USE + "." + translation.toUpperCase(Locale.ROOT)); } else { return Optional.empty(); } } }
3,488
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSHierarchyGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSHierarchyGenerator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import java.io.IOException; import java.net.URISyntaxException; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.MCRStreamUtils; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetaDerivateLink; import org.mycore.datamodel.metadata.MCRMetaElement; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObject; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.metadata.MCRObjectUtils; import org.mycore.datamodel.niofs.MCRContentTypes; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.mets.misc.DefaultStructLinkGenerator; import org.mycore.mets.model.files.FLocat; import org.mycore.mets.model.files.File; import org.mycore.mets.model.files.FileGrp; import org.mycore.mets.model.files.FileSec; import org.mycore.mets.model.header.MetsHdr; import org.mycore.mets.model.sections.AmdSec; import org.mycore.mets.model.sections.DmdSec; import org.mycore.mets.model.struct.AbstractDiv; import org.mycore.mets.model.struct.Area; import org.mycore.mets.model.struct.Fptr; import org.mycore.mets.model.struct.LOCTYPE; import org.mycore.mets.model.struct.LogicalDiv; import org.mycore.mets.model.struct.LogicalStructMap; import org.mycore.mets.model.struct.PhysicalDiv; import org.mycore.mets.model.struct.PhysicalStructMap; import org.mycore.mets.model.struct.PhysicalSubDiv; import org.mycore.mets.model.struct.Seq; import org.mycore.mets.model.struct.StructLink; import org.mycore.mets.tools.MCRMetsSave; /** * This class generates a METS xml file for the METS-Editor. In difference to the default * implementation, the hierarchy of the MCRObjects and their derivate links are considered. * Starting from the root element, all children are hierarchically recorded in the logical * structure map of the METS file. If your application supports derivate links, the struct link * part links to those files. * * @author Matthias Eichner */ public abstract class MCRMETSHierarchyGenerator extends MCRMETSAbstractGenerator { private static final Logger LOGGER = LogManager.getLogger(); protected MCRDerivate mcrDer; protected MCRObject rootObj; protected MetsHdr metsHdr; protected AmdSec amdSection; protected DmdSec dmdSection; protected FileSec fileSection; protected PhysicalStructMap physicalStructMap; protected LogicalStructMap logicalStructMap; protected StructLink structLink; protected List<FileRef> files; /** * Hashmap to store logical and physical ids. */ protected Map<LogicalDiv, List<PhysicalSubDiv>> structLinkMap; public MCRMETSHierarchyGenerator() { this.files = new ArrayList<>(); } @Override public synchronized Mets generate() throws MCRException { long startTime = System.currentTimeMillis(); String derivateId = getOwner(); setup(derivateId); try { Mets mets = createMets(); LOGGER.info("mets creation for derivate {} took {}ms!", derivateId, System.currentTimeMillis() - startTime); return mets; } catch (Exception exc) { throw new MCRException("Unable to create mets.xml of " + derivateId, exc); } } /** * Initializes the derivate and the root object. * * @param derivateId the derivate id to setup */ protected void setup(String derivateId) { // get derivate MCRObjectID derId = MCRObjectID.getInstance(derivateId); this.mcrDer = MCRMetadataManager.retrieveMCRDerivate(derId); // get mycore object MCRObjectID objId = this.mcrDer.getDerivate().getMetaLink().getXLinkHrefID(); this.rootObj = MCRMetadataManager.retrieveMCRObject(objId); } /** * Does the mets creation. * * @return the new created mets * @throws IOException files of the path couldn't be read */ protected Mets createMets() throws IOException { LOGGER.info("create mets for derivate {}...", this.mcrDer.getId()); this.structLinkMap = new HashMap<>(); // create mets sections this.metsHdr = createMetsHdr(); this.amdSection = createAmdSection(); this.dmdSection = createDmdSection(); this.fileSection = createFileSection(); this.physicalStructMap = createPhysicalStruct(); this.logicalStructMap = createLogicalStruct(); this.structLink = createStructLink(); // add to mets Mets mets = new Mets(); mets.setMetsHdr(metsHdr); mets.addAmdSec(this.amdSection); mets.addDmdSec(this.dmdSection); mets.setFileSec(this.fileSection); mets.addStructMap(this.physicalStructMap); mets.addStructMap(this.logicalStructMap); mets.setStructLink(this.structLink); return mets; } /** * Creates a new mets header with current dates and record status = autogenerated. * * @return generated mets header section. */ protected MetsHdr createMetsHdr() { MetsHdr hdr = new MetsHdr(); hdr.setCreateDate(Instant.now()); hdr.setLastModDate(Instant.now()); hdr.setRecordStatus("autogenerated"); return hdr; } /** * Creates a new empty amd section. Id is amd_{derivate id}. * * @return generated amd section. */ protected AmdSec createAmdSection() { String amdId = "amd_" + this.mcrDer.getId(); return new AmdSec(amdId); } /** * Creates a new empty dmd section. Id is dmd_{derivate id}. * * @return generated dmd section. */ protected DmdSec createDmdSection() { String dmdSec = "dmd_" + this.mcrDer.getId(); return new DmdSec(dmdSec); } /** * Creates the file section. * * @return generated file secion. */ protected FileSec createFileSection() throws IOException { FileSec fileSec = new FileSec(); List<MCRPath> filePaths = MCRMetsSave.listFiles(getDerivatePath(), getIgnorePaths()); List<FileGrp> fileGrps = MCRMetsSave.buildFileGroups(filePaths); fileGrps.forEach(fileSec::addFileGrp); for (MCRPath file : filePaths) { String contentType = MCRContentTypes.probeContentType(file); FileRef ref = buildFileRef(file, contentType); this.files.add(ref); } for (FileRef ref : this.files) { String use = MCRMetsModelHelper.getUseForHref(ref.getPath().getOwnerRelativePath()).orElse("UNKNOWN"); FileGrp fileGrp = fileGrps.stream().filter(grp -> grp.getUse().equals(use)).findFirst().orElse(null); if (fileGrp == null) { LOGGER.warn( "Unable to add file '{}' because cannot find corresponding group with @USE='{}'. " + "Ignore file and continue.", ref.toFileId(), use); continue; } addFile(ref, fileGrp); } return fileSec; } protected void addFile(FileRef fileRef, FileGrp fileGroup) { File imageFile = new File(fileRef.toFileId(fileGroup), fileRef.getContentType()); try { final String href = fileRef.toFileHref(fileGroup); FLocat fLocat = new FLocat(LOCTYPE.URL, href); imageFile.setFLocat(fLocat); fileGroup.addFile(imageFile); } catch (Exception exc) { LOGGER.error("invalid href for " + fileRef.getPath(), exc); } } /** * This method creates the physical structure map. * * @return generated pyhiscal struct map secion. */ protected PhysicalStructMap createPhysicalStruct() { PhysicalStructMap pstr = new PhysicalStructMap(); PhysicalDiv physicalDiv = new PhysicalDiv("phys_" + this.mcrDer.getId(), PhysicalDiv.TYPE_PHYS_SEQ); pstr.setDivContainer(physicalDiv); // run through file references for (FileRef ref : this.files) { String physId = ref.toPhysId(); PhysicalSubDiv page = physicalDiv.get(physId); if (page == null) { page = new PhysicalSubDiv(physId, PhysicalSubDiv.TYPE_PAGE); getOrderLabel(ref.toFileId()).ifPresent(page::setOrderLabel); physicalDiv.add(page); } page.add(new Fptr(ref.toFileId())); } return pstr; } /** * Returns the order label for the given file. * * @param fileId of the mets:file in the mets:fileSec * @return optional order label */ protected Optional<String> getOrderLabel(String fileId) { return getOldMets().map(oldMets -> { PhysicalSubDiv subDiv = oldMets.getPhysicalStructMap().getDivContainer().byFileId(fileId); if (subDiv == null) { LOGGER.warn("Unable to get @ORDERLABEL of physical div '{}'.", fileId); return null; } return subDiv.getOrderLabel(); }); } /** * Creates the logical struct map. * * @return a newly created logical struct map */ protected LogicalStructMap createLogicalStruct() { LogicalStructMap lsm = newLogicalStructMap(); mergeOldLogicalStructMap(lsm); return lsm; } protected LogicalStructMap newLogicalStructMap() { LogicalStructMap lstr = new LogicalStructMap(); MCRObjectID objId = this.rootObj.getId(); // create main div String amdId = this.amdSection.getId(); String dmdId = this.dmdSection.getId(); LogicalDiv logicalDiv = new LogicalDiv(objId.toString(), getType(this.rootObj), getLabel(this.rootObj), amdId, dmdId); lstr.setDivContainer(logicalDiv); // run through all children newLogicalStructMap(this.rootObj, logicalDiv); return lstr; } /** * Creates the logical structure recursive. * * @param parentObject mycore object * @param parentLogicalDiv parent div */ protected void newLogicalStructMap(MCRObject parentObject, LogicalDiv parentLogicalDiv) { // run through all children List<MCRObject> children = getChildren(parentObject); children.forEach(childObject -> { // create new logical sub div String id = childObject.getId().toString(); LogicalDiv logicalChildDiv = new LogicalDiv(id, getType(childObject), getLabel(childObject)); // add to parent parentLogicalDiv.add(logicalChildDiv); // check if a derivate link exists and get the linked file FileGrp masterGroup = this.fileSection.getFileGroup(FileGrp.USE_MASTER); updateStructLinkMapUsingDerivateLinks(logicalChildDiv, childObject, masterGroup); // do recursive call for children newLogicalStructMap(childObject, logicalChildDiv); }); } /** * Runs through the logical part of the old mets and copies the ALTO part (mets:fptr/mets:seq/mets:area) * to the newly created logical struct map. This is done by comparing the mets:div @ID's of the old and the new * logical struct map. If two @ID's are equal, we can assume that it is the same mets:div and we just copy all * the old mets:fptr's. * * @param logicalStructMap the logical struct map to enhance */ protected void mergeOldLogicalStructMap(LogicalStructMap logicalStructMap) { if (!this.getOldMets().isPresent()) { return; } Mets oldMets = this.getOldMets().get(); LogicalStructMap oldLsm = oldMets.getLogicalStructMap(); FileGrp oldAltoGroup = oldMets.getFileSec().getFileGroup("ALTO"); FileGrp newAltoGroup = this.fileSection.getFileGroup("ALTO"); List<LogicalDiv> descendants = oldLsm.getDivContainer().getDescendants(); descendants.stream().filter(div -> !div.getFptrList().isEmpty()).forEach(oldDiv -> { String id = oldDiv.getId(); LogicalDiv newDiv = logicalStructMap.getDivContainer().getLogicalSubDiv(id); if (newDiv != null) { for (Fptr fptr : oldDiv.getFptrList()) { copyFptr(oldAltoGroup, newAltoGroup, fptr).ifPresent(newFptr -> newDiv.getFptrList().add(newFptr)); } updateStructLinkMapUsingALTO(newDiv); } else { LOGGER.warn( "Unable to find logical div @ID='{}' of previous mets.xml in this generated mets.xml. " + "Be aware that the content of the 'old' logical div cannot be copied and therefore cannot " + "be preserved!", id); } }); } private Optional<Fptr> copyFptr(FileGrp oldGrp, FileGrp newGrp, Fptr oldFptr) { Fptr newFptr = new Fptr(); for (Seq oldSeq : oldFptr.getSeqList()) { Seq newSeq = new Seq(); for (Area oldArea : oldSeq.getAreaList()) { if (oldArea.getBetype() == null) { continue; } String oldFileID = oldArea.getFileId(); File oldFile = oldGrp.getFileById(oldFileID); String href = oldFile.getFLocat().getHref(); File newFile = newGrp.getFileByHref(href); Area newArea = new Area(); newArea.setBegin(oldArea.getBegin()); newArea.setEnd(oldArea.getEnd()); newArea.setFileId(newFile.getId()); newArea.setBetype("IDREF"); newSeq.getAreaList().add(newArea); } if (!newSeq.getAreaList().isEmpty()) { newFptr.getSeqList().add(newSeq); } } return newFptr.getSeqList().isEmpty() ? Optional.empty() : Optional.of(newFptr); } /** * Fills the structLinkMap for a single logical mets:div using derivate link information. * * @param logicalDiv the logical div to handle * @param mcrObject the mycore object linked in the logical div (mets:div/@ID == mycore object id) * @param group the group to search the corresponding File ID. this is usally the MASTER group */ protected void updateStructLinkMapUsingDerivateLinks(LogicalDiv logicalDiv, MCRObject mcrObject, FileGrp group) { // get the derivate link Optional<String> linkedFileOptional = getLinkedFile(mcrObject); // resolve the derivate link using the FileRef API Optional<String> resolvedFileHref = linkedFileOptional.map(linkedFile -> { FileRef tempRef = buildFileRef(MCRPath.toMCRPath(getDerivatePath().resolve(linkedFile)), null); return tempRef.toFileHref(group); }); // add to struct link map resolvedFileHref.flatMap(linkedFile -> this.getFileId(linkedFile, group)).ifPresent(fileId -> { PhysicalSubDiv physicalDiv = getPhysicalDiv(fileId); addToStructLinkMap(logicalDiv, physicalDiv); }); } /** * Fills the structLinkMap for a single logical mets:div using mets:area/@FILEID information. * * @param logicalDiv the logical div to handle */ protected void updateStructLinkMapUsingALTO(final LogicalDiv logicalDiv) { logicalDiv.getFptrList() .stream() .flatMap(fptr -> fptr.getSeqList().stream()) .flatMap(seq -> seq.getAreaList().stream()) .map(Area::getFileId) .map(this::getPhysicalDiv) .forEach(physicalDiv -> addToStructLinkMap(logicalDiv, physicalDiv)); } /** * Adds the physical div to the logical div. Required to build the mets:structLink section. * * @param from logical div * @param to physical div */ protected void addToStructLinkMap(LogicalDiv from, PhysicalSubDiv to) { if (from == null || to == null) { return; } List<PhysicalSubDiv> physicalSubDivs = this.structLinkMap.getOrDefault(from, new ArrayList<>()); physicalSubDivs.add(to); physicalSubDivs = physicalSubDivs.stream().filter(MCRStreamUtils.distinctByKey(AbstractDiv::getId)) .sorted((div1, div2) -> { if (div1.getOrder() != null && div2.getOrder() != null) { return div1.getOrder().compareTo(div2.getOrder()); } return div1.getId().compareTo(div2.getId()); }).collect(Collectors.toList()); this.structLinkMap.put(from, physicalSubDivs); } /** * Returns all children id's of this MCRObject. * * @param parentObject the mycore object */ protected List<MCRObject> getChildren(MCRObject parentObject) { return MCRObjectUtils.getChildren(parentObject); } /** * Creates the mets:structLink part of the mets.xml * * @return a newly generated StructLink. */ protected StructLink createStructLink() { DefaultStructLinkGenerator structLinkGenerator = new DefaultStructLinkGenerator(this.structLinkMap); structLinkGenerator.setFailEasy(false); return structLinkGenerator.generate(this.physicalStructMap, this.logicalStructMap); } /** * Runs through all files in the given FileGrp and tries to find the corresponding mets:file @ID. * * @param group the file group * @param uriEncodedLinkedFile the file to find * @return the fileSec @ID */ private Optional<String> getFileId(String uriEncodedLinkedFile, FileGrp group) { return group.getFileList().stream().filter(file -> { String href = file.getFLocat().getHref(); boolean equals = href.equals(uriEncodedLinkedFile); boolean equalsWithoutSlash = uriEncodedLinkedFile.startsWith("/") && href.equals(uriEncodedLinkedFile.substring(1)); return equals || equalsWithoutSlash; }).map(File::getId).findFirst(); } /** * Returns a physical sub div by the given fileId. * * @param fileId id of a file element in fileGrp * @return finds a physical div by the given file id */ private PhysicalSubDiv getPhysicalDiv(String fileId) { if (fileId == null) { return null; } PhysicalDiv mainDiv = this.physicalStructMap.getDivContainer(); return mainDiv.getChildren() .stream() .filter(subDiv -> Objects.nonNull(subDiv.getFptr(fileId))) .findAny() .orElse(null); } /** * Returns the URI encoded file path of the first derivate link. * * @param mcrObj object which contains the derivate link */ protected Optional<String> getLinkedFile(MCRObject mcrObj) { MCRMetaElement me = mcrObj.getMetadata().getMetadataElement(getEnclosingDerivateLinkName()); // no derivate link if (me == null) { return Optional.empty(); } return StreamSupport.stream(me.spliterator(), false) .filter(metaInterface -> metaInterface instanceof MCRMetaDerivateLink) .map(MCRMetaDerivateLink.class::cast) .filter(link -> this.mcrDer.getId().equals(MCRObjectID.getInstance(link.getOwner()))) .map(MCRMetaDerivateLink::getRawPath) .findFirst(); } /** * Type attribute used in logical structure. Something like journal, article, * book... */ protected abstract String getType(MCRObject obj); /** * Returns the label of an object. Used in logical structure. */ protected abstract String getLabel(MCRObject obj); /** * Enclosing name of the derivate link element. * In journals this is 'derivateLinks', in archive 'def.derivateLink'. */ protected abstract String getEnclosingDerivateLinkName(); /** * Name of the derivate link element. E.g. 'derivateLink'. */ protected abstract String getDerivateLinkName(); protected FileRef buildFileRef(MCRPath path, String contentType) { return new FileRefImpl(path, contentType); } public interface FileRef { MCRPath getPath(); String getContentType(); default String toFileId() { return this.toFileId(null); } String toFileId(FileGrp fileGroup); String toFileHref(FileGrp fileGroup); String toPhysId(); } public static class FileRefImpl implements FileRef { private MCRPath path; private String contentType; FileRefImpl(MCRPath path, String contentType) { this.path = path; this.contentType = contentType; } @Override public MCRPath getPath() { return this.path; } @Override public String getContentType() { return this.contentType; } @Override public String toFileId(FileGrp fileGroup) { return MCRMetsSave.getFileId(this.path); } @Override public String toFileHref(FileGrp fileGroup) { String path = getPath().getOwnerRelativePath().substring(1); try { return MCRXMLFunctions.encodeURIPath(path, true); } catch (URISyntaxException exc) { throw new MCRException("Unable to encode " + path, exc); } } @Override public String toPhysId() { return PhysicalSubDiv.ID_PREFIX + MCRMetsSave.getFileBase(this.path); } } }
22,837
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSGeneratorFactory.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSGeneratorFactory.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.mycore.common.MCRClassTools; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.datamodel.niofs.MCRPath; /** * Factory to create mets generator's. By default, this class uses the property 'MCR.Component.MetsMods.Generator' to * determine which generator is chosen. You can use either use {@link #setSelector(MCRMETSGeneratorSelector)} to add * your own selector or use the property 'MCR.Component.MetsMods.Generator.Selector'. * * @author Matthias Eichner */ public abstract class MCRMETSGeneratorFactory { private static MCRMETSGeneratorSelector GENERATOR_SELECTOR; private static boolean IGNORE_METS_XML; static { // ignore mets.xml of the derivate by default IGNORE_METS_XML = true; // get selector Class<? extends MCRMETSGeneratorSelector> cn = MCRConfiguration2.<MCRMETSPropertyGeneratorSelector>getClass( "MCR.Component.MetsMods.Generator.Selector").orElse(MCRMETSPropertyGeneratorSelector.class); try { GENERATOR_SELECTOR = cn.getDeclaredConstructor().newInstance(); } catch (Exception cause) { GENERATOR_SELECTOR = new MCRMETSPropertyGeneratorSelector(); throw new MCRException( "Unable to instantiate " + cn + ". Please check the 'MCR.Component.MetsMods.Generator.Selector'." + " Using default MCRMETSPropertyGeneratorSelector.", cause); } } /** * Returns a generator for the given derivate. * * @param derivatePath path to the derivate * @return new created generator * @throws MCRException the generator could not be instantiated */ public static MCRMETSGenerator create(MCRPath derivatePath) throws MCRException { return create(derivatePath, new HashSet<>()); } /** * Returns a generator for the given derivate. * * @param derivatePath path to the derivate * @param ignorePaths set of paths which should be ignored when generating the mets.xml * @return new created generator * @throws MCRException the generator could not be instantiated */ public static MCRMETSGenerator create(MCRPath derivatePath, Set<MCRPath> ignorePaths) throws MCRException { MCRMETSGenerator generator = GENERATOR_SELECTOR.get(derivatePath); if (generator instanceof MCRMETSAbstractGenerator abstractGenerator) { abstractGenerator.setDerivatePath(derivatePath); if (IGNORE_METS_XML) { ignorePaths.add(MCRPath.toMCRPath(derivatePath.resolve("mets.xml"))); } abstractGenerator.setIgnorePaths(ignorePaths); try { getOldMets(derivatePath).ifPresent(abstractGenerator::setOldMets); } catch (Exception exc) { // we should not fail if the old mets.xml is broken LogManager.getLogger().error("Unable to read mets.xml of {}", derivatePath.getOwner(), exc); } } return generator; } /** * If the mets.xml should be ignored for generating the mets.xml or not. * * @param ignore if the mets.xml should be added to the ignorePaths by default */ public static void ignoreMetsXML(boolean ignore) { IGNORE_METS_XML = ignore; } /** * Checks if the mets.xml in the derivate is added to the ignorePaths by default. Ignoring is the default behaviour. * If the mets.xml is not ignored, then the old mets.xml in the derivate will appear in the newly generated. * * @return true if the mets.xml is ignored. */ public static boolean isMetsXMLIgnored() { return IGNORE_METS_XML; } private static Optional<Mets> getOldMets(MCRPath derivatePath) throws IOException, JDOMException { if (derivatePath == null) { return Optional.empty(); } Path metsPath = derivatePath.resolve("mets.xml"); if (!Files.exists(metsPath)) { return Optional.empty(); } SAXBuilder builder = new SAXBuilder(); try (InputStream is = Files.newInputStream(metsPath)) { Document metsDocument = builder.build(is); return Optional.of(new Mets(metsDocument)); } } /** * Sets a new selector for the factory. * * @param selector the selector which determines which generator is chosen */ public static synchronized void setSelector(MCRMETSGeneratorSelector selector) { GENERATOR_SELECTOR = selector; } /** * Base interface to select which mets generator should be chosen. */ public interface MCRMETSGeneratorSelector { /** * Returns the generator. * * @param derivatePath path to the derivate * @return the generator * @throws MCRException something went wrong while getting the generator */ MCRMETSGenerator get(MCRPath derivatePath) throws MCRException; } /** * The default selector. Selects the generator by the property 'MCR.Component.MetsMods.Generator'. */ public static class MCRMETSPropertyGeneratorSelector implements MCRMETSGeneratorSelector { private static Class<? extends MCRMETSGenerator> METS_GENERATOR_CLASS = null; @Override public MCRMETSGenerator get(MCRPath derivatePath) { String cn = MCRConfiguration2.getString("MCR.Component.MetsMods.Generator") .orElse(MCRMETSDefaultGenerator.class.getName()); try { if (METS_GENERATOR_CLASS == null || !cn.equals(METS_GENERATOR_CLASS.getName())) { METS_GENERATOR_CLASS = MCRClassTools.forName(cn); } return METS_GENERATOR_CLASS.getDeclaredConstructor().newInstance(); } catch (Exception cause) { throw new MCRException("Unable to instantiate " + cn + ". Please check the 'MCR.Component.MetsMods.Generator' property'.", cause); } } } }
7,203
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRDefaultLogicalStructMapTypeProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRDefaultLogicalStructMapTypeProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import org.mycore.datamodel.metadata.MCRObjectID; /** * @author silvio * */ public class MCRDefaultLogicalStructMapTypeProvider implements MCRILogicalStructMapTypeProvider { /** * @return always monograph */ @Override public String getType(MCRObjectID objectId) { return "monograph"; } }
1,087
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSAbstractGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSAbstractGenerator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.mycore.datamodel.niofs.MCRPath; /** * Base implementation for a METS generator. * * @author Matthias Eichner */ public abstract class MCRMETSAbstractGenerator implements MCRMETSGenerator { private MCRPath derivatePath; private Set<MCRPath> ignorePaths; private Mets oldMets; public MCRMETSAbstractGenerator() { this.ignorePaths = new HashSet<>(); } /** * Returns the path to the derivate. * * @return path to the derivate */ public MCRPath getDerivatePath() { return derivatePath; } /** * Returns an optional of the old mets. Sometimes a generator needs to copy informations of the previous state * of the mets.xml. * * @return optional of the previous mets.xml */ public Optional<Mets> getOldMets() { return oldMets != null ? Optional.of(this.oldMets) : Optional.empty(); } /** * Returns a set of paths which should be ignore while creating the mets.xml. * * @return set of paths which should be ignored */ public Set<MCRPath> getIgnorePaths() { return ignorePaths; } /** * Returns the owner of the derivate path, so the derivate id as string. * * @return the derivate id */ protected String getOwner() { return this.derivatePath.getOwner(); } public void setDerivatePath(MCRPath derivatePath) { this.derivatePath = derivatePath; } public void setIgnorePaths(Set<MCRPath> ignorePaths) { this.ignorePaths = ignorePaths; } public void setOldMets(Mets oldMets) { this.oldMets = oldMets; } }
2,493
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRILogicalStructMapTypeProvider.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRILogicalStructMapTypeProvider.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import org.mycore.datamodel.metadata.MCRObjectID; /** * @author silvio * */ public interface MCRILogicalStructMapTypeProvider { /** * @return the type depending on metadata given by an object id */ String getType(MCRObjectID objectId); }
1,020
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSGenerator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import org.mycore.common.MCRException; /** * Base interface to create a mets.xml. */ public interface MCRMETSGenerator { /** * Creates a new METS pojo. * * @return the newly generated mets * @throws MCRException unable to generate the mets */ Mets generate() throws MCRException; }
1,079
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMETSDefaultGenerator.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/MCRMETSDefaultGenerator.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mycore.common.MCRException; import org.mycore.common.config.MCRConfiguration2; import org.mycore.common.config.MCRConfigurationException; import org.mycore.common.xml.MCRXMLFunctions; import org.mycore.datamodel.metadata.MCRDerivate; import org.mycore.datamodel.metadata.MCRMetadataManager; import org.mycore.datamodel.metadata.MCRObjectID; import org.mycore.datamodel.niofs.MCRContentTypes; import org.mycore.datamodel.niofs.MCRPath; import org.mycore.mets.model.files.FLocat; import org.mycore.mets.model.files.File; import org.mycore.mets.model.files.FileGrp; import org.mycore.mets.model.files.FileSec; import org.mycore.mets.model.sections.AmdSec; import org.mycore.mets.model.sections.DmdSec; import org.mycore.mets.model.struct.Fptr; import org.mycore.mets.model.struct.LOCTYPE; import org.mycore.mets.model.struct.LogicalDiv; import org.mycore.mets.model.struct.LogicalStructMap; import org.mycore.mets.model.struct.PhysicalDiv; import org.mycore.mets.model.struct.PhysicalStructMap; import org.mycore.mets.model.struct.PhysicalSubDiv; import org.mycore.mets.model.struct.SmLink; import org.mycore.mets.model.struct.StructLink; import org.mycore.mets.tools.MCRMetsSave; import org.mycore.services.i18n.MCRTranslation; /** * @author Thomas Scheffler (yagee) * @author Matthias Eichner * @author Sebastian Hofmann * @author Sebastian Röher (basti890) */ public class MCRMETSDefaultGenerator extends MCRMETSAbstractGenerator { private static final Logger LOGGER = LogManager.getLogger(MCRMETSGenerator.class); private static final List<String> EXCLUDED_ROOT_FOLDERS = Arrays.asList("alto", "tei"); private HashMap<String, String> hrefIdMap = new HashMap<>(); @Override public Mets generate() throws MCRException { try { Mets mets = createMets(); MCRDerivate owner = MCRMetadataManager.retrieveMCRDerivate(MCRObjectID.getInstance(getOwner())); mets.getLogicalStructMap().getDivContainer().setLabel( MCRTranslation.exists("MCR.Mets.LogicalStructMap.Default.Label") ? MCRTranslation.translate("MCR.Mets.LogicalStructMap.Default.Label") : owner.getId().toString()); Map<String, String> urnFileMap = owner.getUrnMap(); if (urnFileMap.size() > 0) { try { MCRMetsSave.updateURNsInMetsDocument(mets, urnFileMap); } catch (Exception e) { LOGGER.error("error while adding urn´s to new Mets file", e); } } return mets; } catch (Exception ioExc) { throw new MCRException("Unable to create mets.xml of " + getOwner(), ioExc); } } private Mets createMets() throws IOException { Mets mets = new Mets(); String owner = getOwner(); // add dmdsec DmdSec dmdSec = new DmdSec("dmd_" + owner); // add amdsec AmdSec amdSec = new AmdSec("amd_" + owner); // file sec FileSec fileSec = new FileSec(); //for (MCRMetsFileUse fileUse : MCRMetsFileUse.values()) { // FileGrp fileGrp = new FileGrp(fileUse.toString()); // fileSec.addFileGrp(fileGrp); //} // physical structure PhysicalStructMap physicalStructMap = new PhysicalStructMap(); PhysicalDiv physicalDiv = new PhysicalDiv("phys_" + owner, "physSequence"); physicalStructMap.setDivContainer(physicalDiv); // logical structure MCRILogicalStructMapTypeProvider typeProvider = getTypeProvider(); LogicalStructMap logicalStructMap = new LogicalStructMap(); LogicalDiv logicalDiv = new LogicalDiv("log_" + owner, typeProvider.getType(MCRObjectID.getInstance(owner)), owner, amdSec.getId(), dmdSec.getId()); logicalDiv.setDmdId(dmdSec.getId()); logicalStructMap.setDivContainer(logicalDiv); // struct Link StructLink structLink = new StructLink(); // create internal structure structureMets(getDerivatePath(), getIgnorePaths(), fileSec, physicalDiv, logicalDiv, structLink, new AtomicInteger(0)); hrefIdMap.clear(); // add to mets mets.addDmdSec(dmdSec); mets.addAmdSec(amdSec); mets.setFileSec(fileSec); mets.addStructMap(physicalStructMap); mets.addStructMap(logicalStructMap); mets.setStructLink(structLink); return mets; } private void structureMets(MCRPath dir, Set<MCRPath> ignoreNodes, FileSec fileSec, PhysicalDiv physicalDiv, LogicalDiv logicalDiv, StructLink structLink, AtomicInteger logCounter) throws IOException { SortedMap<MCRPath, BasicFileAttributes> files = new TreeMap<>(); SortedMap<MCRPath, BasicFileAttributes> directories = new TreeMap<>(); fillFileMap(ignoreNodes, files, directories, dir); for (Map.Entry<MCRPath, BasicFileAttributes> file : files.entrySet()) { createStructure(dir, fileSec, physicalDiv, logicalDiv, structLink, file); } for (Map.Entry<MCRPath, BasicFileAttributes> directory : directories.entrySet()) { String dirName = directory.getKey().getFileName().toString(); if (isInExcludedRootFolder(directory.getKey())) { structureMets(directory.getKey(), ignoreNodes, fileSec, physicalDiv, logicalDiv, structLink, logCounter); } else { LogicalDiv section = new LogicalDiv("log_" + logCounter.incrementAndGet(), "section", dirName); logicalDiv.add(section); structureMets(directory.getKey(), ignoreNodes, fileSec, physicalDiv, section, structLink, logCounter); } } } private void createStructure(MCRPath dir, FileSec fileSec, PhysicalDiv physicalDiv, LogicalDiv logicalDiv, StructLink structLink, Map.Entry<MCRPath, BasicFileAttributes> file) throws IOException { String baseID = MCRMetsSave.getFileBase(file.getKey()); final String physicalID = "phys_" + baseID; final String href; String path = file.getKey().getOwnerRelativePath().substring(1); try { href = MCRXMLFunctions.encodeURIPath(path, true); } catch (URISyntaxException uriSyntaxException) { LOGGER.error("invalid href {}", path, uriSyntaxException); return; } int beginIndex = href.lastIndexOf("/") == -1 ? 0 : href.lastIndexOf("/") + 1; int endIndex = (href.lastIndexOf(".") == -1 || href.lastIndexOf(".") <= beginIndex) ? href.length() : href.lastIndexOf("."); String fileName = href.substring(beginIndex, endIndex); LOGGER.debug("Created fileName: {}", fileName); if (!(hrefIdMap.containsKey(fileName) || hrefIdMap.containsValue(baseID) && isInExcludedRootFolder(dir))) { hrefIdMap.put(fileName, baseID); } //files String fileUse = MCRMetsModelHelper.getUseForHref(href) .orElseThrow(() -> new MCRConfigurationException("Could not create METS!")); String fileID = fileUse.replace('.', '_') + "_" + baseID; sortFileToGrp(fileSec, file, fileID, href, fileUse); // physical buildPhysDivs(dir, physicalDiv, fileID, physicalID, fileName); // struct link if (!isInExcludedRootFolder(dir)) { SmLink smLink = new SmLink(logicalDiv.getId(), physicalID); structLink.addSmLink(smLink); } } private void fillFileMap(Set<MCRPath> ignoreNodes, SortedMap<MCRPath, BasicFileAttributes> files, SortedMap<MCRPath, BasicFileAttributes> directories, Path dir) throws IOException { try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir)) { for (Path child : dirStream) { MCRPath path = MCRPath.toMCRPath(child); if (ignoreNodes.contains(path)) { continue; } BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); if (attrs.isDirectory()) { directories.put(path, attrs); } else { files.put(path, attrs); } } } } private void buildPhysDivs(MCRPath dir, PhysicalDiv physicalDiv, String fileID, final String physicalID, String fileName) { if (!fileName.isEmpty() && hrefIdMap.containsKey(fileName) && isInExcludedRootFolder(dir)) { for (PhysicalSubDiv physSubDiv : physicalDiv.getChildren()) { if (physSubDiv.getId().contains(hrefIdMap.get(fileName))) { physSubDiv.add(new Fptr(fileID)); } } } else { PhysicalSubDiv pyhsicalPage = new PhysicalSubDiv(physicalID, "page"); Fptr fptr = new Fptr(fileID); pyhsicalPage.add(fptr); physicalDiv.add(pyhsicalPage); } } private void sortFileToGrp(FileSec fileSec, Map.Entry<MCRPath, BasicFileAttributes> file, String fileID, final String href, String fileUse) throws IOException { // file File metsFile = new File(fileID, MCRContentTypes.probeContentType(file.getKey())); FLocat fLocat = new FLocat(LOCTYPE.URL, href); metsFile.setFLocat(fLocat); this.createOrGetGroup(fileSec, fileUse).addFile(metsFile); } private FileGrp createOrGetGroup(FileSec fileSec, String fileUse) { FileGrp fileGroup = fileSec.getFileGroup(fileUse); if (fileGroup == null) { fileGroup = new FileGrp(fileUse); fileSec.addFileGrp(fileGroup); } return fileGroup; } /** * Checks if a root directory should be included in mets.xml * * @param directory the directory to check * @return true if the directory should be excluded */ private boolean isInExcludedRootFolder(MCRPath directory) { for (String excludedRoot : EXCLUDED_ROOT_FOLDERS) { String path = directory.toString().substring(directory.toString().indexOf(":/") + 2); if (path.startsWith(excludedRoot)) { return true; } } return false; } private MCRILogicalStructMapTypeProvider getTypeProvider() { try { return MCRConfiguration2.<MCRDefaultLogicalStructMapTypeProvider>getClass( "MCR.Component.MetsMods.LogicalStructMapTypeProvider") .orElse(MCRDefaultLogicalStructMapTypeProvider.class).getDeclaredConstructor().newInstance(); } catch (Exception e) { LOGGER.warn("Could not load class", e); return new MCRDefaultLogicalStructMapTypeProvider(); } } }
12,145
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsAltoLink.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/simple/MCRMetsAltoLink.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.simple; public class MCRMetsAltoLink { private MCRMetsFile file; private String begin; private String end; public MCRMetsAltoLink(MCRMetsFile file, String begin, String end) { this.file = file; this.begin = begin; this.end = end; } public MCRMetsFile getFile() { return file; } public void setFile(MCRMetsFile file) { this.file = file; } public String getBegin() { return begin; } public void setBegin(String begin) { this.begin = begin; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } }
1,440
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsSection.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/simple/MCRMetsSection.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.simple; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MCRMetsSection { private List<MCRMetsSection> metsSectionList; private String id; private String type; private String label; private List<MCRMetsAltoLink> altoLinks; private transient MCRMetsSection parent; public MCRMetsSection() { this.metsSectionList = new ArrayList<>(); this.altoLinks = new ArrayList<>(); } public MCRMetsSection(String id, String type, String label, MCRMetsSection parent) { this(); this.id = id; this.type = type; this.label = label; this.parent = parent; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public List<MCRMetsSection> getMetsSectionList() { return Collections.unmodifiableList(metsSectionList); } public void addSection(MCRMetsSection section) { section.parent = this; this.metsSectionList.add(section); } public void removeSection(MCRMetsSection section) { section.parent = null; this.metsSectionList.remove(section); } public MCRMetsSection getParent() { return parent; } public void setParent(MCRMetsSection parent) { this.parent = parent; } public List<MCRMetsAltoLink> getAltoLinks() { return Collections.unmodifiableList(altoLinks); } public void setAltoLinks(List<MCRMetsAltoLink> altoLinks) { this.altoLinks = altoLinks; } public void addAltoLink(MCRMetsAltoLink link) { this.altoLinks.add(link); } public void removeAltoLink(MCRMetsAltoLink link) { this.altoLinks.remove(link); } }
2,802
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsFile.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/simple/MCRMetsFile.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.simple; public class MCRMetsFile { private String id; private String href; private String mimeType; private String use; public MCRMetsFile() { } public MCRMetsFile(String id, String href, String mimeType, String use) { this.id = id; this.href = href; this.mimeType = mimeType; this.use = use; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getUse() { return use; } public void setUse(String use) { this.use = use; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } }
1,651
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsPage.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/simple/MCRMetsPage.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.simple; import java.util.ArrayList; import java.util.List; public class MCRMetsPage { private String id; private String orderLabel; private String contentIds; private Boolean hidden; private List<MCRMetsFile> fileList; public MCRMetsPage(String id, String orderLabel, String contentIds) { this(); this.id = id; this.orderLabel = orderLabel; this.contentIds = contentIds; } public void setId(String id) { this.id = id; } public String getId() { return id; } public MCRMetsPage() { this.fileList = new ArrayList<>(); } public List<MCRMetsFile> getFileList() { return fileList; } public String getOrderLabel() { return orderLabel; } public void setOrderLabel(String orderLabel) { if (orderLabel == "") { orderLabel = null; } this.orderLabel = orderLabel; } public String getContentIds() { return contentIds; } public void setContentIds(String contentIds) { if (contentIds == "") { contentIds = null; } this.contentIds = contentIds; } public Boolean isHidden() { return hidden; } public void setHidden(Boolean hidden) { this.hidden = hidden; } }
2,092
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsSimpleModel.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/simple/MCRMetsSimpleModel.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.simple; import java.util.ArrayList; import java.util.List; /** * Simple data structure to hold data from mets.xml. * @author Sebastian Hofmann(mcrshofm) */ public class MCRMetsSimpleModel { private MCRMetsSection rootSection; private List<MCRMetsPage> metsPageList; public List<MCRMetsLink> sectionPageLinkList; /** * Creates a new empty MCRMetsSimpleModel. */ public MCRMetsSimpleModel() { metsPageList = new ArrayList<>(); sectionPageLinkList = new ArrayList<>(); } public MCRMetsSection getRootSection() { return rootSection; } public void setRootSection(MCRMetsSection rootSection) { this.rootSection = rootSection; } public List<MCRMetsLink> getSectionPageLinkList() { return sectionPageLinkList; } public List<MCRMetsPage> getMetsPageList() { return metsPageList; } }
1,659
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z
MCRMetsLink.java
/FileExtraction/Java_unseen/MyCoRe-Org_mycore/mycore-mets/src/main/java/org/mycore/mets/model/simple/MCRMetsLink.java
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MyCoRe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ package org.mycore.mets.model.simple; public class MCRMetsLink { private MCRMetsSection from; private MCRMetsPage to; public MCRMetsLink(MCRMetsSection from, MCRMetsPage to) { this.from = from; this.to = to; } public MCRMetsLink() { } public MCRMetsSection getFrom() { return from; } public void setFrom(MCRMetsSection from) { this.from = from; } public MCRMetsPage getTo() { return to; } public void setTo(MCRMetsPage to) { this.to = to; } }
1,283
Java
.java
MyCoRe-Org/mycore
33
14
19
2016-10-07T06:02:02Z
2024-05-08T18:38:30Z