repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
TechzoneMC/NPCLib | base/src/main/java/net/techcable/npclib/NPCMetrics.java | // Path: base/src/main/java/net/techcable/npclib/Metrics.java
// public static class Graph {
//
// /**
// * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
// * rejected
// */
// private final String name;
//
// /**
// * The set of plotters that are contained within this graph
// */
// private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
//
// private Graph(final String name) {
// this.name = name;
// }
//
// /**
// * Gets the graph's name
// *
// * @return the Graph's name
// */
// public String getName() {
// return name;
// }
//
// /**
// * Add a plotter to the graph, which will be used to plot entries
// *
// * @param plotter the plotter to add to the graph
// */
// public void addPlotter(final Plotter plotter) {
// plotters.add(plotter);
// }
//
// /**
// * Remove a plotter from the graph
// *
// * @param plotter the plotter to remove from the graph
// */
// public void removePlotter(final Plotter plotter) {
// plotters.remove(plotter);
// }
//
// /**
// * Gets an <b>unmodifiable</b> set of the plotter objects in the graph
// *
// * @return an unmodifiable {@link java.util.Set} of the plotter objects
// */
// public Set<Plotter> getPlotters() {
// return Collections.unmodifiableSet(plotters);
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(final Object object) {
// if (!(object instanceof Graph)) {
// return false;
// }
//
// final Graph graph = (Graph) object;
// return graph.name.equals(name);
// }
//
// /**
// * Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
// */
// protected void onOptOut() {
// }
// }
//
// Path: base/src/main/java/net/techcable/npclib/Metrics.java
// public static abstract class Plotter {
//
// /**
// * The plot's name
// */
// private final String name;
//
// /**
// * Construct a plotter with the default plot name
// */
// public Plotter() {
// this("Default");
// }
//
// /**
// * Construct a plotter with a specific plot name
// *
// * @param name the name of the plotter to use, which will show up on the website
// */
// public Plotter(final String name) {
// this.name = name;
// }
//
// /**
// * Get the current value for the plotted point. Since this function defers to an external function it may or may
// * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
// * from any thread so care should be taken when accessing resources that need to be synchronized.
// *
// * @return the current value for the point to be plotted.
// */
// public abstract int getValue();
//
// /**
// * Get the column name for the plotted point
// *
// * @return the plotted point's column name
// */
// public String getColumnName() {
// return name;
// }
//
// /**
// * Called after the website graphs have been updated
// */
// public void reset() {
// }
//
// @Override
// public int hashCode() {
// return getColumnName().hashCode();
// }
//
// @Override
// public boolean equals(final Object object) {
// if (!(object instanceof Plotter)) {
// return false;
// }
//
// final Plotter plotter = (Plotter) object;
// return plotter.name.equals(name) && plotter.getValue() == getValue();
// }
// }
//
// Path: api/src/main/java/net/techcable/npclib/utils/NPCLog.java
// @NoArgsConstructor(access = AccessLevel.PRIVATE)
// public class NPCLog {
//
// public static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("npclib.debug", "false"));
//
// public static final String PREFIX = "NPCLib";
//
// public static void info(String msg) {
// log(Level.INFO, msg);
// }
//
// public static void info(String msg, Object... args) {
// log(Level.INFO, msg, args);
// }
//
// public static void warn(String msg) {
// log(Level.WARNING, msg);
// }
//
// public static void warn(String msg, Object... args) {
// log(Level.WARNING, msg, args);
// }
//
// public static void warn(String msg, Throwable t) {
// log(Level.WARNING, msg, t);
// }
//
// public static void severe(String msg, Throwable t) {
// log(Level.SEVERE, msg, t);
// }
//
// public static void debug(String msg) {
// if (DEBUG) {
// log(Level.INFO, msg);
// }
// }
//
// public static void debug(String msg, Throwable t) {
// if (DEBUG) {
// log(Level.INFO, msg, t);
// }
// }
//
// private static void log(Level level, String msg, Throwable t) {
// Bukkit.getLogger().log(level, PREFIX + " " + msg, t);
// }
//
// private static void log(Level level, String msg, Object... args) {
// Bukkit.getLogger().log(level, String.format(msg, args));
// }
//
// private static void log(Level level, String msg) {
// Bukkit.getLogger().log(level, msg);
// }
// }
| import lombok.*;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import net.techcable.npclib.Metrics.Graph;
import net.techcable.npclib.Metrics.Plotter;
import net.techcable.npclib.utils.NPCLog;
import org.bukkit.plugin.Plugin; | package net.techcable.npclib;
@NoArgsConstructor(access = AccessLevel.NONE)
public class NPCMetrics {
private static Metrics metrics; | // Path: base/src/main/java/net/techcable/npclib/Metrics.java
// public static class Graph {
//
// /**
// * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
// * rejected
// */
// private final String name;
//
// /**
// * The set of plotters that are contained within this graph
// */
// private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
//
// private Graph(final String name) {
// this.name = name;
// }
//
// /**
// * Gets the graph's name
// *
// * @return the Graph's name
// */
// public String getName() {
// return name;
// }
//
// /**
// * Add a plotter to the graph, which will be used to plot entries
// *
// * @param plotter the plotter to add to the graph
// */
// public void addPlotter(final Plotter plotter) {
// plotters.add(plotter);
// }
//
// /**
// * Remove a plotter from the graph
// *
// * @param plotter the plotter to remove from the graph
// */
// public void removePlotter(final Plotter plotter) {
// plotters.remove(plotter);
// }
//
// /**
// * Gets an <b>unmodifiable</b> set of the plotter objects in the graph
// *
// * @return an unmodifiable {@link java.util.Set} of the plotter objects
// */
// public Set<Plotter> getPlotters() {
// return Collections.unmodifiableSet(plotters);
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(final Object object) {
// if (!(object instanceof Graph)) {
// return false;
// }
//
// final Graph graph = (Graph) object;
// return graph.name.equals(name);
// }
//
// /**
// * Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
// */
// protected void onOptOut() {
// }
// }
//
// Path: base/src/main/java/net/techcable/npclib/Metrics.java
// public static abstract class Plotter {
//
// /**
// * The plot's name
// */
// private final String name;
//
// /**
// * Construct a plotter with the default plot name
// */
// public Plotter() {
// this("Default");
// }
//
// /**
// * Construct a plotter with a specific plot name
// *
// * @param name the name of the plotter to use, which will show up on the website
// */
// public Plotter(final String name) {
// this.name = name;
// }
//
// /**
// * Get the current value for the plotted point. Since this function defers to an external function it may or may
// * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
// * from any thread so care should be taken when accessing resources that need to be synchronized.
// *
// * @return the current value for the point to be plotted.
// */
// public abstract int getValue();
//
// /**
// * Get the column name for the plotted point
// *
// * @return the plotted point's column name
// */
// public String getColumnName() {
// return name;
// }
//
// /**
// * Called after the website graphs have been updated
// */
// public void reset() {
// }
//
// @Override
// public int hashCode() {
// return getColumnName().hashCode();
// }
//
// @Override
// public boolean equals(final Object object) {
// if (!(object instanceof Plotter)) {
// return false;
// }
//
// final Plotter plotter = (Plotter) object;
// return plotter.name.equals(name) && plotter.getValue() == getValue();
// }
// }
//
// Path: api/src/main/java/net/techcable/npclib/utils/NPCLog.java
// @NoArgsConstructor(access = AccessLevel.PRIVATE)
// public class NPCLog {
//
// public static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("npclib.debug", "false"));
//
// public static final String PREFIX = "NPCLib";
//
// public static void info(String msg) {
// log(Level.INFO, msg);
// }
//
// public static void info(String msg, Object... args) {
// log(Level.INFO, msg, args);
// }
//
// public static void warn(String msg) {
// log(Level.WARNING, msg);
// }
//
// public static void warn(String msg, Object... args) {
// log(Level.WARNING, msg, args);
// }
//
// public static void warn(String msg, Throwable t) {
// log(Level.WARNING, msg, t);
// }
//
// public static void severe(String msg, Throwable t) {
// log(Level.SEVERE, msg, t);
// }
//
// public static void debug(String msg) {
// if (DEBUG) {
// log(Level.INFO, msg);
// }
// }
//
// public static void debug(String msg, Throwable t) {
// if (DEBUG) {
// log(Level.INFO, msg, t);
// }
// }
//
// private static void log(Level level, String msg, Throwable t) {
// Bukkit.getLogger().log(level, PREFIX + " " + msg, t);
// }
//
// private static void log(Level level, String msg, Object... args) {
// Bukkit.getLogger().log(level, String.format(msg, args));
// }
//
// private static void log(Level level, String msg) {
// Bukkit.getLogger().log(level, msg);
// }
// }
// Path: base/src/main/java/net/techcable/npclib/NPCMetrics.java
import lombok.*;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import net.techcable.npclib.Metrics.Graph;
import net.techcable.npclib.Metrics.Plotter;
import net.techcable.npclib.utils.NPCLog;
import org.bukkit.plugin.Plugin;
package net.techcable.npclib;
@NoArgsConstructor(access = AccessLevel.NONE)
public class NPCMetrics {
private static Metrics metrics; | private static Graph graph; |
TechzoneMC/NPCLib | nms-v1_8_R1/src/main/java/net/techcable/npclib/nms/versions/v1_8_R1/network/NPCConnection.java | // Path: nms-v1_8_R1/src/main/java/net/techcable/npclib/nms/versions/v1_8_R1/NMS.java
// public class NMS implements net.techcable.npclib.nms.NMS {
//
// private static NMS instance;
//
// public NMS() {
// if (instance == null) instance = this;
// }
//
// public static NMS getInstance() {
// return instance;
// }
//
//
// @Override
// public IHumanNPCHook spawnHumanNPC(Location toSpawn, HumanNPC npc) {
// return new HumanNPCHook(npc, toSpawn);
// }
//
// @Override
// public void onJoin(Player joined, Collection<? extends NPC> npcs) {
// for (NPC npc : npcs) {
// if (!(npc instanceof HumanNPC)) continue;
// HumanNPCHook hook = getHook((HumanNPC) npc);
// if (hook == null) continue;
// hook.onJoin(joined);
// }
// }
//
// // UTILS
// public static final String NO_CRAFTBUKKIT_MSG = "Non-CraftBukkit implementations are unsupported";
//
// public static EntityPlayer getHandle(Player player) {
// if (!(player instanceof CraftPlayer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftPlayer) player).getHandle();
// }
//
// public static EntityLiving getHandle(LivingEntity player) {
// if (!(player instanceof CraftLivingEntity)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftLivingEntity) player).getHandle();
// }
//
// public static MinecraftServer getServer() {
// Server server = Bukkit.getServer();
// if (!(server instanceof CraftServer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftServer) server).getServer();
// }
//
// public static WorldServer getHandle(World world) {
// if (!(world instanceof CraftWorld)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftWorld) world).getHandle();
// }
//
// public static HumanNPCHook getHook(HumanNPC npc) {
// EntityPlayer player = getHandle(npc.getEntity());
// if (player instanceof EntityNPCPlayer) return null;
// return ((EntityNPCPlayer) player).getHook();
// }
//
// public static LivingNPCHook getHook(LivingNPC npc) {
// if (npc instanceof HumanNPC) return getHook((HumanNPC) npc);
// EntityLiving entity = getHandle(npc.getEntity());
// if (entity instanceof LivingHookable) return ((LivingHookable) entity).getHook();
// return null;
// }
//
// public static void sendToAll(Packet packet) {
// for (Player p : Bukkit.getOnlinePlayers()) {
// getHandle(p).playerConnection.sendPacket(packet);
// }
// }
// private static final LoadingCache<UUID, GameProfile> properties = CacheBuilder.newBuilder()
// .expireAfterAccess(5, TimeUnit.MINUTES)
// .build(new CacheLoader<UUID, GameProfile>() {
//
// @Override
// public GameProfile load(UUID uuid) throws Exception {
// return MinecraftServer.getServer().aB().fillProfileProperties(new GameProfile(uuid, null), true);
// }
// });
//
// public static void setSkin(GameProfile profile, UUID skinId) {
// GameProfile skinProfile;
// if (Bukkit.getPlayer(skinId) != null) {
// skinProfile = getHandle(Bukkit.getPlayer(skinId)).getProfile();
// } else {
// skinProfile = properties.getUnchecked(skinId);
// }
// if (skinProfile.getProperties().containsKey("textures")) {
// profile.getProperties().removeAll("textures");
// profile.getProperties().putAll("textures", skinProfile.getProperties().get("textures"));
// } else {
// NPCLog.debug("Skin with uuid not found: " + skinId);
// }
// }
// }
| import lombok.*;
import net.minecraft.server.v1_8_R1.EntityPlayer;
import net.minecraft.server.v1_8_R1.Packet;
import net.minecraft.server.v1_8_R1.PlayerConnection;
import net.techcable.npclib.nms.versions.v1_8_R1.NMS; | package net.techcable.npclib.nms.versions.v1_8_R1.network;
@Getter
public class NPCConnection extends PlayerConnection {
public NPCConnection(EntityPlayer npc) { | // Path: nms-v1_8_R1/src/main/java/net/techcable/npclib/nms/versions/v1_8_R1/NMS.java
// public class NMS implements net.techcable.npclib.nms.NMS {
//
// private static NMS instance;
//
// public NMS() {
// if (instance == null) instance = this;
// }
//
// public static NMS getInstance() {
// return instance;
// }
//
//
// @Override
// public IHumanNPCHook spawnHumanNPC(Location toSpawn, HumanNPC npc) {
// return new HumanNPCHook(npc, toSpawn);
// }
//
// @Override
// public void onJoin(Player joined, Collection<? extends NPC> npcs) {
// for (NPC npc : npcs) {
// if (!(npc instanceof HumanNPC)) continue;
// HumanNPCHook hook = getHook((HumanNPC) npc);
// if (hook == null) continue;
// hook.onJoin(joined);
// }
// }
//
// // UTILS
// public static final String NO_CRAFTBUKKIT_MSG = "Non-CraftBukkit implementations are unsupported";
//
// public static EntityPlayer getHandle(Player player) {
// if (!(player instanceof CraftPlayer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftPlayer) player).getHandle();
// }
//
// public static EntityLiving getHandle(LivingEntity player) {
// if (!(player instanceof CraftLivingEntity)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftLivingEntity) player).getHandle();
// }
//
// public static MinecraftServer getServer() {
// Server server = Bukkit.getServer();
// if (!(server instanceof CraftServer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftServer) server).getServer();
// }
//
// public static WorldServer getHandle(World world) {
// if (!(world instanceof CraftWorld)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftWorld) world).getHandle();
// }
//
// public static HumanNPCHook getHook(HumanNPC npc) {
// EntityPlayer player = getHandle(npc.getEntity());
// if (player instanceof EntityNPCPlayer) return null;
// return ((EntityNPCPlayer) player).getHook();
// }
//
// public static LivingNPCHook getHook(LivingNPC npc) {
// if (npc instanceof HumanNPC) return getHook((HumanNPC) npc);
// EntityLiving entity = getHandle(npc.getEntity());
// if (entity instanceof LivingHookable) return ((LivingHookable) entity).getHook();
// return null;
// }
//
// public static void sendToAll(Packet packet) {
// for (Player p : Bukkit.getOnlinePlayers()) {
// getHandle(p).playerConnection.sendPacket(packet);
// }
// }
// private static final LoadingCache<UUID, GameProfile> properties = CacheBuilder.newBuilder()
// .expireAfterAccess(5, TimeUnit.MINUTES)
// .build(new CacheLoader<UUID, GameProfile>() {
//
// @Override
// public GameProfile load(UUID uuid) throws Exception {
// return MinecraftServer.getServer().aB().fillProfileProperties(new GameProfile(uuid, null), true);
// }
// });
//
// public static void setSkin(GameProfile profile, UUID skinId) {
// GameProfile skinProfile;
// if (Bukkit.getPlayer(skinId) != null) {
// skinProfile = getHandle(Bukkit.getPlayer(skinId)).getProfile();
// } else {
// skinProfile = properties.getUnchecked(skinId);
// }
// if (skinProfile.getProperties().containsKey("textures")) {
// profile.getProperties().removeAll("textures");
// profile.getProperties().putAll("textures", skinProfile.getProperties().get("textures"));
// } else {
// NPCLog.debug("Skin with uuid not found: " + skinId);
// }
// }
// }
// Path: nms-v1_8_R1/src/main/java/net/techcable/npclib/nms/versions/v1_8_R1/network/NPCConnection.java
import lombok.*;
import net.minecraft.server.v1_8_R1.EntityPlayer;
import net.minecraft.server.v1_8_R1.Packet;
import net.minecraft.server.v1_8_R1.PlayerConnection;
import net.techcable.npclib.nms.versions.v1_8_R1.NMS;
package net.techcable.npclib.nms.versions.v1_8_R1.network;
@Getter
public class NPCConnection extends PlayerConnection {
public NPCConnection(EntityPlayer npc) { | super(NMS.getServer(), new NPCNetworkManager(), npc); |
TechzoneMC/NPCLib | nms-v1_9_R1/src/main/java/net/techcable/npclib/nms/versions/v1_9_R1/network/NPCNetworkManager.java | // Path: api/src/main/java/net/techcable/npclib/utils/Reflection.java
// public class Reflection {
//
// public static Class<?> getNmsClass(String name) {
// String className = "net.minecraft.server." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getCbClass(String name) {
// String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getUtilClass(String name) {
// try {
// return Class.forName(name); //Try before 1.8 first
// } catch (ClassNotFoundException ex) {
// try {
// return Class.forName("net.minecraft.util." + name); //Not 1.8
// } catch (ClassNotFoundException ex2) {
// return null;
// }
// }
// }
//
// public static String getVersion() {
// String packageName = Bukkit.getServer().getClass().getPackage().getName();
// return packageName.substring(packageName.lastIndexOf('.') + 1);
// }
//
// public static Object getHandle(Object wrapper) {
// Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
// return callMethod(getHandle, wrapper);
// }
//
// //Utils
// public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
// try {
// return clazz.getDeclaredMethod(methodName, paramaters);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
// if (method == null) throw new RuntimeException("No such method");
// method.setAccessible(true);
// try {
// return (T) method.invoke(instance, paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
// try {
// return (Constructor<T>) clazz.getConstructor(paramaterTypes);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
// if (constructor == null) throw new RuntimeException("No such constructor");
// constructor.setAccessible(true);
// try {
// return (T) constructor.newInstance(paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Field makeField(Class<?> clazz, String name) {
// try {
// return clazz.getDeclaredField(name);
// } catch (NoSuchFieldException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getField(Field field, Object instance) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// return (T) field.get(instance);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static void setField(Field field, Object instance, Object value) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// field.set(instance, value);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Class<?> getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException ex) {
// return null;
// }
// }
//
// public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
// try {
// return Class.forName(name).asSubclass(superClass);
// } catch (ClassCastException | ClassNotFoundException ex) {
// return null;
// }
// }
// }
| import lombok.*;
import java.lang.reflect.Field;
import net.minecraft.server.v1_9_R1.EnumProtocolDirection;
import net.minecraft.server.v1_9_R1.NetworkManager;
import net.techcable.npclib.utils.Reflection; | package net.techcable.npclib.nms.versions.v1_9_R1.network;
@Getter
public class NPCNetworkManager extends NetworkManager {
public NPCNetworkManager() {
super(EnumProtocolDirection.CLIENTBOUND); //MCP = isClientSide ---- SRG=field_150747_h | // Path: api/src/main/java/net/techcable/npclib/utils/Reflection.java
// public class Reflection {
//
// public static Class<?> getNmsClass(String name) {
// String className = "net.minecraft.server." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getCbClass(String name) {
// String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getUtilClass(String name) {
// try {
// return Class.forName(name); //Try before 1.8 first
// } catch (ClassNotFoundException ex) {
// try {
// return Class.forName("net.minecraft.util." + name); //Not 1.8
// } catch (ClassNotFoundException ex2) {
// return null;
// }
// }
// }
//
// public static String getVersion() {
// String packageName = Bukkit.getServer().getClass().getPackage().getName();
// return packageName.substring(packageName.lastIndexOf('.') + 1);
// }
//
// public static Object getHandle(Object wrapper) {
// Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
// return callMethod(getHandle, wrapper);
// }
//
// //Utils
// public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
// try {
// return clazz.getDeclaredMethod(methodName, paramaters);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
// if (method == null) throw new RuntimeException("No such method");
// method.setAccessible(true);
// try {
// return (T) method.invoke(instance, paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
// try {
// return (Constructor<T>) clazz.getConstructor(paramaterTypes);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
// if (constructor == null) throw new RuntimeException("No such constructor");
// constructor.setAccessible(true);
// try {
// return (T) constructor.newInstance(paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Field makeField(Class<?> clazz, String name) {
// try {
// return clazz.getDeclaredField(name);
// } catch (NoSuchFieldException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getField(Field field, Object instance) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// return (T) field.get(instance);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static void setField(Field field, Object instance, Object value) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// field.set(instance, value);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Class<?> getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException ex) {
// return null;
// }
// }
//
// public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
// try {
// return Class.forName(name).asSubclass(superClass);
// } catch (ClassCastException | ClassNotFoundException ex) {
// return null;
// }
// }
// }
// Path: nms-v1_9_R1/src/main/java/net/techcable/npclib/nms/versions/v1_9_R1/network/NPCNetworkManager.java
import lombok.*;
import java.lang.reflect.Field;
import net.minecraft.server.v1_9_R1.EnumProtocolDirection;
import net.minecraft.server.v1_9_R1.NetworkManager;
import net.techcable.npclib.utils.Reflection;
package net.techcable.npclib.nms.versions.v1_9_R1.network;
@Getter
public class NPCNetworkManager extends NetworkManager {
public NPCNetworkManager() {
super(EnumProtocolDirection.CLIENTBOUND); //MCP = isClientSide ---- SRG=field_150747_h | Field channel = Reflection.makeField(NetworkManager.class, "channel"); //MCP = channel ---- SRG=field_150746_k |
TechzoneMC/NPCLib | nms-v1_7_R3/src/main/java/net/techcable/npclib/nms/versions/v1_7_R3/network/NPCConnection.java | // Path: nms-v1_7_R3/src/main/java/net/techcable/npclib/nms/versions/v1_7_R3/NMS.java
// public class NMS implements net.techcable.npclib.nms.NMS {
//
// private static NMS instance;
//
// public NMS() {
// if (instance == null) instance = this;
// }
//
// public static NMS getInstance() {
// return instance;
// }
//
//
// @Override
// public IHumanNPCHook spawnHumanNPC(Location toSpawn, HumanNPC npc) {
// return new HumanNPCHook(npc, toSpawn);
// }
//
// @Override
// public void onJoin(Player joined, Collection<? extends NPC> npcs) {
// for (NPC npc : npcs) {
// if (!(npc instanceof HumanNPC)) continue;
// HumanNPCHook hook = getHandle((HumanNPC) npc);
// if (hook == null) continue;
// hook.onJoin(joined);
// }
// }
//
// // UTILS
// public static final String NO_CRAFTBUKKIT_MSG = "Non-CraftBukkit implementations are unsupported";
//
// public static EntityPlayer getHandle(Player player) {
// if (!(player instanceof CraftPlayer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftPlayer) player).getHandle();
// }
//
// public static EntityLiving getHandle(LivingEntity entity) {
// if (!(entity instanceof CraftLivingEntity)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftLivingEntity) entity).getHandle();
// }
//
// public static MinecraftServer getServer() {
// Server server = Bukkit.getServer();
// if (!(server instanceof CraftServer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftServer) server).getServer();
// }
//
// public static WorldServer getHandle(World world) {
// if (!(world instanceof CraftWorld)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftWorld) world).getHandle();
// }
//
// public static HumanNPCHook getHandle(HumanNPC npc) {
// EntityPlayer player = getHandle(npc.getEntity());
// if (player instanceof EntityNPCPlayer) return null;
// return ((EntityNPCPlayer) player).getHook();
// }
//
// public static LivingNPCHook getHook(LivingNPC npc) {
// if (getHandle((HumanNPC) npc) != null) return getHandle((HumanNPC) npc);
// EntityLiving entity = getHandle(npc.getEntity());
// if (entity instanceof LivingHookable) {
// return ((LivingHookable) entity).getHook();
// }
// return null;
// }
//
// public static void sendToAll(Packet packet) {
// for (Player p : Bukkit.getOnlinePlayers()) {
// getHandle(p).playerConnection.sendPacket(packet);
// }
// }
//
// private static final Cache<UUID, GameProfile> properties = CacheBuilder.newBuilder()
// .expireAfterAccess(5, TimeUnit.MINUTES)
// .build(new CacheLoader<UUID, GameProfile>() {
//
// @Override
// public GameProfile load(UUID uuid) throws Exception {
// return MinecraftServer.getServer().av().fillProfileProperties(new GameProfile(uuid, null), true);
// }
// });
//
// public static void setSkin(GameProfile profile, UUID skinId) {
// GameProfile skinProfile;
// if (Bukkit.getPlayer(skinId) != null) {
// skinProfile = getHandle(Bukkit.getPlayer(skinId)).getProfile();
// } else {
// skinProfile = properties.getUnchecked(skinId);
// }
// if (skinProfile.getProperties().containsKey("textures")) {
// profile.getProperties().removeAll("textures");
// profile.getProperties().putAll("textures", skinProfile.getProperties().get("textures"));
// } else {
// NPCLog.debug("Skin with uuid not found: " + skinId);
// }
// }
// }
| import lombok.*;
import net.minecraft.server.v1_7_R3.EntityPlayer;
import net.minecraft.server.v1_7_R3.Packet;
import net.minecraft.server.v1_7_R3.PlayerConnection;
import net.techcable.npclib.nms.versions.v1_7_R3.NMS; | package net.techcable.npclib.nms.versions.v1_7_R3.network;
@Getter
public class NPCConnection extends PlayerConnection {
public NPCConnection(EntityPlayer npc) { | // Path: nms-v1_7_R3/src/main/java/net/techcable/npclib/nms/versions/v1_7_R3/NMS.java
// public class NMS implements net.techcable.npclib.nms.NMS {
//
// private static NMS instance;
//
// public NMS() {
// if (instance == null) instance = this;
// }
//
// public static NMS getInstance() {
// return instance;
// }
//
//
// @Override
// public IHumanNPCHook spawnHumanNPC(Location toSpawn, HumanNPC npc) {
// return new HumanNPCHook(npc, toSpawn);
// }
//
// @Override
// public void onJoin(Player joined, Collection<? extends NPC> npcs) {
// for (NPC npc : npcs) {
// if (!(npc instanceof HumanNPC)) continue;
// HumanNPCHook hook = getHandle((HumanNPC) npc);
// if (hook == null) continue;
// hook.onJoin(joined);
// }
// }
//
// // UTILS
// public static final String NO_CRAFTBUKKIT_MSG = "Non-CraftBukkit implementations are unsupported";
//
// public static EntityPlayer getHandle(Player player) {
// if (!(player instanceof CraftPlayer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftPlayer) player).getHandle();
// }
//
// public static EntityLiving getHandle(LivingEntity entity) {
// if (!(entity instanceof CraftLivingEntity)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftLivingEntity) entity).getHandle();
// }
//
// public static MinecraftServer getServer() {
// Server server = Bukkit.getServer();
// if (!(server instanceof CraftServer)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftServer) server).getServer();
// }
//
// public static WorldServer getHandle(World world) {
// if (!(world instanceof CraftWorld)) throw new UnsupportedOperationException(NO_CRAFTBUKKIT_MSG);
// return ((CraftWorld) world).getHandle();
// }
//
// public static HumanNPCHook getHandle(HumanNPC npc) {
// EntityPlayer player = getHandle(npc.getEntity());
// if (player instanceof EntityNPCPlayer) return null;
// return ((EntityNPCPlayer) player).getHook();
// }
//
// public static LivingNPCHook getHook(LivingNPC npc) {
// if (getHandle((HumanNPC) npc) != null) return getHandle((HumanNPC) npc);
// EntityLiving entity = getHandle(npc.getEntity());
// if (entity instanceof LivingHookable) {
// return ((LivingHookable) entity).getHook();
// }
// return null;
// }
//
// public static void sendToAll(Packet packet) {
// for (Player p : Bukkit.getOnlinePlayers()) {
// getHandle(p).playerConnection.sendPacket(packet);
// }
// }
//
// private static final Cache<UUID, GameProfile> properties = CacheBuilder.newBuilder()
// .expireAfterAccess(5, TimeUnit.MINUTES)
// .build(new CacheLoader<UUID, GameProfile>() {
//
// @Override
// public GameProfile load(UUID uuid) throws Exception {
// return MinecraftServer.getServer().av().fillProfileProperties(new GameProfile(uuid, null), true);
// }
// });
//
// public static void setSkin(GameProfile profile, UUID skinId) {
// GameProfile skinProfile;
// if (Bukkit.getPlayer(skinId) != null) {
// skinProfile = getHandle(Bukkit.getPlayer(skinId)).getProfile();
// } else {
// skinProfile = properties.getUnchecked(skinId);
// }
// if (skinProfile.getProperties().containsKey("textures")) {
// profile.getProperties().removeAll("textures");
// profile.getProperties().putAll("textures", skinProfile.getProperties().get("textures"));
// } else {
// NPCLog.debug("Skin with uuid not found: " + skinId);
// }
// }
// }
// Path: nms-v1_7_R3/src/main/java/net/techcable/npclib/nms/versions/v1_7_R3/network/NPCConnection.java
import lombok.*;
import net.minecraft.server.v1_7_R3.EntityPlayer;
import net.minecraft.server.v1_7_R3.Packet;
import net.minecraft.server.v1_7_R3.PlayerConnection;
import net.techcable.npclib.nms.versions.v1_7_R3.NMS;
package net.techcable.npclib.nms.versions.v1_7_R3.network;
@Getter
public class NPCConnection extends PlayerConnection {
public NPCConnection(EntityPlayer npc) { | super(NMS.getServer(), new NPCNetworkManager(), npc); |
TechzoneMC/NPCLib | nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/NPCHook.java | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
| import lombok.*;
import net.minecraft.server.v1_7_R4.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook; | package net.techcable.npclib.nms.versions.v1_7_R4;
@Getter
@RequiredArgsConstructor | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
// Path: nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/NPCHook.java
import lombok.*;
import net.minecraft.server.v1_7_R4.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook;
package net.techcable.npclib.nms.versions.v1_7_R4;
@Getter
@RequiredArgsConstructor | public class NPCHook implements INPCHook { |
TechzoneMC/NPCLib | nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/NPCHook.java | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
| import lombok.*;
import net.minecraft.server.v1_7_R4.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook; | package net.techcable.npclib.nms.versions.v1_7_R4;
@Getter
@RequiredArgsConstructor
public class NPCHook implements INPCHook {
| // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
// Path: nms-v1_7_R4/src/main/java/net/techcable/npclib/nms/versions/v1_7_R4/NPCHook.java
import lombok.*;
import net.minecraft.server.v1_7_R4.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook;
package net.techcable.npclib.nms.versions.v1_7_R4;
@Getter
@RequiredArgsConstructor
public class NPCHook implements INPCHook {
| private final NPC npc; |
TechzoneMC/NPCLib | nms-v1_7_R3/src/main/java/net/techcable/npclib/nms/versions/v1_7_R3/network/NPCNetworkManager.java | // Path: api/src/main/java/net/techcable/npclib/utils/Reflection.java
// public class Reflection {
//
// public static Class<?> getNmsClass(String name) {
// String className = "net.minecraft.server." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getCbClass(String name) {
// String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getUtilClass(String name) {
// try {
// return Class.forName(name); //Try before 1.8 first
// } catch (ClassNotFoundException ex) {
// try {
// return Class.forName("net.minecraft.util." + name); //Not 1.8
// } catch (ClassNotFoundException ex2) {
// return null;
// }
// }
// }
//
// public static String getVersion() {
// String packageName = Bukkit.getServer().getClass().getPackage().getName();
// return packageName.substring(packageName.lastIndexOf('.') + 1);
// }
//
// public static Object getHandle(Object wrapper) {
// Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
// return callMethod(getHandle, wrapper);
// }
//
// //Utils
// public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
// try {
// return clazz.getDeclaredMethod(methodName, paramaters);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
// if (method == null) throw new RuntimeException("No such method");
// method.setAccessible(true);
// try {
// return (T) method.invoke(instance, paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
// try {
// return (Constructor<T>) clazz.getConstructor(paramaterTypes);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
// if (constructor == null) throw new RuntimeException("No such constructor");
// constructor.setAccessible(true);
// try {
// return (T) constructor.newInstance(paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Field makeField(Class<?> clazz, String name) {
// try {
// return clazz.getDeclaredField(name);
// } catch (NoSuchFieldException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getField(Field field, Object instance) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// return (T) field.get(instance);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static void setField(Field field, Object instance, Object value) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// field.set(instance, value);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Class<?> getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException ex) {
// return null;
// }
// }
//
// public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
// try {
// return Class.forName(name).asSubclass(superClass);
// } catch (ClassCastException | ClassNotFoundException ex) {
// return null;
// }
// }
// }
| import lombok.*;
import java.lang.reflect.Field;
import net.minecraft.server.v1_7_R3.NetworkManager;
import net.techcable.npclib.utils.Reflection; | package net.techcable.npclib.nms.versions.v1_7_R3.network;
@Getter
public class NPCNetworkManager extends NetworkManager {
public NPCNetworkManager() {
super(false); //MCP = isClientSide | // Path: api/src/main/java/net/techcable/npclib/utils/Reflection.java
// public class Reflection {
//
// public static Class<?> getNmsClass(String name) {
// String className = "net.minecraft.server." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getCbClass(String name) {
// String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getUtilClass(String name) {
// try {
// return Class.forName(name); //Try before 1.8 first
// } catch (ClassNotFoundException ex) {
// try {
// return Class.forName("net.minecraft.util." + name); //Not 1.8
// } catch (ClassNotFoundException ex2) {
// return null;
// }
// }
// }
//
// public static String getVersion() {
// String packageName = Bukkit.getServer().getClass().getPackage().getName();
// return packageName.substring(packageName.lastIndexOf('.') + 1);
// }
//
// public static Object getHandle(Object wrapper) {
// Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
// return callMethod(getHandle, wrapper);
// }
//
// //Utils
// public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
// try {
// return clazz.getDeclaredMethod(methodName, paramaters);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
// if (method == null) throw new RuntimeException("No such method");
// method.setAccessible(true);
// try {
// return (T) method.invoke(instance, paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
// try {
// return (Constructor<T>) clazz.getConstructor(paramaterTypes);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
// if (constructor == null) throw new RuntimeException("No such constructor");
// constructor.setAccessible(true);
// try {
// return (T) constructor.newInstance(paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Field makeField(Class<?> clazz, String name) {
// try {
// return clazz.getDeclaredField(name);
// } catch (NoSuchFieldException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getField(Field field, Object instance) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// return (T) field.get(instance);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static void setField(Field field, Object instance, Object value) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// field.set(instance, value);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Class<?> getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException ex) {
// return null;
// }
// }
//
// public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
// try {
// return Class.forName(name).asSubclass(superClass);
// } catch (ClassCastException | ClassNotFoundException ex) {
// return null;
// }
// }
// }
// Path: nms-v1_7_R3/src/main/java/net/techcable/npclib/nms/versions/v1_7_R3/network/NPCNetworkManager.java
import lombok.*;
import java.lang.reflect.Field;
import net.minecraft.server.v1_7_R3.NetworkManager;
import net.techcable.npclib.utils.Reflection;
package net.techcable.npclib.nms.versions.v1_7_R3.network;
@Getter
public class NPCNetworkManager extends NetworkManager {
public NPCNetworkManager() {
super(false); //MCP = isClientSide | Field channel = Reflection.makeField(NetworkManager.class, "m"); //MCP = channel |
TechzoneMC/NPCLib | nms-v1_8_R3/src/main/java/net/techcable/npclib/nms/versions/v1_8_R3/network/NPCNetworkManager.java | // Path: api/src/main/java/net/techcable/npclib/utils/Reflection.java
// public class Reflection {
//
// public static Class<?> getNmsClass(String name) {
// String className = "net.minecraft.server." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getCbClass(String name) {
// String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getUtilClass(String name) {
// try {
// return Class.forName(name); //Try before 1.8 first
// } catch (ClassNotFoundException ex) {
// try {
// return Class.forName("net.minecraft.util." + name); //Not 1.8
// } catch (ClassNotFoundException ex2) {
// return null;
// }
// }
// }
//
// public static String getVersion() {
// String packageName = Bukkit.getServer().getClass().getPackage().getName();
// return packageName.substring(packageName.lastIndexOf('.') + 1);
// }
//
// public static Object getHandle(Object wrapper) {
// Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
// return callMethod(getHandle, wrapper);
// }
//
// //Utils
// public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
// try {
// return clazz.getDeclaredMethod(methodName, paramaters);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
// if (method == null) throw new RuntimeException("No such method");
// method.setAccessible(true);
// try {
// return (T) method.invoke(instance, paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
// try {
// return (Constructor<T>) clazz.getConstructor(paramaterTypes);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
// if (constructor == null) throw new RuntimeException("No such constructor");
// constructor.setAccessible(true);
// try {
// return (T) constructor.newInstance(paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Field makeField(Class<?> clazz, String name) {
// try {
// return clazz.getDeclaredField(name);
// } catch (NoSuchFieldException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getField(Field field, Object instance) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// return (T) field.get(instance);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static void setField(Field field, Object instance, Object value) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// field.set(instance, value);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Class<?> getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException ex) {
// return null;
// }
// }
//
// public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
// try {
// return Class.forName(name).asSubclass(superClass);
// } catch (ClassCastException | ClassNotFoundException ex) {
// return null;
// }
// }
// }
| import lombok.*;
import java.lang.reflect.Field;
import net.minecraft.server.v1_8_R3.EnumProtocolDirection;
import net.minecraft.server.v1_8_R3.NetworkManager;
import net.techcable.npclib.utils.Reflection; | package net.techcable.npclib.nms.versions.v1_8_R3.network;
@Getter
public class NPCNetworkManager extends NetworkManager {
public NPCNetworkManager() {
super(EnumProtocolDirection.CLIENTBOUND); //MCP = isClientSide ---- SRG=field_150747_h | // Path: api/src/main/java/net/techcable/npclib/utils/Reflection.java
// public class Reflection {
//
// public static Class<?> getNmsClass(String name) {
// String className = "net.minecraft.server." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getCbClass(String name) {
// String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
// return getClass(className);
// }
//
// public static Class<?> getUtilClass(String name) {
// try {
// return Class.forName(name); //Try before 1.8 first
// } catch (ClassNotFoundException ex) {
// try {
// return Class.forName("net.minecraft.util." + name); //Not 1.8
// } catch (ClassNotFoundException ex2) {
// return null;
// }
// }
// }
//
// public static String getVersion() {
// String packageName = Bukkit.getServer().getClass().getPackage().getName();
// return packageName.substring(packageName.lastIndexOf('.') + 1);
// }
//
// public static Object getHandle(Object wrapper) {
// Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
// return callMethod(getHandle, wrapper);
// }
//
// //Utils
// public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
// try {
// return clazz.getDeclaredMethod(methodName, paramaters);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
// if (method == null) throw new RuntimeException("No such method");
// method.setAccessible(true);
// try {
// return (T) method.invoke(instance, paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
// try {
// return (Constructor<T>) clazz.getConstructor(paramaterTypes);
// } catch (NoSuchMethodException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
// if (constructor == null) throw new RuntimeException("No such constructor");
// constructor.setAccessible(true);
// try {
// return (T) constructor.newInstance(paramaters);
// } catch (InvocationTargetException ex) {
// throw new RuntimeException(ex.getCause());
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Field makeField(Class<?> clazz, String name) {
// try {
// return clazz.getDeclaredField(name);
// } catch (NoSuchFieldException ex) {
// return null;
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T getField(Field field, Object instance) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// return (T) field.get(instance);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static void setField(Field field, Object instance, Object value) {
// if (field == null) throw new RuntimeException("No such field");
// field.setAccessible(true);
// try {
// field.set(instance, value);
// } catch (Exception ex) {
// throw new RuntimeException(ex);
// }
// }
//
// public static Class<?> getClass(String name) {
// try {
// return Class.forName(name);
// } catch (ClassNotFoundException ex) {
// return null;
// }
// }
//
// public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
// try {
// return Class.forName(name).asSubclass(superClass);
// } catch (ClassCastException | ClassNotFoundException ex) {
// return null;
// }
// }
// }
// Path: nms-v1_8_R3/src/main/java/net/techcable/npclib/nms/versions/v1_8_R3/network/NPCNetworkManager.java
import lombok.*;
import java.lang.reflect.Field;
import net.minecraft.server.v1_8_R3.EnumProtocolDirection;
import net.minecraft.server.v1_8_R3.NetworkManager;
import net.techcable.npclib.utils.Reflection;
package net.techcable.npclib.nms.versions.v1_8_R3.network;
@Getter
public class NPCNetworkManager extends NetworkManager {
public NPCNetworkManager() {
super(EnumProtocolDirection.CLIENTBOUND); //MCP = isClientSide ---- SRG=field_150747_h | Field channel = Reflection.makeField(NetworkManager.class, "channel"); //MCP = channel ---- SRG=field_150746_k |
TechzoneMC/NPCLib | nms-v1_8_R2/src/main/java/net/techcable/npclib/nms/versions/v1_8_R2/NPCHook.java | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
| import lombok.*;
import net.minecraft.server.v1_8_R2.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook; | package net.techcable.npclib.nms.versions.v1_8_R2;
@Getter
@RequiredArgsConstructor | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
// Path: nms-v1_8_R2/src/main/java/net/techcable/npclib/nms/versions/v1_8_R2/NPCHook.java
import lombok.*;
import net.minecraft.server.v1_8_R2.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook;
package net.techcable.npclib.nms.versions.v1_8_R2;
@Getter
@RequiredArgsConstructor | public class NPCHook implements INPCHook { |
TechzoneMC/NPCLib | nms-v1_8_R2/src/main/java/net/techcable/npclib/nms/versions/v1_8_R2/NPCHook.java | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
| import lombok.*;
import net.minecraft.server.v1_8_R2.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook; | package net.techcable.npclib.nms.versions.v1_8_R2;
@Getter
@RequiredArgsConstructor
public class NPCHook implements INPCHook {
| // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
// Path: nms-v1_8_R2/src/main/java/net/techcable/npclib/nms/versions/v1_8_R2/NPCHook.java
import lombok.*;
import net.minecraft.server.v1_8_R2.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook;
package net.techcable.npclib.nms.versions.v1_8_R2;
@Getter
@RequiredArgsConstructor
public class NPCHook implements INPCHook {
| private final NPC npc; |
TechzoneMC/NPCLib | nms-v1_9_R1/src/main/java/net/techcable/npclib/nms/versions/v1_9_R1/NPCHook.java | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
| import lombok.*;
import net.minecraft.server.v1_9_R1.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook; | package net.techcable.npclib.nms.versions.v1_9_R1;
@Getter
@RequiredArgsConstructor | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
// Path: nms-v1_9_R1/src/main/java/net/techcable/npclib/nms/versions/v1_9_R1/NPCHook.java
import lombok.*;
import net.minecraft.server.v1_9_R1.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook;
package net.techcable.npclib.nms.versions.v1_9_R1;
@Getter
@RequiredArgsConstructor | public class NPCHook implements INPCHook { |
TechzoneMC/NPCLib | nms-v1_9_R1/src/main/java/net/techcable/npclib/nms/versions/v1_9_R1/NPCHook.java | // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
| import lombok.*;
import net.minecraft.server.v1_9_R1.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook; | package net.techcable.npclib.nms.versions.v1_9_R1;
@Getter
@RequiredArgsConstructor
public class NPCHook implements INPCHook {
| // Path: api/src/main/java/net/techcable/npclib/NPC.java
// public interface NPC {
//
// /**
// * Despawn this npc
// * <p/>
// * Once despawned it can not be respawned
// * It will be deregistered from the registry
// *
// * @return true if was able to despawn
// *
// * @throws java.lang.IllegalStateException if the npc is already despawned
// */
// public void despawn();
//
// /**
// * Get the nmsEntity associated with this npc
// *
// * @return the nmsEntity
// */
// public Entity getEntity();
//
// /**
// * Get this npc's uuid
// *
// * @return the uuid of this npc
// */
// public UUID getUUID();
//
// /**
// * Returns whether the npc is spawned
// *
// * @return true if the npc is spawned
// */
// public boolean isSpawned();
//
// /**
// * Returns whether the npc has been destroyed
// * <p>
// * NPCs that are destroyed can never be respawned
// * </p>
// *
// * @return true if the npc has been destroyed
// */
// public boolean isDestroyed();
//
// /**
// * Spawn this npc
// *
// * @param toSpawn location to spawn this npc
// *
// * @return true if the npc was able to spawn
// *
// * @throws java.lang.NullPointerException if location is null
// * @throws java.lang.IllegalArgumentException if already or spawned or {@link #despawn()} has been called
// */
// public void spawn(Location toSpawn);
//
// /**
// * Set the protected status of this NPC
// * true by default
// *
// * @param protect whether or not this npc is invincible
// */
// public void setProtected(boolean protect);
//
// /**
// * Check if the NPC is protected from damage
// *
// * @return The protected status of the NPC
// */
// public boolean isProtected();
//
// /**
// * Add the specified task to the npc
// *
// * @param task the task to add
// */
// public void addTask(AITask task);
//
// /**
// * Get the npc's ai environment
// * <p>
// * The ai environment manages the npc's ai
// * </p>
// *
// * @return the npc's ai environment
// */
// public AIEnvironment getAIEnvironment();
//
// }
//
// Path: api/src/main/java/net/techcable/npclib/nms/INPCHook.java
// public interface INPCHook {
//
// public void onDespawn();
//
// public Entity getEntity();
// }
// Path: nms-v1_9_R1/src/main/java/net/techcable/npclib/nms/versions/v1_9_R1/NPCHook.java
import lombok.*;
import net.minecraft.server.v1_9_R1.Entity;
import net.techcable.npclib.NPC;
import net.techcable.npclib.nms.INPCHook;
package net.techcable.npclib.nms.versions.v1_9_R1;
@Getter
@RequiredArgsConstructor
public class NPCHook implements INPCHook {
| private final NPC npc; |
golo-lang/golo-jmh-benchmarks | src/test/java/org/gololang/microbenchmarks/filtermapreduce/JavaCopyingFilterMapReduceTest.java | // Path: src/main/java/org/gololang/microbenchmarks/filtermapreduce/JavaCopyingFilterMapReduce.java
// public class JavaCopyingFilterMapReduce {
//
// public static interface Predicate {
// boolean apply(Object object);
// }
//
// public static interface Function {
// Object apply(Object a);
// }
//
// public static interface BiFunction {
// Object apply(Object a, Object b);
// }
//
// public static Collection<Object> newWithSameType(Collection<?> collection) {
// if (collection instanceof RandomAccess) {
// return new ArrayList<>();
// } else if (collection instanceof List) {
// return new LinkedList<>();
// } else if (collection instanceof Set) {
// return new HashSet<>();
// } else {
// throw new RuntimeException("Not a supported collection: " + collection.getClass());
// }
// }
//
// public static Collection<?> filter(Collection<?> collection, Predicate predicate) {
// Collection<Object> result = newWithSameType(collection);
// for (Object obj : collection) {
// if (predicate.apply(obj)) {
// result.add(obj);
// }
// }
// return result;
// }
//
// public static Collection<?> map(Collection<?> collection, Function fun) {
// Collection<Object> result = newWithSameType(collection);
// for (Object obj : collection) {
// result.add(fun.apply(obj));
// }
// return result;
// }
//
// public static Object reduce(Collection<?> collection, Object initialValue, BiFunction reducer) {
// Object result = initialValue;
// for (Object obj : collection) {
// result = reducer.apply(result, obj);
// }
// return result;
// }
// }
| import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import static org.gololang.microbenchmarks.filtermapreduce.JavaCopyingFilterMapReduce.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.filtermapreduce;
public class JavaCopyingFilterMapReduceTest {
@Test
public void test_newWithSameType() throws Exception {
assertEquals(ArrayList.class, newWithSameType(new ArrayList<>()).getClass());
assertEquals(LinkedList.class, newWithSameType(new LinkedList<>()).getClass());
assertEquals(HashSet.class, newWithSameType(new HashSet<>()).getClass());
}
@Test
public void test_filter() throws Exception {
ArrayList<Object> list = new ArrayList<Object>() {
{
add(1);
add(2);
add(3);
}
}; | // Path: src/main/java/org/gololang/microbenchmarks/filtermapreduce/JavaCopyingFilterMapReduce.java
// public class JavaCopyingFilterMapReduce {
//
// public static interface Predicate {
// boolean apply(Object object);
// }
//
// public static interface Function {
// Object apply(Object a);
// }
//
// public static interface BiFunction {
// Object apply(Object a, Object b);
// }
//
// public static Collection<Object> newWithSameType(Collection<?> collection) {
// if (collection instanceof RandomAccess) {
// return new ArrayList<>();
// } else if (collection instanceof List) {
// return new LinkedList<>();
// } else if (collection instanceof Set) {
// return new HashSet<>();
// } else {
// throw new RuntimeException("Not a supported collection: " + collection.getClass());
// }
// }
//
// public static Collection<?> filter(Collection<?> collection, Predicate predicate) {
// Collection<Object> result = newWithSameType(collection);
// for (Object obj : collection) {
// if (predicate.apply(obj)) {
// result.add(obj);
// }
// }
// return result;
// }
//
// public static Collection<?> map(Collection<?> collection, Function fun) {
// Collection<Object> result = newWithSameType(collection);
// for (Object obj : collection) {
// result.add(fun.apply(obj));
// }
// return result;
// }
//
// public static Object reduce(Collection<?> collection, Object initialValue, BiFunction reducer) {
// Object result = initialValue;
// for (Object obj : collection) {
// result = reducer.apply(result, obj);
// }
// return result;
// }
// }
// Path: src/test/java/org/gololang/microbenchmarks/filtermapreduce/JavaCopyingFilterMapReduceTest.java
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import static org.gololang.microbenchmarks.filtermapreduce.JavaCopyingFilterMapReduce.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.filtermapreduce;
public class JavaCopyingFilterMapReduceTest {
@Test
public void test_newWithSameType() throws Exception {
assertEquals(ArrayList.class, newWithSameType(new ArrayList<>()).getClass());
assertEquals(LinkedList.class, newWithSameType(new LinkedList<>()).getClass());
assertEquals(HashSet.class, newWithSameType(new HashSet<>()).getClass());
}
@Test
public void test_filter() throws Exception {
ArrayList<Object> list = new ArrayList<Object>() {
{
add(1);
add(2);
add(3);
}
}; | Collection<?> result = filter(list, new JavaCopyingFilterMapReduce.Predicate() { |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/dispatch/ClosureDispatchMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
| import gololang.FunctionReference;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType; | }
}
}
@State(Scope.Thread)
static public class DataState {
Object argument = new HashSet<Object>() {
{
add(1);
add(2L);
add("3");
add(new Object());
}
};
}
@State(Scope.Thread)
static public class GoloState {
FunctionReference stringify;
MethodHandle target;
@Setup(Level.Trial)
public void prepare() {
MethodHandles.Lookup lookup = MethodHandles.lookup();
try {
stringify = new FunctionReference(
lookup.findStatic(
ClosureDispatchMicroBenchmark.class, "stringify", genericMethodType(1))); | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/dispatch/ClosureDispatchMicroBenchmark.java
import gololang.FunctionReference;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType;
}
}
}
@State(Scope.Thread)
static public class DataState {
Object argument = new HashSet<Object>() {
{
add(1);
add(2L);
add("3");
add(new Object());
}
};
}
@State(Scope.Thread)
static public class GoloState {
FunctionReference stringify;
MethodHandle target;
@Setup(Level.Trial)
public void prepare() {
MethodHandles.Lookup lookup = MethodHandles.lookup();
try {
stringify = new FunctionReference(
lookup.findStatic(
ClosureDispatchMicroBenchmark.class, "stringify", genericMethodType(1))); | target = new CodeLoader().golo("dispatch", "closure_dispatch", 2); |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/arithmetic/CostOfSumMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
| import org.gololang.microbenchmarks.support.CodeLoader;
import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType; |
@State(Scope.Thread)
static public class JavaState {
MethodHandle sumHandle;
MethodHandle boxedSumHandle;
MethodHandle boxedSumWithConstantHandle;
@Setup(Level.Trial)
public void setup() {
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
sumHandle = lookup.findStatic(CostOfSumMicroBenchmark.class, "sum", methodType(long.class, long.class, long.class));
boxedSumHandle = lookup.findStatic(CostOfSumMicroBenchmark.class, "boxed_sum", genericMethodType(2));
boxedSumWithConstantHandle = lookup.findStatic(CostOfSumMicroBenchmark.class, "boxed_sum_with_constant", genericMethodType(1));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle sumHandle;
MethodHandle sumWithConstantHandle;
MethodHandle sumOfConstantsHandle;
@Setup(Level.Trial)
public void setup() { | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/arithmetic/CostOfSumMicroBenchmark.java
import org.gololang.microbenchmarks.support.CodeLoader;
import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType;
@State(Scope.Thread)
static public class JavaState {
MethodHandle sumHandle;
MethodHandle boxedSumHandle;
MethodHandle boxedSumWithConstantHandle;
@Setup(Level.Trial)
public void setup() {
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
sumHandle = lookup.findStatic(CostOfSumMicroBenchmark.class, "sum", methodType(long.class, long.class, long.class));
boxedSumHandle = lookup.findStatic(CostOfSumMicroBenchmark.class, "boxed_sum", genericMethodType(2));
boxedSumWithConstantHandle = lookup.findStatic(CostOfSumMicroBenchmark.class, "boxed_sum_with_constant", genericMethodType(1));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle sumHandle;
MethodHandle sumWithConstantHandle;
MethodHandle sumOfConstantsHandle;
@Setup(Level.Trial)
public void setup() { | sumHandle = new CodeLoader().golo("arithmetic", "sum", 2); |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/fibonacci/FibonacciMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
| import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType; | /*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.fibonacci;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class FibonacciMicroBenchmark {
@State(Scope.Thread)
static public class State40 {
long n = 40L;
}
@State(Scope.Thread)
static public class State30 {
long n = 30L;
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle fib;
@Setup(Level.Trial)
public void prepare() { | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/fibonacci/FibonacciMicroBenchmark.java
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType;
/*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.fibonacci;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class FibonacciMicroBenchmark {
@State(Scope.Thread)
static public class State40 {
long n = 40L;
}
@State(Scope.Thread)
static public class State30 {
long n = 30L;
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle fib;
@Setup(Level.Trial)
public void prepare() { | fib = new CodeLoader().golo("fibonacci", "fib", 1); |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/fibonacci/FibonacciMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
| import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType; | MethodHandle fib;
@Setup(Level.Trial)
public void prepare() {
fib = new CodeLoader().groovy("Fibonacci", "fib", genericMethodType(1));
}
}
@State(Scope.Thread)
static public class GroovyIndyState {
MethodHandle fib;
@Setup(Level.Trial)
public void prepare() {
fib = new CodeLoader().groovy_indy("Fibonacci", "fib", genericMethodType(1));
}
}
@State(Scope.Thread)
static public class ClojureState {
Var fib;
@Setup(Level.Trial)
public void prepare() {
fib = new CodeLoader().clojure("fibonacci", "fibonacci", "fib");
}
}
@State(Scope.Thread)
static public class JRubyState { | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/fibonacci/FibonacciMicroBenchmark.java
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.genericMethodType;
MethodHandle fib;
@Setup(Level.Trial)
public void prepare() {
fib = new CodeLoader().groovy("Fibonacci", "fib", genericMethodType(1));
}
}
@State(Scope.Thread)
static public class GroovyIndyState {
MethodHandle fib;
@Setup(Level.Trial)
public void prepare() {
fib = new CodeLoader().groovy_indy("Fibonacci", "fib", genericMethodType(1));
}
}
@State(Scope.Thread)
static public class ClojureState {
Var fib;
@Setup(Level.Trial)
public void prepare() {
fib = new CodeLoader().clojure("fibonacci", "fibonacci", "fib");
}
}
@State(Scope.Thread)
static public class JRubyState { | JRubyContainerAndReceiver containerAndReceiver; |
golo-lang/golo-jmh-benchmarks | src/test/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacciTest.java | // Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static Long withBoxing(Long n) {
// if (n.longValue() <= Long.valueOf(2L)) {
// return Long.valueOf(1L);
// } else {
// return Long.valueOf(withBoxing(Long.valueOf(n.longValue() - Long.valueOf(1L))) + withBoxing(Long.valueOf(n.longValue() - Long.valueOf(2L))));
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static long withPrimitives(long n) {
// if (n <= 2L) {
// return 1L;
// } else {
// return withPrimitives(n - 1L) + withPrimitives(n - 2L);
// }
// }
| import org.junit.Test;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withBoxing;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withPrimitives;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.fibonacci;
public class JavaRecursiveFibonacciTest {
@Test
public void test_withPrimitives() throws Exception { | // Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static Long withBoxing(Long n) {
// if (n.longValue() <= Long.valueOf(2L)) {
// return Long.valueOf(1L);
// } else {
// return Long.valueOf(withBoxing(Long.valueOf(n.longValue() - Long.valueOf(1L))) + withBoxing(Long.valueOf(n.longValue() - Long.valueOf(2L))));
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static long withPrimitives(long n) {
// if (n <= 2L) {
// return 1L;
// } else {
// return withPrimitives(n - 1L) + withPrimitives(n - 2L);
// }
// }
// Path: src/test/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacciTest.java
import org.junit.Test;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withBoxing;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withPrimitives;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.fibonacci;
public class JavaRecursiveFibonacciTest {
@Test
public void test_withPrimitives() throws Exception { | assertEquals(1L, withPrimitives(1L)); |
golo-lang/golo-jmh-benchmarks | src/test/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacciTest.java | // Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static Long withBoxing(Long n) {
// if (n.longValue() <= Long.valueOf(2L)) {
// return Long.valueOf(1L);
// } else {
// return Long.valueOf(withBoxing(Long.valueOf(n.longValue() - Long.valueOf(1L))) + withBoxing(Long.valueOf(n.longValue() - Long.valueOf(2L))));
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static long withPrimitives(long n) {
// if (n <= 2L) {
// return 1L;
// } else {
// return withPrimitives(n - 1L) + withPrimitives(n - 2L);
// }
// }
| import org.junit.Test;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withBoxing;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withPrimitives;
import static org.junit.Assert.assertEquals; | /*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.fibonacci;
public class JavaRecursiveFibonacciTest {
@Test
public void test_withPrimitives() throws Exception {
assertEquals(1L, withPrimitives(1L));
assertEquals(1L, withPrimitives(2L));
assertEquals(2L, withPrimitives(3L));
assertEquals(3L, withPrimitives(4L));
assertEquals(5L, withPrimitives(5L));
assertEquals(8L, withPrimitives(6L));
assertEquals(13L, withPrimitives(7L));
}
@Test
public void test_withBoxing() throws Exception { | // Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static Long withBoxing(Long n) {
// if (n.longValue() <= Long.valueOf(2L)) {
// return Long.valueOf(1L);
// } else {
// return Long.valueOf(withBoxing(Long.valueOf(n.longValue() - Long.valueOf(1L))) + withBoxing(Long.valueOf(n.longValue() - Long.valueOf(2L))));
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacci.java
// public static long withPrimitives(long n) {
// if (n <= 2L) {
// return 1L;
// } else {
// return withPrimitives(n - 1L) + withPrimitives(n - 2L);
// }
// }
// Path: src/test/java/org/gololang/microbenchmarks/fibonacci/JavaRecursiveFibonacciTest.java
import org.junit.Test;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withBoxing;
import static org.gololang.microbenchmarks.fibonacci.JavaRecursiveFibonacci.withPrimitives;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.fibonacci;
public class JavaRecursiveFibonacciTest {
@Test
public void test_withPrimitives() throws Exception {
assertEquals(1L, withPrimitives(1L));
assertEquals(1L, withPrimitives(2L));
assertEquals(2L, withPrimitives(3L));
assertEquals(3L, withPrimitives(4L));
assertEquals(5L, withPrimitives(5L));
assertEquals(8L, withPrimitives(6L));
assertEquals(13L, withPrimitives(7L));
}
@Test
public void test_withBoxing() throws Exception { | assertEquals((Long) 1L, withBoxing(1L)); |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/arithmetic/EuclidianGcdMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
| import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType;
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.TimeUnit; | } else {
b = b - a;
}
}
return a;
}
@State(Scope.Thread)
static public class JavaState {
MethodHandle gcdHandle;
@Setup(Level.Trial)
public void setup() {
try {
gcdHandle = MethodHandles.lookup().findStatic(EuclidianGcdMicroBenchmark.class, "gcd", methodType(long.class, long.class, long.class));
gcdHandle = gcdHandle.asType(genericMethodType(2));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle gcdHandle;
@Setup(Level.Trial)
public void setup() { | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/arithmetic/EuclidianGcdMicroBenchmark.java
import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType;
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.TimeUnit;
} else {
b = b - a;
}
}
return a;
}
@State(Scope.Thread)
static public class JavaState {
MethodHandle gcdHandle;
@Setup(Level.Trial)
public void setup() {
try {
gcdHandle = MethodHandles.lookup().findStatic(EuclidianGcdMicroBenchmark.class, "gcd", methodType(long.class, long.class, long.class));
gcdHandle = gcdHandle.asType(genericMethodType(2));
} catch (NoSuchMethodException | IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle gcdHandle;
@Setup(Level.Trial)
public void setup() { | gcdHandle = new CodeLoader().golo("arithmetic", "gcd", 2); |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/arithmetic/EuclidianGcdMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
| import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType;
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.TimeUnit; | MethodHandle gcdHandle;
MethodHandle fast_gcdHandle;
MethodHandle fastest_gcdHandle;
@Setup(Level.Trial)
public void setup() {
gcdHandle = new CodeLoader().groovy("arithmetic", "gcd", genericMethodType(2));
fast_gcdHandle = new CodeLoader().groovy("arithmetic", "fast_gcd", methodType(long.class, long.class, long.class));
fastest_gcdHandle = new CodeLoader().groovy("arithmetic", "fastest_gcd", methodType(long.class, long.class, long.class));
}
}
@State(Scope.Thread)
static public class GroovyIndyState {
MethodHandle gcdHandle;
MethodHandle fast_gcdHandle;
MethodHandle fastest_gcdHandle;
@Setup(Level.Trial)
public void setup() {
gcdHandle = new CodeLoader().groovy_indy("arithmetic", "gcd", genericMethodType(2));
fast_gcdHandle = new CodeLoader().groovy_indy("arithmetic", "fast_gcd", methodType(long.class, long.class, long.class));
fastest_gcdHandle = new CodeLoader().groovy_indy("arithmetic", "fastest_gcd", methodType(long.class, long.class, long.class));
}
}
@State(Scope.Thread)
static public class JRubyState {
| // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/arithmetic/EuclidianGcdMicroBenchmark.java
import static java.lang.invoke.MethodType.genericMethodType;
import static java.lang.invoke.MethodType.methodType;
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyFunction;
import org.python.core.PyLong;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Random;
import java.util.concurrent.TimeUnit;
MethodHandle gcdHandle;
MethodHandle fast_gcdHandle;
MethodHandle fastest_gcdHandle;
@Setup(Level.Trial)
public void setup() {
gcdHandle = new CodeLoader().groovy("arithmetic", "gcd", genericMethodType(2));
fast_gcdHandle = new CodeLoader().groovy("arithmetic", "fast_gcd", methodType(long.class, long.class, long.class));
fastest_gcdHandle = new CodeLoader().groovy("arithmetic", "fastest_gcd", methodType(long.class, long.class, long.class));
}
}
@State(Scope.Thread)
static public class GroovyIndyState {
MethodHandle gcdHandle;
MethodHandle fast_gcdHandle;
MethodHandle fastest_gcdHandle;
@Setup(Level.Trial)
public void setup() {
gcdHandle = new CodeLoader().groovy_indy("arithmetic", "gcd", genericMethodType(2));
fast_gcdHandle = new CodeLoader().groovy_indy("arithmetic", "fast_gcd", methodType(long.class, long.class, long.class));
fastest_gcdHandle = new CodeLoader().groovy_indy("arithmetic", "fastest_gcd", methodType(long.class, long.class, long.class));
}
}
@State(Scope.Thread)
static public class JRubyState {
| JRubyContainerAndReceiver containerAndReceiver; |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/dispatch/DecoratorsMicrobenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
| import org.gololang.microbenchmarks.support.CodeLoader;
import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit; | /*
* Copyright 2018 Julien Ponge.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.dispatch;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class DecoratorsMicrobenchmark {
static long add(long v, long n) {
return v + n;
}
static long times(long v, long n) {
return v * n;
}
@State(Scope.Thread)
static public class JavaState {
long A = 123456;
long B = 465;
long C = 123;
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle add;
long A = 123456;
long B = 465;
// long C -> in the decorator call
@Setup
public void setup() { | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/dispatch/DecoratorsMicrobenchmark.java
import org.gololang.microbenchmarks.support.CodeLoader;
import org.openjdk.jmh.annotations.*;
import java.lang.invoke.MethodHandle;
import java.util.concurrent.TimeUnit;
/*
* Copyright 2018 Julien Ponge.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.dispatch;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class DecoratorsMicrobenchmark {
static long add(long v, long n) {
return v + n;
}
static long times(long v, long n) {
return v * n;
}
@State(Scope.Thread)
static public class JavaState {
long A = 123456;
long B = 465;
long C = 123;
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle add;
long A = 123456;
long B = 465;
// long C -> in the decorator call
@Setup
public void setup() { | add = new CodeLoader().golo("decorators", "add", 2); |
golo-lang/golo-jmh-benchmarks | src/main/java/org/gololang/microbenchmarks/dispatch/MethodDispatchMicroBenchmark.java | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
| import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.methodType;
import static org.jruby.javasupport.JavaUtil.convertJavaArrayToRuby;
import clojure.lang.PersistentVector;
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.jruby.runtime.builtin.IRubyObject;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyArray;
import org.python.core.PyFunction;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.HashMap; | /*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.dispatch;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public class MethodDispatchMicroBenchmark {
/* ................................................................................................................ */
private static final int N = 1024;
/* ................................................................................................................ */
@State(Scope.Thread)
static public class JavaState {
JavaDispatch dispatcher;
@Setup(Level.Trial)
public void prepare() {
dispatcher = new JavaDispatch();
}
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle dispatcher;
@Setup(Level.Trial)
public void prepare() { | // Path: src/main/java/org/gololang/microbenchmarks/support/CodeLoader.java
// public class CodeLoader {
//
// private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
//
// public MethodHandle golo(String file, String func, int argCount) {
// GoloClassLoader classLoader = new GoloClassLoader();
// String filename = "snippets/golo/" + file + ".golo";
// Class<?> module = classLoader.load(filename, CodeLoader.class.getResourceAsStream("/" + filename));
// try {
// return LOOKUP.findStatic(module, func, MethodType.genericMethodType(argCount));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public MethodHandle groovy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", false);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", false);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// public MethodHandle groovy_indy(String file, String method, MethodType type) {
// CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
// CompilerConfiguration configuration = new CompilerConfiguration();
// configuration.getOptimizationOptions().put("indy", true);
// GroovyClassLoader classLoader = new GroovyClassLoader();
// return _groovy(file, method, type, classLoader);
// }
//
// private MethodHandle _groovy(String file, String method, MethodType type, GroovyClassLoader classLoader) {
// String filename = "snippets/groovy/" + file + ".groovy";
// Class klass = classLoader.parseClass(CodeLoader.class.getResourceAsStream("/" + filename), filename);
// try {
// return LOOKUP.findStatic(klass, method, type);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public clojure.lang.Var clojure(String file, String namespace, String ref) {
// try {
// // Damn you Clojure 1.5, somehow RT needs to be loaded in a way or the other
// Class.forName("clojure.lang.RT");
// String filename = "snippets/clojure/" + file + ".clj";
// InputStreamReader reader = new InputStreamReader(CodeLoader.class.getResourceAsStream("/" + filename));
// clojure.lang.Compiler.load(reader);
// return clojure.lang.RT.var(namespace, ref);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public JRubyContainerAndReceiver jruby(String file) {
// ScriptingContainer container = new ScriptingContainer();
// String filename = "snippets/jruby/" + file + ".rb";
// return new JRubyContainerAndReceiver(container,
// container.runScriptlet(CodeLoader.class.getResourceAsStream("/" + filename), filename));
// }
//
// public ScriptEngine nashorn(String file) {
// try {
// ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// if (engine != null) {
// engine.eval(new InputStreamReader(CodeLoader.class.getResourceAsStream("/snippets/js/" + file + ".js")));
// }
// return engine;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public PythonInterpreter jython(String file) {
// PythonInterpreter pythonInterpreter = new PythonInterpreter();
// String filename = "snippets/jython/" + file + ".py";
// pythonInterpreter.execfile(CodeLoader.class.getResourceAsStream("/" + filename));
// return pythonInterpreter;
// }
// }
//
// Path: src/main/java/org/gololang/microbenchmarks/support/JRubyContainerAndReceiver.java
// public final class JRubyContainerAndReceiver {
//
// private final ScriptingContainer container;
// private final Object receiver;
//
// public JRubyContainerAndReceiver(ScriptingContainer container, Object receiver) {
// this.container = container;
// this.receiver = receiver;
// }
//
// public ScriptingContainer container() {
// return container;
// }
//
// public Object receiver() {
// return receiver;
// }
// }
// Path: src/main/java/org/gololang/microbenchmarks/dispatch/MethodDispatchMicroBenchmark.java
import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import static java.lang.invoke.MethodType.methodType;
import static org.jruby.javasupport.JavaUtil.convertJavaArrayToRuby;
import clojure.lang.PersistentVector;
import clojure.lang.Var;
import org.gololang.microbenchmarks.support.CodeLoader;
import org.gololang.microbenchmarks.support.JRubyContainerAndReceiver;
import org.jruby.runtime.builtin.IRubyObject;
import org.openjdk.jmh.annotations.*;
import org.python.core.PyArray;
import org.python.core.PyFunction;
import org.python.util.PythonInterpreter;
import javax.script.Invocable;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.HashMap;
/*
* Copyright 2012-2016 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gololang.microbenchmarks.dispatch;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public class MethodDispatchMicroBenchmark {
/* ................................................................................................................ */
private static final int N = 1024;
/* ................................................................................................................ */
@State(Scope.Thread)
static public class JavaState {
JavaDispatch dispatcher;
@Setup(Level.Trial)
public void prepare() {
dispatcher = new JavaDispatch();
}
}
@State(Scope.Thread)
static public class GoloState {
MethodHandle dispatcher;
@Setup(Level.Trial)
public void prepare() { | dispatcher = new CodeLoader().golo("dispatch", "dispatch", 1); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/RxSet.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import android.content.ContentValues;
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Set;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import com.raizlabs.android.dbflow.structure.BaseModel;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | public RxWhere<TModel> offset(int offset) {
Where<TModel> where = mRealSet.offset(offset);
return new RxWhere<>(where);
}
@Override
public RxWhere<TModel> having(SQLOperator... conditions) {
Where<TModel> where = mRealSet.having(conditions);
return new RxWhere<>(where);
}
@Override
public String getQuery() {
return mRealSet.getQuery();
}
@Override
public Class<TModel> getTable() {
return mRealSet.getTable();
}
@Override
public Query getQueryBuilderBase() {
return mRealSet.getQueryBuilderBase();
}
@Override | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/RxSet.java
import android.content.ContentValues;
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Set;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import com.raizlabs.android.dbflow.structure.BaseModel;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
public RxWhere<TModel> offset(int offset) {
Where<TModel> where = mRealSet.offset(offset);
return new RxWhere<>(where);
}
@Override
public RxWhere<TModel> having(SQLOperator... conditions) {
Where<TModel> where = mRealSet.having(conditions);
return new RxWhere<>(where);
}
@Override
public String getQuery() {
return mRealSet.getQuery();
}
@Override
public Class<TModel> getTable() {
return mRealSet.getTable();
}
@Override
public Query getQueryBuilderBase() {
return mRealSet.getQueryBuilderBase();
}
@Override | public DBFlowSingle<Long> asCountSingle() { |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/RxSet.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import android.content.ContentValues;
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Set;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import com.raizlabs.android.dbflow.structure.BaseModel;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | }
@Override
public String getQuery() {
return mRealSet.getQuery();
}
@Override
public Class<TModel> getTable() {
return mRealSet.getTable();
}
@Override
public Query getQueryBuilderBase() {
return mRealSet.getQueryBuilderBase();
}
@Override
public DBFlowSingle<Long> asCountSingle() {
return where().asCountSingle();
}
@Override
public DBFlowSingle<Long> asCountSingle(DatabaseWrapper databaseWrapper) {
return where().asCountSingle(databaseWrapper);
}
@Override | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/RxSet.java
import android.content.ContentValues;
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Set;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import com.raizlabs.android.dbflow.structure.BaseModel;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
}
@Override
public String getQuery() {
return mRealSet.getQuery();
}
@Override
public Class<TModel> getTable() {
return mRealSet.getTable();
}
@Override
public Query getQueryBuilderBase() {
return mRealSet.getQueryBuilderBase();
}
@Override
public DBFlowSingle<Long> asCountSingle() {
return where().asCountSingle();
}
@Override
public DBFlowSingle<Long> asCountSingle(DatabaseWrapper databaseWrapper) {
return where().asCountSingle(databaseWrapper);
}
@Override | public DBFlowExecuteCompletable asExecuteCompletable() { |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/NotifyOfUpdate.java
// public class NotifyOfUpdate<ModelType> extends DBFlowBaseCompletable<ModelType> implements HasUpstreamCompletableSource {
//
// private final Completable mSource;
// private final String mQuery;
//
// public NotifyOfUpdate(Completable source, String query, Class<ModelType> clazz) {
// super(clazz);
// mSource = source;
// mQuery = query;
// }
//
// @Override
// public CompletableSource source() {
// return mSource;
// }
//
// @Override
// protected void subscribeActual(CompletableObserver observer) {
// mSource.subscribe(new CompletableObservable(observer, mQuery, getPrimaryModelClass()));
// super.subscribeActual(observer);
// }
//
// @Override
// public void run() {
// if(mQuery.toLowerCase().contains("delete ")){
// SqlUtils.notifyModelChanged(getPrimaryModelClass(), BaseModel.Action.DELETE, null);
// } else if(mQuery.toLowerCase().contains("update ")){
// SqlUtils.notifyModelChanged(getPrimaryModelClass(), BaseModel.Action.UPDATE, null);
// }
// }
//
// private class CompletableObservable implements CompletableObserver, Disposable {
//
// private final CompletableObserver mActual;
// private final String mQuery;
// private final Class mModelClazz;
// private boolean mIsDisposed = false;
//
// public CompletableObservable(CompletableObserver observer, String query, Class modelClazz) {
// mActual = observer;
// mQuery = query;
// mModelClazz = modelClazz;
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// if(mQuery.toLowerCase().contains("delete ")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.DELETE, null);
// } else if(mQuery.toLowerCase().contains("update ")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.UPDATE, null);
// }
//
// mActual.onComplete();
// }
//
// @Override
// public void dispose() {
// mIsDisposed = true;
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
// }
// }
| import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.sql.language.BaseQueriable;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.NotifyOfUpdate;
import io.reactivex.Completable; | package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* Given an RxSQLite query, executes a statement without a result.
*/
public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
private final BaseQueriable mBaseQueriable;
private final DatabaseWrapper mDatabaseWrapper;
/**
* Creates a new Observable which executes a sql statement against a table
* @param clazz The model class representing the table to execute against
* @param modelQueriable The query to execute
* @param databaseWrapper The database in which the target table resides
*/
public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
super(clazz);
mBaseQueriable = modelQueriable;
mDatabaseWrapper = databaseWrapper;
}
public Completable notifyOfUpdates(){ | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/NotifyOfUpdate.java
// public class NotifyOfUpdate<ModelType> extends DBFlowBaseCompletable<ModelType> implements HasUpstreamCompletableSource {
//
// private final Completable mSource;
// private final String mQuery;
//
// public NotifyOfUpdate(Completable source, String query, Class<ModelType> clazz) {
// super(clazz);
// mSource = source;
// mQuery = query;
// }
//
// @Override
// public CompletableSource source() {
// return mSource;
// }
//
// @Override
// protected void subscribeActual(CompletableObserver observer) {
// mSource.subscribe(new CompletableObservable(observer, mQuery, getPrimaryModelClass()));
// super.subscribeActual(observer);
// }
//
// @Override
// public void run() {
// if(mQuery.toLowerCase().contains("delete ")){
// SqlUtils.notifyModelChanged(getPrimaryModelClass(), BaseModel.Action.DELETE, null);
// } else if(mQuery.toLowerCase().contains("update ")){
// SqlUtils.notifyModelChanged(getPrimaryModelClass(), BaseModel.Action.UPDATE, null);
// }
// }
//
// private class CompletableObservable implements CompletableObserver, Disposable {
//
// private final CompletableObserver mActual;
// private final String mQuery;
// private final Class mModelClazz;
// private boolean mIsDisposed = false;
//
// public CompletableObservable(CompletableObserver observer, String query, Class modelClazz) {
// mActual = observer;
// mQuery = query;
// mModelClazz = modelClazz;
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// if(mQuery.toLowerCase().contains("delete ")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.DELETE, null);
// } else if(mQuery.toLowerCase().contains("update ")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.UPDATE, null);
// }
//
// mActual.onComplete();
// }
//
// @Override
// public void dispose() {
// mIsDisposed = true;
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.sql.language.BaseQueriable;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.NotifyOfUpdate;
import io.reactivex.Completable;
package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* Given an RxSQLite query, executes a statement without a result.
*/
public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
private final BaseQueriable mBaseQueriable;
private final DatabaseWrapper mDatabaseWrapper;
/**
* Creates a new Observable which executes a sql statement against a table
* @param clazz The model class representing the table to execute against
* @param modelQueriable The query to execute
* @param databaseWrapper The database in which the target table resides
*/
public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
super(clazz);
mBaseQueriable = modelQueriable;
mDatabaseWrapper = databaseWrapper;
}
public Completable notifyOfUpdates(){ | return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass()); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/structure/RxBaseModel.java | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/RxDbFlow.java
// public class RxDbFlow {
//
// public static <TModel> RxModelAdapter<TModel> getModelAdapter(Class<TModel> modelClass) {
// return new RxModelAdapter<>(FlowManager.getModelAdapter(modelClass));
// }
//
// }
| import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.InvalidDBConfiguration;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx1.RxDbFlow;
import rx.Observable; | * @return An observable
*/
public Observable<M> updateAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().updateAsObservable(this, databaseWrapper);
}
/**
* Returns an observable which will refresh the model's data based on the primary key when subscribed.
* @return An observable
*/
public Observable<M> loadAsObservable(){
return getRxModelAdapter().loadAsObservable(this);
}
/**
* Returns an observable which will refresh the model's data based on the primary key when subscribed.
* @param databaseWrapper The database wrapper for the database holding the table
* @return An observable
*/
public Observable<M> loadAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().loadAsObservable(this, databaseWrapper);
}
/**
* @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
* may throw a {@link InvalidDBConfiguration} for this call if this class
* is not associated with a table, so be careful when using this method.
*/
public RxModelAdapter getRxModelAdapter() {
if (mModelAdapter == null) { | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/RxDbFlow.java
// public class RxDbFlow {
//
// public static <TModel> RxModelAdapter<TModel> getModelAdapter(Class<TModel> modelClass) {
// return new RxModelAdapter<>(FlowManager.getModelAdapter(modelClass));
// }
//
// }
// Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/structure/RxBaseModel.java
import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.InvalidDBConfiguration;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx1.RxDbFlow;
import rx.Observable;
* @return An observable
*/
public Observable<M> updateAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().updateAsObservable(this, databaseWrapper);
}
/**
* Returns an observable which will refresh the model's data based on the primary key when subscribed.
* @return An observable
*/
public Observable<M> loadAsObservable(){
return getRxModelAdapter().loadAsObservable(this);
}
/**
* Returns an observable which will refresh the model's data based on the primary key when subscribed.
* @param databaseWrapper The database wrapper for the database holding the table
* @return An observable
*/
public Observable<M> loadAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().loadAsObservable(this, databaseWrapper);
}
/**
* @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
* may throw a {@link InvalidDBConfiguration} for this call if this class
* is not associated with a table, so be careful when using this method.
*/
public RxModelAdapter getRxModelAdapter() {
if (mModelAdapter == null) { | mModelAdapter = RxDbFlow.getModelAdapter(getClass()); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/transaction/RxModelOperationTransaction.java | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/structure/RxBaseModel.java
// @SuppressWarnings("unchecked")
// public class RxBaseModel<M extends RxBaseModel> extends BaseModel implements RxModifications<M> {
//
// private RxModelAdapter<? extends RxBaseModel> mModelAdapter;
//
// /**
// * Returns an observable for saving the object in the database
// * @return An observable
// */
// public Observable<M> saveAsObservable(){
// return getRxModelAdapter().saveAsObservable(this);
// }
//
// /**
// * Returns an observable for saving the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// @SuppressWarnings("unchecked")
// public Observable<M> saveAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().saveAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable for inserting the object in the database
// * @return An observable
// */
// public Observable<M> insertAsObservable(){
// return getRxModelAdapter().insertAsObservable(this);
// }
//
// /**
// * Returns an observable for inserting the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> insertAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().insertAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable for deleting the object from the database
// * @return An observable
// */
// public Observable<M> deleteAsObservable(){
// return getRxModelAdapter().deleteAsObservable(this);
// }
//
// /**
// * Returns an observable for deleting the object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> deleteAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().deleteAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable for update the object in the database
// * @return An observable
// */
// public Observable<M> updateAsObservable(){
// return getRxModelAdapter().updateAsObservable(this);
// }
//
// /**
// * Returns an observable for update in object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> updateAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().updateAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable which will refresh the model's data based on the primary key when subscribed.
// * @return An observable
// */
// public Observable<M> loadAsObservable(){
// return getRxModelAdapter().loadAsObservable(this);
// }
//
// /**
// * Returns an observable which will refresh the model's data based on the primary key when subscribed.
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> loadAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().loadAsObservable(this, databaseWrapper);
// }
//
// /**
// * @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
// * may throw a {@link InvalidDBConfiguration} for this call if this class
// * is not associated with a table, so be careful when using this method.
// */
// public RxModelAdapter getRxModelAdapter() {
// if (mModelAdapter == null) {
// mModelAdapter = RxDbFlow.getModelAdapter(getClass());
// }
// return mModelAdapter;
// }
// }
| import android.support.annotation.IntDef;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.structure.Model;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx1.structure.RxBaseModel;
import rx.Observable;
import rx.Subscriber; | this(FlowManager.getDatabaseForTable(clazz).getWritableDatabase());
}
/**
* Sets a default operation, this is useful when adding a list of models to the builder.
*
* @param modelOperation The model operation to use when no model operation is specified
* @return An instance of the current builder.
*/
public Builder setDefaultOperation(@ModelOperation int modelOperation) {
mDefaultOperation = modelOperation;
return this;
}
/**
* Adds a model and it's associated operation to be performed within the transaction
* block
*
* @param model The model to perform the transaction on
* @param modelOperation The operation to be performed.
* @return An instance of the current builder.
*/
public Builder addModel(Object model, @ModelOperation int modelOperation) {
if (mModelList.size() == 0) {
mCanBatchTransaction = true;
mMustUseAdapters = false;
} else {
if (!mMustUseAdapters) { | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/structure/RxBaseModel.java
// @SuppressWarnings("unchecked")
// public class RxBaseModel<M extends RxBaseModel> extends BaseModel implements RxModifications<M> {
//
// private RxModelAdapter<? extends RxBaseModel> mModelAdapter;
//
// /**
// * Returns an observable for saving the object in the database
// * @return An observable
// */
// public Observable<M> saveAsObservable(){
// return getRxModelAdapter().saveAsObservable(this);
// }
//
// /**
// * Returns an observable for saving the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// @SuppressWarnings("unchecked")
// public Observable<M> saveAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().saveAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable for inserting the object in the database
// * @return An observable
// */
// public Observable<M> insertAsObservable(){
// return getRxModelAdapter().insertAsObservable(this);
// }
//
// /**
// * Returns an observable for inserting the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> insertAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().insertAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable for deleting the object from the database
// * @return An observable
// */
// public Observable<M> deleteAsObservable(){
// return getRxModelAdapter().deleteAsObservable(this);
// }
//
// /**
// * Returns an observable for deleting the object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> deleteAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().deleteAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable for update the object in the database
// * @return An observable
// */
// public Observable<M> updateAsObservable(){
// return getRxModelAdapter().updateAsObservable(this);
// }
//
// /**
// * Returns an observable for update in object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> updateAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().updateAsObservable(this, databaseWrapper);
// }
//
// /**
// * Returns an observable which will refresh the model's data based on the primary key when subscribed.
// * @return An observable
// */
// public Observable<M> loadAsObservable(){
// return getRxModelAdapter().loadAsObservable(this);
// }
//
// /**
// * Returns an observable which will refresh the model's data based on the primary key when subscribed.
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An observable
// */
// public Observable<M> loadAsObservable(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().loadAsObservable(this, databaseWrapper);
// }
//
// /**
// * @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
// * may throw a {@link InvalidDBConfiguration} for this call if this class
// * is not associated with a table, so be careful when using this method.
// */
// public RxModelAdapter getRxModelAdapter() {
// if (mModelAdapter == null) {
// mModelAdapter = RxDbFlow.getModelAdapter(getClass());
// }
// return mModelAdapter;
// }
// }
// Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/transaction/RxModelOperationTransaction.java
import android.support.annotation.IntDef;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.structure.Model;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx1.structure.RxBaseModel;
import rx.Observable;
import rx.Subscriber;
this(FlowManager.getDatabaseForTable(clazz).getWritableDatabase());
}
/**
* Sets a default operation, this is useful when adding a list of models to the builder.
*
* @param modelOperation The model operation to use when no model operation is specified
* @return An instance of the current builder.
*/
public Builder setDefaultOperation(@ModelOperation int modelOperation) {
mDefaultOperation = modelOperation;
return this;
}
/**
* Adds a model and it's associated operation to be performed within the transaction
* block
*
* @param model The model to perform the transaction on
* @param modelOperation The operation to be performed.
* @return An instance of the current builder.
*/
public Builder addModel(Object model, @ModelOperation int modelOperation) {
if (mModelList.size() == 0) {
mCanBatchTransaction = true;
mMustUseAdapters = false;
} else {
if (!mMustUseAdapters) { | mMustUseAdapters = !(model instanceof RxBaseModel); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/transaction/DbTransaction.java
// public class DbTransaction {
//
// private final Class mClass;
// private static Map<String, List<OnDbTransactionListener>> sTransactionListenerMap = new HashMap<>();
//
// public DbTransaction(Class tableClass){
// mClass = tableClass;
// }
//
// public static void registerDbTransactionListener(Class tableClass, OnDbTransactionListener listener){
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).add(listener);
// } else {
// List<OnDbTransactionListener> listenerList = new ArrayList<>();
// listenerList.add(listener);
// sTransactionListenerMap.put(databaseName, listenerList);
// }
// }
//
// public static void unregisterDbTransactionListener(Class tableClass, OnDbTransactionListener listener) {
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).remove(databaseName);
// if(sTransactionListenerMap.get(databaseName).size() == 0){
// sTransactionListenerMap.remove(databaseName);
// }
// } else {
// Log.e("DbTransaction", "Attempting to unregister a listener which was not registered");
//
// }
// }
//
// public void beginTransaction(){
// FlowManager.getDatabase(mClass).getWritableDatabase().beginTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionStarted();
// }
// }
// }
//
// public void setTransactionSuccessful(){
// FlowManager.getDatabase(mClass).getWritableDatabase().setTransactionSuccessful();
// }
//
// public void endTransaction() {
// FlowManager.getDatabase(mClass).getWritableDatabase().endTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionEnded();
// }
// }
// }
//
// public interface OnDbTransactionListener {
// void onTransactionStarted();
// void onTransactionEnded();
// }
// }
| import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.runtime.FlowContentObserver;
import com.raizlabs.android.dbflow.structure.BaseModel;
import java.util.Arrays;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.transaction.DbTransaction;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.fuseable.HasUpstreamObservableSource; | package au.com.roadhouse.rxdbflow.rx2.sql.observables.operators;
public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
private final ObservableSource<T> mSource;
private final Class[] mSubscribedClasses; | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/transaction/DbTransaction.java
// public class DbTransaction {
//
// private final Class mClass;
// private static Map<String, List<OnDbTransactionListener>> sTransactionListenerMap = new HashMap<>();
//
// public DbTransaction(Class tableClass){
// mClass = tableClass;
// }
//
// public static void registerDbTransactionListener(Class tableClass, OnDbTransactionListener listener){
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).add(listener);
// } else {
// List<OnDbTransactionListener> listenerList = new ArrayList<>();
// listenerList.add(listener);
// sTransactionListenerMap.put(databaseName, listenerList);
// }
// }
//
// public static void unregisterDbTransactionListener(Class tableClass, OnDbTransactionListener listener) {
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).remove(databaseName);
// if(sTransactionListenerMap.get(databaseName).size() == 0){
// sTransactionListenerMap.remove(databaseName);
// }
// } else {
// Log.e("DbTransaction", "Attempting to unregister a listener which was not registered");
//
// }
// }
//
// public void beginTransaction(){
// FlowManager.getDatabase(mClass).getWritableDatabase().beginTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionStarted();
// }
// }
// }
//
// public void setTransactionSuccessful(){
// FlowManager.getDatabase(mClass).getWritableDatabase().setTransactionSuccessful();
// }
//
// public void endTransaction() {
// FlowManager.getDatabase(mClass).getWritableDatabase().endTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionEnded();
// }
// }
// }
//
// public interface OnDbTransactionListener {
// void onTransactionStarted();
// void onTransactionEnded();
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.runtime.FlowContentObserver;
import com.raizlabs.android.dbflow.structure.BaseModel;
import java.util.Arrays;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.transaction.DbTransaction;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.fuseable.HasUpstreamObservableSource;
package au.com.roadhouse.rxdbflow.rx2.sql.observables.operators;
public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
private final ObservableSource<T> mSource;
private final Class[] mSubscribedClasses; | private final ValueAction<T> mRestartAction; |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/transaction/DbTransaction.java
// public class DbTransaction {
//
// private final Class mClass;
// private static Map<String, List<OnDbTransactionListener>> sTransactionListenerMap = new HashMap<>();
//
// public DbTransaction(Class tableClass){
// mClass = tableClass;
// }
//
// public static void registerDbTransactionListener(Class tableClass, OnDbTransactionListener listener){
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).add(listener);
// } else {
// List<OnDbTransactionListener> listenerList = new ArrayList<>();
// listenerList.add(listener);
// sTransactionListenerMap.put(databaseName, listenerList);
// }
// }
//
// public static void unregisterDbTransactionListener(Class tableClass, OnDbTransactionListener listener) {
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).remove(databaseName);
// if(sTransactionListenerMap.get(databaseName).size() == 0){
// sTransactionListenerMap.remove(databaseName);
// }
// } else {
// Log.e("DbTransaction", "Attempting to unregister a listener which was not registered");
//
// }
// }
//
// public void beginTransaction(){
// FlowManager.getDatabase(mClass).getWritableDatabase().beginTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionStarted();
// }
// }
// }
//
// public void setTransactionSuccessful(){
// FlowManager.getDatabase(mClass).getWritableDatabase().setTransactionSuccessful();
// }
//
// public void endTransaction() {
// FlowManager.getDatabase(mClass).getWritableDatabase().endTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionEnded();
// }
// }
// }
//
// public interface OnDbTransactionListener {
// void onTransactionStarted();
// void onTransactionEnded();
// }
// }
| import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.runtime.FlowContentObserver;
import com.raizlabs.android.dbflow.structure.BaseModel;
import java.util.Arrays;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.transaction.DbTransaction;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.fuseable.HasUpstreamObservableSource; | package au.com.roadhouse.rxdbflow.rx2.sql.observables.operators;
public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
private final ObservableSource<T> mSource;
private final Class[] mSubscribedClasses;
private final ValueAction<T> mRestartAction;
public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
mSource = source;
mSubscribedClasses = subscribedClasses;
mRestartAction = restartAction;
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
mSource.subscribe(disposable);
}
@Override
public ObservableSource<T> source() {
return mSource;
}
| // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/transaction/DbTransaction.java
// public class DbTransaction {
//
// private final Class mClass;
// private static Map<String, List<OnDbTransactionListener>> sTransactionListenerMap = new HashMap<>();
//
// public DbTransaction(Class tableClass){
// mClass = tableClass;
// }
//
// public static void registerDbTransactionListener(Class tableClass, OnDbTransactionListener listener){
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).add(listener);
// } else {
// List<OnDbTransactionListener> listenerList = new ArrayList<>();
// listenerList.add(listener);
// sTransactionListenerMap.put(databaseName, listenerList);
// }
// }
//
// public static void unregisterDbTransactionListener(Class tableClass, OnDbTransactionListener listener) {
// String databaseName = FlowManager.getDatabaseForTable(tableClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// sTransactionListenerMap.get(databaseName).remove(databaseName);
// if(sTransactionListenerMap.get(databaseName).size() == 0){
// sTransactionListenerMap.remove(databaseName);
// }
// } else {
// Log.e("DbTransaction", "Attempting to unregister a listener which was not registered");
//
// }
// }
//
// public void beginTransaction(){
// FlowManager.getDatabase(mClass).getWritableDatabase().beginTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionStarted();
// }
// }
// }
//
// public void setTransactionSuccessful(){
// FlowManager.getDatabase(mClass).getWritableDatabase().setTransactionSuccessful();
// }
//
// public void endTransaction() {
// FlowManager.getDatabase(mClass).getWritableDatabase().endTransaction();
// String databaseName = FlowManager.getDatabaseForTable(mClass).getDatabaseName();
// if(sTransactionListenerMap.containsKey(databaseName)){
// List<OnDbTransactionListener> listenerList = sTransactionListenerMap.get(databaseName);
// for(int i = 0; i < listenerList.size(); i++){
// listenerList.get(i).onTransactionEnded();
// }
// }
// }
//
// public interface OnDbTransactionListener {
// void onTransactionStarted();
// void onTransactionEnded();
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.runtime.FlowContentObserver;
import com.raizlabs.android.dbflow.structure.BaseModel;
import java.util.Arrays;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.transaction.DbTransaction;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.fuseable.HasUpstreamObservableSource;
package au.com.roadhouse.rxdbflow.rx2.sql.observables.operators;
public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
private final ObservableSource<T> mSource;
private final Class[] mSubscribedClasses;
private final ValueAction<T> mRestartAction;
public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
mSource = source;
mSubscribedClasses = subscribedClasses;
mRestartAction = restartAction;
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
mSource.subscribe(disposable);
}
@Override
public ObservableSource<T> source() {
return mSource;
}
| private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener { |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/QueriableObservable.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | package au.com.roadhouse.rxdbflow.rx2.sql.language;
public interface QueriableObservable {
/**
* Creates an Single that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in unexpected return values
*
* @return An Single that emits a long result
*/
DBFlowSingle<Long> asCountSingle();
/**
* Creates an Single that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in an unexpected emitted
* value
*
* @param databaseWrapper The database wrapper to use for the query
* @return An Single that emits a long result
*/
DBFlowSingle<Long> asCountSingle(DatabaseWrapper databaseWrapper);
/**
* Creates an Single that executes a SQL statement. This is usually used with CRUD statements as
* it only emits a Void value
*
* @return An Single that executes a SQL statement
*/ | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/QueriableObservable.java
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
package au.com.roadhouse.rxdbflow.rx2.sql.language;
public interface QueriableObservable {
/**
* Creates an Single that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in unexpected return values
*
* @return An Single that emits a long result
*/
DBFlowSingle<Long> asCountSingle();
/**
* Creates an Single that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in an unexpected emitted
* value
*
* @param databaseWrapper The database wrapper to use for the query
* @return An Single that emits a long result
*/
DBFlowSingle<Long> asCountSingle(DatabaseWrapper databaseWrapper);
/**
* Creates an Single that executes a SQL statement. This is usually used with CRUD statements as
* it only emits a Void value
*
* @return An Single that executes a SQL statement
*/ | DBFlowExecuteCompletable asExecuteCompletable(); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/ModelQueriableObservable.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowMaybe.java
// public abstract class DBFlowMaybe<T> extends Maybe<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import com.raizlabs.android.dbflow.list.FlowCursorList;
import com.raizlabs.android.dbflow.list.FlowQueryList;
import com.raizlabs.android.dbflow.sql.language.CursorResult;
import com.raizlabs.android.dbflow.structure.BaseQueryModel;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowMaybe;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | package au.com.roadhouse.rxdbflow.rx2.sql.language;
public interface ModelQueriableObservable<TModel> extends QueriableObservable {
/**
* Creates an Single that emits a single model from a query. This will be the first record
* returned by the query.
* @return An Single that emits a single model
*/
DBFlowSingle<TModel> asSingle();
/**
* Creates an Maybe that emits a single model or null from a query. This will be the first record
* returned by the query or null if the query was empty.
* @return An Single that emits a single model
*/ | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowMaybe.java
// public abstract class DBFlowMaybe<T> extends Maybe<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/ModelQueriableObservable.java
import com.raizlabs.android.dbflow.list.FlowCursorList;
import com.raizlabs.android.dbflow.list.FlowQueryList;
import com.raizlabs.android.dbflow.sql.language.CursorResult;
import com.raizlabs.android.dbflow.structure.BaseQueryModel;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowMaybe;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
package au.com.roadhouse.rxdbflow.rx2.sql.language;
public interface ModelQueriableObservable<TModel> extends QueriableObservable {
/**
* Creates an Single that emits a single model from a query. This will be the first record
* returned by the query.
* @return An Single that emits a single model
*/
DBFlowSingle<TModel> asSingle();
/**
* Creates an Maybe that emits a single model or null from a query. This will be the first record
* returned by the query or null if the query was empty.
* @return An Single that emits a single model
*/ | DBFlowMaybe<TModel> asMaybe(); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/structure/RxBaseModel.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/RxDbFlow.java
// public class RxDbFlow {
//
// public static <TModel> RxModelAdapter<TModel> getModelAdapter(Class<TModel> modelClass) {
// return new RxModelAdapter<>(FlowManager.getModelAdapter(modelClass));
// }
//
// }
| import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.InvalidDBConfiguration;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.RxDbFlow;
import io.reactivex.Single; | * @return An Single
*/
public Single<M> updateAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().updateAsSingle(this, databaseWrapper);
}
/**
* Returns an Single which will refresh the model's data based on the primary key when subscribed.
* @return An Single
*/
public Single<M> loadAsSingle(){
return getRxModelAdapter().loadAsSingle(this);
}
/**
* Returns an Single which will refresh the model's data based on the primary key when subscribed.
* @param databaseWrapper The database wrapper for the database holding the table
* @return An Single
*/
public Single<M> loadAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().loadAsSingle(this, databaseWrapper);
}
/**
* @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
* may throw a {@link InvalidDBConfiguration} for this call if this class
* is not associated with a table, so be careful when using this method.
*/
public RxModelAdapter getRxModelAdapter() {
if (mModelAdapter == null) { | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/RxDbFlow.java
// public class RxDbFlow {
//
// public static <TModel> RxModelAdapter<TModel> getModelAdapter(Class<TModel> modelClass) {
// return new RxModelAdapter<>(FlowManager.getModelAdapter(modelClass));
// }
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/structure/RxBaseModel.java
import android.support.annotation.Nullable;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.InvalidDBConfiguration;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.RxDbFlow;
import io.reactivex.Single;
* @return An Single
*/
public Single<M> updateAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().updateAsSingle(this, databaseWrapper);
}
/**
* Returns an Single which will refresh the model's data based on the primary key when subscribed.
* @return An Single
*/
public Single<M> loadAsSingle(){
return getRxModelAdapter().loadAsSingle(this);
}
/**
* Returns an Single which will refresh the model's data based on the primary key when subscribed.
* @param databaseWrapper The database wrapper for the database holding the table
* @return An Single
*/
public Single<M> loadAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
return getRxModelAdapter().loadAsSingle(this, databaseWrapper);
}
/**
* @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
* may throw a {@link InvalidDBConfiguration} for this call if this class
* is not associated with a table, so be careful when using this method.
*/
public RxModelAdapter getRxModelAdapter() {
if (mModelAdapter == null) { | mModelAdapter = RxDbFlow.getModelAdapter(getClass()); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/transaction/RxModelOperationTransaction.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/NullValue.java
// public class NullValue {
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/structure/RxBaseModel.java
// @SuppressWarnings("unchecked")
// public class RxBaseModel<M extends RxBaseModel> extends BaseModel implements RxModifications<M> {
//
// private transient RxModelAdapter<? extends RxBaseModel> mModelAdapter;
//
// /**
// * Returns an Single for saving the object in the database
// * @return An Single
// */
// public Single<M> saveAsSingle(){
// return getRxModelAdapter().saveAsSingle(this);
// }
//
// /**
// * Returns an Single for saving the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// @SuppressWarnings("unchecked")
// public Single<M> saveAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().saveAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single for inserting the object in the database
// * @return An Single
// */
// public Single<M> insertAsSingle(){
// return getRxModelAdapter().insertAsSingle(this);
// }
//
// /**
// * Returns an Single for inserting the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> insertAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().insertAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single for deleting the object from the database
// * @return An Single
// */
// public Single<M> deleteAsSingle(){
// return getRxModelAdapter().deleteAsSingle(this);
// }
//
// /**
// * Returns an Single for deleting the object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> deleteAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().deleteAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single for update the object in the database
// * @return An Single
// */
// public Single<M> updateAsSingle(){
// return getRxModelAdapter().updateAsSingle(this);
// }
//
// /**
// * Returns an Single for update in object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> updateAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().updateAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single which will refresh the model's data based on the primary key when subscribed.
// * @return An Single
// */
// public Single<M> loadAsSingle(){
// return getRxModelAdapter().loadAsSingle(this);
// }
//
// /**
// * Returns an Single which will refresh the model's data based on the primary key when subscribed.
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> loadAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().loadAsSingle(this, databaseWrapper);
// }
//
// /**
// * @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
// * may throw a {@link InvalidDBConfiguration} for this call if this class
// * is not associated with a table, so be careful when using this method.
// */
// public RxModelAdapter getRxModelAdapter() {
// if (mModelAdapter == null) {
// mModelAdapter = RxDbFlow.getModelAdapter(getClass());
// }
// return mModelAdapter;
// }
// }
| import android.support.annotation.IntDef;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.structure.Model;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.language.NullValue;
import au.com.roadhouse.rxdbflow.rx2.structure.RxBaseModel;
import io.reactivex.Observable;
import io.reactivex.Observer; | this(FlowManager.getDatabaseForTable(clazz).getWritableDatabase());
}
/**
* Sets a default operation, this is useful when adding a list of models to the builder.
*
* @param modelOperation The model operation to use when no model operation is specified
* @return An instance of the current builder.
*/
public Builder setDefaultOperation(@ModelOperation int modelOperation) {
mDefaultOperation = modelOperation;
return this;
}
/**
* Adds a model and it's associated operation to be performed within the transaction
* block
*
* @param model The model to perform the transaction on
* @param modelOperation The operation to be performed.
* @return An instance of the current builder.
*/
public Builder addModel(Object model, @ModelOperation int modelOperation) {
if (mModelList.size() == 0) {
mCanBatchTransaction = true;
mMustUseAdapters = false;
} else {
if (!mMustUseAdapters) { | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/NullValue.java
// public class NullValue {
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/structure/RxBaseModel.java
// @SuppressWarnings("unchecked")
// public class RxBaseModel<M extends RxBaseModel> extends BaseModel implements RxModifications<M> {
//
// private transient RxModelAdapter<? extends RxBaseModel> mModelAdapter;
//
// /**
// * Returns an Single for saving the object in the database
// * @return An Single
// */
// public Single<M> saveAsSingle(){
// return getRxModelAdapter().saveAsSingle(this);
// }
//
// /**
// * Returns an Single for saving the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// @SuppressWarnings("unchecked")
// public Single<M> saveAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().saveAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single for inserting the object in the database
// * @return An Single
// */
// public Single<M> insertAsSingle(){
// return getRxModelAdapter().insertAsSingle(this);
// }
//
// /**
// * Returns an Single for inserting the object in the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> insertAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().insertAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single for deleting the object from the database
// * @return An Single
// */
// public Single<M> deleteAsSingle(){
// return getRxModelAdapter().deleteAsSingle(this);
// }
//
// /**
// * Returns an Single for deleting the object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> deleteAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().deleteAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single for update the object in the database
// * @return An Single
// */
// public Single<M> updateAsSingle(){
// return getRxModelAdapter().updateAsSingle(this);
// }
//
// /**
// * Returns an Single for update in object from the database
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> updateAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().updateAsSingle(this, databaseWrapper);
// }
//
// /**
// * Returns an Single which will refresh the model's data based on the primary key when subscribed.
// * @return An Single
// */
// public Single<M> loadAsSingle(){
// return getRxModelAdapter().loadAsSingle(this);
// }
//
// /**
// * Returns an Single which will refresh the model's data based on the primary key when subscribed.
// * @param databaseWrapper The database wrapper for the database holding the table
// * @return An Single
// */
// public Single<M> loadAsSingle(@Nullable final DatabaseWrapper databaseWrapper){
// return getRxModelAdapter().loadAsSingle(this, databaseWrapper);
// }
//
// /**
// * @return The associated {@link RxModelAdapter}. The {@link RxDbFlow}
// * may throw a {@link InvalidDBConfiguration} for this call if this class
// * is not associated with a table, so be careful when using this method.
// */
// public RxModelAdapter getRxModelAdapter() {
// if (mModelAdapter == null) {
// mModelAdapter = RxDbFlow.getModelAdapter(getClass());
// }
// return mModelAdapter;
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/transaction/RxModelOperationTransaction.java
import android.support.annotation.IntDef;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.structure.Model;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import au.com.roadhouse.rxdbflow.rx2.sql.language.NullValue;
import au.com.roadhouse.rxdbflow.rx2.structure.RxBaseModel;
import io.reactivex.Observable;
import io.reactivex.Observer;
this(FlowManager.getDatabaseForTable(clazz).getWritableDatabase());
}
/**
* Sets a default operation, this is useful when adding a list of models to the builder.
*
* @param modelOperation The model operation to use when no model operation is specified
* @return An instance of the current builder.
*/
public Builder setDefaultOperation(@ModelOperation int modelOperation) {
mDefaultOperation = modelOperation;
return this;
}
/**
* Adds a model and it's associated operation to be performed within the transaction
* block
*
* @param model The model to perform the transaction on
* @param modelOperation The operation to be performed.
* @return An instance of the current builder.
*/
public Builder addModel(Object model, @ModelOperation int modelOperation) {
if (mModelList.size() == 0) {
mCanBatchTransaction = true;
mMustUseAdapters = false;
} else {
if (!mMustUseAdapters) { | mMustUseAdapters = !(model instanceof RxBaseModel); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowMaybe.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
// public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
// private final ObservableSource<T> mSource;
// private final Class[] mSubscribedClasses;
// private final ValueAction<T> mRestartAction;
//
// public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
// mSource = source;
// mSubscribedClasses = subscribedClasses;
// mRestartAction = restartAction;
// }
//
// @Override
// protected void subscribeActual(Observer<? super T> observer) {
// final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
// mSource.subscribe(disposable);
// }
//
// @Override
// public ObservableSource<T> source() {
// return mSource;
// }
//
// private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener {
// private final Observer<? super T> mActual;
// private final ValueAction<T> mRestartAction;
// private List<Class> mSubscribedClasses;
// private boolean mIsDisposed = false;
// private FlowContentObserver mFlowContentObserver = new FlowContentObserver();
// private boolean mIsInTransaction = false;
// private boolean mHasPendingChange = false;
//
//
// public RestartOnChangeObserver(Observer<? super T> observer, Class[] subscribedClasses, ValueAction<T> action) {
// mActual = observer;
// mSubscribedClasses = Arrays.asList(subscribedClasses);
// mRestartAction = action;
// DbTransaction.registerDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
//
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// //We capture any completes here to avoid disposing
// }
//
// @Override
// public void onNext(T o) {
// mActual.onNext(o);
//
// for (int i = 0; i < mSubscribedClasses.size(); i++) {
// mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i));
// }
//
// mFlowContentObserver.addOnTableChangedListener(
// new FlowContentObserver.OnTableChangedListener() {
// @Override
// public void onTableChanged(@Nullable Class<?> tableChanged, BaseModel.Action action) {
// if(isDisposed()){
// return;
// }
//
// if (!mIsInTransaction) {
// mActual.onNext(mRestartAction.run());
// } else {
// mHasPendingChange = true;
// }
// }
// });
// }
//
// @Override
// public void dispose() {
// mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext());
// mIsDisposed = true;
// mActual.onComplete();
// DbTransaction.unregisterDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
//
// @Override
// public void onTransactionStarted() {
// mIsInTransaction = true;
// }
//
// @Override
// public void onTransactionEnded() {
// mIsInTransaction = false;
// if(mHasPendingChange && !isDisposed()){
// mHasPendingChange = false;
// mActual.onNext(mRestartAction.run());
// }
// }
// }
// }
| import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.DBFlowRestartOnChange;
import io.reactivex.Maybe;
import io.reactivex.Observable; | package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* A base observable which provides DBFlow specific operators
* @param <T> The observable result type
*/
public abstract class DBFlowMaybe<T> extends Maybe<T> implements ValueAction<T> {
/**
* Observes changes on the current table, restarting the query on change and emits the new count
* to any subscribers
* @return An observable which observes any changes in the current table
*/
public final Observable<T> restartOnChange(){ | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
// public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
// private final ObservableSource<T> mSource;
// private final Class[] mSubscribedClasses;
// private final ValueAction<T> mRestartAction;
//
// public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
// mSource = source;
// mSubscribedClasses = subscribedClasses;
// mRestartAction = restartAction;
// }
//
// @Override
// protected void subscribeActual(Observer<? super T> observer) {
// final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
// mSource.subscribe(disposable);
// }
//
// @Override
// public ObservableSource<T> source() {
// return mSource;
// }
//
// private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener {
// private final Observer<? super T> mActual;
// private final ValueAction<T> mRestartAction;
// private List<Class> mSubscribedClasses;
// private boolean mIsDisposed = false;
// private FlowContentObserver mFlowContentObserver = new FlowContentObserver();
// private boolean mIsInTransaction = false;
// private boolean mHasPendingChange = false;
//
//
// public RestartOnChangeObserver(Observer<? super T> observer, Class[] subscribedClasses, ValueAction<T> action) {
// mActual = observer;
// mSubscribedClasses = Arrays.asList(subscribedClasses);
// mRestartAction = action;
// DbTransaction.registerDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
//
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// //We capture any completes here to avoid disposing
// }
//
// @Override
// public void onNext(T o) {
// mActual.onNext(o);
//
// for (int i = 0; i < mSubscribedClasses.size(); i++) {
// mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i));
// }
//
// mFlowContentObserver.addOnTableChangedListener(
// new FlowContentObserver.OnTableChangedListener() {
// @Override
// public void onTableChanged(@Nullable Class<?> tableChanged, BaseModel.Action action) {
// if(isDisposed()){
// return;
// }
//
// if (!mIsInTransaction) {
// mActual.onNext(mRestartAction.run());
// } else {
// mHasPendingChange = true;
// }
// }
// });
// }
//
// @Override
// public void dispose() {
// mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext());
// mIsDisposed = true;
// mActual.onComplete();
// DbTransaction.unregisterDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
//
// @Override
// public void onTransactionStarted() {
// mIsInTransaction = true;
// }
//
// @Override
// public void onTransactionEnded() {
// mIsInTransaction = false;
// if(mHasPendingChange && !isDisposed()){
// mHasPendingChange = false;
// mActual.onNext(mRestartAction.run());
// }
// }
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowMaybe.java
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.DBFlowRestartOnChange;
import io.reactivex.Maybe;
import io.reactivex.Observable;
package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* A base observable which provides DBFlow specific operators
* @param <T> The observable result type
*/
public abstract class DBFlowMaybe<T> extends Maybe<T> implements ValueAction<T> {
/**
* Observes changes on the current table, restarting the query on change and emits the new count
* to any subscribers
* @return An observable which observes any changes in the current table
*/
public final Observable<T> restartOnChange(){ | return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowObservable.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
// public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
// private final ObservableSource<T> mSource;
// private final Class[] mSubscribedClasses;
// private final ValueAction<T> mRestartAction;
//
// public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
// mSource = source;
// mSubscribedClasses = subscribedClasses;
// mRestartAction = restartAction;
// }
//
// @Override
// protected void subscribeActual(Observer<? super T> observer) {
// final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
// mSource.subscribe(disposable);
// }
//
// @Override
// public ObservableSource<T> source() {
// return mSource;
// }
//
// private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener {
// private final Observer<? super T> mActual;
// private final ValueAction<T> mRestartAction;
// private List<Class> mSubscribedClasses;
// private boolean mIsDisposed = false;
// private FlowContentObserver mFlowContentObserver = new FlowContentObserver();
// private boolean mIsInTransaction = false;
// private boolean mHasPendingChange = false;
//
//
// public RestartOnChangeObserver(Observer<? super T> observer, Class[] subscribedClasses, ValueAction<T> action) {
// mActual = observer;
// mSubscribedClasses = Arrays.asList(subscribedClasses);
// mRestartAction = action;
// DbTransaction.registerDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
//
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// //We capture any completes here to avoid disposing
// }
//
// @Override
// public void onNext(T o) {
// mActual.onNext(o);
//
// for (int i = 0; i < mSubscribedClasses.size(); i++) {
// mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i));
// }
//
// mFlowContentObserver.addOnTableChangedListener(
// new FlowContentObserver.OnTableChangedListener() {
// @Override
// public void onTableChanged(@Nullable Class<?> tableChanged, BaseModel.Action action) {
// if(isDisposed()){
// return;
// }
//
// if (!mIsInTransaction) {
// mActual.onNext(mRestartAction.run());
// } else {
// mHasPendingChange = true;
// }
// }
// });
// }
//
// @Override
// public void dispose() {
// mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext());
// mIsDisposed = true;
// mActual.onComplete();
// DbTransaction.unregisterDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
//
// @Override
// public void onTransactionStarted() {
// mIsInTransaction = true;
// }
//
// @Override
// public void onTransactionEnded() {
// mIsInTransaction = false;
// if(mHasPendingChange && !isDisposed()){
// mHasPendingChange = false;
// mActual.onNext(mRestartAction.run());
// }
// }
// }
// }
| import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.DBFlowRestartOnChange;
import io.reactivex.Observable; | package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* A base observable which provides DBFlow specific operators
* @param <T> The observable result type
*/
public abstract class DBFlowObservable<T> extends Observable<T> implements ValueAction<T>, DisposableOwner{
/**
* Observes changes on the current table, restarting the query on change and emits the new count
* to any subscribers
* @return An observable which observes any changes in the current table
*/
public final Observable<T> restartOnChange(){ | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
// public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
// private final ObservableSource<T> mSource;
// private final Class[] mSubscribedClasses;
// private final ValueAction<T> mRestartAction;
//
// public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
// mSource = source;
// mSubscribedClasses = subscribedClasses;
// mRestartAction = restartAction;
// }
//
// @Override
// protected void subscribeActual(Observer<? super T> observer) {
// final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
// mSource.subscribe(disposable);
// }
//
// @Override
// public ObservableSource<T> source() {
// return mSource;
// }
//
// private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener {
// private final Observer<? super T> mActual;
// private final ValueAction<T> mRestartAction;
// private List<Class> mSubscribedClasses;
// private boolean mIsDisposed = false;
// private FlowContentObserver mFlowContentObserver = new FlowContentObserver();
// private boolean mIsInTransaction = false;
// private boolean mHasPendingChange = false;
//
//
// public RestartOnChangeObserver(Observer<? super T> observer, Class[] subscribedClasses, ValueAction<T> action) {
// mActual = observer;
// mSubscribedClasses = Arrays.asList(subscribedClasses);
// mRestartAction = action;
// DbTransaction.registerDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
//
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// //We capture any completes here to avoid disposing
// }
//
// @Override
// public void onNext(T o) {
// mActual.onNext(o);
//
// for (int i = 0; i < mSubscribedClasses.size(); i++) {
// mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i));
// }
//
// mFlowContentObserver.addOnTableChangedListener(
// new FlowContentObserver.OnTableChangedListener() {
// @Override
// public void onTableChanged(@Nullable Class<?> tableChanged, BaseModel.Action action) {
// if(isDisposed()){
// return;
// }
//
// if (!mIsInTransaction) {
// mActual.onNext(mRestartAction.run());
// } else {
// mHasPendingChange = true;
// }
// }
// });
// }
//
// @Override
// public void dispose() {
// mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext());
// mIsDisposed = true;
// mActual.onComplete();
// DbTransaction.unregisterDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
//
// @Override
// public void onTransactionStarted() {
// mIsInTransaction = true;
// }
//
// @Override
// public void onTransactionEnded() {
// mIsInTransaction = false;
// if(mHasPendingChange && !isDisposed()){
// mHasPendingChange = false;
// mActual.onNext(mRestartAction.run());
// }
// }
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowObservable.java
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.DBFlowRestartOnChange;
import io.reactivex.Observable;
package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* A base observable which provides DBFlow specific operators
* @param <T> The observable result type
*/
public abstract class DBFlowObservable<T> extends Observable<T> implements ValueAction<T>, DisposableOwner{
/**
* Observes changes on the current table, restarting the query on change and emits the new count
* to any subscribers
* @return An observable which observes any changes in the current table
*/
public final Observable<T> restartOnChange(){ | return new DBFlowRestartOnChange<>(this, new Class[]{getPrimaryModelClass()}, this); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/BaseQueriableObservable.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCountSingle.java
// public class DBFlowCountSingle<TModel> extends DBFlowBaseSingle<TModel, Long> {
//
// private final BaseQueriable mBaseModelQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new DBFlowCountSingle. Generally this constructor is not used directly, but used
// * as part of a query statement. {@see au.com.roadhouse.rxdbflow.rx2.sql.language.RxSQLite}
// * @param clazz The class of the table/view the query effects.
// * @param baseModelQueriable The query to run when computing the count
// * @param databaseWrapper The database wrapper that the target table/view belongs too.
// */
// public DBFlowCountSingle(@NonNull Class<TModel> clazz, final BaseQueriable baseModelQueriable,
// @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseModelQueriable = baseModelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// @Override
// public Long run() {
// if(mDatabaseWrapper != null){
// return mBaseModelQueriable.count(mDatabaseWrapper);
// } else {
// return mBaseModelQueriable.count();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCursorSingle.java
// public class DBFlowCursorSingle<TModel> extends DBFlowBaseSingle<TModel, Cursor> {
//
// private final Queriable mQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new observable which runs a query and emits the result as a Cursor
// * @param clazz The table/view model in which the FlowCursorList will contain
// * @param queriable The query to run
// */
// public DBFlowCursorSingle( Class<TModel> clazz, Queriable queriable, DatabaseWrapper databaseWrapper) {
// super(clazz);
// mQueriable = queriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public Cursor run() {
// if(mDatabaseWrapper != null){
// return mQueriable.query(mDatabaseWrapper);
// } else {
// return mQueriable.query();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.BaseQueriable;
import com.raizlabs.android.dbflow.sql.queriable.Queriable;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCountSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCursorSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | package au.com.roadhouse.rxdbflow.rx2.sql.language;
public class BaseQueriableObservable<TModel> implements QueriableObservable {
private BaseQueriable<TModel> mRealQueriable;
public BaseQueriableObservable(BaseQueriable<TModel> queriable) {
mRealQueriable = queriable;
}
/**
* {@inheritDoc}
*/
@Override | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCountSingle.java
// public class DBFlowCountSingle<TModel> extends DBFlowBaseSingle<TModel, Long> {
//
// private final BaseQueriable mBaseModelQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new DBFlowCountSingle. Generally this constructor is not used directly, but used
// * as part of a query statement. {@see au.com.roadhouse.rxdbflow.rx2.sql.language.RxSQLite}
// * @param clazz The class of the table/view the query effects.
// * @param baseModelQueriable The query to run when computing the count
// * @param databaseWrapper The database wrapper that the target table/view belongs too.
// */
// public DBFlowCountSingle(@NonNull Class<TModel> clazz, final BaseQueriable baseModelQueriable,
// @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseModelQueriable = baseModelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// @Override
// public Long run() {
// if(mDatabaseWrapper != null){
// return mBaseModelQueriable.count(mDatabaseWrapper);
// } else {
// return mBaseModelQueriable.count();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCursorSingle.java
// public class DBFlowCursorSingle<TModel> extends DBFlowBaseSingle<TModel, Cursor> {
//
// private final Queriable mQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new observable which runs a query and emits the result as a Cursor
// * @param clazz The table/view model in which the FlowCursorList will contain
// * @param queriable The query to run
// */
// public DBFlowCursorSingle( Class<TModel> clazz, Queriable queriable, DatabaseWrapper databaseWrapper) {
// super(clazz);
// mQueriable = queriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public Cursor run() {
// if(mDatabaseWrapper != null){
// return mQueriable.query(mDatabaseWrapper);
// } else {
// return mQueriable.query();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/BaseQueriableObservable.java
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.BaseQueriable;
import com.raizlabs.android.dbflow.sql.queriable.Queriable;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCountSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCursorSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
package au.com.roadhouse.rxdbflow.rx2.sql.language;
public class BaseQueriableObservable<TModel> implements QueriableObservable {
private BaseQueriable<TModel> mRealQueriable;
public BaseQueriableObservable(BaseQueriable<TModel> queriable) {
mRealQueriable = queriable;
}
/**
* {@inheritDoc}
*/
@Override | public DBFlowSingle<Long> asCountSingle() { |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/BaseQueriableObservable.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCountSingle.java
// public class DBFlowCountSingle<TModel> extends DBFlowBaseSingle<TModel, Long> {
//
// private final BaseQueriable mBaseModelQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new DBFlowCountSingle. Generally this constructor is not used directly, but used
// * as part of a query statement. {@see au.com.roadhouse.rxdbflow.rx2.sql.language.RxSQLite}
// * @param clazz The class of the table/view the query effects.
// * @param baseModelQueriable The query to run when computing the count
// * @param databaseWrapper The database wrapper that the target table/view belongs too.
// */
// public DBFlowCountSingle(@NonNull Class<TModel> clazz, final BaseQueriable baseModelQueriable,
// @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseModelQueriable = baseModelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// @Override
// public Long run() {
// if(mDatabaseWrapper != null){
// return mBaseModelQueriable.count(mDatabaseWrapper);
// } else {
// return mBaseModelQueriable.count();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCursorSingle.java
// public class DBFlowCursorSingle<TModel> extends DBFlowBaseSingle<TModel, Cursor> {
//
// private final Queriable mQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new observable which runs a query and emits the result as a Cursor
// * @param clazz The table/view model in which the FlowCursorList will contain
// * @param queriable The query to run
// */
// public DBFlowCursorSingle( Class<TModel> clazz, Queriable queriable, DatabaseWrapper databaseWrapper) {
// super(clazz);
// mQueriable = queriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public Cursor run() {
// if(mDatabaseWrapper != null){
// return mQueriable.query(mDatabaseWrapper);
// } else {
// return mQueriable.query();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.BaseQueriable;
import com.raizlabs.android.dbflow.sql.queriable.Queriable;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCountSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCursorSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | package au.com.roadhouse.rxdbflow.rx2.sql.language;
public class BaseQueriableObservable<TModel> implements QueriableObservable {
private BaseQueriable<TModel> mRealQueriable;
public BaseQueriableObservable(BaseQueriable<TModel> queriable) {
mRealQueriable = queriable;
}
/**
* {@inheritDoc}
*/
@Override
public DBFlowSingle<Long> asCountSingle() { | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCountSingle.java
// public class DBFlowCountSingle<TModel> extends DBFlowBaseSingle<TModel, Long> {
//
// private final BaseQueriable mBaseModelQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new DBFlowCountSingle. Generally this constructor is not used directly, but used
// * as part of a query statement. {@see au.com.roadhouse.rxdbflow.rx2.sql.language.RxSQLite}
// * @param clazz The class of the table/view the query effects.
// * @param baseModelQueriable The query to run when computing the count
// * @param databaseWrapper The database wrapper that the target table/view belongs too.
// */
// public DBFlowCountSingle(@NonNull Class<TModel> clazz, final BaseQueriable baseModelQueriable,
// @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseModelQueriable = baseModelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// @Override
// public Long run() {
// if(mDatabaseWrapper != null){
// return mBaseModelQueriable.count(mDatabaseWrapper);
// } else {
// return mBaseModelQueriable.count();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowCursorSingle.java
// public class DBFlowCursorSingle<TModel> extends DBFlowBaseSingle<TModel, Cursor> {
//
// private final Queriable mQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new observable which runs a query and emits the result as a Cursor
// * @param clazz The table/view model in which the FlowCursorList will contain
// * @param queriable The query to run
// */
// public DBFlowCursorSingle( Class<TModel> clazz, Queriable queriable, DatabaseWrapper databaseWrapper) {
// super(clazz);
// mQueriable = queriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public Cursor run() {
// if(mDatabaseWrapper != null){
// return mQueriable.query(mDatabaseWrapper);
// } else {
// return mQueriable.query();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowExecuteCompletable.java
// public class DBFlowExecuteCompletable<TModel> extends DBFlowBaseCompletable<TModel> {
//
// private final BaseQueriable mBaseQueriable;
// private final DatabaseWrapper mDatabaseWrapper;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteCompletable(Class<TModel> clazz, BaseQueriable modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(clazz);
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
//
// public Completable notifyOfUpdates(){
// return new NotifyOfUpdate<>(this, mBaseQueriable.getQuery(), getPrimaryModelClass());
// }
//
// @Override
// public void run() {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
// }
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/BaseQueriableObservable.java
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.BaseQueriable;
import com.raizlabs.android.dbflow.sql.queriable.Queriable;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCountSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowCursorSingle;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowExecuteCompletable;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
package au.com.roadhouse.rxdbflow.rx2.sql.language;
public class BaseQueriableObservable<TModel> implements QueriableObservable {
private BaseQueriable<TModel> mRealQueriable;
public BaseQueriableObservable(BaseQueriable<TModel> queriable) {
mRealQueriable = queriable;
}
/**
* {@inheritDoc}
*/
@Override
public DBFlowSingle<Long> asCountSingle() { | return new DBFlowCountSingle(mRealQueriable.getTable(), mRealQueriable, null); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
// public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
// private final ObservableSource<T> mSource;
// private final Class[] mSubscribedClasses;
// private final ValueAction<T> mRestartAction;
//
// public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
// mSource = source;
// mSubscribedClasses = subscribedClasses;
// mRestartAction = restartAction;
// }
//
// @Override
// protected void subscribeActual(Observer<? super T> observer) {
// final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
// mSource.subscribe(disposable);
// }
//
// @Override
// public ObservableSource<T> source() {
// return mSource;
// }
//
// private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener {
// private final Observer<? super T> mActual;
// private final ValueAction<T> mRestartAction;
// private List<Class> mSubscribedClasses;
// private boolean mIsDisposed = false;
// private FlowContentObserver mFlowContentObserver = new FlowContentObserver();
// private boolean mIsInTransaction = false;
// private boolean mHasPendingChange = false;
//
//
// public RestartOnChangeObserver(Observer<? super T> observer, Class[] subscribedClasses, ValueAction<T> action) {
// mActual = observer;
// mSubscribedClasses = Arrays.asList(subscribedClasses);
// mRestartAction = action;
// DbTransaction.registerDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
//
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// //We capture any completes here to avoid disposing
// }
//
// @Override
// public void onNext(T o) {
// mActual.onNext(o);
//
// for (int i = 0; i < mSubscribedClasses.size(); i++) {
// mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i));
// }
//
// mFlowContentObserver.addOnTableChangedListener(
// new FlowContentObserver.OnTableChangedListener() {
// @Override
// public void onTableChanged(@Nullable Class<?> tableChanged, BaseModel.Action action) {
// if(isDisposed()){
// return;
// }
//
// if (!mIsInTransaction) {
// mActual.onNext(mRestartAction.run());
// } else {
// mHasPendingChange = true;
// }
// }
// });
// }
//
// @Override
// public void dispose() {
// mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext());
// mIsDisposed = true;
// mActual.onComplete();
// DbTransaction.unregisterDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
//
// @Override
// public void onTransactionStarted() {
// mIsInTransaction = true;
// }
//
// @Override
// public void onTransactionEnded() {
// mIsInTransaction = false;
// if(mHasPendingChange && !isDisposed()){
// mHasPendingChange = false;
// mActual.onNext(mRestartAction.run());
// }
// }
// }
// }
| import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.DBFlowRestartOnChange;
import io.reactivex.Observable;
import io.reactivex.Single; | package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* A base observable which provides DBFlow specific operators
* @param <T> The observable result type
*/
public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
/**
* Observes changes on the current table, restarting the query on change and emits the new count
* to any subscribers
* @return An observable which observes any changes in the current table
*/
public final Observable<T> restartOnChange(){ | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/functions/ValueAction.java
// public interface ValueAction<T> {
// T run();
// }
//
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/operators/DBFlowRestartOnChange.java
// public class DBFlowRestartOnChange<T> extends Observable<T> implements HasUpstreamObservableSource<T> {
// private final ObservableSource<T> mSource;
// private final Class[] mSubscribedClasses;
// private final ValueAction<T> mRestartAction;
//
// public DBFlowRestartOnChange(Observable<T> source, Class[] subscribedClasses, ValueAction<T> restartAction) {
// mSource = source;
// mSubscribedClasses = subscribedClasses;
// mRestartAction = restartAction;
// }
//
// @Override
// protected void subscribeActual(Observer<? super T> observer) {
// final RestartOnChangeObserver<T> disposable = new RestartOnChangeObserver<T>(observer, mSubscribedClasses, mRestartAction);
// mSource.subscribe(disposable);
// }
//
// @Override
// public ObservableSource<T> source() {
// return mSource;
// }
//
// private class RestartOnChangeObserver<T> implements Observer<T>, Disposable, DbTransaction.OnDbTransactionListener {
// private final Observer<? super T> mActual;
// private final ValueAction<T> mRestartAction;
// private List<Class> mSubscribedClasses;
// private boolean mIsDisposed = false;
// private FlowContentObserver mFlowContentObserver = new FlowContentObserver();
// private boolean mIsInTransaction = false;
// private boolean mHasPendingChange = false;
//
//
// public RestartOnChangeObserver(Observer<? super T> observer, Class[] subscribedClasses, ValueAction<T> action) {
// mActual = observer;
// mSubscribedClasses = Arrays.asList(subscribedClasses);
// mRestartAction = action;
// DbTransaction.registerDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public void onSubscribe(Disposable d) {
// mActual.onSubscribe(this);
//
// }
//
// @Override
// public void onError(Throwable e) {
// mActual.onError(e);
// }
//
// @Override
// public void onComplete() {
// //We capture any completes here to avoid disposing
// }
//
// @Override
// public void onNext(T o) {
// mActual.onNext(o);
//
// for (int i = 0; i < mSubscribedClasses.size(); i++) {
// mFlowContentObserver.registerForContentChanges(FlowManager.getContext(), mSubscribedClasses.get(i));
// }
//
// mFlowContentObserver.addOnTableChangedListener(
// new FlowContentObserver.OnTableChangedListener() {
// @Override
// public void onTableChanged(@Nullable Class<?> tableChanged, BaseModel.Action action) {
// if(isDisposed()){
// return;
// }
//
// if (!mIsInTransaction) {
// mActual.onNext(mRestartAction.run());
// } else {
// mHasPendingChange = true;
// }
// }
// });
// }
//
// @Override
// public void dispose() {
// mFlowContentObserver.unregisterForContentChanges(FlowManager.getContext());
// mIsDisposed = true;
// mActual.onComplete();
// DbTransaction.unregisterDbTransactionListener(mSubscribedClasses.get(0), this);
// }
//
// @Override
// public boolean isDisposed() {
// return mIsDisposed;
// }
//
// @Override
// public void onTransactionStarted() {
// mIsInTransaction = true;
// }
//
// @Override
// public void onTransactionEnded() {
// mIsInTransaction = false;
// if(mHasPendingChange && !isDisposed()){
// mHasPendingChange = false;
// mActual.onNext(mRestartAction.run());
// }
// }
// }
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
import au.com.roadhouse.rxdbflow.rx2.sql.observables.functions.ValueAction;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.operators.DBFlowRestartOnChange;
import io.reactivex.Observable;
import io.reactivex.Single;
package au.com.roadhouse.rxdbflow.rx2.sql.observables;
/**
* A base observable which provides DBFlow specific operators
* @param <T> The observable result type
*/
public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
/**
* Observes changes on the current table, restarting the query on change and emits the new count
* to any subscribers
* @return An observable which observes any changes in the current table
*/
public final Observable<T> restartOnChange(){ | return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this); |
roadhouse-dev/RxDbflow | RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/RxFrom.java | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
| import android.database.Cursor;
import android.support.annotation.NonNull;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.From;
import com.raizlabs.android.dbflow.sql.language.Join;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.sql.language.property.IndexProperty;
import com.raizlabs.android.dbflow.sql.queriable.ModelQueriable;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.Model;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle; | @Override
public RxWhere<TModel> orderBy(OrderBy orderBy) {
return where().orderBy(orderBy);
}
/**
* {@inheritDoc}
*/
@Override
public RxWhere<TModel> limit(int count) {
return where().limit(count);
}
/**
* {@inheritDoc}
*/
@Override
public RxWhere<TModel> offset(int offset) {
return where().offset(offset);
}
/**
* {@inheritDoc}
*/
@Override
public RxWhere<TModel> having(SQLOperator... conditions) {
return this.where().having(conditions);
}
@Override | // Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/observables/DBFlowSingle.java
// public abstract class DBFlowSingle<T> extends Single<T> implements ValueAction<T> {
//
// /**
// * Observes changes on the current table, restarting the query on change and emits the new count
// * to any subscribers
// * @return An observable which observes any changes in the current table
// */
// public final Observable<T> restartOnChange(){
// return new DBFlowRestartOnChange<>(this.toObservable(), new Class[]{getPrimaryModelClass()}, this);
// }
//
// /**
// * Observes changes for specific tables, restarting the query on change and emits the new count
// * to any subscribers
// * @param tableToListen The tables to observe for changes
// * @return An observable which observes any changes in the specified tables
// */
// public final Observable<T> restartOnChange(Class... tableToListen){
// return new DBFlowRestartOnChange<>(this.toObservable(), tableToListen, this);
// }
//
// /**
// * Returns the class for the primary table model effected by this query
// * @return The class for the primary table model
// */
// protected abstract Class getPrimaryModelClass();
//
// }
// Path: RxDbFlow-Rx2/src/main/java/au/com/roadhouse/rxdbflow/rx2/sql/language/RxFrom.java
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.From;
import com.raizlabs.android.dbflow.sql.language.Join;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.sql.language.property.IndexProperty;
import com.raizlabs.android.dbflow.sql.queriable.ModelQueriable;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.Model;
import au.com.roadhouse.rxdbflow.rx2.sql.observables.DBFlowSingle;
@Override
public RxWhere<TModel> orderBy(OrderBy orderBy) {
return where().orderBy(orderBy);
}
/**
* {@inheritDoc}
*/
@Override
public RxWhere<TModel> limit(int count) {
return where().limit(count);
}
/**
* {@inheritDoc}
*/
@Override
public RxWhere<TModel> offset(int offset) {
return where().offset(offset);
}
/**
* {@inheritDoc}
*/
@Override
public RxWhere<TModel> having(SQLOperator... conditions) {
return this.where().having(conditions);
}
@Override | public DBFlowSingle<Cursor> asQuerySingle() { |
roadhouse-dev/RxDbflow | RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/language/RxSet.java | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/observables/DBFlowExecuteObservable.java
// public class DBFlowExecuteObservable<TModel> extends Observable<Void> {
//
// private final Class mModelClazz;
// private final BaseQueriable<TModel> mBaseQueriable;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteObservable(Class clazz, BaseQueriable<TModel> modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(new OnDBFlowSubscribe(modelQueriable, databaseWrapper));
// mModelClazz = clazz;
// mBaseQueriable = modelQueriable;
// }
//
// /**
// * Publishes the results to all onchange observers after the statement has been executued.
// * @return An observable which publishes the change to all onchange observers
// */
// public Observable<Void> publishTableUpdates(){
// return lift(new DBFlowNotifyOfUpdate());
// }
//
// private static class OnDBFlowSubscribe implements OnSubscribe<Void> {
//
// private final Queriable mBaseQueriable;;
// private final DatabaseWrapper mDatabaseWrapper;
//
// OnDBFlowSubscribe(Queriable modelQueriable, DatabaseWrapper databaseWrapper){
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public void call(final Subscriber<? super Void> subscriber) {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
//
// subscriber.onNext(null);
// subscriber.onCompleted();
// }
// }
//
// private class DBFlowNotifyOfUpdate implements Operator<Void, Void> {
// @Override
// public Subscriber<? super Void> call(final Subscriber<? super Void> subscriber) {
// return new Subscriber<Void>() {
// @Override
// public void onCompleted() {
//
// }
//
// @Override
// public void onError(Throwable e) {
//
// }
//
// @Override
// public void onNext(Void tModels) {
// subscriber.onNext(tModels);
//
// if(mBaseQueriable.getQuery().toLowerCase().contains("delete")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.DELETE, null);
// } else if(mBaseQueriable.getQuery().toLowerCase().contains("update")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.UPDATE, null);
// }
// }
// };
//
// }
// }
// }
| import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Set;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx1.sql.observables.DBFlowExecuteObservable;
import rx.Observable; |
@Override
public String getQuery() {
return mRealSet.getQuery();
}
@NonNull
@Override
public Class<TModel> getTable() {
return mRealSet.getTable();
}
@NonNull
@Override
public Query getQueryBuilderBase() {
return mRealSet.getQueryBuilderBase();
}
@Override
public Observable<Long> asCountObservable() {
return where().asCountObservable();
}
@Override
public Observable<Long> asCountObservable(DatabaseWrapper databaseWrapper) {
return where().asCountObservable(databaseWrapper);
}
@Override | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/observables/DBFlowExecuteObservable.java
// public class DBFlowExecuteObservable<TModel> extends Observable<Void> {
//
// private final Class mModelClazz;
// private final BaseQueriable<TModel> mBaseQueriable;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteObservable(Class clazz, BaseQueriable<TModel> modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(new OnDBFlowSubscribe(modelQueriable, databaseWrapper));
// mModelClazz = clazz;
// mBaseQueriable = modelQueriable;
// }
//
// /**
// * Publishes the results to all onchange observers after the statement has been executued.
// * @return An observable which publishes the change to all onchange observers
// */
// public Observable<Void> publishTableUpdates(){
// return lift(new DBFlowNotifyOfUpdate());
// }
//
// private static class OnDBFlowSubscribe implements OnSubscribe<Void> {
//
// private final Queriable mBaseQueriable;;
// private final DatabaseWrapper mDatabaseWrapper;
//
// OnDBFlowSubscribe(Queriable modelQueriable, DatabaseWrapper databaseWrapper){
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public void call(final Subscriber<? super Void> subscriber) {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
//
// subscriber.onNext(null);
// subscriber.onCompleted();
// }
// }
//
// private class DBFlowNotifyOfUpdate implements Operator<Void, Void> {
// @Override
// public Subscriber<? super Void> call(final Subscriber<? super Void> subscriber) {
// return new Subscriber<Void>() {
// @Override
// public void onCompleted() {
//
// }
//
// @Override
// public void onError(Throwable e) {
//
// }
//
// @Override
// public void onNext(Void tModels) {
// subscriber.onNext(tModels);
//
// if(mBaseQueriable.getQuery().toLowerCase().contains("delete")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.DELETE, null);
// } else if(mBaseQueriable.getQuery().toLowerCase().contains("update")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.UPDATE, null);
// }
// }
// };
//
// }
// }
// }
// Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/language/RxSet.java
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.raizlabs.android.dbflow.sql.Query;
import com.raizlabs.android.dbflow.sql.language.NameAlias;
import com.raizlabs.android.dbflow.sql.language.OrderBy;
import com.raizlabs.android.dbflow.sql.language.SQLOperator;
import com.raizlabs.android.dbflow.sql.language.Set;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.WhereBase;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx1.sql.observables.DBFlowExecuteObservable;
import rx.Observable;
@Override
public String getQuery() {
return mRealSet.getQuery();
}
@NonNull
@Override
public Class<TModel> getTable() {
return mRealSet.getTable();
}
@NonNull
@Override
public Query getQueryBuilderBase() {
return mRealSet.getQueryBuilderBase();
}
@Override
public Observable<Long> asCountObservable() {
return where().asCountObservable();
}
@Override
public Observable<Long> asCountObservable(DatabaseWrapper databaseWrapper) {
return where().asCountObservable(databaseWrapper);
}
@Override | public DBFlowExecuteObservable asExecuteObservable() { |
roadhouse-dev/RxDbflow | RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/language/QueriableObservable.java | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/observables/DBFlowExecuteObservable.java
// public class DBFlowExecuteObservable<TModel> extends Observable<Void> {
//
// private final Class mModelClazz;
// private final BaseQueriable<TModel> mBaseQueriable;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteObservable(Class clazz, BaseQueriable<TModel> modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(new OnDBFlowSubscribe(modelQueriable, databaseWrapper));
// mModelClazz = clazz;
// mBaseQueriable = modelQueriable;
// }
//
// /**
// * Publishes the results to all onchange observers after the statement has been executued.
// * @return An observable which publishes the change to all onchange observers
// */
// public Observable<Void> publishTableUpdates(){
// return lift(new DBFlowNotifyOfUpdate());
// }
//
// private static class OnDBFlowSubscribe implements OnSubscribe<Void> {
//
// private final Queriable mBaseQueriable;;
// private final DatabaseWrapper mDatabaseWrapper;
//
// OnDBFlowSubscribe(Queriable modelQueriable, DatabaseWrapper databaseWrapper){
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public void call(final Subscriber<? super Void> subscriber) {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
//
// subscriber.onNext(null);
// subscriber.onCompleted();
// }
// }
//
// private class DBFlowNotifyOfUpdate implements Operator<Void, Void> {
// @Override
// public Subscriber<? super Void> call(final Subscriber<? super Void> subscriber) {
// return new Subscriber<Void>() {
// @Override
// public void onCompleted() {
//
// }
//
// @Override
// public void onError(Throwable e) {
//
// }
//
// @Override
// public void onNext(Void tModels) {
// subscriber.onNext(tModels);
//
// if(mBaseQueriable.getQuery().toLowerCase().contains("delete")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.DELETE, null);
// } else if(mBaseQueriable.getQuery().toLowerCase().contains("update")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.UPDATE, null);
// }
// }
// };
//
// }
// }
// }
| import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx1.sql.observables.DBFlowExecuteObservable;
import rx.Observable; | package au.com.roadhouse.rxdbflow.rx1.sql.language;
public interface QueriableObservable {
/**
* Creates an observable that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in unexpected return values
*
* @return An observable that emits a long result
*/
Observable<Long> asCountObservable();
/**
* Creates an observable that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in an unexpected emitted
* value
*
* @param databaseWrapper The database wrapper to use for the query
* @return An observable that emits a long result
*/
Observable<Long> asCountObservable(DatabaseWrapper databaseWrapper);
/**
* Creates an observable that executes a SQL statement. This is usually used with CRUD statements as
* it only emits a Void value
*
* @return An observable that executes a SQL statement
*/ | // Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/observables/DBFlowExecuteObservable.java
// public class DBFlowExecuteObservable<TModel> extends Observable<Void> {
//
// private final Class mModelClazz;
// private final BaseQueriable<TModel> mBaseQueriable;
//
// /**
// * Creates a new Observable which executes a sql statement against a table
// * @param clazz The model class representing the table to execute against
// * @param modelQueriable The query to execute
// * @param databaseWrapper The database in which the target table resides
// */
// public DBFlowExecuteObservable(Class clazz, BaseQueriable<TModel> modelQueriable, @Nullable DatabaseWrapper databaseWrapper) {
// super(new OnDBFlowSubscribe(modelQueriable, databaseWrapper));
// mModelClazz = clazz;
// mBaseQueriable = modelQueriable;
// }
//
// /**
// * Publishes the results to all onchange observers after the statement has been executued.
// * @return An observable which publishes the change to all onchange observers
// */
// public Observable<Void> publishTableUpdates(){
// return lift(new DBFlowNotifyOfUpdate());
// }
//
// private static class OnDBFlowSubscribe implements OnSubscribe<Void> {
//
// private final Queriable mBaseQueriable;;
// private final DatabaseWrapper mDatabaseWrapper;
//
// OnDBFlowSubscribe(Queriable modelQueriable, DatabaseWrapper databaseWrapper){
// mBaseQueriable = modelQueriable;
// mDatabaseWrapper = databaseWrapper;
// }
//
// @Override
// public void call(final Subscriber<? super Void> subscriber) {
// if(mDatabaseWrapper != null) {
// mBaseQueriable.execute(mDatabaseWrapper);
// } else {
// mBaseQueriable.execute();
// }
//
// subscriber.onNext(null);
// subscriber.onCompleted();
// }
// }
//
// private class DBFlowNotifyOfUpdate implements Operator<Void, Void> {
// @Override
// public Subscriber<? super Void> call(final Subscriber<? super Void> subscriber) {
// return new Subscriber<Void>() {
// @Override
// public void onCompleted() {
//
// }
//
// @Override
// public void onError(Throwable e) {
//
// }
//
// @Override
// public void onNext(Void tModels) {
// subscriber.onNext(tModels);
//
// if(mBaseQueriable.getQuery().toLowerCase().contains("delete")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.DELETE, null);
// } else if(mBaseQueriable.getQuery().toLowerCase().contains("update")){
// SqlUtils.notifyModelChanged(mModelClazz, BaseModel.Action.UPDATE, null);
// }
// }
// };
//
// }
// }
// }
// Path: RxDbFlow-Rx1/src/main/java/au/com/roadhouse/rxdbflow/rx1/sql/language/QueriableObservable.java
import android.database.Cursor;
import com.raizlabs.android.dbflow.sql.language.property.IProperty;
import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper;
import au.com.roadhouse.rxdbflow.rx1.sql.observables.DBFlowExecuteObservable;
import rx.Observable;
package au.com.roadhouse.rxdbflow.rx1.sql.language;
public interface QueriableObservable {
/**
* Creates an observable that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in unexpected return values
*
* @return An observable that emits a long result
*/
Observable<Long> asCountObservable();
/**
* Creates an observable that emits a long value. This should be paired with {@link RxSQLite#selectCountOf(IProperty[])}
* or a query that returns a single long/integer value. Calling this on any other query could result in an unexpected emitted
* value
*
* @param databaseWrapper The database wrapper to use for the query
* @return An observable that emits a long result
*/
Observable<Long> asCountObservable(DatabaseWrapper databaseWrapper);
/**
* Creates an observable that executes a SQL statement. This is usually used with CRUD statements as
* it only emits a Void value
*
* @return An observable that executes a SQL statement
*/ | DBFlowExecuteObservable asExecuteObservable(); |
leavjenn/Hews | app/src/main/java/com/leavjenn/hews/data/local/DbOpenHelper.java | // Path: app/src/main/java/com/leavjenn/hews/data/local/table/CommentTable.java
// public class CommentTable {
// public static final String TABLE = "comment";
// public static final String COLUMN_COMMENT_ID = "comment_id";
// public static final String COLUMN_INDEX = "_index";
// public static final String COLUMN_PARENT = "parent";
// public static final String COLUMN_LEVEL = "level";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DELETED = "deleted";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TEXT = "text";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_COMMENT_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_INDEX + " INTEGER NOT NULL, "
// + COLUMN_PARENT + " INTEGER NOT NULL, "
// + COLUMN_LEVEL + " INTEGER, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DELETED + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TEXT + " TEXT"
// + ");";
// }
// }
//
// Path: app/src/main/java/com/leavjenn/hews/data/local/table/PostTable.java
// public class PostTable {
//
// public static final String TABLE = "post";
// public static final String COLUMN_ID = "id";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DESCENDANTS = "descendants";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_SCORE = "score";
// public static final String COLUMN_TEXT = "text";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_URL = "url";
// public static final String COLUMN_PRETTY_URL = "prettyUrl";
// public static final String COLUMN_SUMMARY = "summary";
// public static final String COLUMN_ISBOOKMARKED = "isBookmarked";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DESCENDANTS + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_SCORE + " TEXT, "
// + COLUMN_TEXT + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TITLE + " TEXT, "
// + COLUMN_TYPE + " TEXT, "
// + COLUMN_URL + " TEXT, "
// + COLUMN_PRETTY_URL + " TEXT, "
// + COLUMN_SUMMARY + " TEXT, "
// + COLUMN_ISBOOKMARKED + " INTEGER"
// + ");";
// }
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.leavjenn.hews.data.local.table.CommentTable;
import com.leavjenn.hews.data.local.table.PostTable; | package com.leavjenn.hews.data.local;
public class DbOpenHelper extends SQLiteOpenHelper {
public DbOpenHelper(Context context) {
super(context, "hews_db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) { | // Path: app/src/main/java/com/leavjenn/hews/data/local/table/CommentTable.java
// public class CommentTable {
// public static final String TABLE = "comment";
// public static final String COLUMN_COMMENT_ID = "comment_id";
// public static final String COLUMN_INDEX = "_index";
// public static final String COLUMN_PARENT = "parent";
// public static final String COLUMN_LEVEL = "level";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DELETED = "deleted";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TEXT = "text";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_COMMENT_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_INDEX + " INTEGER NOT NULL, "
// + COLUMN_PARENT + " INTEGER NOT NULL, "
// + COLUMN_LEVEL + " INTEGER, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DELETED + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TEXT + " TEXT"
// + ");";
// }
// }
//
// Path: app/src/main/java/com/leavjenn/hews/data/local/table/PostTable.java
// public class PostTable {
//
// public static final String TABLE = "post";
// public static final String COLUMN_ID = "id";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DESCENDANTS = "descendants";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_SCORE = "score";
// public static final String COLUMN_TEXT = "text";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_URL = "url";
// public static final String COLUMN_PRETTY_URL = "prettyUrl";
// public static final String COLUMN_SUMMARY = "summary";
// public static final String COLUMN_ISBOOKMARKED = "isBookmarked";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DESCENDANTS + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_SCORE + " TEXT, "
// + COLUMN_TEXT + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TITLE + " TEXT, "
// + COLUMN_TYPE + " TEXT, "
// + COLUMN_URL + " TEXT, "
// + COLUMN_PRETTY_URL + " TEXT, "
// + COLUMN_SUMMARY + " TEXT, "
// + COLUMN_ISBOOKMARKED + " INTEGER"
// + ");";
// }
// }
// Path: app/src/main/java/com/leavjenn/hews/data/local/DbOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.leavjenn.hews.data.local.table.CommentTable;
import com.leavjenn.hews.data.local.table.PostTable;
package com.leavjenn.hews.data.local;
public class DbOpenHelper extends SQLiteOpenHelper {
public DbOpenHelper(Context context) {
super(context, "hews_db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) { | db.execSQL(PostTable.getCreateTableQuery()); |
leavjenn/Hews | app/src/main/java/com/leavjenn/hews/data/local/DbOpenHelper.java | // Path: app/src/main/java/com/leavjenn/hews/data/local/table/CommentTable.java
// public class CommentTable {
// public static final String TABLE = "comment";
// public static final String COLUMN_COMMENT_ID = "comment_id";
// public static final String COLUMN_INDEX = "_index";
// public static final String COLUMN_PARENT = "parent";
// public static final String COLUMN_LEVEL = "level";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DELETED = "deleted";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TEXT = "text";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_COMMENT_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_INDEX + " INTEGER NOT NULL, "
// + COLUMN_PARENT + " INTEGER NOT NULL, "
// + COLUMN_LEVEL + " INTEGER, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DELETED + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TEXT + " TEXT"
// + ");";
// }
// }
//
// Path: app/src/main/java/com/leavjenn/hews/data/local/table/PostTable.java
// public class PostTable {
//
// public static final String TABLE = "post";
// public static final String COLUMN_ID = "id";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DESCENDANTS = "descendants";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_SCORE = "score";
// public static final String COLUMN_TEXT = "text";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_URL = "url";
// public static final String COLUMN_PRETTY_URL = "prettyUrl";
// public static final String COLUMN_SUMMARY = "summary";
// public static final String COLUMN_ISBOOKMARKED = "isBookmarked";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DESCENDANTS + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_SCORE + " TEXT, "
// + COLUMN_TEXT + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TITLE + " TEXT, "
// + COLUMN_TYPE + " TEXT, "
// + COLUMN_URL + " TEXT, "
// + COLUMN_PRETTY_URL + " TEXT, "
// + COLUMN_SUMMARY + " TEXT, "
// + COLUMN_ISBOOKMARKED + " INTEGER"
// + ");";
// }
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.leavjenn.hews.data.local.table.CommentTable;
import com.leavjenn.hews.data.local.table.PostTable; | package com.leavjenn.hews.data.local;
public class DbOpenHelper extends SQLiteOpenHelper {
public DbOpenHelper(Context context) {
super(context, "hews_db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(PostTable.getCreateTableQuery()); | // Path: app/src/main/java/com/leavjenn/hews/data/local/table/CommentTable.java
// public class CommentTable {
// public static final String TABLE = "comment";
// public static final String COLUMN_COMMENT_ID = "comment_id";
// public static final String COLUMN_INDEX = "_index";
// public static final String COLUMN_PARENT = "parent";
// public static final String COLUMN_LEVEL = "level";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DELETED = "deleted";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TEXT = "text";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_COMMENT_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_INDEX + " INTEGER NOT NULL, "
// + COLUMN_PARENT + " INTEGER NOT NULL, "
// + COLUMN_LEVEL + " INTEGER, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DELETED + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TEXT + " TEXT"
// + ");";
// }
// }
//
// Path: app/src/main/java/com/leavjenn/hews/data/local/table/PostTable.java
// public class PostTable {
//
// public static final String TABLE = "post";
// public static final String COLUMN_ID = "id";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DESCENDANTS = "descendants";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_SCORE = "score";
// public static final String COLUMN_TEXT = "text";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TITLE = "title";
// public static final String COLUMN_TYPE = "type";
// public static final String COLUMN_URL = "url";
// public static final String COLUMN_PRETTY_URL = "prettyUrl";
// public static final String COLUMN_SUMMARY = "summary";
// public static final String COLUMN_ISBOOKMARKED = "isBookmarked";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DESCENDANTS + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_SCORE + " TEXT, "
// + COLUMN_TEXT + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TITLE + " TEXT, "
// + COLUMN_TYPE + " TEXT, "
// + COLUMN_URL + " TEXT, "
// + COLUMN_PRETTY_URL + " TEXT, "
// + COLUMN_SUMMARY + " TEXT, "
// + COLUMN_ISBOOKMARKED + " INTEGER"
// + ");";
// }
// }
// Path: app/src/main/java/com/leavjenn/hews/data/local/DbOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.leavjenn.hews.data.local.table.CommentTable;
import com.leavjenn.hews.data.local.table.PostTable;
package com.leavjenn.hews.data.local;
public class DbOpenHelper extends SQLiteOpenHelper {
public DbOpenHelper(Context context) {
super(context, "hews_db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(PostTable.getCreateTableQuery()); | db.execSQL(CommentTable.getCreateTableQuery()); |
leavjenn/Hews | app/src/main/java/com/leavjenn/hews/ui/bookmark/BookmarkView.java | // Path: app/src/main/java/com/leavjenn/hews/model/Post.java
// @Parcel
// @StorIOSQLiteType(table = "post")
// public class Post extends HNItem {
//
// @StorIOSQLiteColumn(name = "id", key = true)
// long id;
//
// int index;
//
// @StorIOSQLiteColumn(name = "by")
// String by;
//
// @StorIOSQLiteColumn(name = "descendants")
// long descendants;
//
// // StorIO not support List annotation
// List<Long> kids;
//
// @StorIOSQLiteColumn(name = "score")
// long score;
//
// @StorIOSQLiteColumn(name = "text")
// String text;
//
// @StorIOSQLiteColumn(name = "time")
// long time;
//
// @StorIOSQLiteColumn(name = "title")
// String title;
//
// @StorIOSQLiteColumn(name = "type")
// String type;
//
// @StorIOSQLiteColumn(name = "url")
// String url;
//
// @StorIOSQLiteColumn(name = "prettyUrl")
// String prettyUrl;
//
// @StorIOSQLiteColumn(name = "summary")
// String summary;
//
// @StorIOSQLiteColumn(name = "isBookmarked")
// boolean isBookmarked;
//
// boolean isRead;
//
// public Post() {
// }
//
// public Post(Long id) {
// this.id = id;
// }
//
// public Post(Long id, int index) {
// this.id = id;
// this.index = index;
// }
//
// public int getIndex() {
// return index;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public String getBy() {
// return by;
// }
//
// public void setBy(String by) {
// this.by = by;
// }
//
// public long getDescendants() {
// return descendants;
// }
//
// public void setDescendants(long descendants) {
// this.descendants = descendants;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public List<Long> getKids() {
// return kids;
// }
//
// public void setKids(List<Long> kids) {
// this.kids = kids;
// }
//
// public long getScore() {
// return score;
// }
//
// public void setScore(long score) {
// this.score = score;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getPrettyUrl() {
// return prettyUrl;
// }
//
// public void setPrettyUrl(String prettyUrl) {
// this.prettyUrl = prettyUrl;
// }
//
// public String getSummary() {
// return summary;
// }
//
// public void setSummary(String summary) {
// this.summary = summary;
// }
//
// public boolean isBookmarked() {
// return isBookmarked;
// }
//
// public void setIsBookmarked(boolean isBookmarked) {
// this.isBookmarked = isBookmarked;
// }
//
// public boolean isRead() {
// return isRead;
// }
//
// public void setRead(boolean read) {
// isRead = read;
// }
// }
| import android.support.annotation.StringRes;
import com.leavjenn.hews.model.Post;
import java.util.List; | package com.leavjenn.hews.ui.bookmark;
public interface BookmarkView {
void showSwipeRefresh();
void hideSwipeRefresh();
| // Path: app/src/main/java/com/leavjenn/hews/model/Post.java
// @Parcel
// @StorIOSQLiteType(table = "post")
// public class Post extends HNItem {
//
// @StorIOSQLiteColumn(name = "id", key = true)
// long id;
//
// int index;
//
// @StorIOSQLiteColumn(name = "by")
// String by;
//
// @StorIOSQLiteColumn(name = "descendants")
// long descendants;
//
// // StorIO not support List annotation
// List<Long> kids;
//
// @StorIOSQLiteColumn(name = "score")
// long score;
//
// @StorIOSQLiteColumn(name = "text")
// String text;
//
// @StorIOSQLiteColumn(name = "time")
// long time;
//
// @StorIOSQLiteColumn(name = "title")
// String title;
//
// @StorIOSQLiteColumn(name = "type")
// String type;
//
// @StorIOSQLiteColumn(name = "url")
// String url;
//
// @StorIOSQLiteColumn(name = "prettyUrl")
// String prettyUrl;
//
// @StorIOSQLiteColumn(name = "summary")
// String summary;
//
// @StorIOSQLiteColumn(name = "isBookmarked")
// boolean isBookmarked;
//
// boolean isRead;
//
// public Post() {
// }
//
// public Post(Long id) {
// this.id = id;
// }
//
// public Post(Long id, int index) {
// this.id = id;
// this.index = index;
// }
//
// public int getIndex() {
// return index;
// }
//
// public void setIndex(int index) {
// this.index = index;
// }
//
// public String getBy() {
// return by;
// }
//
// public void setBy(String by) {
// this.by = by;
// }
//
// public long getDescendants() {
// return descendants;
// }
//
// public void setDescendants(long descendants) {
// this.descendants = descendants;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public List<Long> getKids() {
// return kids;
// }
//
// public void setKids(List<Long> kids) {
// this.kids = kids;
// }
//
// public long getScore() {
// return score;
// }
//
// public void setScore(long score) {
// this.score = score;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public String getPrettyUrl() {
// return prettyUrl;
// }
//
// public void setPrettyUrl(String prettyUrl) {
// this.prettyUrl = prettyUrl;
// }
//
// public String getSummary() {
// return summary;
// }
//
// public void setSummary(String summary) {
// this.summary = summary;
// }
//
// public boolean isBookmarked() {
// return isBookmarked;
// }
//
// public void setIsBookmarked(boolean isBookmarked) {
// this.isBookmarked = isBookmarked;
// }
//
// public boolean isRead() {
// return isRead;
// }
//
// public void setRead(boolean read) {
// isRead = read;
// }
// }
// Path: app/src/main/java/com/leavjenn/hews/ui/bookmark/BookmarkView.java
import android.support.annotation.StringRes;
import com.leavjenn.hews.model.Post;
import java.util.List;
package com.leavjenn.hews.ui.bookmark;
public interface BookmarkView {
void showSwipeRefresh();
void hideSwipeRefresh();
| void showPosts(List<Post> postList); |
leavjenn/Hews | app/src/main/java/com/leavjenn/hews/model/Comment.java | // Path: app/src/main/java/com/leavjenn/hews/data/local/table/CommentTable.java
// public class CommentTable {
// public static final String TABLE = "comment";
// public static final String COLUMN_COMMENT_ID = "comment_id";
// public static final String COLUMN_INDEX = "_index";
// public static final String COLUMN_PARENT = "parent";
// public static final String COLUMN_LEVEL = "level";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DELETED = "deleted";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TEXT = "text";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_COMMENT_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_INDEX + " INTEGER NOT NULL, "
// + COLUMN_PARENT + " INTEGER NOT NULL, "
// + COLUMN_LEVEL + " INTEGER, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DELETED + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TEXT + " TEXT"
// + ");";
// }
// }
| import com.google.gson.annotations.SerializedName;
import com.leavjenn.hews.data.local.table.CommentTable;
import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteColumn;
import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteType;
import org.parceler.Parcel;
import java.util.ArrayList; | package com.leavjenn.hews.model;
@Parcel
@StorIOSQLiteType(table = "comment")
public class Comment extends HNItem {
| // Path: app/src/main/java/com/leavjenn/hews/data/local/table/CommentTable.java
// public class CommentTable {
// public static final String TABLE = "comment";
// public static final String COLUMN_COMMENT_ID = "comment_id";
// public static final String COLUMN_INDEX = "_index";
// public static final String COLUMN_PARENT = "parent";
// public static final String COLUMN_LEVEL = "level";
// public static final String COLUMN_BY = "by";
// public static final String COLUMN_DELETED = "deleted";
// public static final String COLUMN_KIDS = "kids";
// public static final String COLUMN_TIME = "time";
// public static final String COLUMN_TEXT = "text";
//
//
// public static String getCreateTableQuery() {
// return "CREATE TABLE " + TABLE + "("
// + COLUMN_COMMENT_ID + " INTEGER NOT NULL PRIMARY KEY, "
// + COLUMN_INDEX + " INTEGER NOT NULL, "
// + COLUMN_PARENT + " INTEGER NOT NULL, "
// + COLUMN_LEVEL + " INTEGER, "
// + COLUMN_BY + " TEXT, "
// + COLUMN_DELETED + " TEXT, "
// + COLUMN_KIDS + " TEXT, "
// + COLUMN_TIME + " TEXT, "
// + COLUMN_TEXT + " TEXT"
// + ");";
// }
// }
// Path: app/src/main/java/com/leavjenn/hews/model/Comment.java
import com.google.gson.annotations.SerializedName;
import com.leavjenn.hews.data.local.table.CommentTable;
import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteColumn;
import com.pushtorefresh.storio.sqlite.annotations.StorIOSQLiteType;
import org.parceler.Parcel;
import java.util.ArrayList;
package com.leavjenn.hews.model;
@Parcel
@StorIOSQLiteType(table = "comment")
public class Comment extends HNItem {
| @StorIOSQLiteColumn(name = CommentTable.COLUMN_COMMENT_ID, key = true) |
leavjenn/Hews | app/src/main/java/com/leavjenn/hews/data/remote/RetrofitHelper.java | // Path: app/src/main/java/com/leavjenn/hews/Constants.java
// public final class Constants {
// public static final String KEY_POST_PARCEL = "post";
// public static final String KEY_IS_BOOKMARKED = "is_bookmarked";
// public static final String YCOMBINATOR_ITEM_URL = "https://news.ycombinator.com/item?id=";
// public static final String TYPE_SEARCH = "search";
// public static final String TYPE_BOOKMARK = "type_bookmark";
// public static final String TYPE_STORY = "type_story";
// public static final String KEY_API_URL = "https://hacker-news.firebaseio.com/v0";
// public static final String KEY_ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/";
// public static final String STORY_TYPE_TOP_PATH = "topstories";
// public static final String STORY_TYPE_NEW_PATH = "newstories";
// public static final String STORY_TYPE_ASK_HN_PATH = "askstories";
// public static final String STORY_TYPE_SHOW_HN_PATH = "showstories";
//
// public static final String SEARCH_BASE_URL = "https://hn.algolia.com/api/v1/";
//
// public final static int NUM_LOADING_ITEMS = 25;
// public final static int NUM_LOADING_ITEMS_SPLIT = 7;
//
// public final static int LOADING_IDLE = 0;
// public final static int LOADING_IN_PROGRESS = 1;
// public final static int LOADING_FINISH = 2;
// public final static int LOADING_ERROR = 3;
// public final static int LOADING_PROMPT_NO_CONTENT = 4;
//
// public static final boolean LOGIN_STATE_IN = true;
// public static final boolean LOGIN_STATE_OUT = false;
//
// public static final int OPERATE_SUCCESS = 0;
// public static final int OPERATE_ERROR_NO_COOKIE = 1;
// public static final int OPERATE_ERROR_COOKIE_EXPIRED = 2;
// public static final int OPERATE_ERROR_HAVE_VOTED = 3;
// public static final int OPERATE_ERROR_NOT_ENOUGH_KARMA = 4;
// public static final int OPERATE_ERROR_UNKNOWN = 64;
//
// public static final int VOTE_UP = 1;
// public static final int VOTE_DOWN = 2;
//
// public static final String FRAGMENT_TAG_COMMENT = "comment_fragment";
// }
| import com.google.gson.GsonBuilder;
import com.leavjenn.hews.Constants;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter; | package com.leavjenn.hews.data.remote;
public class RetrofitHelper {
public HackerNewsService getHackerNewsService() {
RestAdapter restAdapter = new RestAdapter.Builder() | // Path: app/src/main/java/com/leavjenn/hews/Constants.java
// public final class Constants {
// public static final String KEY_POST_PARCEL = "post";
// public static final String KEY_IS_BOOKMARKED = "is_bookmarked";
// public static final String YCOMBINATOR_ITEM_URL = "https://news.ycombinator.com/item?id=";
// public static final String TYPE_SEARCH = "search";
// public static final String TYPE_BOOKMARK = "type_bookmark";
// public static final String TYPE_STORY = "type_story";
// public static final String KEY_API_URL = "https://hacker-news.firebaseio.com/v0";
// public static final String KEY_ITEM_URL = "https://hacker-news.firebaseio.com/v0/item/";
// public static final String STORY_TYPE_TOP_PATH = "topstories";
// public static final String STORY_TYPE_NEW_PATH = "newstories";
// public static final String STORY_TYPE_ASK_HN_PATH = "askstories";
// public static final String STORY_TYPE_SHOW_HN_PATH = "showstories";
//
// public static final String SEARCH_BASE_URL = "https://hn.algolia.com/api/v1/";
//
// public final static int NUM_LOADING_ITEMS = 25;
// public final static int NUM_LOADING_ITEMS_SPLIT = 7;
//
// public final static int LOADING_IDLE = 0;
// public final static int LOADING_IN_PROGRESS = 1;
// public final static int LOADING_FINISH = 2;
// public final static int LOADING_ERROR = 3;
// public final static int LOADING_PROMPT_NO_CONTENT = 4;
//
// public static final boolean LOGIN_STATE_IN = true;
// public static final boolean LOGIN_STATE_OUT = false;
//
// public static final int OPERATE_SUCCESS = 0;
// public static final int OPERATE_ERROR_NO_COOKIE = 1;
// public static final int OPERATE_ERROR_COOKIE_EXPIRED = 2;
// public static final int OPERATE_ERROR_HAVE_VOTED = 3;
// public static final int OPERATE_ERROR_NOT_ENOUGH_KARMA = 4;
// public static final int OPERATE_ERROR_UNKNOWN = 64;
//
// public static final int VOTE_UP = 1;
// public static final int VOTE_DOWN = 2;
//
// public static final String FRAGMENT_TAG_COMMENT = "comment_fragment";
// }
// Path: app/src/main/java/com/leavjenn/hews/data/remote/RetrofitHelper.java
import com.google.gson.GsonBuilder;
import com.leavjenn.hews.Constants;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
package com.leavjenn.hews.data.remote;
public class RetrofitHelper {
public HackerNewsService getHackerNewsService() {
RestAdapter restAdapter = new RestAdapter.Builder() | .setEndpoint(Constants.KEY_API_URL) |
leavjenn/Hews | app/src/main/java/com/leavjenn/hews/ui/widget/CommentOptionDialogFragment.java | // Path: app/src/main/java/com/leavjenn/hews/model/Comment.java
// @Parcel
// @StorIOSQLiteType(table = "comment")
// public class Comment extends HNItem {
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_COMMENT_ID, key = true)
// @SerializedName("id")
// long commentId;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_INDEX)
// int _index;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_BY)
// String by;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_DELETED)
// boolean deleted;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_PARENT)
// long parent;
//
// ArrayList<Long> kids;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_TIME)
// long time;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_TEXT)
// String text;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_LEVEL)
// int level;
//
// //FIXME necessary?
// public String error;
//
// public Comment() {
// }
//
// public Comment(long commentId, String by, long parent, ArrayList<Long> kids, long time, String text) {
// this.commentId = commentId;
// this.by = by;
// this.parent = parent;
// this.kids = kids;
// this.time = time;
// this.text = text;
// }
//
// public int getIndex() {
// return _index;
// }
//
// public void setIndex(int _index) {
// this._index = _index;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getBy() {
// return by;
// }
//
// public void setBy(String by) {
// this.by = by;
// }
//
// public long getCommentId() {
// return commentId;
// }
//
// public void setCommentId(long commentId) {
// this.commentId = commentId;
// }
//
// public void setDeleted(boolean deleted) {
// this.deleted = deleted;
// }
//
// public boolean getDeleted() {
// return deleted;
// }
//
// public long getParent() {
// return parent;
// }
//
// public void setParent(long parent) {
// this.parent = parent;
// }
//
// public ArrayList<Long> getKids() {
// return kids;
// }
//
// public void setKids(ArrayList<Long> kids) {
// this.kids = kids;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public int getLevel() {
// return level;
// }
//
// public void setLevel(int level) {
// this.level = level;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.leavjenn.hews.R;
import com.leavjenn.hews.model.Comment; | package com.leavjenn.hews.ui.widget;
public class CommentOptionDialogFragment extends DialogFragment {
OnSelectCommentListener mListener; | // Path: app/src/main/java/com/leavjenn/hews/model/Comment.java
// @Parcel
// @StorIOSQLiteType(table = "comment")
// public class Comment extends HNItem {
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_COMMENT_ID, key = true)
// @SerializedName("id")
// long commentId;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_INDEX)
// int _index;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_BY)
// String by;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_DELETED)
// boolean deleted;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_PARENT)
// long parent;
//
// ArrayList<Long> kids;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_TIME)
// long time;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_TEXT)
// String text;
//
// @StorIOSQLiteColumn(name = CommentTable.COLUMN_LEVEL)
// int level;
//
// //FIXME necessary?
// public String error;
//
// public Comment() {
// }
//
// public Comment(long commentId, String by, long parent, ArrayList<Long> kids, long time, String text) {
// this.commentId = commentId;
// this.by = by;
// this.parent = parent;
// this.kids = kids;
// this.time = time;
// this.text = text;
// }
//
// public int getIndex() {
// return _index;
// }
//
// public void setIndex(int _index) {
// this._index = _index;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getBy() {
// return by;
// }
//
// public void setBy(String by) {
// this.by = by;
// }
//
// public long getCommentId() {
// return commentId;
// }
//
// public void setCommentId(long commentId) {
// this.commentId = commentId;
// }
//
// public void setDeleted(boolean deleted) {
// this.deleted = deleted;
// }
//
// public boolean getDeleted() {
// return deleted;
// }
//
// public long getParent() {
// return parent;
// }
//
// public void setParent(long parent) {
// this.parent = parent;
// }
//
// public ArrayList<Long> getKids() {
// return kids;
// }
//
// public void setKids(ArrayList<Long> kids) {
// this.kids = kids;
// }
//
// public long getTime() {
// return time;
// }
//
// public void setTime(long time) {
// this.time = time;
// }
//
// public int getLevel() {
// return level;
// }
//
// public void setLevel(int level) {
// this.level = level;
// }
//
// public String getError() {
// return error;
// }
//
// public void setError(String error) {
// this.error = error;
// }
// }
// Path: app/src/main/java/com/leavjenn/hews/ui/widget/CommentOptionDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.leavjenn.hews.R;
import com.leavjenn.hews.model.Comment;
package com.leavjenn.hews.ui.widget;
public class CommentOptionDialogFragment extends DialogFragment {
OnSelectCommentListener mListener; | Comment mComment; |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java | // Path: app/src/main/java/com/hadithbd/banglahadith/util/Constants.java
// public class Constants {
//
// public static final String LOCALE_BENGALI = "bengali";
//
// public static final String LOCALE_ARABIC = "arabic";
//
// public static final String FONT_FOLDER_LOCATION = "fonts/";
//
// public static final String FONT_NAME_BANGLA = "solaimanlipinormal.ttf";
//
// public static final String FONT_NAME_ARABIC = "a_nefel_adeti.ttf";
//
// public static final String MENU_ITEM_ID = "menu_item_id";
//
// public static final int NUMBER_OF_GRID_COLUMNS = 2;
//
// public static final String BOOK_ID = "book_id";
//
// public static final String HADITH_SECTION_ID = "hadith_chapter_id";
//
// public static final String LATEST_UPDATE_URL = "http://www.hadithbd.com/";
//
// public static final String HADITH_TITLE="hadith_title";
//
// public static final String BOOK_TYPE_ID = "book_type_id";
//
// public static final String BOOK_CONTENT_ID = "book_content_id";
//
// public static final String HADITH_SHARE_URL = "http://www.hadithbd.com/share.php?hid=";
//
// public static final String REPORT_SENDTO_ADDRESS = "info@hadithbd.com";
// }
| import android.app.Application;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
import com.hadithbd.banglahadith.util.Constants;
import java.util.ArrayList;
import java.util.List; | package com.hadithbd.banglahadith;
/**
* Created by Sharif on 2/5/2015.
*/
public class BanglaHadithApp extends Application {
public static final String TAG = "VolleyTag";
public static Typeface typefaceBangla;
public static Typeface typefaceArabic;
private RequestQueue mRequestQueue;
private static BanglaHadithApp mInstance;
public static final List<Integer> itemStripColors = new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
typefaceBangla = Typeface.createFromAsset(getAssets(), | // Path: app/src/main/java/com/hadithbd/banglahadith/util/Constants.java
// public class Constants {
//
// public static final String LOCALE_BENGALI = "bengali";
//
// public static final String LOCALE_ARABIC = "arabic";
//
// public static final String FONT_FOLDER_LOCATION = "fonts/";
//
// public static final String FONT_NAME_BANGLA = "solaimanlipinormal.ttf";
//
// public static final String FONT_NAME_ARABIC = "a_nefel_adeti.ttf";
//
// public static final String MENU_ITEM_ID = "menu_item_id";
//
// public static final int NUMBER_OF_GRID_COLUMNS = 2;
//
// public static final String BOOK_ID = "book_id";
//
// public static final String HADITH_SECTION_ID = "hadith_chapter_id";
//
// public static final String LATEST_UPDATE_URL = "http://www.hadithbd.com/";
//
// public static final String HADITH_TITLE="hadith_title";
//
// public static final String BOOK_TYPE_ID = "book_type_id";
//
// public static final String BOOK_CONTENT_ID = "book_content_id";
//
// public static final String HADITH_SHARE_URL = "http://www.hadithbd.com/share.php?hid=";
//
// public static final String REPORT_SENDTO_ADDRESS = "info@hadithbd.com";
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
import android.app.Application;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
import com.hadithbd.banglahadith.util.Constants;
import java.util.ArrayList;
import java.util.List;
package com.hadithbd.banglahadith;
/**
* Created by Sharif on 2/5/2015.
*/
public class BanglaHadithApp extends Application {
public static final String TAG = "VolleyTag";
public static Typeface typefaceBangla;
public static Typeface typefaceArabic;
private RequestQueue mRequestQueue;
private static BanglaHadithApp mInstance;
public static final List<Integer> itemStripColors = new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
typefaceBangla = Typeface.createFromAsset(getAssets(), | Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA); |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/util/UIUtils.java | // Path: app/src/main/java/com/hadithbd/banglahadith/bangla/UtilBanglaSupport.java
// public class UtilBanglaSupport {
//
// public static String SUTONNI_MJ = "sutonni.TTF";
//
// public static String SOLAIMAN_LIPI = "solaimanlipinormal.ttf";
//
// public static String WEBVIEW_LOADED = "loaded";
//
// /**
// * Logs messages based on the class it gets sent from
// *
// * @param obj
// * @param msg
// */
// public static void log(Object obj, String msg) {
// Log.d(obj.getClass().getSimpleName(), msg);
// }
//
// public static SpannableString getSpannableWithFont(String text, Typeface font, float size) {
// SpannableString retVal = new SpannableString(text);
// TypefaceSpan span = new TypefaceSpan(font);
// retVal.setSpan(span, 0, retVal.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// if (size != -1) {
// retVal.setSpan(new RelativeSizeSpan(size), 0, retVal.length(),
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return retVal;
// }
//
// public static SpannableString getBanglaSpannableString(String banglaText) {
// if (banglaText == null) {
// return new SpannableString("");
// }
// if (Utils.IS_BUILD_ABOVE_HONEYCOMB) {
// SpannableString spannableString = new SpannableString(banglaText);
// if (Utils.isLocaleAvailable(Constants.LOCALE_BENGALI)) {
// TypefaceSpan span = new TypefaceSpan(BanglaHadithApp.typefaceBangla);
// spannableString.setSpan(span, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return spannableString;
// }
// return AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1);
// }
//
// public static SpannableString getArabicSpannableString(String arabicText) {
// if (arabicText == null) {
// return new SpannableString("");
// }
// if (Utils.IS_BUILD_ABOVE_HONEYCOMB) {
// SpannableString spannableString = new SpannableString(arabicText);
// if (Utils.isLocaleAvailable(Constants.LOCALE_ARABIC)) {
// TypefaceSpan span = new TypefaceSpan(BanglaHadithApp.typefaceArabic);
// spannableString.setSpan(span, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return spannableString;
// }
// return AndroidCustomFontSupport.getCorrectedBengaliFormat(arabicText, BanglaHadithApp.typefaceArabic, -1);
// }
//
// /**
// * Used to get bangla texts for UI components.
// *
// * @param text
// * @param size
// * @param banglaSupported TODO
// * @param fontName TODO
// */
// public static SpannableString getBanglaSpannableWithSize(String text, Typeface font, float size, boolean banglaSupported) {
// SpannableString retVal = null;
// if (banglaSupported)//device supports bangla
// {
// log(UtilBanglaSupport.class, "Bangla Supported Device");
// retVal = new SpannableString(text);
// } else {
// //device doesn't support,need unicode.
// retVal = new SpannableString(BengaliUnicodeString.getBengaliUTF(text));
// }
// TypefaceSpan span = new TypefaceSpan(font);
//
// retVal.setSpan(span, 0, retVal.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// if (size != -1) {
// retVal.setSpan(new RelativeSizeSpan(size), 0, retVal.length(),
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return retVal;
// }
// }
| import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.hadithbd.banglahadith.bangla.UtilBanglaSupport; | package com.hadithbd.banglahadith.util;
/**
* Created by Sharif on 3/5/2015.
*/
public class UIUtils {
public static void setRadioButtonTexts(RadioGroup radioGroup, String buttonTextOne, String buttonTextTwo) {
String[] radioButtonTexts = new String[]{buttonTextOne, buttonTextTwo};
for (int i = 0; i < radioGroup.getChildCount(); i++) {
((RadioButton) radioGroup.getChildAt(i)) | // Path: app/src/main/java/com/hadithbd/banglahadith/bangla/UtilBanglaSupport.java
// public class UtilBanglaSupport {
//
// public static String SUTONNI_MJ = "sutonni.TTF";
//
// public static String SOLAIMAN_LIPI = "solaimanlipinormal.ttf";
//
// public static String WEBVIEW_LOADED = "loaded";
//
// /**
// * Logs messages based on the class it gets sent from
// *
// * @param obj
// * @param msg
// */
// public static void log(Object obj, String msg) {
// Log.d(obj.getClass().getSimpleName(), msg);
// }
//
// public static SpannableString getSpannableWithFont(String text, Typeface font, float size) {
// SpannableString retVal = new SpannableString(text);
// TypefaceSpan span = new TypefaceSpan(font);
// retVal.setSpan(span, 0, retVal.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// if (size != -1) {
// retVal.setSpan(new RelativeSizeSpan(size), 0, retVal.length(),
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return retVal;
// }
//
// public static SpannableString getBanglaSpannableString(String banglaText) {
// if (banglaText == null) {
// return new SpannableString("");
// }
// if (Utils.IS_BUILD_ABOVE_HONEYCOMB) {
// SpannableString spannableString = new SpannableString(banglaText);
// if (Utils.isLocaleAvailable(Constants.LOCALE_BENGALI)) {
// TypefaceSpan span = new TypefaceSpan(BanglaHadithApp.typefaceBangla);
// spannableString.setSpan(span, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return spannableString;
// }
// return AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1);
// }
//
// public static SpannableString getArabicSpannableString(String arabicText) {
// if (arabicText == null) {
// return new SpannableString("");
// }
// if (Utils.IS_BUILD_ABOVE_HONEYCOMB) {
// SpannableString spannableString = new SpannableString(arabicText);
// if (Utils.isLocaleAvailable(Constants.LOCALE_ARABIC)) {
// TypefaceSpan span = new TypefaceSpan(BanglaHadithApp.typefaceArabic);
// spannableString.setSpan(span, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return spannableString;
// }
// return AndroidCustomFontSupport.getCorrectedBengaliFormat(arabicText, BanglaHadithApp.typefaceArabic, -1);
// }
//
// /**
// * Used to get bangla texts for UI components.
// *
// * @param text
// * @param size
// * @param banglaSupported TODO
// * @param fontName TODO
// */
// public static SpannableString getBanglaSpannableWithSize(String text, Typeface font, float size, boolean banglaSupported) {
// SpannableString retVal = null;
// if (banglaSupported)//device supports bangla
// {
// log(UtilBanglaSupport.class, "Bangla Supported Device");
// retVal = new SpannableString(text);
// } else {
// //device doesn't support,need unicode.
// retVal = new SpannableString(BengaliUnicodeString.getBengaliUTF(text));
// }
// TypefaceSpan span = new TypefaceSpan(font);
//
// retVal.setSpan(span, 0, retVal.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// if (size != -1) {
// retVal.setSpan(new RelativeSizeSpan(size), 0, retVal.length(),
// Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// }
// return retVal;
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/util/UIUtils.java
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.hadithbd.banglahadith.bangla.UtilBanglaSupport;
package com.hadithbd.banglahadith.util;
/**
* Created by Sharif on 3/5/2015.
*/
public class UIUtils {
public static void setRadioButtonTexts(RadioGroup radioGroup, String buttonTextOne, String buttonTextTwo) {
String[] radioButtonTexts = new String[]{buttonTextOne, buttonTextTwo};
for (int i = 0; i < radioGroup.getChildCount(); i++) {
((RadioButton) radioGroup.getChildAt(i)) | .setText(UtilBanglaSupport.getBanglaSpannableString(radioButtonTexts[i])); |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/ui/fragments/LatestUpdate.java | // Path: app/src/main/java/com/hadithbd/banglahadith/util/Constants.java
// public class Constants {
//
// public static final String LOCALE_BENGALI = "bengali";
//
// public static final String LOCALE_ARABIC = "arabic";
//
// public static final String FONT_FOLDER_LOCATION = "fonts/";
//
// public static final String FONT_NAME_BANGLA = "solaimanlipinormal.ttf";
//
// public static final String FONT_NAME_ARABIC = "a_nefel_adeti.ttf";
//
// public static final String MENU_ITEM_ID = "menu_item_id";
//
// public static final int NUMBER_OF_GRID_COLUMNS = 2;
//
// public static final String BOOK_ID = "book_id";
//
// public static final String HADITH_SECTION_ID = "hadith_chapter_id";
//
// public static final String LATEST_UPDATE_URL = "http://www.hadithbd.com/";
//
// public static final String HADITH_TITLE="hadith_title";
//
// public static final String BOOK_TYPE_ID = "book_type_id";
//
// public static final String BOOK_CONTENT_ID = "book_content_id";
//
// public static final String HADITH_SHARE_URL = "http://www.hadithbd.com/share.php?hid=";
//
// public static final String REPORT_SENDTO_ADDRESS = "info@hadithbd.com";
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/util/Utils.java
// public class Utils {
//
// private static final HashMap<Character, Character> digitsMap = new HashMap<>();
//
// static {
// digitsMap.put('0', '০');
// digitsMap.put('1', '১');
// digitsMap.put('2', '২');
// digitsMap.put('3', '৩');
// digitsMap.put('4', '৪');
// digitsMap.put('5', '৫');
// digitsMap.put('6', '৬');
// digitsMap.put('7', '৭');
// digitsMap.put('8', '৮');
// digitsMap.put('9', '৯');
// }
//
// public static final boolean IS_BUILD_ABOVE_HONEYCOMB = Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2;
//
// public static boolean isLocaleAvailable(String localeName) {
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// if (locale.getDisplayName().toLowerCase().contains(localeName)) {
// return true;
// }
// }
// return false;
// }
//
// /**
// * Check internet connection availability
// */
// public static boolean isNetworkAvailable(Context context) {
// ConnectivityManager connectionManager = (ConnectivityManager) context
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = connectionManager.getActiveNetworkInfo();
// if (netInfo != null && netInfo.isConnected()) {
// return true;
// } else {
// return false;
// }
// }
//
// public static Spannable getColoredSpannableWithBanglaSupport(String text, int colorCode) {
// Spannable spannable = new SpannableString(text);
// spannable.setSpan(new ForegroundColorSpan(colorCode), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// return spannable;
// }
//
// public static String translateNumber(long number) {
// char[] digits = (String.valueOf(number)).toCharArray();
// StringBuilder sb = new StringBuilder();
// for (char digit : digits) {
// sb.append(digitsMap.get(digit));
// }
// return sb.toString();
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Toast;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.util.Constants;
import com.hadithbd.banglahadith.util.Utils; | package com.hadithbd.banglahadith.ui.fragments;
/**
* Created by U on 3/2/2015.
*/
public class LatestUpdate extends Fragment {
private WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
| // Path: app/src/main/java/com/hadithbd/banglahadith/util/Constants.java
// public class Constants {
//
// public static final String LOCALE_BENGALI = "bengali";
//
// public static final String LOCALE_ARABIC = "arabic";
//
// public static final String FONT_FOLDER_LOCATION = "fonts/";
//
// public static final String FONT_NAME_BANGLA = "solaimanlipinormal.ttf";
//
// public static final String FONT_NAME_ARABIC = "a_nefel_adeti.ttf";
//
// public static final String MENU_ITEM_ID = "menu_item_id";
//
// public static final int NUMBER_OF_GRID_COLUMNS = 2;
//
// public static final String BOOK_ID = "book_id";
//
// public static final String HADITH_SECTION_ID = "hadith_chapter_id";
//
// public static final String LATEST_UPDATE_URL = "http://www.hadithbd.com/";
//
// public static final String HADITH_TITLE="hadith_title";
//
// public static final String BOOK_TYPE_ID = "book_type_id";
//
// public static final String BOOK_CONTENT_ID = "book_content_id";
//
// public static final String HADITH_SHARE_URL = "http://www.hadithbd.com/share.php?hid=";
//
// public static final String REPORT_SENDTO_ADDRESS = "info@hadithbd.com";
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/util/Utils.java
// public class Utils {
//
// private static final HashMap<Character, Character> digitsMap = new HashMap<>();
//
// static {
// digitsMap.put('0', '০');
// digitsMap.put('1', '১');
// digitsMap.put('2', '২');
// digitsMap.put('3', '৩');
// digitsMap.put('4', '৪');
// digitsMap.put('5', '৫');
// digitsMap.put('6', '৬');
// digitsMap.put('7', '৭');
// digitsMap.put('8', '৮');
// digitsMap.put('9', '৯');
// }
//
// public static final boolean IS_BUILD_ABOVE_HONEYCOMB = Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2;
//
// public static boolean isLocaleAvailable(String localeName) {
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// if (locale.getDisplayName().toLowerCase().contains(localeName)) {
// return true;
// }
// }
// return false;
// }
//
// /**
// * Check internet connection availability
// */
// public static boolean isNetworkAvailable(Context context) {
// ConnectivityManager connectionManager = (ConnectivityManager) context
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = connectionManager.getActiveNetworkInfo();
// if (netInfo != null && netInfo.isConnected()) {
// return true;
// } else {
// return false;
// }
// }
//
// public static Spannable getColoredSpannableWithBanglaSupport(String text, int colorCode) {
// Spannable spannable = new SpannableString(text);
// spannable.setSpan(new ForegroundColorSpan(colorCode), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// return spannable;
// }
//
// public static String translateNumber(long number) {
// char[] digits = (String.valueOf(number)).toCharArray();
// StringBuilder sb = new StringBuilder();
// for (char digit : digits) {
// sb.append(digitsMap.get(digit));
// }
// return sb.toString();
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/ui/fragments/LatestUpdate.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Toast;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.util.Constants;
import com.hadithbd.banglahadith.util.Utils;
package com.hadithbd.banglahadith.ui.fragments;
/**
* Created by U on 3/2/2015.
*/
public class LatestUpdate extends Fragment {
private WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
| if (!Utils.isNetworkAvailable(getActivity())) { |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/ui/fragments/LatestUpdate.java | // Path: app/src/main/java/com/hadithbd/banglahadith/util/Constants.java
// public class Constants {
//
// public static final String LOCALE_BENGALI = "bengali";
//
// public static final String LOCALE_ARABIC = "arabic";
//
// public static final String FONT_FOLDER_LOCATION = "fonts/";
//
// public static final String FONT_NAME_BANGLA = "solaimanlipinormal.ttf";
//
// public static final String FONT_NAME_ARABIC = "a_nefel_adeti.ttf";
//
// public static final String MENU_ITEM_ID = "menu_item_id";
//
// public static final int NUMBER_OF_GRID_COLUMNS = 2;
//
// public static final String BOOK_ID = "book_id";
//
// public static final String HADITH_SECTION_ID = "hadith_chapter_id";
//
// public static final String LATEST_UPDATE_URL = "http://www.hadithbd.com/";
//
// public static final String HADITH_TITLE="hadith_title";
//
// public static final String BOOK_TYPE_ID = "book_type_id";
//
// public static final String BOOK_CONTENT_ID = "book_content_id";
//
// public static final String HADITH_SHARE_URL = "http://www.hadithbd.com/share.php?hid=";
//
// public static final String REPORT_SENDTO_ADDRESS = "info@hadithbd.com";
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/util/Utils.java
// public class Utils {
//
// private static final HashMap<Character, Character> digitsMap = new HashMap<>();
//
// static {
// digitsMap.put('0', '০');
// digitsMap.put('1', '১');
// digitsMap.put('2', '২');
// digitsMap.put('3', '৩');
// digitsMap.put('4', '৪');
// digitsMap.put('5', '৫');
// digitsMap.put('6', '৬');
// digitsMap.put('7', '৭');
// digitsMap.put('8', '৮');
// digitsMap.put('9', '৯');
// }
//
// public static final boolean IS_BUILD_ABOVE_HONEYCOMB = Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2;
//
// public static boolean isLocaleAvailable(String localeName) {
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// if (locale.getDisplayName().toLowerCase().contains(localeName)) {
// return true;
// }
// }
// return false;
// }
//
// /**
// * Check internet connection availability
// */
// public static boolean isNetworkAvailable(Context context) {
// ConnectivityManager connectionManager = (ConnectivityManager) context
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = connectionManager.getActiveNetworkInfo();
// if (netInfo != null && netInfo.isConnected()) {
// return true;
// } else {
// return false;
// }
// }
//
// public static Spannable getColoredSpannableWithBanglaSupport(String text, int colorCode) {
// Spannable spannable = new SpannableString(text);
// spannable.setSpan(new ForegroundColorSpan(colorCode), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// return spannable;
// }
//
// public static String translateNumber(long number) {
// char[] digits = (String.valueOf(number)).toCharArray();
// StringBuilder sb = new StringBuilder();
// for (char digit : digits) {
// sb.append(digitsMap.get(digit));
// }
// return sb.toString();
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Toast;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.util.Constants;
import com.hadithbd.banglahadith.util.Utils; | package com.hadithbd.banglahadith.ui.fragments;
/**
* Created by U on 3/2/2015.
*/
public class LatestUpdate extends Fragment {
private WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!Utils.isNetworkAvailable(getActivity())) {
Toast.makeText(getActivity(), getString(R.string.text_internet_connection_failed),
Toast.LENGTH_SHORT).show();
}
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_latest_update, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true); | // Path: app/src/main/java/com/hadithbd/banglahadith/util/Constants.java
// public class Constants {
//
// public static final String LOCALE_BENGALI = "bengali";
//
// public static final String LOCALE_ARABIC = "arabic";
//
// public static final String FONT_FOLDER_LOCATION = "fonts/";
//
// public static final String FONT_NAME_BANGLA = "solaimanlipinormal.ttf";
//
// public static final String FONT_NAME_ARABIC = "a_nefel_adeti.ttf";
//
// public static final String MENU_ITEM_ID = "menu_item_id";
//
// public static final int NUMBER_OF_GRID_COLUMNS = 2;
//
// public static final String BOOK_ID = "book_id";
//
// public static final String HADITH_SECTION_ID = "hadith_chapter_id";
//
// public static final String LATEST_UPDATE_URL = "http://www.hadithbd.com/";
//
// public static final String HADITH_TITLE="hadith_title";
//
// public static final String BOOK_TYPE_ID = "book_type_id";
//
// public static final String BOOK_CONTENT_ID = "book_content_id";
//
// public static final String HADITH_SHARE_URL = "http://www.hadithbd.com/share.php?hid=";
//
// public static final String REPORT_SENDTO_ADDRESS = "info@hadithbd.com";
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/util/Utils.java
// public class Utils {
//
// private static final HashMap<Character, Character> digitsMap = new HashMap<>();
//
// static {
// digitsMap.put('0', '০');
// digitsMap.put('1', '১');
// digitsMap.put('2', '২');
// digitsMap.put('3', '৩');
// digitsMap.put('4', '৪');
// digitsMap.put('5', '৫');
// digitsMap.put('6', '৬');
// digitsMap.put('7', '৭');
// digitsMap.put('8', '৮');
// digitsMap.put('9', '৯');
// }
//
// public static final boolean IS_BUILD_ABOVE_HONEYCOMB = Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2;
//
// public static boolean isLocaleAvailable(String localeName) {
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// if (locale.getDisplayName().toLowerCase().contains(localeName)) {
// return true;
// }
// }
// return false;
// }
//
// /**
// * Check internet connection availability
// */
// public static boolean isNetworkAvailable(Context context) {
// ConnectivityManager connectionManager = (ConnectivityManager) context
// .getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = connectionManager.getActiveNetworkInfo();
// if (netInfo != null && netInfo.isConnected()) {
// return true;
// } else {
// return false;
// }
// }
//
// public static Spannable getColoredSpannableWithBanglaSupport(String text, int colorCode) {
// Spannable spannable = new SpannableString(text);
// spannable.setSpan(new ForegroundColorSpan(colorCode), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// return spannable;
// }
//
// public static String translateNumber(long number) {
// char[] digits = (String.valueOf(number)).toCharArray();
// StringBuilder sb = new StringBuilder();
// for (char digit : digits) {
// sb.append(digitsMap.get(digit));
// }
// return sb.toString();
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/ui/fragments/LatestUpdate.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Toast;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.util.Constants;
import com.hadithbd.banglahadith.util.Utils;
package com.hadithbd.banglahadith.ui.fragments;
/**
* Created by U on 3/2/2015.
*/
public class LatestUpdate extends Fragment {
private WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!Utils.isNetworkAvailable(getActivity())) {
Toast.makeText(getActivity(), getString(R.string.text_internet_connection_failed),
Toast.LENGTH_SHORT).show();
}
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_latest_update, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true); | mWebView.loadUrl(Constants.LATEST_UPDATE_URL); |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/adapters/BookCategoryListAdapter.java | // Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
// public class BanglaHadithApp extends Application {
//
// public static final String TAG = "VolleyTag";
//
// public static Typeface typefaceBangla;
//
// public static Typeface typefaceArabic;
//
// private RequestQueue mRequestQueue;
//
// private static BanglaHadithApp mInstance;
//
// public static final List<Integer> itemStripColors = new ArrayList<>();
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// typefaceBangla = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA);
// typefaceArabic = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_ARABIC);
// mInstance = this;
// preLoadListStripColors();
// }
//
// private void preLoadListStripColors() {
// TypedArray ta = getResources().obtainTypedArray(R.array.hadith_item_strip_colors);
//
// for (int i = 0; i < ta.length(); i++) {
// itemStripColors.add(ta.getColor(i, 0));
// }
//
// ta.recycle();
// }
//
// public static synchronized BanglaHadithApp getInstance() {
// return mInstance;
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// }
//
// return mRequestQueue;
// }
//
// public <T> void addToRequestQueue(Request<T> request, String tag) {
// request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//
// VolleyLog.d("Adding to request queue %s", request.getUrl());
//
// getRequestQueue().add(request);
// }
//
// public <T> void addToRequestQueue(Request<T> request) {
// request.setTag(TAG);
// getRequestQueue().add(request);
// }
//
// public void cancelPendingRequest(Object tag) {
// if (mRequestQueue != null) {
// mRequestQueue.cancelAll(tag);
// }
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/BookTypeInfo.java
// public class BookTypeInfo {
// private int typeId;
// private String categoryName;
// private long bookCount;
//
// public BookTypeInfo(int typeId, String categoryName, long bookCount) {
// this.typeId = typeId;
// this.categoryName = categoryName;
// this.bookCount = bookCount;
// }
//
// public int getTypeId() {
// return typeId;
// }
//
// public String getCategoryName() {
// return categoryName;
// }
//
// public long getBookCount() {
// return bookCount;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.BanglaHadithApp;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.BookTypeInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List; | package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 3/3/2015.
*/
public class BookCategoryListAdapter extends RecyclerView.Adapter<BookCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private BookCategoryItemClickListener mBookCategoryItemClickListener;
| // Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
// public class BanglaHadithApp extends Application {
//
// public static final String TAG = "VolleyTag";
//
// public static Typeface typefaceBangla;
//
// public static Typeface typefaceArabic;
//
// private RequestQueue mRequestQueue;
//
// private static BanglaHadithApp mInstance;
//
// public static final List<Integer> itemStripColors = new ArrayList<>();
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// typefaceBangla = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA);
// typefaceArabic = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_ARABIC);
// mInstance = this;
// preLoadListStripColors();
// }
//
// private void preLoadListStripColors() {
// TypedArray ta = getResources().obtainTypedArray(R.array.hadith_item_strip_colors);
//
// for (int i = 0; i < ta.length(); i++) {
// itemStripColors.add(ta.getColor(i, 0));
// }
//
// ta.recycle();
// }
//
// public static synchronized BanglaHadithApp getInstance() {
// return mInstance;
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// }
//
// return mRequestQueue;
// }
//
// public <T> void addToRequestQueue(Request<T> request, String tag) {
// request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//
// VolleyLog.d("Adding to request queue %s", request.getUrl());
//
// getRequestQueue().add(request);
// }
//
// public <T> void addToRequestQueue(Request<T> request) {
// request.setTag(TAG);
// getRequestQueue().add(request);
// }
//
// public void cancelPendingRequest(Object tag) {
// if (mRequestQueue != null) {
// mRequestQueue.cancelAll(tag);
// }
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/BookTypeInfo.java
// public class BookTypeInfo {
// private int typeId;
// private String categoryName;
// private long bookCount;
//
// public BookTypeInfo(int typeId, String categoryName, long bookCount) {
// this.typeId = typeId;
// this.categoryName = categoryName;
// this.bookCount = bookCount;
// }
//
// public int getTypeId() {
// return typeId;
// }
//
// public String getCategoryName() {
// return categoryName;
// }
//
// public long getBookCount() {
// return bookCount;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/adapters/BookCategoryListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.BanglaHadithApp;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.BookTypeInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List;
package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 3/3/2015.
*/
public class BookCategoryListAdapter extends RecyclerView.Adapter<BookCategoryListAdapter.ViewHolder> implements View.OnClickListener {
private BookCategoryItemClickListener mBookCategoryItemClickListener;
| private List<BookTypeInfo> mBookTypeInfoList; |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/adapters/BookListAdapter.java | // Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
// public class BanglaHadithApp extends Application {
//
// public static final String TAG = "VolleyTag";
//
// public static Typeface typefaceBangla;
//
// public static Typeface typefaceArabic;
//
// private RequestQueue mRequestQueue;
//
// private static BanglaHadithApp mInstance;
//
// public static final List<Integer> itemStripColors = new ArrayList<>();
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// typefaceBangla = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA);
// typefaceArabic = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_ARABIC);
// mInstance = this;
// preLoadListStripColors();
// }
//
// private void preLoadListStripColors() {
// TypedArray ta = getResources().obtainTypedArray(R.array.hadith_item_strip_colors);
//
// for (int i = 0; i < ta.length(); i++) {
// itemStripColors.add(ta.getColor(i, 0));
// }
//
// ta.recycle();
// }
//
// public static synchronized BanglaHadithApp getInstance() {
// return mInstance;
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// }
//
// return mRequestQueue;
// }
//
// public <T> void addToRequestQueue(Request<T> request, String tag) {
// request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//
// VolleyLog.d("Adding to request queue %s", request.getUrl());
//
// getRequestQueue().add(request);
// }
//
// public <T> void addToRequestQueue(Request<T> request) {
// request.setTag(TAG);
// getRequestQueue().add(request);
// }
//
// public void cancelPendingRequest(Object tag) {
// if (mRequestQueue != null) {
// mRequestQueue.cancelAll(tag);
// }
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/BookInfo.java
// public class BookInfo {
// private int bookId;
// private String bookName;
// private long questionCount;
//
// public BookInfo(int bookId, String bookName, long sectionCount) {
// this.bookId = bookId;
// this.bookName = bookName;
// this.questionCount = sectionCount;
// }
//
// public int getBookId() {
// return bookId;
// }
//
// public String getBookName() {
// return bookName;
// }
//
// public long getQuestionCount() {
// return questionCount;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.BanglaHadithApp;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.BookInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List; | package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 3/1/2015.
*/
public class BookListAdapter extends RecyclerView.Adapter<BookListAdapter.ViewHolder> implements View.OnClickListener {
private BookItemClickListener mBookItemClickListener;
| // Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
// public class BanglaHadithApp extends Application {
//
// public static final String TAG = "VolleyTag";
//
// public static Typeface typefaceBangla;
//
// public static Typeface typefaceArabic;
//
// private RequestQueue mRequestQueue;
//
// private static BanglaHadithApp mInstance;
//
// public static final List<Integer> itemStripColors = new ArrayList<>();
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// typefaceBangla = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA);
// typefaceArabic = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_ARABIC);
// mInstance = this;
// preLoadListStripColors();
// }
//
// private void preLoadListStripColors() {
// TypedArray ta = getResources().obtainTypedArray(R.array.hadith_item_strip_colors);
//
// for (int i = 0; i < ta.length(); i++) {
// itemStripColors.add(ta.getColor(i, 0));
// }
//
// ta.recycle();
// }
//
// public static synchronized BanglaHadithApp getInstance() {
// return mInstance;
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// }
//
// return mRequestQueue;
// }
//
// public <T> void addToRequestQueue(Request<T> request, String tag) {
// request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//
// VolleyLog.d("Adding to request queue %s", request.getUrl());
//
// getRequestQueue().add(request);
// }
//
// public <T> void addToRequestQueue(Request<T> request) {
// request.setTag(TAG);
// getRequestQueue().add(request);
// }
//
// public void cancelPendingRequest(Object tag) {
// if (mRequestQueue != null) {
// mRequestQueue.cancelAll(tag);
// }
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/BookInfo.java
// public class BookInfo {
// private int bookId;
// private String bookName;
// private long questionCount;
//
// public BookInfo(int bookId, String bookName, long sectionCount) {
// this.bookId = bookId;
// this.bookName = bookName;
// this.questionCount = sectionCount;
// }
//
// public int getBookId() {
// return bookId;
// }
//
// public String getBookName() {
// return bookName;
// }
//
// public long getQuestionCount() {
// return questionCount;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/adapters/BookListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.BanglaHadithApp;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.BookInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List;
package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 3/1/2015.
*/
public class BookListAdapter extends RecyclerView.Adapter<BookListAdapter.ViewHolder> implements View.OnClickListener {
private BookItemClickListener mBookItemClickListener;
| private List<BookInfo> mBookInfoList; |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/adapters/HadithListAdapter.java | // Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
// public class BanglaHadithApp extends Application {
//
// public static final String TAG = "VolleyTag";
//
// public static Typeface typefaceBangla;
//
// public static Typeface typefaceArabic;
//
// private RequestQueue mRequestQueue;
//
// private static BanglaHadithApp mInstance;
//
// public static final List<Integer> itemStripColors = new ArrayList<>();
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// typefaceBangla = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA);
// typefaceArabic = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_ARABIC);
// mInstance = this;
// preLoadListStripColors();
// }
//
// private void preLoadListStripColors() {
// TypedArray ta = getResources().obtainTypedArray(R.array.hadith_item_strip_colors);
//
// for (int i = 0; i < ta.length(); i++) {
// itemStripColors.add(ta.getColor(i, 0));
// }
//
// ta.recycle();
// }
//
// public static synchronized BanglaHadithApp getInstance() {
// return mInstance;
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// }
//
// return mRequestQueue;
// }
//
// public <T> void addToRequestQueue(Request<T> request, String tag) {
// request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//
// VolleyLog.d("Adding to request queue %s", request.getUrl());
//
// getRequestQueue().add(request);
// }
//
// public <T> void addToRequestQueue(Request<T> request) {
// request.setTag(TAG);
// getRequestQueue().add(request);
// }
//
// public void cancelPendingRequest(Object tag) {
// if (mRequestQueue != null) {
// mRequestQueue.cancelAll(tag);
// }
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/HadithBookInfo.java
// public class HadithBookInfo {
//
// private int bookId;
// private String bookName;
// private long sectionCount;
// private long hadithCount;
//
// public HadithBookInfo(int bookId, String bookName, long chapterCount, long hadithCount) {
// this.bookId = bookId;
// this.bookName = bookName;
// this.sectionCount = chapterCount;
// this.hadithCount = hadithCount;
// }
//
// public int getBookId() {
// return bookId;
// }
//
// public String getBookName() {
// return bookName;
// }
//
// public long getSectionCount() {
// return sectionCount;
// }
//
// public long getHadithCount() {
// return hadithCount;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.BanglaHadithApp;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.HadithBookInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List; | package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 2/24/2015.
*/
public class HadithListAdapter extends RecyclerView.Adapter<HadithListAdapter.ViewHolder> implements View.OnClickListener {
private HadithItemClickListener mHadithItemClickListener;
| // Path: app/src/main/java/com/hadithbd/banglahadith/BanglaHadithApp.java
// public class BanglaHadithApp extends Application {
//
// public static final String TAG = "VolleyTag";
//
// public static Typeface typefaceBangla;
//
// public static Typeface typefaceArabic;
//
// private RequestQueue mRequestQueue;
//
// private static BanglaHadithApp mInstance;
//
// public static final List<Integer> itemStripColors = new ArrayList<>();
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// typefaceBangla = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_BANGLA);
// typefaceArabic = Typeface.createFromAsset(getAssets(),
// Constants.FONT_FOLDER_LOCATION + Constants.FONT_NAME_ARABIC);
// mInstance = this;
// preLoadListStripColors();
// }
//
// private void preLoadListStripColors() {
// TypedArray ta = getResources().obtainTypedArray(R.array.hadith_item_strip_colors);
//
// for (int i = 0; i < ta.length(); i++) {
// itemStripColors.add(ta.getColor(i, 0));
// }
//
// ta.recycle();
// }
//
// public static synchronized BanglaHadithApp getInstance() {
// return mInstance;
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// }
//
// return mRequestQueue;
// }
//
// public <T> void addToRequestQueue(Request<T> request, String tag) {
// request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
//
// VolleyLog.d("Adding to request queue %s", request.getUrl());
//
// getRequestQueue().add(request);
// }
//
// public <T> void addToRequestQueue(Request<T> request) {
// request.setTag(TAG);
// getRequestQueue().add(request);
// }
//
// public void cancelPendingRequest(Object tag) {
// if (mRequestQueue != null) {
// mRequestQueue.cancelAll(tag);
// }
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/HadithBookInfo.java
// public class HadithBookInfo {
//
// private int bookId;
// private String bookName;
// private long sectionCount;
// private long hadithCount;
//
// public HadithBookInfo(int bookId, String bookName, long chapterCount, long hadithCount) {
// this.bookId = bookId;
// this.bookName = bookName;
// this.sectionCount = chapterCount;
// this.hadithCount = hadithCount;
// }
//
// public int getBookId() {
// return bookId;
// }
//
// public String getBookName() {
// return bookName;
// }
//
// public long getSectionCount() {
// return sectionCount;
// }
//
// public long getHadithCount() {
// return hadithCount;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/adapters/HadithListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.BanglaHadithApp;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.HadithBookInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List;
package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 2/24/2015.
*/
public class HadithListAdapter extends RecyclerView.Adapter<HadithListAdapter.ViewHolder> implements View.OnClickListener {
private HadithItemClickListener mHadithItemClickListener;
| private List<HadithBookInfo> mBookInfoList; |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/adapters/HadithSectionListAdapter.java | // Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/HadithBookSectionInfo.java
// public class HadithBookSectionInfo {
// private int chapterId;
// private String sectionName;
// private long hadithCount;
//
// public HadithBookSectionInfo(int chapterId, String sectionName, long hadithCount) {
// this.chapterId = chapterId;
// this.sectionName = sectionName;
// this.hadithCount = hadithCount;
// }
//
// public long getHadithCount() {
// return hadithCount;
// }
//
// public int getChapterId() {
// return chapterId;
// }
//
// public String getSectionName() {
// return sectionName;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.HadithBookSectionInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List; | package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 2/19/2015.
*/
public class HadithSectionListAdapter extends RecyclerView.Adapter<HadithSectionListAdapter.ViewHolder>
implements View.OnClickListener {
private String mHadithListPrefixText, mCountSuffix; | // Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/HadithBookSectionInfo.java
// public class HadithBookSectionInfo {
// private int chapterId;
// private String sectionName;
// private long hadithCount;
//
// public HadithBookSectionInfo(int chapterId, String sectionName, long hadithCount) {
// this.chapterId = chapterId;
// this.sectionName = sectionName;
// this.hadithCount = hadithCount;
// }
//
// public long getHadithCount() {
// return hadithCount;
// }
//
// public int getChapterId() {
// return chapterId;
// }
//
// public String getSectionName() {
// return sectionName;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/adapters/HadithSectionListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.HadithBookSectionInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List;
package com.hadithbd.banglahadith.adapters;
/**
* Created by Sharif on 2/19/2015.
*/
public class HadithSectionListAdapter extends RecyclerView.Adapter<HadithSectionListAdapter.ViewHolder>
implements View.OnClickListener {
private String mHadithListPrefixText, mCountSuffix; | private List<HadithBookSectionInfo> mHadithBookSectionInfoList; |
Apptitive/BanglaHadith | app/src/main/java/com/hadithbd/banglahadith/adapters/HadithSectionListAdapter.java | // Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/HadithBookSectionInfo.java
// public class HadithBookSectionInfo {
// private int chapterId;
// private String sectionName;
// private long hadithCount;
//
// public HadithBookSectionInfo(int chapterId, String sectionName, long hadithCount) {
// this.chapterId = chapterId;
// this.sectionName = sectionName;
// this.hadithCount = hadithCount;
// }
//
// public long getHadithCount() {
// return hadithCount;
// }
//
// public int getChapterId() {
// return chapterId;
// }
//
// public String getSectionName() {
// return sectionName;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.HadithBookSectionInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List; |
final View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.hadith_section_list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final HadithBookSectionInfo hadithBookSectionInfo = mHadithBookSectionInfoList.get(position);
viewHolder.hadithSectionName.setBanglaText(hadithBookSectionInfo.getSectionName());
viewHolder.hadithCount.setBanglaText(mHadithListPrefixText + " " + String.valueOf(hadithBookSectionInfo.getHadithCount() + mCountSuffix));
viewHolder.itemView.setTag(position);
}
@Override
public int getItemCount() {
return mHadithBookSectionInfoList != null ? mHadithBookSectionInfoList.size() : 0;
}
@Override
public void onClick(View v) {
if (mHadithSectionItemClickListener != null) {
mHadithSectionItemClickListener.onHadithSectionItemClicked((int) v.getTag());
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
| // Path: app/src/main/java/com/hadithbd/banglahadith/viewmodel/HadithBookSectionInfo.java
// public class HadithBookSectionInfo {
// private int chapterId;
// private String sectionName;
// private long hadithCount;
//
// public HadithBookSectionInfo(int chapterId, String sectionName, long hadithCount) {
// this.chapterId = chapterId;
// this.sectionName = sectionName;
// this.hadithCount = hadithCount;
// }
//
// public long getHadithCount() {
// return hadithCount;
// }
//
// public int getChapterId() {
// return chapterId;
// }
//
// public String getSectionName() {
// return sectionName;
// }
// }
//
// Path: app/src/main/java/com/hadithbd/banglahadith/views/BanglaTextView.java
// public class BanglaTextView extends TextView {
//
// public static final boolean IS_BANGLA_AVAILABLE = Utils.isLocaleAvailable(Constants.LOCALE_BENGALI);
//
// private TypedArray typedArray;
// private String banglaText;
//
// public BanglaTextView(Context context) {
// super(context);
// init(null, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// init(attrs, 0);
// }
//
// public BanglaTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// init(attrs, defStyle);
// }
//
// public void setBanglaText(String banglaText) {
// setBanglaSupportedText(banglaText);
// if (typedArray != null) {
// typedArray.recycle();
// }
// }
//
// private void init(AttributeSet attrs, int defStyle) {
// // Load attributes
// if (attrs != null) {
// try {
// typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.BanglaTextView);
// banglaText = typedArray.getString(R.styleable.BanglaTextView_banglaText);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// setUpTypeFace();
//
// setBanglaSupportedText(banglaText);
// typedArray.recycle();
// }
// }
//
// private void setUpTypeFace() {
// if (isBanglaAvailableAndAboveHoneyComb()) {
// setTypeface(BanglaHadithApp.typefaceBangla);
// }
// }
//
// private boolean isBanglaAvailableAndAboveHoneyComb() {
// return IS_BANGLA_AVAILABLE & Utils.IS_BUILD_ABOVE_HONEYCOMB;
// }
//
// private void setBanglaSupportedText(String banglaText) {
// if (banglaText != null) {
// setText(Utils.IS_BUILD_ABOVE_HONEYCOMB ? banglaText :
// AndroidCustomFontSupport.getCorrectedBengaliFormat(banglaText, BanglaHadithApp.typefaceBangla, -1));
// }
// }
// }
// Path: app/src/main/java/com/hadithbd/banglahadith/adapters/HadithSectionListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.hadithbd.banglahadith.R;
import com.hadithbd.banglahadith.viewmodel.HadithBookSectionInfo;
import com.hadithbd.banglahadith.views.BanglaTextView;
import java.util.List;
final View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.hadith_section_list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final HadithBookSectionInfo hadithBookSectionInfo = mHadithBookSectionInfoList.get(position);
viewHolder.hadithSectionName.setBanglaText(hadithBookSectionInfo.getSectionName());
viewHolder.hadithCount.setBanglaText(mHadithListPrefixText + " " + String.valueOf(hadithBookSectionInfo.getHadithCount() + mCountSuffix));
viewHolder.itemView.setTag(position);
}
@Override
public int getItemCount() {
return mHadithBookSectionInfoList != null ? mHadithBookSectionInfoList.size() : 0;
}
@Override
public void onClick(View v) {
if (mHadithSectionItemClickListener != null) {
mHadithSectionItemClickListener.onHadithSectionItemClicked((int) v.getTag());
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
| public BanglaTextView hadithSectionName, hadithCount; |
kraftek/awsdownload | src/main/java/ro/cs/products/base/AbstractSearch.java | // Path: src/main/java/ro/cs/products/util/Polygon2D.java
// public class Polygon2D {
// private static final Pattern polyPattern = Pattern.compile("POLYGON\\(\\(.*\\)\\)");
// private static final Pattern coordPattern = Pattern.compile("((?:-?(?:\\d+\\.\\d+)) (?:-?(?:\\d+\\.\\d+)))");
//
// private Path2D.Double polygon;
// private int numPoints;
//
// /**
// * Creates a polygon from a well-known text.
// * For now, only single POLYGONs are supported.
// * If multiple polygons are encountered, only the first one is taken into account.
// *
// * @param wkt The text to parse.
// * @return A closed polygon.
// */
// public static Polygon2D fromWKT(String wkt) {
// Polygon2D polygon = new Polygon2D();
// Matcher matcher = polyPattern.matcher(wkt);
// if (matcher.matches()) {
// String polyText = matcher.toMatchResult().group(0);
// if (polyText != null) {
// Matcher coordMatcher = coordPattern.matcher(polyText);
// while (coordMatcher.find()) {
// //for (int i = 0; i < coordMatcher.groupCount(); i++) {
// String[] coords = coordMatcher.group().split(" ");
// polygon.append(Double.parseDouble(coords[0]), Double.parseDouble(coords[1]));
// //}
// }
// }
// } else {
// // maybe we have only a list of coordinates, without being wrapped in a POLYGON((..))
// Matcher coordMatcher = coordPattern.matcher(wkt);
// while (coordMatcher.find()) {
// //for (int i = 0; i < coordMatcher.groupCount(); i++) {
// String[] coords = coordMatcher.group().split(" ");
// polygon.append(Double.parseDouble(coords[0]), Double.parseDouble(coords[1]));
// //}
// }
// }
// return polygon;
// }
//
// public Polygon2D() {
// }
//
// /**
// * Adds a point to the current polygon.
// * If this is not the first point, then it also adds a line between the previous point and the new one.
// *
// * @param x The x coordinate
// * @param y The y coordinate
// */
// public void append(double x, double y) {
// if (polygon == null) {
// polygon = new Path2D.Double();
// polygon.moveTo(x, y);
// } else {
// polygon.lineTo(x, y);
// }
// numPoints++;
// }
//
// /**
// * Adds a list of points to the current polygon.
// * The list items are pairs of coordinates.
// *
// * @param points The points to be added
// */
// public void append(List<double[]> points) {
// if (points != null) {
// for (double[] pair : points) {
// if (pair != null && pair.length == 2) {
// append(pair[0], pair[1]);
// }
// }
// }
// }
//
// /**
// * Returns the number of points of the current polygon.
// *
// */
// public int getNumPoints() {
// return numPoints;
// }
//
// /**
// * Produces a WKT representation of this polygon.
// */
// public String toWKT() {
// StringBuilder buffer = new StringBuilder();
// buffer.append("POLYGON((");
// PathIterator pathIterator = polygon.getPathIterator(null);
// while (!pathIterator.isDone()) {
// double[] segment = new double[6];
// pathIterator.currentSegment(segment);
// buffer.append(String.valueOf(segment[0])).append(" ").append(String.valueOf(segment[1])).append(",");
// pathIterator.next();
// }
// buffer.setLength(buffer.length() - 1);
// buffer.append("))");
// return buffer.toString();
// }
//
// public Rectangle2D getBounds2D() {
// return polygon.getBounds2D();
// }
//
// public String toWKTBounds() {
// Rectangle2D bounds2D = polygon.getBounds2D();
// return "POLYGON((" +
// bounds2D.getMinX() + " " + bounds2D.getMinY() + "," +
// bounds2D.getMaxX() + " " + bounds2D.getMinY() + "," +
// bounds2D.getMaxX() + " " + bounds2D.getMaxY() + "," +
// bounds2D.getMinX() + " " + bounds2D.getMaxY() + "," +
// bounds2D.getMinX() + " " + bounds2D.getMinY() + "))";
// }
//
// }
| import java.util.stream.Collectors;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import ro.cs.products.util.Polygon2D;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ro.cs.products.base;
/**
* Base class for search providers
*
* @author Cosmin Cara
*/
public abstract class AbstractSearch<T extends Object> {
protected URI url; | // Path: src/main/java/ro/cs/products/util/Polygon2D.java
// public class Polygon2D {
// private static final Pattern polyPattern = Pattern.compile("POLYGON\\(\\(.*\\)\\)");
// private static final Pattern coordPattern = Pattern.compile("((?:-?(?:\\d+\\.\\d+)) (?:-?(?:\\d+\\.\\d+)))");
//
// private Path2D.Double polygon;
// private int numPoints;
//
// /**
// * Creates a polygon from a well-known text.
// * For now, only single POLYGONs are supported.
// * If multiple polygons are encountered, only the first one is taken into account.
// *
// * @param wkt The text to parse.
// * @return A closed polygon.
// */
// public static Polygon2D fromWKT(String wkt) {
// Polygon2D polygon = new Polygon2D();
// Matcher matcher = polyPattern.matcher(wkt);
// if (matcher.matches()) {
// String polyText = matcher.toMatchResult().group(0);
// if (polyText != null) {
// Matcher coordMatcher = coordPattern.matcher(polyText);
// while (coordMatcher.find()) {
// //for (int i = 0; i < coordMatcher.groupCount(); i++) {
// String[] coords = coordMatcher.group().split(" ");
// polygon.append(Double.parseDouble(coords[0]), Double.parseDouble(coords[1]));
// //}
// }
// }
// } else {
// // maybe we have only a list of coordinates, without being wrapped in a POLYGON((..))
// Matcher coordMatcher = coordPattern.matcher(wkt);
// while (coordMatcher.find()) {
// //for (int i = 0; i < coordMatcher.groupCount(); i++) {
// String[] coords = coordMatcher.group().split(" ");
// polygon.append(Double.parseDouble(coords[0]), Double.parseDouble(coords[1]));
// //}
// }
// }
// return polygon;
// }
//
// public Polygon2D() {
// }
//
// /**
// * Adds a point to the current polygon.
// * If this is not the first point, then it also adds a line between the previous point and the new one.
// *
// * @param x The x coordinate
// * @param y The y coordinate
// */
// public void append(double x, double y) {
// if (polygon == null) {
// polygon = new Path2D.Double();
// polygon.moveTo(x, y);
// } else {
// polygon.lineTo(x, y);
// }
// numPoints++;
// }
//
// /**
// * Adds a list of points to the current polygon.
// * The list items are pairs of coordinates.
// *
// * @param points The points to be added
// */
// public void append(List<double[]> points) {
// if (points != null) {
// for (double[] pair : points) {
// if (pair != null && pair.length == 2) {
// append(pair[0], pair[1]);
// }
// }
// }
// }
//
// /**
// * Returns the number of points of the current polygon.
// *
// */
// public int getNumPoints() {
// return numPoints;
// }
//
// /**
// * Produces a WKT representation of this polygon.
// */
// public String toWKT() {
// StringBuilder buffer = new StringBuilder();
// buffer.append("POLYGON((");
// PathIterator pathIterator = polygon.getPathIterator(null);
// while (!pathIterator.isDone()) {
// double[] segment = new double[6];
// pathIterator.currentSegment(segment);
// buffer.append(String.valueOf(segment[0])).append(" ").append(String.valueOf(segment[1])).append(",");
// pathIterator.next();
// }
// buffer.setLength(buffer.length() - 1);
// buffer.append("))");
// return buffer.toString();
// }
//
// public Rectangle2D getBounds2D() {
// return polygon.getBounds2D();
// }
//
// public String toWKTBounds() {
// Rectangle2D bounds2D = polygon.getBounds2D();
// return "POLYGON((" +
// bounds2D.getMinX() + " " + bounds2D.getMinY() + "," +
// bounds2D.getMaxX() + " " + bounds2D.getMinY() + "," +
// bounds2D.getMaxX() + " " + bounds2D.getMaxY() + "," +
// bounds2D.getMinX() + " " + bounds2D.getMaxY() + "," +
// bounds2D.getMinX() + " " + bounds2D.getMinY() + "))";
// }
//
// }
// Path: src/main/java/ro/cs/products/base/AbstractSearch.java
import java.util.stream.Collectors;
import org.apache.http.NameValuePair;
import org.apache.http.auth.UsernamePasswordCredentials;
import ro.cs.products.util.Polygon2D;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package ro.cs.products.base;
/**
* Base class for search providers
*
* @author Cosmin Cara
*/
public abstract class AbstractSearch<T extends Object> {
protected URI url; | protected Polygon2D aoi; |
kumuluz/kumuluzee | components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java | // Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/exceptions/CannotRetrieveTxException.java
// public class CannotRetrieveTxException extends IllegalStateException {
//
// public CannotRetrieveTxException(Throwable cause) {
// super("There was an error retrieving the current threads transaction.", cause);
// }
// }
| import com.kumuluz.ee.jta.common.JtaProvider;
import com.kumuluz.ee.jta.common.exceptions.CannotRetrieveTxException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.jta.common.utils;
/**
* @author Tilen Faganel
* @since 2.4.0
*/
public class TxUtils {
public static Boolean isActive(TransactionManager transactionManager) {
try {
Transaction tx = transactionManager.getTransaction();
return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
} catch (SystemException e) { | // Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/exceptions/CannotRetrieveTxException.java
// public class CannotRetrieveTxException extends IllegalStateException {
//
// public CannotRetrieveTxException(Throwable cause) {
// super("There was an error retrieving the current threads transaction.", cause);
// }
// }
// Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java
import com.kumuluz.ee.jta.common.JtaProvider;
import com.kumuluz.ee.jta.common.exceptions.CannotRetrieveTxException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.jta.common.utils;
/**
* @author Tilen Faganel
* @since 2.4.0
*/
public class TxUtils {
public static Boolean isActive(TransactionManager transactionManager) {
try {
Transaction tx = transactionManager.getTransaction();
return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
} catch (SystemException e) { | throw new CannotRetrieveTxException(e); |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/configuration/sources/SystemPropertyConfigurationSource.java | // Path: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationDispatcher.java
// public class ConfigurationDispatcher {
//
// private List<ConfigurationListener> subscriptions = new ArrayList<>();
//
// public void notifyChange(String key, String value) {
//
// for (ConfigurationListener subscription : subscriptions) {
// subscription.onChange(key, value);
// }
// }
//
// public void subscribe(ConfigurationListener listener) {
// subscriptions.add(listener);
// }
//
// public void unsubscribe(ConfigurationListener listener) {
// subscriptions.remove(listener);
// }
// }
| import com.kumuluz.ee.configuration.ConfigurationSource;
import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher;
import com.kumuluz.ee.configuration.utils.ConfigurationSourceUtils;
import java.util.List;
import java.util.Optional; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.configuration.sources;
/**
* @author Urban Malc
* @since 2.4.0
*/
public class SystemPropertyConfigurationSource implements ConfigurationSource {
@Override | // Path: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationDispatcher.java
// public class ConfigurationDispatcher {
//
// private List<ConfigurationListener> subscriptions = new ArrayList<>();
//
// public void notifyChange(String key, String value) {
//
// for (ConfigurationListener subscription : subscriptions) {
// subscription.onChange(key, value);
// }
// }
//
// public void subscribe(ConfigurationListener listener) {
// subscriptions.add(listener);
// }
//
// public void unsubscribe(ConfigurationListener listener) {
// subscriptions.remove(listener);
// }
// }
// Path: common/src/main/java/com/kumuluz/ee/configuration/sources/SystemPropertyConfigurationSource.java
import com.kumuluz.ee.configuration.ConfigurationSource;
import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher;
import com.kumuluz.ee.configuration.utils.ConfigurationSourceUtils;
import java.util.List;
import java.util.Optional;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.configuration.sources;
/**
* @author Urban Malc
* @since 2.4.0
*/
public class SystemPropertyConfigurationSource implements ConfigurationSource {
@Override | public void init(ConfigurationDispatcher configurationDispatcher) { |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/common/datasources/XADataSourceBuilder.java | // Path: common/src/main/java/com/kumuluz/ee/common/config/XaDataSourceConfig.java
// public class XaDataSourceConfig {
//
// public static class Builder {
//
// private String jndiName;
// private String xaDatasourceClass;
// private String username;
// private String password;
//
// private DataSourcePoolConfig.Builder pool = new DataSourcePoolConfig.Builder();
//
// private Map<String, String> props = new HashMap<>();
//
// public Builder jndiName(String jndiName) {
// this.jndiName = jndiName;
// return this;
// }
//
// public Builder xaDatasourceClass(String xaDatasourceClass) {
// this.xaDatasourceClass = xaDatasourceClass;
// return this;
// }
//
// public Builder username(String username) {
// this.username = username;
// return this;
// }
//
// public Builder password(String password) {
// this.password = password;
// return this;
// }
//
// public Builder pool(DataSourcePoolConfig.Builder pool) {
// this.pool = pool;
// return this;
// }
//
// public Builder prop(String key, String value) {
// this.props.put(key, value);
// return this;
// }
//
// public XaDataSourceConfig build() {
//
// XaDataSourceConfig xaDataSourceConfig = new XaDataSourceConfig();
// xaDataSourceConfig.jndiName = jndiName;
// xaDataSourceConfig.xaDatasourceClass = xaDatasourceClass;
// xaDataSourceConfig.username = username;
// xaDataSourceConfig.password = password;
//
// xaDataSourceConfig.pool = pool.build();
//
// xaDataSourceConfig.props = Collections.unmodifiableMap(props);
//
// return xaDataSourceConfig;
// }
// }
//
// private String jndiName;
// private String xaDatasourceClass;
// private String username;
// private String password;
//
// private DataSourcePoolConfig pool;
//
// private Map<String, String> props;
//
// private XaDataSourceConfig() {
// }
//
// public String getJndiName() {
// return jndiName;
// }
//
// public String getXaDatasourceClass() {
// return xaDatasourceClass;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public DataSourcePoolConfig getPool() {
// return pool;
// }
//
// public Map<String, String> getProps() {
// return props;
// }
// }
| import com.kumuluz.ee.common.config.XaDataSourceConfig;
import com.kumuluz.ee.common.exceptions.KumuluzServerException;
import javax.sql.XADataSource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common.datasources;
/**
* @author Tilen Faganel
* @since 2.3.0
*/
@Deprecated
public class XADataSourceBuilder {
| // Path: common/src/main/java/com/kumuluz/ee/common/config/XaDataSourceConfig.java
// public class XaDataSourceConfig {
//
// public static class Builder {
//
// private String jndiName;
// private String xaDatasourceClass;
// private String username;
// private String password;
//
// private DataSourcePoolConfig.Builder pool = new DataSourcePoolConfig.Builder();
//
// private Map<String, String> props = new HashMap<>();
//
// public Builder jndiName(String jndiName) {
// this.jndiName = jndiName;
// return this;
// }
//
// public Builder xaDatasourceClass(String xaDatasourceClass) {
// this.xaDatasourceClass = xaDatasourceClass;
// return this;
// }
//
// public Builder username(String username) {
// this.username = username;
// return this;
// }
//
// public Builder password(String password) {
// this.password = password;
// return this;
// }
//
// public Builder pool(DataSourcePoolConfig.Builder pool) {
// this.pool = pool;
// return this;
// }
//
// public Builder prop(String key, String value) {
// this.props.put(key, value);
// return this;
// }
//
// public XaDataSourceConfig build() {
//
// XaDataSourceConfig xaDataSourceConfig = new XaDataSourceConfig();
// xaDataSourceConfig.jndiName = jndiName;
// xaDataSourceConfig.xaDatasourceClass = xaDatasourceClass;
// xaDataSourceConfig.username = username;
// xaDataSourceConfig.password = password;
//
// xaDataSourceConfig.pool = pool.build();
//
// xaDataSourceConfig.props = Collections.unmodifiableMap(props);
//
// return xaDataSourceConfig;
// }
// }
//
// private String jndiName;
// private String xaDatasourceClass;
// private String username;
// private String password;
//
// private DataSourcePoolConfig pool;
//
// private Map<String, String> props;
//
// private XaDataSourceConfig() {
// }
//
// public String getJndiName() {
// return jndiName;
// }
//
// public String getXaDatasourceClass() {
// return xaDatasourceClass;
// }
//
// public String getUsername() {
// return username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public DataSourcePoolConfig getPool() {
// return pool;
// }
//
// public Map<String, String> getProps() {
// return props;
// }
// }
// Path: common/src/main/java/com/kumuluz/ee/common/datasources/XADataSourceBuilder.java
import com.kumuluz.ee.common.config.XaDataSourceConfig;
import com.kumuluz.ee.common.exceptions.KumuluzServerException;
import javax.sql.XADataSource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common.datasources;
/**
* @author Tilen Faganel
* @since 2.3.0
*/
@Deprecated
public class XADataSourceBuilder {
| private XaDataSourceConfig xaDataSourceConfig; |
kumuluz/kumuluzee | components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/HibernateValidatorTest.java | // Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/Project.java
// public class Project {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String name;
//
// @Size(min = 1, max = 3000)
// private String description;
//
// @NotNull
// private User user;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
// }
//
// Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/User.java
// public class User {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String username;
//
// @NotNull
// @Email
// private String email;
//
// @Size(min = 2, max = 20)
// private String firstname;
//
// @Size(min = 2, max = 20)
// private String lastname;
//
// @NotNull
// @Min(0)
// private Integer age;
//
// @NotNull
// @Min(0)
// private Double salary;
//
// @NotNull
// private Date createdAt;
//
// @Valid
// private List<Project> projects;
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public String getLastname() {
// return lastname;
// }
//
// public void setLastname(String lastname) {
// this.lastname = lastname;
// }
//
// public Integer getAge() {
// return age;
// }
//
// public void setAge(Integer age) {
// this.age = age;
// }
//
// public Double getSalary() {
// return salary;
// }
//
// public void setSalary(Double salary) {
// this.salary = salary;
// }
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
// public List<Project> getProjects() {
// return projects;
// }
//
// public void setProjects(List<Project> projects) {
// this.projects = projects;
// }
// }
| import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import com.kumuluz.ee.beanvalidation.test.beans.Project;
import com.kumuluz.ee.beanvalidation.test.beans.User;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.beanvalidation.test;
/**
* @author Tilen
*/
public class HibernateValidatorTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testCorrectEntities() {
| // Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/Project.java
// public class Project {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String name;
//
// @Size(min = 1, max = 3000)
// private String description;
//
// @NotNull
// private User user;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
// }
//
// Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/User.java
// public class User {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String username;
//
// @NotNull
// @Email
// private String email;
//
// @Size(min = 2, max = 20)
// private String firstname;
//
// @Size(min = 2, max = 20)
// private String lastname;
//
// @NotNull
// @Min(0)
// private Integer age;
//
// @NotNull
// @Min(0)
// private Double salary;
//
// @NotNull
// private Date createdAt;
//
// @Valid
// private List<Project> projects;
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public String getLastname() {
// return lastname;
// }
//
// public void setLastname(String lastname) {
// this.lastname = lastname;
// }
//
// public Integer getAge() {
// return age;
// }
//
// public void setAge(Integer age) {
// this.age = age;
// }
//
// public Double getSalary() {
// return salary;
// }
//
// public void setSalary(Double salary) {
// this.salary = salary;
// }
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
// public List<Project> getProjects() {
// return projects;
// }
//
// public void setProjects(List<Project> projects) {
// this.projects = projects;
// }
// }
// Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/HibernateValidatorTest.java
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import com.kumuluz.ee.beanvalidation.test.beans.Project;
import com.kumuluz.ee.beanvalidation.test.beans.User;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.beanvalidation.test;
/**
* @author Tilen
*/
public class HibernateValidatorTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testCorrectEntities() {
| Project p1 = new Project(); |
kumuluz/kumuluzee | components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/HibernateValidatorTest.java | // Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/Project.java
// public class Project {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String name;
//
// @Size(min = 1, max = 3000)
// private String description;
//
// @NotNull
// private User user;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
// }
//
// Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/User.java
// public class User {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String username;
//
// @NotNull
// @Email
// private String email;
//
// @Size(min = 2, max = 20)
// private String firstname;
//
// @Size(min = 2, max = 20)
// private String lastname;
//
// @NotNull
// @Min(0)
// private Integer age;
//
// @NotNull
// @Min(0)
// private Double salary;
//
// @NotNull
// private Date createdAt;
//
// @Valid
// private List<Project> projects;
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public String getLastname() {
// return lastname;
// }
//
// public void setLastname(String lastname) {
// this.lastname = lastname;
// }
//
// public Integer getAge() {
// return age;
// }
//
// public void setAge(Integer age) {
// this.age = age;
// }
//
// public Double getSalary() {
// return salary;
// }
//
// public void setSalary(Double salary) {
// this.salary = salary;
// }
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
// public List<Project> getProjects() {
// return projects;
// }
//
// public void setProjects(List<Project> projects) {
// this.projects = projects;
// }
// }
| import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import com.kumuluz.ee.beanvalidation.test.beans.Project;
import com.kumuluz.ee.beanvalidation.test.beans.User;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.beanvalidation.test;
/**
* @author Tilen
*/
public class HibernateValidatorTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testCorrectEntities() {
Project p1 = new Project();
p1.setName("Test project");
p1.setDescription("Sample description of a project");
| // Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/Project.java
// public class Project {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String name;
//
// @Size(min = 1, max = 3000)
// private String description;
//
// @NotNull
// private User user;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
// }
//
// Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/beans/User.java
// public class User {
//
// @NotNull
// @Size(min = 2, max = 30)
// private String username;
//
// @NotNull
// @Email
// private String email;
//
// @Size(min = 2, max = 20)
// private String firstname;
//
// @Size(min = 2, max = 20)
// private String lastname;
//
// @NotNull
// @Min(0)
// private Integer age;
//
// @NotNull
// @Min(0)
// private Double salary;
//
// @NotNull
// private Date createdAt;
//
// @Valid
// private List<Project> projects;
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getFirstname() {
// return firstname;
// }
//
// public void setFirstname(String firstname) {
// this.firstname = firstname;
// }
//
// public String getLastname() {
// return lastname;
// }
//
// public void setLastname(String lastname) {
// this.lastname = lastname;
// }
//
// public Integer getAge() {
// return age;
// }
//
// public void setAge(Integer age) {
// this.age = age;
// }
//
// public Double getSalary() {
// return salary;
// }
//
// public void setSalary(Double salary) {
// this.salary = salary;
// }
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
// public List<Project> getProjects() {
// return projects;
// }
//
// public void setProjects(List<Project> projects) {
// this.projects = projects;
// }
// }
// Path: components/bean-validation/hibernate-validator/src/test/java/com/kumuluz/ee/beanvalidation/test/HibernateValidatorTest.java
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import com.kumuluz.ee.beanvalidation.test.beans.Project;
import com.kumuluz.ee.beanvalidation.test.beans.User;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.beanvalidation.test;
/**
* @author Tilen
*/
public class HibernateValidatorTest {
private static Validator validator;
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testCorrectEntities() {
Project p1 = new Project();
p1.setName("Test project");
p1.setDescription("Sample description of a project");
| User u1 = new User(); |
kumuluz/kumuluzee | tools/loader/src/main/java/com/kumuluz/ee/loader/EeBootLoader.java | // Path: tools/loader/src/main/java/com/kumuluz/ee/loader/exception/EeClassLoaderException.java
// public class EeClassLoaderException extends RuntimeException {
//
// public EeClassLoaderException(String message) {
// super(message);
// }
//
// public EeClassLoaderException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public String getMessageAll() {
// StringBuilder stringBuilder = new StringBuilder();
//
// for (Throwable e = this; e != null; e = e.getCause()) {
// if (stringBuilder.length() > 0) {
// stringBuilder.append(" / ");
// }
//
// String message = e.getMessage();
// if (message == null || message.length() == 0) {
// message = e.getClass().getSimpleName();
// }
//
// stringBuilder.append(message);
// }
//
// return stringBuilder.toString();
// }
// }
| import java.util.MissingResourceException;
import java.util.ResourceBundle;
import com.kumuluz.ee.loader.exception.EeClassLoaderException; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.loader;
/**
* @author Benjamin Kastelic
*
*/
public class EeBootLoader {
public static void main(String[] args) throws Throwable {
try {
ResourceBundle bootLoaderProperties = ResourceBundle.getBundle("META-INF/kumuluzee/boot-loader");
String mainClass = bootLoaderProperties.getString("main-class");
launch(args, mainClass);
} catch (MissingResourceException e) {
| // Path: tools/loader/src/main/java/com/kumuluz/ee/loader/exception/EeClassLoaderException.java
// public class EeClassLoaderException extends RuntimeException {
//
// public EeClassLoaderException(String message) {
// super(message);
// }
//
// public EeClassLoaderException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public String getMessageAll() {
// StringBuilder stringBuilder = new StringBuilder();
//
// for (Throwable e = this; e != null; e = e.getCause()) {
// if (stringBuilder.length() > 0) {
// stringBuilder.append(" / ");
// }
//
// String message = e.getMessage();
// if (message == null || message.length() == 0) {
// message = e.getClass().getSimpleName();
// }
//
// stringBuilder.append(message);
// }
//
// return stringBuilder.toString();
// }
// }
// Path: tools/loader/src/main/java/com/kumuluz/ee/loader/EeBootLoader.java
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import com.kumuluz.ee.loader.exception.EeClassLoaderException;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.loader;
/**
* @author Benjamin Kastelic
*
*/
public class EeBootLoader {
public static void main(String[] args) throws Throwable {
try {
ResourceBundle bootLoaderProperties = ResourceBundle.getBundle("META-INF/kumuluzee/boot-loader");
String mainClass = bootLoaderProperties.getString("main-class");
launch(args, mainClass);
} catch (MissingResourceException e) {
| throw new EeClassLoaderException("KumuluzEE Boot Loader config properties are malformed or missing.", e); |
kumuluz/kumuluzee | core/src/main/java/com/kumuluz/ee/loaders/ConfigExtensionLoader.java | // Path: common/src/main/java/com/kumuluz/ee/common/ConfigExtension.java
// public interface ConfigExtension extends Extension {
//
// /**
// * @deprecated Use {@link #getConfigurationSources()} instead.
// */
// @Deprecated
// ConfigurationSource getConfigurationSource();
//
// default List<ConfigurationSource> getConfigurationSources() {
// return Collections.emptyList();
// }
// }
| import com.kumuluz.ee.common.ConfigExtension;
import com.kumuluz.ee.common.dependencies.EeExtensionDef;
import com.kumuluz.ee.common.dependencies.EeExtensionGroup;
import com.kumuluz.ee.common.exceptions.KumuluzServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Logger; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.loaders;
/**
* @author Tilen Faganel
* @since 2.3.0
*/
public class ConfigExtensionLoader {
private static final Logger log = Logger.getLogger(ConfigExtensionLoader.class.getSimpleName());
| // Path: common/src/main/java/com/kumuluz/ee/common/ConfigExtension.java
// public interface ConfigExtension extends Extension {
//
// /**
// * @deprecated Use {@link #getConfigurationSources()} instead.
// */
// @Deprecated
// ConfigurationSource getConfigurationSource();
//
// default List<ConfigurationSource> getConfigurationSources() {
// return Collections.emptyList();
// }
// }
// Path: core/src/main/java/com/kumuluz/ee/loaders/ConfigExtensionLoader.java
import com.kumuluz.ee.common.ConfigExtension;
import com.kumuluz.ee.common.dependencies.EeExtensionDef;
import com.kumuluz.ee.common.dependencies.EeExtensionGroup;
import com.kumuluz.ee.common.exceptions.KumuluzServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Logger;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.loaders;
/**
* @author Tilen Faganel
* @since 2.3.0
*/
public class ConfigExtensionLoader {
private static final Logger log = Logger.getLogger(ConfigExtensionLoader.class.getSimpleName());
| public static List<ConfigExtension> loadExtensions() { |
kumuluz/kumuluzee | core/src/main/java/com/kumuluz/ee/loaders/ExtensionLoader.java | // Path: common/src/main/java/com/kumuluz/ee/common/Extension.java
// public interface Extension {
//
// void load();
//
// void init(KumuluzServerWrapper server, EeConfig eeConfig);
//
// default boolean isEnabled() {
// return true;
// }
//
// default List<String> scanLibraries() {
// return Collections.emptyList();
// }
// }
| import com.kumuluz.ee.common.Extension;
import com.kumuluz.ee.common.dependencies.EeExtensionDef;
import com.kumuluz.ee.common.dependencies.EeExtensionGroup;
import com.kumuluz.ee.common.exceptions.KumuluzServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Logger; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.loaders;
/**
* @author Jan Meznarič
* @since 2.3.0
*/
public class ExtensionLoader {
private static final Logger log = Logger.getLogger(ExtensionLoader.class.getSimpleName());
| // Path: common/src/main/java/com/kumuluz/ee/common/Extension.java
// public interface Extension {
//
// void load();
//
// void init(KumuluzServerWrapper server, EeConfig eeConfig);
//
// default boolean isEnabled() {
// return true;
// }
//
// default List<String> scanLibraries() {
// return Collections.emptyList();
// }
// }
// Path: core/src/main/java/com/kumuluz/ee/loaders/ExtensionLoader.java
import com.kumuluz.ee.common.Extension;
import com.kumuluz.ee.common.dependencies.EeExtensionDef;
import com.kumuluz.ee.common.dependencies.EeExtensionGroup;
import com.kumuluz.ee.common.exceptions.KumuluzServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Logger;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.loaders;
/**
* @author Jan Meznarič
* @since 2.3.0
*/
public class ExtensionLoader {
private static final Logger log = Logger.getLogger(ExtensionLoader.class.getSimpleName());
| public static List<Extension> loadExtensions() { |
kumuluz/kumuluzee | components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtilTest.java | // Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/NoWsContextAnnotatedEndpointBean.java
// @WebService
// public class NoWsContextAnnotatedEndpointBean {
// }
//
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WsContextAnnotatedEndpointBean.java
// @WsContext(contextRoot = WsContextAnnotatedEndpointBean.CTX_ROOT, urlPattern = WsContextAnnotatedEndpointBean.URL_PATTERN)
// @WebService(wsdlLocation = WsContextAnnotatedEndpointBean.WSDL_URL, portName = WsContextAnnotatedEndpointBean.PORT, serviceName =
// WsContextAnnotatedEndpointBean.SERVICE, endpointInterface = WsContextAnnotatedEndpointBean.INTERFACE)
// public class WsContextAnnotatedEndpointBean implements WsContextAnnotatedEndpoint {
//
// public static final String WSDL_URL = "http://cloud.si/example.wsdl";
// public static final String CTX_ROOT = "/ws/*";
// public static final String URL_PATTERN = "/endpoint";
// public static final String PORT = "EndpointPort";
// public static final String SERVICE = "ServiceName";
// public static final String INTERFACE = "com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpoint";
//
// }
| import com.kumuluz.ee.jaxws.cxf.impl.NoWsContextAnnotatedEndpointBean;
import com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpointBean;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.util.stream.Stream;
import static org.junit.Assert.*; | package com.kumuluz.ee.jaxws.cxf.processor;
public class JaxWsAnnotationProcessorUtilTest {
private JaxWsAnnotationProcessorUtil instance = JaxWsAnnotationProcessorUtil.getInstance();
@Test
public void shouldReturnDefaultWsInfo() {
| // Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/NoWsContextAnnotatedEndpointBean.java
// @WebService
// public class NoWsContextAnnotatedEndpointBean {
// }
//
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WsContextAnnotatedEndpointBean.java
// @WsContext(contextRoot = WsContextAnnotatedEndpointBean.CTX_ROOT, urlPattern = WsContextAnnotatedEndpointBean.URL_PATTERN)
// @WebService(wsdlLocation = WsContextAnnotatedEndpointBean.WSDL_URL, portName = WsContextAnnotatedEndpointBean.PORT, serviceName =
// WsContextAnnotatedEndpointBean.SERVICE, endpointInterface = WsContextAnnotatedEndpointBean.INTERFACE)
// public class WsContextAnnotatedEndpointBean implements WsContextAnnotatedEndpoint {
//
// public static final String WSDL_URL = "http://cloud.si/example.wsdl";
// public static final String CTX_ROOT = "/ws/*";
// public static final String URL_PATTERN = "/endpoint";
// public static final String PORT = "EndpointPort";
// public static final String SERVICE = "ServiceName";
// public static final String INTERFACE = "com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpoint";
//
// }
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtilTest.java
import com.kumuluz.ee.jaxws.cxf.impl.NoWsContextAnnotatedEndpointBean;
import com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpointBean;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.util.stream.Stream;
import static org.junit.Assert.*;
package com.kumuluz.ee.jaxws.cxf.processor;
public class JaxWsAnnotationProcessorUtilTest {
private JaxWsAnnotationProcessorUtil instance = JaxWsAnnotationProcessorUtil.getInstance();
@Test
public void shouldReturnDefaultWsInfo() {
| String className = NoWsContextAnnotatedEndpointBean.class.getName(); |
kumuluz/kumuluzee | components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtilTest.java | // Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/NoWsContextAnnotatedEndpointBean.java
// @WebService
// public class NoWsContextAnnotatedEndpointBean {
// }
//
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WsContextAnnotatedEndpointBean.java
// @WsContext(contextRoot = WsContextAnnotatedEndpointBean.CTX_ROOT, urlPattern = WsContextAnnotatedEndpointBean.URL_PATTERN)
// @WebService(wsdlLocation = WsContextAnnotatedEndpointBean.WSDL_URL, portName = WsContextAnnotatedEndpointBean.PORT, serviceName =
// WsContextAnnotatedEndpointBean.SERVICE, endpointInterface = WsContextAnnotatedEndpointBean.INTERFACE)
// public class WsContextAnnotatedEndpointBean implements WsContextAnnotatedEndpoint {
//
// public static final String WSDL_URL = "http://cloud.si/example.wsdl";
// public static final String CTX_ROOT = "/ws/*";
// public static final String URL_PATTERN = "/endpoint";
// public static final String PORT = "EndpointPort";
// public static final String SERVICE = "ServiceName";
// public static final String INTERFACE = "com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpoint";
//
// }
| import com.kumuluz.ee.jaxws.cxf.impl.NoWsContextAnnotatedEndpointBean;
import com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpointBean;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.util.stream.Stream;
import static org.junit.Assert.*; | package com.kumuluz.ee.jaxws.cxf.processor;
public class JaxWsAnnotationProcessorUtilTest {
private JaxWsAnnotationProcessorUtil instance = JaxWsAnnotationProcessorUtil.getInstance();
@Test
public void shouldReturnDefaultWsInfo() {
String className = NoWsContextAnnotatedEndpointBean.class.getName();
Class<?> clazz = NoWsContextAnnotatedEndpointBean.class;
prepareEndpointList(className);
instance.reinitialize();
String expectedContextRoot = "/*";
String expectedUrl = "/" + className;
//check implementation class
assertEquals("Ws endpoint returned wrong implementation value", clazz, instance.getEndpointList().get(0).getImplementationClass());
//assert @WsContext
assertEquals("Ws endpoint without defined contextRoot returned wrong value", expectedContextRoot, instance.getContextRoot());
assertFalse(instance.getEndpointList().isEmpty());
assertEquals("Ws endpoint without defined url returned wrong value", expectedUrl, instance.getEndpointList().get(0).getUrl());
//assert @Webservice
assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).wsdlLocation());
assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).portName());
assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).serviceName());
}
@Test
public void shouldReturnConfiguredWsInfo() {
| // Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/NoWsContextAnnotatedEndpointBean.java
// @WebService
// public class NoWsContextAnnotatedEndpointBean {
// }
//
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WsContextAnnotatedEndpointBean.java
// @WsContext(contextRoot = WsContextAnnotatedEndpointBean.CTX_ROOT, urlPattern = WsContextAnnotatedEndpointBean.URL_PATTERN)
// @WebService(wsdlLocation = WsContextAnnotatedEndpointBean.WSDL_URL, portName = WsContextAnnotatedEndpointBean.PORT, serviceName =
// WsContextAnnotatedEndpointBean.SERVICE, endpointInterface = WsContextAnnotatedEndpointBean.INTERFACE)
// public class WsContextAnnotatedEndpointBean implements WsContextAnnotatedEndpoint {
//
// public static final String WSDL_URL = "http://cloud.si/example.wsdl";
// public static final String CTX_ROOT = "/ws/*";
// public static final String URL_PATTERN = "/endpoint";
// public static final String PORT = "EndpointPort";
// public static final String SERVICE = "ServiceName";
// public static final String INTERFACE = "com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpoint";
//
// }
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtilTest.java
import com.kumuluz.ee.jaxws.cxf.impl.NoWsContextAnnotatedEndpointBean;
import com.kumuluz.ee.jaxws.cxf.impl.WsContextAnnotatedEndpointBean;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.util.stream.Stream;
import static org.junit.Assert.*;
package com.kumuluz.ee.jaxws.cxf.processor;
public class JaxWsAnnotationProcessorUtilTest {
private JaxWsAnnotationProcessorUtil instance = JaxWsAnnotationProcessorUtil.getInstance();
@Test
public void shouldReturnDefaultWsInfo() {
String className = NoWsContextAnnotatedEndpointBean.class.getName();
Class<?> clazz = NoWsContextAnnotatedEndpointBean.class;
prepareEndpointList(className);
instance.reinitialize();
String expectedContextRoot = "/*";
String expectedUrl = "/" + className;
//check implementation class
assertEquals("Ws endpoint returned wrong implementation value", clazz, instance.getEndpointList().get(0).getImplementationClass());
//assert @WsContext
assertEquals("Ws endpoint without defined contextRoot returned wrong value", expectedContextRoot, instance.getContextRoot());
assertFalse(instance.getEndpointList().isEmpty());
assertEquals("Ws endpoint without defined url returned wrong value", expectedUrl, instance.getEndpointList().get(0).getUrl());
//assert @Webservice
assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).wsdlLocation());
assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).portName());
assertNull("Ws endpoint without defined wsdlLocation returned wrong value", instance.getEndpointList().get(0).serviceName());
}
@Test
public void shouldReturnConfiguredWsInfo() {
| String className = WsContextAnnotatedEndpointBean.class.getName(); |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationUtil.java | // Path: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationDecoder.java
// public interface ConfigurationDecoder {
//
// /**
// * Check if key's value should be decoded.
// *
// * @param key configuration key to be checked for decoding
// * @return returns true if key's value should be decoded with the decode(String key, String value) method
// */
// boolean shouldDecode(String key);
//
// /**
// * Decode values of encoded keys.
// *
// * @param key encoded key
// * @param value encoded value
// * @return decoded value
// */
// String decode(String key, String value);
// }
| import com.kumuluz.ee.configuration.ConfigurationDecoder;
import com.kumuluz.ee.configuration.ConfigurationListener;
import com.kumuluz.ee.configuration.ConfigurationSource;
import com.kumuluz.ee.configuration.enums.ConfigurationValueType;
import java.util.*; | mapKeys.add(s);
}
}
}
}
if (mapKeys.isEmpty()) {
return Optional.empty();
}
return Optional.of(new ArrayList<>(mapKeys));
}
public void subscribe(String key, ConfigurationListener listener) {
config.getDispatcher().subscribe(listener);
for (ConfigurationSource configurationSource : config.getConfigurationSources()) {
configurationSource.watch(key);
}
}
public void unsubscribe(ConfigurationListener listener) {
config.getDispatcher().unsubscribe(listener);
}
public List<ConfigurationSource> getConfigurationSources() {
return Collections.unmodifiableList(this.config.getConfigurationSources());
}
| // Path: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationDecoder.java
// public interface ConfigurationDecoder {
//
// /**
// * Check if key's value should be decoded.
// *
// * @param key configuration key to be checked for decoding
// * @return returns true if key's value should be decoded with the decode(String key, String value) method
// */
// boolean shouldDecode(String key);
//
// /**
// * Decode values of encoded keys.
// *
// * @param key encoded key
// * @param value encoded value
// * @return decoded value
// */
// String decode(String key, String value);
// }
// Path: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationUtil.java
import com.kumuluz.ee.configuration.ConfigurationDecoder;
import com.kumuluz.ee.configuration.ConfigurationListener;
import com.kumuluz.ee.configuration.ConfigurationSource;
import com.kumuluz.ee.configuration.enums.ConfigurationValueType;
import java.util.*;
mapKeys.add(s);
}
}
}
}
if (mapKeys.isEmpty()) {
return Optional.empty();
}
return Optional.of(new ArrayList<>(mapKeys));
}
public void subscribe(String key, ConfigurationListener listener) {
config.getDispatcher().subscribe(listener);
for (ConfigurationSource configurationSource : config.getConfigurationSources()) {
configurationSource.watch(key);
}
}
public void unsubscribe(ConfigurationListener listener) {
config.getDispatcher().unsubscribe(listener);
}
public List<ConfigurationSource> getConfigurationSources() {
return Collections.unmodifiableList(this.config.getConfigurationSources());
}
| public ConfigurationDecoder getConfigurationDecoder() { |
kumuluz/kumuluzee | components/jta/common/src/main/java/com/kumuluz/ee/jta/common/datasources/JtaXAConnectionWrapper.java | // Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java
// public class TxUtils {
//
// public static Boolean isActive(TransactionManager transactionManager) {
//
// try {
// Transaction tx = transactionManager.getTransaction();
//
// return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
// } catch (SystemException e) {
// throw new CannotRetrieveTxException(e);
// }
// }
// }
| import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import com.kumuluz.ee.jta.common.JtaProvider;
import com.kumuluz.ee.jta.common.utils.TxUtils;
import javax.sql.XAConnection;
import javax.transaction.RollbackException;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import java.sql.*; | jtaPreInvoke();
return xaConnection.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
checkIfValid();
jtaPreInvoke();
return xaConnection.isWrapperFor(iface);
}
private void checkIfValid() throws SQLException {
if (isClosed) throw new SQLException("The connection is closed");
if (xaConnection == null) throw new SQLException("The connection is invalid");
}
private void jtaPreInvoke() throws SQLException {
if (isEnlistedInJTA) return;
try {
if (transactionManager == null) {
transactionManager = JtaProvider.getInstance().getTransactionManager();
}
| // Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java
// public class TxUtils {
//
// public static Boolean isActive(TransactionManager transactionManager) {
//
// try {
// Transaction tx = transactionManager.getTransaction();
//
// return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
// } catch (SystemException e) {
// throw new CannotRetrieveTxException(e);
// }
// }
// }
// Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/datasources/JtaXAConnectionWrapper.java
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import com.kumuluz.ee.jta.common.JtaProvider;
import com.kumuluz.ee.jta.common.utils.TxUtils;
import javax.sql.XAConnection;
import javax.transaction.RollbackException;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
import java.sql.*;
jtaPreInvoke();
return xaConnection.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
checkIfValid();
jtaPreInvoke();
return xaConnection.isWrapperFor(iface);
}
private void checkIfValid() throws SQLException {
if (isClosed) throw new SQLException("The connection is closed");
if (xaConnection == null) throw new SQLException("The connection is invalid");
}
private void jtaPreInvoke() throws SQLException {
if (isEnlistedInJTA) return;
try {
if (transactionManager == null) {
transactionManager = JtaProvider.getInstance().getTransactionManager();
}
| if (TxUtils.isActive(transactionManager)) { |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationImpl.java | // Path: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationDecoder.java
// public interface ConfigurationDecoder {
//
// /**
// * Check if key's value should be decoded.
// *
// * @param key configuration key to be checked for decoding
// * @return returns true if key's value should be decoded with the decode(String key, String value) method
// */
// boolean shouldDecode(String key);
//
// /**
// * Decode values of encoded keys.
// *
// * @param key encoded key
// * @param value encoded value
// * @return decoded value
// */
// String decode(String key, String value);
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Logger;
import com.kumuluz.ee.configuration.ConfigurationDecoder;
import com.kumuluz.ee.configuration.ConfigurationSource; | /*
* Copyright (c) 2014-2019 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.configuration.utils;
/**
* @author Tilen Faganel
* @since 2.1.0
*/
public class ConfigurationImpl {
private Logger utilLogger;
private ConfigurationDispatcher dispatcher;
private List<ConfigurationSource> configurationSources; | // Path: common/src/main/java/com/kumuluz/ee/configuration/ConfigurationDecoder.java
// public interface ConfigurationDecoder {
//
// /**
// * Check if key's value should be decoded.
// *
// * @param key configuration key to be checked for decoding
// * @return returns true if key's value should be decoded with the decode(String key, String value) method
// */
// boolean shouldDecode(String key);
//
// /**
// * Decode values of encoded keys.
// *
// * @param key encoded key
// * @param value encoded value
// * @return decoded value
// */
// String decode(String key, String value);
// }
// Path: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationImpl.java
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Logger;
import com.kumuluz.ee.configuration.ConfigurationDecoder;
import com.kumuluz.ee.configuration.ConfigurationSource;
/*
* Copyright (c) 2014-2019 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.configuration.utils;
/**
* @author Tilen Faganel
* @since 2.1.0
*/
public class ConfigurationImpl {
private Logger utilLogger;
private ConfigurationDispatcher dispatcher;
private List<ConfigurationSource> configurationSources; | private ConfigurationDecoder configurationDecoder; |
kumuluz/kumuluzee | components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/ws/KumuluzWebServiceContextTest.java | // Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WebServiceContextBean.java
// public class WebServiceContextBean implements WebServiceContext {
//
// MessageContext messageContext;
//
// public WebServiceContextBean(String id) {
// MessageImpl message = new MessageImpl();
// message.put("id", id);
// messageContext = new LogicalMessageContextImpl(message);
// }
//
// @Override
// public MessageContext getMessageContext() {
// return messageContext;
// }
//
// @Override
// public Principal getUserPrincipal() {
// return null;
// }
//
// @Override
// public boolean isUserInRole(String role) {
// return false;
// }
//
// @Override
// public EndpointReference getEndpointReference(Element... referenceParameters) {
// return null;
// }
//
// @Override
// public <T extends EndpointReference> T getEndpointReference(Class<T> clazz, Element... referenceParameters) {
// return null;
// }
// }
| import com.kumuluz.ee.jaxws.cxf.impl.WebServiceContextBean;
import org.junit.Test;
import static org.junit.Assert.assertTrue; | package com.kumuluz.ee.jaxws.cxf.ws;
public class KumuluzWebServiceContextTest {
@Test
public void shouldUseRightContext() throws InterruptedException {
WsThread one = new WsThread();
WsThread two = new WsThread();
one.start();
two.start();
one.join();
two.join();
assertTrue("Thread 1 context not properly propagated", one.isSuccessful());
assertTrue("Thread 2 context not properly propagated", two.isSuccessful());
}
public static class WsThread extends Thread {
private boolean successful = true;
public void run() {
String threadName = Thread.currentThread().getName();
| // Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/impl/WebServiceContextBean.java
// public class WebServiceContextBean implements WebServiceContext {
//
// MessageContext messageContext;
//
// public WebServiceContextBean(String id) {
// MessageImpl message = new MessageImpl();
// message.put("id", id);
// messageContext = new LogicalMessageContextImpl(message);
// }
//
// @Override
// public MessageContext getMessageContext() {
// return messageContext;
// }
//
// @Override
// public Principal getUserPrincipal() {
// return null;
// }
//
// @Override
// public boolean isUserInRole(String role) {
// return false;
// }
//
// @Override
// public EndpointReference getEndpointReference(Element... referenceParameters) {
// return null;
// }
//
// @Override
// public <T extends EndpointReference> T getEndpointReference(Class<T> clazz, Element... referenceParameters) {
// return null;
// }
// }
// Path: components/jax-ws/cxf/src/test/java/com/kumuluz/ee/jaxws/cxf/ws/KumuluzWebServiceContextTest.java
import com.kumuluz.ee.jaxws.cxf.impl.WebServiceContextBean;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
package com.kumuluz.ee.jaxws.cxf.ws;
public class KumuluzWebServiceContextTest {
@Test
public void shouldUseRightContext() throws InterruptedException {
WsThread one = new WsThread();
WsThread two = new WsThread();
one.start();
two.start();
one.join();
two.join();
assertTrue("Thread 1 context not properly propagated", one.isSuccessful());
assertTrue("Thread 2 context not properly propagated", two.isSuccessful());
}
public static class WsThread extends Thread {
private boolean successful = true;
public void run() {
String threadName = Thread.currentThread().getName();
| KumuluzWebServiceContext.getInstance().setMessageContext(new WebServiceContextBean(threadName)); |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/common/ServletServer.java | // Path: common/src/main/java/com/kumuluz/ee/common/servlet/ServletWrapper.java
// public class ServletWrapper {
//
// private String name;
// private String contextPath;
//
// public ServletWrapper(String name, String contextPath) {
// this.name = name;
// this.contextPath = contextPath;
// }
//
// public String getName() {
// return name;
// }
//
// public String getContextPath() {
// return contextPath;
// }
// }
| import com.kumuluz.ee.common.servlet.ServletWrapper;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;
import java.util.*; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common;
/**
* @author Tilen Faganel
* @since 1.0.0
*/
public interface ServletServer extends KumuluzServer {
void registerServlet(Class<? extends Servlet> servletClass, String mapping);
void registerServlet(Class<? extends Servlet> servletClass, String mapping, Map<String, String> parameters);
void registerServlet(Class<? extends Servlet> servletClass, String mapping, Map<String, String> parameters, int initOrder);
void registerListener(EventListener listener);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec, Map<String, String> parameters);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec, EnumSet<DispatcherType> dispatches);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec, EnumSet<DispatcherType> dispatches, Map<String, String> parameters);
void registerResource(Object o, String jndiName);
void registerDataSource(DataSource ds, String jndiName);
void registerTransactionManager(UserTransaction userTransaction);
void initWebContext(List<String> scanLibraries);
| // Path: common/src/main/java/com/kumuluz/ee/common/servlet/ServletWrapper.java
// public class ServletWrapper {
//
// private String name;
// private String contextPath;
//
// public ServletWrapper(String name, String contextPath) {
// this.name = name;
// this.contextPath = contextPath;
// }
//
// public String getName() {
// return name;
// }
//
// public String getContextPath() {
// return contextPath;
// }
// }
// Path: common/src/main/java/com/kumuluz/ee/common/ServletServer.java
import com.kumuluz.ee.common.servlet.ServletWrapper;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;
import java.util.*;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common;
/**
* @author Tilen Faganel
* @since 1.0.0
*/
public interface ServletServer extends KumuluzServer {
void registerServlet(Class<? extends Servlet> servletClass, String mapping);
void registerServlet(Class<? extends Servlet> servletClass, String mapping, Map<String, String> parameters);
void registerServlet(Class<? extends Servlet> servletClass, String mapping, Map<String, String> parameters, int initOrder);
void registerListener(EventListener listener);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec, Map<String, String> parameters);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec, EnumSet<DispatcherType> dispatches);
void registerFilter(Class<? extends Filter> filterClass, String pathSpec, EnumSet<DispatcherType> dispatches, Map<String, String> parameters);
void registerResource(Object o, String jndiName);
void registerDataSource(DataSource ds, String jndiName);
void registerTransactionManager(UserTransaction userTransaction);
void initWebContext(List<String> scanLibraries);
| List<ServletWrapper> getRegisteredServlets(); |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/common/wrapper/KumuluzServerWrapper.java | // Path: common/src/main/java/com/kumuluz/ee/common/KumuluzServer.java
// public interface KumuluzServer {
//
// void initServer();
//
// void startServer();
//
// void stopServer();
//
// void setServerConfig(ServerConfig serverConfig);
//
// ServerConfig getServerConfig();
// }
//
// Path: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentType.java
// public enum EeComponentType {
//
// SERVLET("Servlet"),
//
// WEBSOCKET("WebSocket"),
//
// JSP("JSP"),
//
// EL("EL"),
//
// JSF("JSF"),
//
// JPA("JPA"),
//
// CDI("CDI"),
//
// JAX_RS("JAX-RS"),
//
// JAX_WS("JAX-WS"),
//
// BEAN_VALIDATION("Bean Validation"),
//
// JSON_P("JSON-P"),
//
// JSON_B("JSON-B"),
//
// JTA("JTA"),
//
// EJB("EJB"),
//
// BATCH("Batch"),
//
// MAIL("JavaMail");
//
// private final String name;
//
// EeComponentType(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
// }
| import java.util.List;
import com.kumuluz.ee.common.KumuluzServer;
import com.kumuluz.ee.common.dependencies.EeComponentType; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common.wrapper;
/**
* @author Tilen Faganel
* @since 2.0.0
*/
public class KumuluzServerWrapper {
private KumuluzServer server;
private String name; | // Path: common/src/main/java/com/kumuluz/ee/common/KumuluzServer.java
// public interface KumuluzServer {
//
// void initServer();
//
// void startServer();
//
// void stopServer();
//
// void setServerConfig(ServerConfig serverConfig);
//
// ServerConfig getServerConfig();
// }
//
// Path: common/src/main/java/com/kumuluz/ee/common/dependencies/EeComponentType.java
// public enum EeComponentType {
//
// SERVLET("Servlet"),
//
// WEBSOCKET("WebSocket"),
//
// JSP("JSP"),
//
// EL("EL"),
//
// JSF("JSF"),
//
// JPA("JPA"),
//
// CDI("CDI"),
//
// JAX_RS("JAX-RS"),
//
// JAX_WS("JAX-WS"),
//
// BEAN_VALIDATION("Bean Validation"),
//
// JSON_P("JSON-P"),
//
// JSON_B("JSON-B"),
//
// JTA("JTA"),
//
// EJB("EJB"),
//
// BATCH("Batch"),
//
// MAIL("JavaMail");
//
// private final String name;
//
// EeComponentType(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
// }
// Path: common/src/main/java/com/kumuluz/ee/common/wrapper/KumuluzServerWrapper.java
import java.util.List;
import com.kumuluz.ee.common.KumuluzServer;
import com.kumuluz.ee.common.dependencies.EeComponentType;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common.wrapper;
/**
* @author Tilen Faganel
* @since 2.0.0
*/
public class KumuluzServerWrapper {
private KumuluzServer server;
private String name; | private EeComponentType[] providedEeComponents; |
kumuluz/kumuluzee | tools/loader/src/main/java/com/kumuluz/ee/loader/jar/JarEntryInfo.java | // Path: tools/loader/src/main/java/com/kumuluz/ee/loader/exception/EeClassLoaderException.java
// public class EeClassLoaderException extends RuntimeException {
//
// public EeClassLoaderException(String message) {
// super(message);
// }
//
// public EeClassLoaderException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public String getMessageAll() {
// StringBuilder stringBuilder = new StringBuilder();
//
// for (Throwable e = this; e != null; e = e.getCause()) {
// if (stringBuilder.length() > 0) {
// stringBuilder.append(" / ");
// }
//
// String message = e.getMessage();
// if (message == null || message.length() == 0) {
// message = e.getClass().getSimpleName();
// }
//
// stringBuilder.append(message);
// }
//
// return stringBuilder.toString();
// }
// }
| import java.util.jar.JarEntry;
import com.kumuluz.ee.loader.exception.EeClassLoaderException;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; |
public void setJarFileInfo(JarFileInfo jarFileInfo) {
this.jarFileInfo = jarFileInfo;
}
public JarEntry getJarEntry() {
return jarEntry;
}
public void setJarEntry(JarEntry jarEntry) {
this.jarEntry = jarEntry;
}
public URL getURL() { // used in findResource() and findResources()
try {
String jarFileName = new File(jarFileInfo.getJarFile().getName()).toURI().toString();
URI uri = new URI("jar:" + jarFileName + "!/" + jarEntry);
return uri.toURL();
} catch (URISyntaxException | MalformedURLException e) {
return null;
}
}
public String getName() { // used in createTempFile() and loadJar()
return jarEntry.getName().replace('/', '_');
}
/**
* Read JAR entry and return byte array of this JAR entry.
*/ | // Path: tools/loader/src/main/java/com/kumuluz/ee/loader/exception/EeClassLoaderException.java
// public class EeClassLoaderException extends RuntimeException {
//
// public EeClassLoaderException(String message) {
// super(message);
// }
//
// public EeClassLoaderException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public String getMessageAll() {
// StringBuilder stringBuilder = new StringBuilder();
//
// for (Throwable e = this; e != null; e = e.getCause()) {
// if (stringBuilder.length() > 0) {
// stringBuilder.append(" / ");
// }
//
// String message = e.getMessage();
// if (message == null || message.length() == 0) {
// message = e.getClass().getSimpleName();
// }
//
// stringBuilder.append(message);
// }
//
// return stringBuilder.toString();
// }
// }
// Path: tools/loader/src/main/java/com/kumuluz/ee/loader/jar/JarEntryInfo.java
import java.util.jar.JarEntry;
import com.kumuluz.ee.loader.exception.EeClassLoaderException;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public void setJarFileInfo(JarFileInfo jarFileInfo) {
this.jarFileInfo = jarFileInfo;
}
public JarEntry getJarEntry() {
return jarEntry;
}
public void setJarEntry(JarEntry jarEntry) {
this.jarEntry = jarEntry;
}
public URL getURL() { // used in findResource() and findResources()
try {
String jarFileName = new File(jarFileInfo.getJarFile().getName()).toURI().toString();
URI uri = new URI("jar:" + jarFileName + "!/" + jarEntry);
return uri.toURL();
} catch (URISyntaxException | MalformedURLException e) {
return null;
}
}
public String getName() { // used in createTempFile() and loadJar()
return jarEntry.getName().replace('/', '_');
}
/**
* Read JAR entry and return byte array of this JAR entry.
*/ | public byte[] getJarBytes() throws EeClassLoaderException { |
kumuluz/kumuluzee | components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtil.java | // Path: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/Endpoint.java
// public class Endpoint {
//
// private String url;
// private Class<?> implementationClass;
// private WebService ws;
//
// public Endpoint(Class<?> implementationClass, String url, WebService webService) {
// this.url = url;
// this.implementationClass = implementationClass;
// this.ws = webService;
// }
//
// public String getUrl() {
// return url != null ? url : defaultEndpointUrl();
// }
//
// public Class<?> getImplementationClass() {
// return implementationClass;
// }
//
// public String wsdlLocation() {
//
// if (ws == null) {
// return null;
// }
//
// return ws.wsdlLocation() != null && ws.wsdlLocation().isEmpty() ? null : ws.wsdlLocation();
// }
//
// private String defaultEndpointUrl() {
//
// if (ws == null || implementationClass == null) {
// return null;
// }
//
// return "/" + implementationClass.getName();
// }
//
// public String serviceName() {
//
// if (ws == null) {
// return null;
// }
//
// return ws.serviceName() != null && ws.serviceName().isEmpty() ? null : ws.serviceName();
// }
//
// public String portName() {
//
// if (ws == null) {
// return null;
// }
//
// return ws.portName() != null && ws.portName().isEmpty() ? null : ws.portName();
// }
// }
| import com.kumuluz.ee.jaxws.cxf.annotations.WsContext;
import com.kumuluz.ee.jaxws.cxf.ws.Endpoint;
import javax.jws.WebService;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger; | /*
* Copyright (c) 2014-2018 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.jaxws.cxf.processor;
/**
* @author gpor89
* @since 3.0.0
*/
public class JaxWsAnnotationProcessorUtil {
private static final Logger LOG = Logger.getLogger(JaxWsAnnotationProcessorUtil.class.getName());
private static final JaxWsAnnotationProcessorUtil INSTANCE = new JaxWsAnnotationProcessorUtil();
private static final String DEFAULT_CTX_ROOT = "/*";
private boolean initialized; | // Path: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/ws/Endpoint.java
// public class Endpoint {
//
// private String url;
// private Class<?> implementationClass;
// private WebService ws;
//
// public Endpoint(Class<?> implementationClass, String url, WebService webService) {
// this.url = url;
// this.implementationClass = implementationClass;
// this.ws = webService;
// }
//
// public String getUrl() {
// return url != null ? url : defaultEndpointUrl();
// }
//
// public Class<?> getImplementationClass() {
// return implementationClass;
// }
//
// public String wsdlLocation() {
//
// if (ws == null) {
// return null;
// }
//
// return ws.wsdlLocation() != null && ws.wsdlLocation().isEmpty() ? null : ws.wsdlLocation();
// }
//
// private String defaultEndpointUrl() {
//
// if (ws == null || implementationClass == null) {
// return null;
// }
//
// return "/" + implementationClass.getName();
// }
//
// public String serviceName() {
//
// if (ws == null) {
// return null;
// }
//
// return ws.serviceName() != null && ws.serviceName().isEmpty() ? null : ws.serviceName();
// }
//
// public String portName() {
//
// if (ws == null) {
// return null;
// }
//
// return ws.portName() != null && ws.portName().isEmpty() ? null : ws.portName();
// }
// }
// Path: components/jax-ws/cxf/src/main/java/com/kumuluz/ee/jaxws/cxf/processor/JaxWsAnnotationProcessorUtil.java
import com.kumuluz.ee.jaxws.cxf.annotations.WsContext;
import com.kumuluz.ee.jaxws.cxf.ws.Endpoint;
import javax.jws.WebService;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
/*
* Copyright (c) 2014-2018 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.jaxws.cxf.processor;
/**
* @author gpor89
* @since 3.0.0
*/
public class JaxWsAnnotationProcessorUtil {
private static final Logger LOG = Logger.getLogger(JaxWsAnnotationProcessorUtil.class.getName());
private static final JaxWsAnnotationProcessorUtil INSTANCE = new JaxWsAnnotationProcessorUtil();
private static final String DEFAULT_CTX_ROOT = "/*";
private boolean initialized; | private List<Endpoint> endpointList; |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/common/KumuluzServer.java | // Path: common/src/main/java/com/kumuluz/ee/common/config/ServerConfig.java
// public class ServerConfig {
//
// public static class Builder {
//
// private String baseUrl;
// private String contextPath = "/";
// private Boolean dirBrowsing = false;
// private Boolean etags = false;
// private Integer minThreads = 5;
// private Integer maxThreads = 100;
// private Boolean forceHttps = false;
// private Boolean showServerInfo = true;
// private Boolean forwardStartupException;
//
// private ServerConnectorConfig.Builder http = new ServerConnectorConfig.Builder();
// private ServerConnectorConfig.Builder https;
//
// private GzipConfig.Builder gzip;
//
// public Builder baseUrl(String baseUrl) {
// this.baseUrl = baseUrl;
// return this;
// }
//
// public Builder contextPath(String contextPath) {
// this.contextPath = contextPath;
// return this;
// }
//
// public Builder dirBrowsing(Boolean dirBrowsing) {
// this.dirBrowsing = dirBrowsing;
// return this;
// }
//
// public Builder etags(Boolean etags) {
// this.etags = etags;
// return this;
// }
//
// public Builder minThreads(Integer minThreads) {
// this.minThreads = minThreads;
// return this;
// }
//
// public Builder maxThreads(Integer maxThreads) {
// this.maxThreads = maxThreads;
// return this;
// }
//
// public Builder forceHttps(Boolean forceHttps) {
// this.forceHttps = forceHttps;
// return this;
// }
//
// public Builder http(ServerConnectorConfig.Builder http) {
// this.http = http;
// return this;
// }
//
// public Builder https(ServerConnectorConfig.Builder https) {
// this.https = https;
// return this;
// }
//
// public Builder gzip(GzipConfig.Builder gzip) {
// this.gzip = gzip;
// return this;
// }
//
// public Builder showServerInfo(Boolean showServerInfo) {
// this.showServerInfo = showServerInfo;
// return this;
// }
//
// public Builder forwardStartupException(Boolean forwardStartupException) {
// this.forwardStartupException = forwardStartupException;
// return this;
// }
//
// public ServerConfig build() {
//
// ServerConfig serverConfig = new ServerConfig();
// serverConfig.baseUrl = baseUrl;
// serverConfig.contextPath = contextPath;
// serverConfig.dirBrowsing = dirBrowsing;
// serverConfig.etags = etags;
// serverConfig.minThreads = minThreads;
// serverConfig.maxThreads = maxThreads;
// serverConfig.forceHttps = forceHttps;
// serverConfig.showServerInfo = showServerInfo;
// serverConfig.forwardStartupException = forwardStartupException;
//
// serverConfig.http = http.build();
// if (https != null) serverConfig.https = https.build();
//
// if (gzip != null) serverConfig.gzip = gzip.build();
//
// return serverConfig;
// }
// }
//
// private String baseUrl;
// private String contextPath;
// private Boolean dirBrowsing;
// private Boolean etags;
// private Integer minThreads;
// private Integer maxThreads;
// private Boolean forceHttps;
// private Boolean showServerInfo;
// private Boolean forwardStartupException;
//
// private ServerConnectorConfig http;
// private ServerConnectorConfig https;
//
// private GzipConfig gzip;
//
// private ServerConfig() {
// }
//
// public String getBaseUrl() {
// return baseUrl;
// }
//
// public String getContextPath() {
// return contextPath;
// }
//
// public Boolean getDirBrowsing() {
// return dirBrowsing;
// }
//
// public Boolean getEtags() {
// return etags;
// }
//
// public Integer getMinThreads() {
// return minThreads;
// }
//
// public Integer getMaxThreads() {
// return maxThreads;
// }
//
// public Boolean getForceHttps() {
// return forceHttps;
// }
//
// public Boolean getShowServerInfo(){
// return showServerInfo;
// }
//
// public Boolean getForwardStartupException() {
// return forwardStartupException;
// }
//
// public ServerConnectorConfig getHttp() {
// return http;
// }
//
// public ServerConnectorConfig getHttps() {
// return https;
// }
//
// public GzipConfig getGzip() {
// return gzip;
// }
// }
| import java.util.EventListener;
import java.util.Map;
import javax.servlet.Servlet;
import com.kumuluz.ee.common.config.ServerConfig; | /*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common;
/**
* @author Tilen Faganel
* @since 1.0.0
*/
public interface KumuluzServer {
void initServer();
void startServer();
void stopServer();
| // Path: common/src/main/java/com/kumuluz/ee/common/config/ServerConfig.java
// public class ServerConfig {
//
// public static class Builder {
//
// private String baseUrl;
// private String contextPath = "/";
// private Boolean dirBrowsing = false;
// private Boolean etags = false;
// private Integer minThreads = 5;
// private Integer maxThreads = 100;
// private Boolean forceHttps = false;
// private Boolean showServerInfo = true;
// private Boolean forwardStartupException;
//
// private ServerConnectorConfig.Builder http = new ServerConnectorConfig.Builder();
// private ServerConnectorConfig.Builder https;
//
// private GzipConfig.Builder gzip;
//
// public Builder baseUrl(String baseUrl) {
// this.baseUrl = baseUrl;
// return this;
// }
//
// public Builder contextPath(String contextPath) {
// this.contextPath = contextPath;
// return this;
// }
//
// public Builder dirBrowsing(Boolean dirBrowsing) {
// this.dirBrowsing = dirBrowsing;
// return this;
// }
//
// public Builder etags(Boolean etags) {
// this.etags = etags;
// return this;
// }
//
// public Builder minThreads(Integer minThreads) {
// this.minThreads = minThreads;
// return this;
// }
//
// public Builder maxThreads(Integer maxThreads) {
// this.maxThreads = maxThreads;
// return this;
// }
//
// public Builder forceHttps(Boolean forceHttps) {
// this.forceHttps = forceHttps;
// return this;
// }
//
// public Builder http(ServerConnectorConfig.Builder http) {
// this.http = http;
// return this;
// }
//
// public Builder https(ServerConnectorConfig.Builder https) {
// this.https = https;
// return this;
// }
//
// public Builder gzip(GzipConfig.Builder gzip) {
// this.gzip = gzip;
// return this;
// }
//
// public Builder showServerInfo(Boolean showServerInfo) {
// this.showServerInfo = showServerInfo;
// return this;
// }
//
// public Builder forwardStartupException(Boolean forwardStartupException) {
// this.forwardStartupException = forwardStartupException;
// return this;
// }
//
// public ServerConfig build() {
//
// ServerConfig serverConfig = new ServerConfig();
// serverConfig.baseUrl = baseUrl;
// serverConfig.contextPath = contextPath;
// serverConfig.dirBrowsing = dirBrowsing;
// serverConfig.etags = etags;
// serverConfig.minThreads = minThreads;
// serverConfig.maxThreads = maxThreads;
// serverConfig.forceHttps = forceHttps;
// serverConfig.showServerInfo = showServerInfo;
// serverConfig.forwardStartupException = forwardStartupException;
//
// serverConfig.http = http.build();
// if (https != null) serverConfig.https = https.build();
//
// if (gzip != null) serverConfig.gzip = gzip.build();
//
// return serverConfig;
// }
// }
//
// private String baseUrl;
// private String contextPath;
// private Boolean dirBrowsing;
// private Boolean etags;
// private Integer minThreads;
// private Integer maxThreads;
// private Boolean forceHttps;
// private Boolean showServerInfo;
// private Boolean forwardStartupException;
//
// private ServerConnectorConfig http;
// private ServerConnectorConfig https;
//
// private GzipConfig gzip;
//
// private ServerConfig() {
// }
//
// public String getBaseUrl() {
// return baseUrl;
// }
//
// public String getContextPath() {
// return contextPath;
// }
//
// public Boolean getDirBrowsing() {
// return dirBrowsing;
// }
//
// public Boolean getEtags() {
// return etags;
// }
//
// public Integer getMinThreads() {
// return minThreads;
// }
//
// public Integer getMaxThreads() {
// return maxThreads;
// }
//
// public Boolean getForceHttps() {
// return forceHttps;
// }
//
// public Boolean getShowServerInfo(){
// return showServerInfo;
// }
//
// public Boolean getForwardStartupException() {
// return forwardStartupException;
// }
//
// public ServerConnectorConfig getHttp() {
// return http;
// }
//
// public ServerConnectorConfig getHttps() {
// return https;
// }
//
// public GzipConfig getGzip() {
// return gzip;
// }
// }
// Path: common/src/main/java/com/kumuluz/ee/common/KumuluzServer.java
import java.util.EventListener;
import java.util.Map;
import javax.servlet.Servlet;
import com.kumuluz.ee.common.config.ServerConfig;
/*
* Copyright (c) 2014-2017 Kumuluz and/or its affiliates
* and other contributors as indicated by the @author tags and
* the contributor list.
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. in no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the software or the use or other dealings in the
* software. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kumuluz.ee.common;
/**
* @author Tilen Faganel
* @since 1.0.0
*/
public interface KumuluzServer {
void initServer();
void startServer();
void stopServer();
| void setServerConfig(ServerConfig serverConfig); |
kumuluz/kumuluzee | common/src/main/java/com/kumuluz/ee/configuration/sources/FileConfigurationSource.java | // Path: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationDispatcher.java
// public class ConfigurationDispatcher {
//
// private List<ConfigurationListener> subscriptions = new ArrayList<>();
//
// public void notifyChange(String key, String value) {
//
// for (ConfigurationListener subscription : subscriptions) {
// subscription.onChange(key, value);
// }
// }
//
// public void subscribe(ConfigurationListener listener) {
// subscriptions.add(listener);
// }
//
// public void unsubscribe(ConfigurationListener listener) {
// subscriptions.remove(listener);
// }
// }
| import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import com.kumuluz.ee.configuration.ConfigurationSource;
import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher;
import com.kumuluz.ee.configuration.utils.ConfigurationSourceUtils;
import com.kumuluz.ee.logs.LogDeferrer;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths; | public FileConfigurationSource() {
this.ymlFileName = "config.yml";
this.yamlFileName = "config.yaml";
this.propertiesFileName = "config.properties";
this.microProfilePropertiesFileName = "META-INF/microprofile-config.properties";
String configurationFileName = System.getProperty("com.kumuluz.ee.configuration.file");
if (configurationFileName != null && !configurationFileName.isEmpty()) {
this.ymlFileName = configurationFileName;
this.yamlFileName = configurationFileName;
this.propertiesFileName = configurationFileName;
}
this.logDeferrer = new LogDeferrer<>();
this.logDeferrer.init(() -> Logger.getLogger(FileConfigurationSource.class.getName()));
}
public void postInit() {
logDeferrer.execute();
logDeferrer = null;
log = Logger.getLogger(FileConfigurationSource.class.getName());
}
@Override
@SuppressWarnings("unchecked") | // Path: common/src/main/java/com/kumuluz/ee/configuration/utils/ConfigurationDispatcher.java
// public class ConfigurationDispatcher {
//
// private List<ConfigurationListener> subscriptions = new ArrayList<>();
//
// public void notifyChange(String key, String value) {
//
// for (ConfigurationListener subscription : subscriptions) {
// subscription.onChange(key, value);
// }
// }
//
// public void subscribe(ConfigurationListener listener) {
// subscriptions.add(listener);
// }
//
// public void unsubscribe(ConfigurationListener listener) {
// subscriptions.remove(listener);
// }
// }
// Path: common/src/main/java/com/kumuluz/ee/configuration/sources/FileConfigurationSource.java
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import com.kumuluz.ee.configuration.ConfigurationSource;
import com.kumuluz.ee.configuration.utils.ConfigurationDispatcher;
import com.kumuluz.ee.configuration.utils.ConfigurationSourceUtils;
import com.kumuluz.ee.logs.LogDeferrer;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public FileConfigurationSource() {
this.ymlFileName = "config.yml";
this.yamlFileName = "config.yaml";
this.propertiesFileName = "config.properties";
this.microProfilePropertiesFileName = "META-INF/microprofile-config.properties";
String configurationFileName = System.getProperty("com.kumuluz.ee.configuration.file");
if (configurationFileName != null && !configurationFileName.isEmpty()) {
this.ymlFileName = configurationFileName;
this.yamlFileName = configurationFileName;
this.propertiesFileName = configurationFileName;
}
this.logDeferrer = new LogDeferrer<>();
this.logDeferrer.init(() -> Logger.getLogger(FileConfigurationSource.class.getName()));
}
public void postInit() {
logDeferrer.execute();
logDeferrer = null;
log = Logger.getLogger(FileConfigurationSource.class.getName());
}
@Override
@SuppressWarnings("unchecked") | public void init(ConfigurationDispatcher configurationDispatcher) { |
kumuluz/kumuluzee | components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/TxScopedEntityManager.java | // Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java
// public class TxUtils {
//
// public static Boolean isActive(TransactionManager transactionManager) {
//
// try {
// Transaction tx = transactionManager.getTransaction();
//
// return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
// } catch (SystemException e) {
// throw new CannotRetrieveTxException(e);
// }
// }
// }
| import java.util.List;
import java.util.Map;
import com.kumuluz.ee.jta.common.utils.TxUtils;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.metamodel.Metamodel;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry; | @Override
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return getEntityManager().createEntityGraph(rootType);
}
@Override
public EntityGraph<?> createEntityGraph(String graphName) {
return getEntityManager().createEntityGraph(graphName);
}
@Override
public EntityGraph<?> getEntityGraph(String graphName) {
return getEntityManager().getEntityGraph(graphName);
}
@Override
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return getEntityManager().getEntityGraphs(entityClass);
}
//// Private logic methods
private EntityManager getEntityManager() {
EntityManager em;
| // Path: components/jta/common/src/main/java/com/kumuluz/ee/jta/common/utils/TxUtils.java
// public class TxUtils {
//
// public static Boolean isActive(TransactionManager transactionManager) {
//
// try {
// Transaction tx = transactionManager.getTransaction();
//
// return tx != null && JtaProvider.TRANSACTION_ACTIVE_STATUS.contains(tx.getStatus());
// } catch (SystemException e) {
// throw new CannotRetrieveTxException(e);
// }
// }
// }
// Path: components/jpa/common/src/main/java/com/kumuluz/ee/jpa/common/jta/TxScopedEntityManager.java
import java.util.List;
import java.util.Map;
import com.kumuluz.ee.jta.common.utils.TxUtils;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.metamodel.Metamodel;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
@Override
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return getEntityManager().createEntityGraph(rootType);
}
@Override
public EntityGraph<?> createEntityGraph(String graphName) {
return getEntityManager().createEntityGraph(graphName);
}
@Override
public EntityGraph<?> getEntityGraph(String graphName) {
return getEntityManager().getEntityGraph(graphName);
}
@Override
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return getEntityManager().getEntityGraphs(entityClass);
}
//// Private logic methods
private EntityManager getEntityManager() {
EntityManager em;
| if (TxUtils.isActive(transactionManager)) { |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/client/IGCMClientTick.java | // Path: src/main/java/com/creativemd/igcm/packets/OpenGUIPacket.java
// public class OpenGUIPacket extends CreativeCorePacket {
//
// public OpenGUIPacket() {
//
// }
//
// @Override
// public void writeBytes(ByteBuf buf) {
//
// }
//
// @Override
// public void readBytes(ByteBuf buf) {
//
// }
//
// @Override
// public void executeClient(EntityPlayer player) {
//
// }
//
// @Override
// public void executeServer(EntityPlayer player) {
// if (IGCM.gui.checkPermission(player.getServer(), player))
// IGCMGuiManager.openConfigGui(player);
// }
//
// }
| import com.creativemd.creativecore.common.gui.mc.ContainerSub;
import com.creativemd.creativecore.common.packet.PacketHandler;
import com.creativemd.igcm.packets.OpenGUIPacket;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.RenderTickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package com.creativemd.igcm.client;
@SideOnly(Side.CLIENT)
public class IGCMClientTick {
public Minecraft mc = Minecraft.getMinecraft();
@SubscribeEvent
public void openGui(RenderTickEvent event) {
if (mc.player != null && mc.world != null) {
if (mc.gameSettings.isKeyDown(IGCMClient.openConfig) && mc.player != null && mc.inGameHasFocus && !(mc.player.openContainer instanceof ContainerSub)) | // Path: src/main/java/com/creativemd/igcm/packets/OpenGUIPacket.java
// public class OpenGUIPacket extends CreativeCorePacket {
//
// public OpenGUIPacket() {
//
// }
//
// @Override
// public void writeBytes(ByteBuf buf) {
//
// }
//
// @Override
// public void readBytes(ByteBuf buf) {
//
// }
//
// @Override
// public void executeClient(EntityPlayer player) {
//
// }
//
// @Override
// public void executeServer(EntityPlayer player) {
// if (IGCM.gui.checkPermission(player.getServer(), player))
// IGCMGuiManager.openConfigGui(player);
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/client/IGCMClientTick.java
import com.creativemd.creativecore.common.gui.mc.ContainerSub;
import com.creativemd.creativecore.common.packet.PacketHandler;
import com.creativemd.igcm.packets.OpenGUIPacket;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.RenderTickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
package com.creativemd.igcm.client;
@SideOnly(Side.CLIENT)
public class IGCMClientTick {
public Minecraft mc = Minecraft.getMinecraft();
@SubscribeEvent
public void openGui(RenderTickEvent event) {
if (mc.player != null && mc.world != null) {
if (mc.gameSettings.isKeyDown(IGCMClient.openConfig) && mc.player != null && mc.inGameHasFocus && !(mc.player.openContainer instanceof ContainerSub)) | PacketHandler.sendPacketToServer(new OpenGUIPacket()); |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/api/ConfigGroupElement.java | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
//
// Path: src/main/java/com/creativemd/igcm/utils/SearchUtils.java
// public class SearchUtils {
//
// public static boolean canStackBeFound(ItemStack stack, String search) {
// try {
// if (stack.getItem() instanceof ItemBlock)
// if (Block.REGISTRY.getNameForObject(Block.getBlockFromItem(stack.getItem())).toString().toLowerCase().contains(search))
// return true;
// else if (Item.REGISTRY.getNameForObject(stack.getItem()).toString().toLowerCase().contains(search))
// return true;
//
// return stack.getDisplayName().toLowerCase().contains(search);
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean canInfoBeFound(InfoStack info, String search) {
// return info == null ? false : canStackBeFound(info.getItemStack(), search);
// }
//
// }
| import java.util.ArrayList;
import com.creativemd.creativecore.client.avatar.AvatarItemStack;
import com.creativemd.creativecore.common.gui.ContainerControl;
import com.creativemd.creativecore.common.gui.GuiControl;
import com.creativemd.creativecore.common.gui.container.SubContainer;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiAvatarButton;
import com.creativemd.igcm.IGCMGuiManager;
import com.creativemd.igcm.utils.SearchUtils;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package com.creativemd.igcm.api;
public abstract class ConfigGroupElement extends ConfigSegment {
public ItemStack avatar;
public ConfigGroupElement(String title, ItemStack avatar) {
super(title);
this.avatar = avatar;
}
public ArrayList<ContainerControl> createContainerControls(SubContainer container, int x, int y, int maxWidth) {
return new ArrayList<>();
}
@SideOnly(Side.CLIENT)
public ArrayList<GuiControl> createGuiControls(SubGui gui, int x, int y, int maxWidth) {
ArrayList<GuiControl> controls = new ArrayList<>();
controls.add(new GuiAvatarButton(getPath(), title, x + 5, y, 155, 16, new AvatarItemStack(avatar)) {
@Override
public void onClicked(int x, int y, int button) { | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
//
// Path: src/main/java/com/creativemd/igcm/utils/SearchUtils.java
// public class SearchUtils {
//
// public static boolean canStackBeFound(ItemStack stack, String search) {
// try {
// if (stack.getItem() instanceof ItemBlock)
// if (Block.REGISTRY.getNameForObject(Block.getBlockFromItem(stack.getItem())).toString().toLowerCase().contains(search))
// return true;
// else if (Item.REGISTRY.getNameForObject(stack.getItem()).toString().toLowerCase().contains(search))
// return true;
//
// return stack.getDisplayName().toLowerCase().contains(search);
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean canInfoBeFound(InfoStack info, String search) {
// return info == null ? false : canStackBeFound(info.getItemStack(), search);
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/api/ConfigGroupElement.java
import java.util.ArrayList;
import com.creativemd.creativecore.client.avatar.AvatarItemStack;
import com.creativemd.creativecore.common.gui.ContainerControl;
import com.creativemd.creativecore.common.gui.GuiControl;
import com.creativemd.creativecore.common.gui.container.SubContainer;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiAvatarButton;
import com.creativemd.igcm.IGCMGuiManager;
import com.creativemd.igcm.utils.SearchUtils;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
package com.creativemd.igcm.api;
public abstract class ConfigGroupElement extends ConfigSegment {
public ItemStack avatar;
public ConfigGroupElement(String title, ItemStack avatar) {
super(title);
this.avatar = avatar;
}
public ArrayList<ContainerControl> createContainerControls(SubContainer container, int x, int y, int maxWidth) {
return new ArrayList<>();
}
@SideOnly(Side.CLIENT)
public ArrayList<GuiControl> createGuiControls(SubGui gui, int x, int y, int maxWidth) {
ArrayList<GuiControl> controls = new ArrayList<>();
controls.add(new GuiAvatarButton(getPath(), title, x + 5, y, 155, 16, new AvatarItemStack(avatar)) {
@Override
public void onClicked(int x, int y, int button) { | IGCMGuiManager.openConfigGui(gui.getPlayer(), this.name); |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/api/ConfigGroupElement.java | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
//
// Path: src/main/java/com/creativemd/igcm/utils/SearchUtils.java
// public class SearchUtils {
//
// public static boolean canStackBeFound(ItemStack stack, String search) {
// try {
// if (stack.getItem() instanceof ItemBlock)
// if (Block.REGISTRY.getNameForObject(Block.getBlockFromItem(stack.getItem())).toString().toLowerCase().contains(search))
// return true;
// else if (Item.REGISTRY.getNameForObject(stack.getItem()).toString().toLowerCase().contains(search))
// return true;
//
// return stack.getDisplayName().toLowerCase().contains(search);
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean canInfoBeFound(InfoStack info, String search) {
// return info == null ? false : canStackBeFound(info.getItemStack(), search);
// }
//
// }
| import java.util.ArrayList;
import com.creativemd.creativecore.client.avatar.AvatarItemStack;
import com.creativemd.creativecore.common.gui.ContainerControl;
import com.creativemd.creativecore.common.gui.GuiControl;
import com.creativemd.creativecore.common.gui.container.SubContainer;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiAvatarButton;
import com.creativemd.igcm.IGCMGuiManager;
import com.creativemd.igcm.utils.SearchUtils;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package com.creativemd.igcm.api;
public abstract class ConfigGroupElement extends ConfigSegment {
public ItemStack avatar;
public ConfigGroupElement(String title, ItemStack avatar) {
super(title);
this.avatar = avatar;
}
public ArrayList<ContainerControl> createContainerControls(SubContainer container, int x, int y, int maxWidth) {
return new ArrayList<>();
}
@SideOnly(Side.CLIENT)
public ArrayList<GuiControl> createGuiControls(SubGui gui, int x, int y, int maxWidth) {
ArrayList<GuiControl> controls = new ArrayList<>();
controls.add(new GuiAvatarButton(getPath(), title, x + 5, y, 155, 16, new AvatarItemStack(avatar)) {
@Override
public void onClicked(int x, int y, int button) {
IGCMGuiManager.openConfigGui(gui.getPlayer(), this.name);
}
});
return controls;
}
@Override
public boolean contains(String search) { | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
//
// Path: src/main/java/com/creativemd/igcm/utils/SearchUtils.java
// public class SearchUtils {
//
// public static boolean canStackBeFound(ItemStack stack, String search) {
// try {
// if (stack.getItem() instanceof ItemBlock)
// if (Block.REGISTRY.getNameForObject(Block.getBlockFromItem(stack.getItem())).toString().toLowerCase().contains(search))
// return true;
// else if (Item.REGISTRY.getNameForObject(stack.getItem()).toString().toLowerCase().contains(search))
// return true;
//
// return stack.getDisplayName().toLowerCase().contains(search);
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean canInfoBeFound(InfoStack info, String search) {
// return info == null ? false : canStackBeFound(info.getItemStack(), search);
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/api/ConfigGroupElement.java
import java.util.ArrayList;
import com.creativemd.creativecore.client.avatar.AvatarItemStack;
import com.creativemd.creativecore.common.gui.ContainerControl;
import com.creativemd.creativecore.common.gui.GuiControl;
import com.creativemd.creativecore.common.gui.container.SubContainer;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiAvatarButton;
import com.creativemd.igcm.IGCMGuiManager;
import com.creativemd.igcm.utils.SearchUtils;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
package com.creativemd.igcm.api;
public abstract class ConfigGroupElement extends ConfigSegment {
public ItemStack avatar;
public ConfigGroupElement(String title, ItemStack avatar) {
super(title);
this.avatar = avatar;
}
public ArrayList<ContainerControl> createContainerControls(SubContainer container, int x, int y, int maxWidth) {
return new ArrayList<>();
}
@SideOnly(Side.CLIENT)
public ArrayList<GuiControl> createGuiControls(SubGui gui, int x, int y, int maxWidth) {
ArrayList<GuiControl> controls = new ArrayList<>();
controls.add(new GuiAvatarButton(getPath(), title, x + 5, y, 155, 16, new AvatarItemStack(avatar)) {
@Override
public void onClicked(int x, int y, int button) {
IGCMGuiManager.openConfigGui(gui.getPlayer(), this.name);
}
});
return controls;
}
@Override
public boolean contains(String search) { | return title.toLowerCase().contains(search) || key.toLowerCase().contains(search) || SearchUtils.canStackBeFound(avatar, search); |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/command/CommandGUI.java | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
| import com.creativemd.igcm.IGCMGuiManager;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer; | package com.creativemd.igcm.command;
public class CommandGUI extends CommandBase {
@Override
public String getName() {
return "ConfigManager";
}
@Override
public String getUsage(ICommandSender icommandsender) {
return "/ConfigManager";
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
if (sender instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) sender; | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/command/CommandGUI.java
import com.creativemd.igcm.IGCMGuiManager;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
package com.creativemd.igcm.command;
public class CommandGUI extends CommandBase {
@Override
public String getName() {
return "ConfigManager";
}
@Override
public String getUsage(ICommandSender icommandsender) {
return "/ConfigManager";
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
if (sender instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) sender; | IGCMGuiManager.openConfigGui(player); |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/jei/AdvRecipeWrapper.java | // Path: src/main/java/com/creativemd/igcm/block/AdvancedGridRecipe.java
// public class AdvancedGridRecipe extends GridRecipe {
//
// public int duration;
//
// public AdvancedGridRecipe(ItemStack[] output, int width, int height, InfoStack[] input, int duration) {
// super(output, width, height, input);
// this.duration = duration;
// }
//
// }
| import java.util.Arrays;
import java.util.List;
import javax.annotation.Nonnull;
import com.creativemd.igcm.block.AdvancedGridRecipe;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.IStackHelper;
import mezz.jei.api.recipe.wrapper.IShapedCraftingRecipeWrapper;
import net.minecraft.item.ItemStack; | package com.creativemd.igcm.jei;
public class AdvRecipeWrapper implements IRecipeWrapper, IShapedCraftingRecipeWrapper {
@Nonnull | // Path: src/main/java/com/creativemd/igcm/block/AdvancedGridRecipe.java
// public class AdvancedGridRecipe extends GridRecipe {
//
// public int duration;
//
// public AdvancedGridRecipe(ItemStack[] output, int width, int height, InfoStack[] input, int duration) {
// super(output, width, height, input);
// this.duration = duration;
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/jei/AdvRecipeWrapper.java
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nonnull;
import com.creativemd.igcm.block.AdvancedGridRecipe;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.ingredients.IIngredients;
import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jei.api.recipe.IStackHelper;
import mezz.jei.api.recipe.wrapper.IShapedCraftingRecipeWrapper;
import net.minecraft.item.ItemStack;
package com.creativemd.igcm.jei;
public class AdvRecipeWrapper implements IRecipeWrapper, IShapedCraftingRecipeWrapper {
@Nonnull | private final AdvancedGridRecipe recipe; |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/api/segments/advanced/InfoSegment.java | // Path: src/main/java/com/creativemd/igcm/api/segments/ValueSegment.java
// public abstract class ValueSegment<T> extends ConfigSegment implements ICommandSupport {
//
// public T defaultValue;
//
// public T value;
//
// public ValueSegment(String title, T defaultValue) {
// super(title);
// this.value = defaultValue;
// this.defaultValue = defaultValue;
// }
//
// @Override
// public void initDefault() {
// value = defaultValue;
// super.initDefault();
// }
//
// @Override
// public boolean contains(String search) {
// if (title != null && title.toLowerCase().contains(search))
// return true;
// if (value != null && value.toString().toLowerCase().contains(search))
// return true;
// return getKey().toLowerCase().contains(search);
// }
//
// public abstract void set(T newValue);
//
// @Override
// public boolean hasCommandSupport() {
// return CommandParser.canParseObject(value.getClass());
// }
//
// @Override
// public void parseValue(String arg) throws CommandException {
// set((T) CommandParser.parseObject(arg, value.getClass()));
// }
//
// @Override
// public String printValue() {
// return CommandParser.printObject(value);
// }
//
// @Override
// public String printDefaultValue() {
// return CommandParser.printObject(defaultValue);
// }
//
// @Override
// public String[] getPossibleValues() {
// if (value instanceof Boolean)
// return new String[] { "true", "false" };
// return null;
// }
// }
//
// Path: src/main/java/com/creativemd/igcm/container/controls/InfoSlotControl.java
// public class InfoSlotControl extends SlotControlNoSync {
//
// public InfoStack info;
// public InventoryBasic inventory;
//
// public InfoSlotControl(IInventory inventory, int index, int x, int y, InfoStack info) {
// super(new SlotPreview(inventory, index, x, y));
// this.info = info;
// inventory = (InventoryBasic) slot.inventory;
// if (info != null)
// slot.putStack(info.getItemStack());
// }
//
// public void putInfo(InfoStack info) {
// this.info = info;
// if (info != null)
// slot.putStack(info.getItemStack());
// else
// slot.putStack(ItemStack.EMPTY);
// }
//
// }
//
// Path: src/main/java/com/creativemd/igcm/utils/SearchUtils.java
// public class SearchUtils {
//
// public static boolean canStackBeFound(ItemStack stack, String search) {
// try {
// if (stack.getItem() instanceof ItemBlock)
// if (Block.REGISTRY.getNameForObject(Block.getBlockFromItem(stack.getItem())).toString().toLowerCase().contains(search))
// return true;
// else if (Item.REGISTRY.getNameForObject(stack.getItem()).toString().toLowerCase().contains(search))
// return true;
//
// return stack.getDisplayName().toLowerCase().contains(search);
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean canInfoBeFound(InfoStack info, String search) {
// return info == null ? false : canStackBeFound(info.getItemStack(), search);
// }
//
// }
| import java.lang.reflect.Modifier;
import java.util.ArrayList;
import com.creativemd.creativecore.common.gui.ContainerControl;
import com.creativemd.creativecore.common.gui.GuiControl;
import com.creativemd.creativecore.common.gui.GuiRenderHelper;
import com.creativemd.creativecore.common.gui.container.SubContainer;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiLabel;
import com.creativemd.creativecore.common.utils.stack.InfoBlock;
import com.creativemd.creativecore.common.utils.stack.InfoContainOre;
import com.creativemd.creativecore.common.utils.stack.InfoFuel;
import com.creativemd.creativecore.common.utils.stack.InfoItem;
import com.creativemd.creativecore.common.utils.stack.InfoItemStack;
import com.creativemd.creativecore.common.utils.stack.InfoMaterial;
import com.creativemd.creativecore.common.utils.stack.InfoName;
import com.creativemd.creativecore.common.utils.stack.InfoOre;
import com.creativemd.creativecore.common.utils.stack.InfoStack;
import com.creativemd.igcm.api.segments.ValueSegment;
import com.creativemd.igcm.container.controls.InfoSlotControl;
import com.creativemd.igcm.utils.SearchUtils;
import com.mojang.realmsclient.gui.ChatFormatting;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; |
InventoryBasic basic = new InventoryBasic(getKey(), false, 1);
slots.add(new InfoSlotControl(basic, 0, x + 5, y + 5, value) {
@Override
public void putInfo(InfoStack info) {
super.putInfo(info);
label.caption = getLabelText(info);
label.width = GuiRenderHelper.instance.font.getStringWidth(label.caption) + label.getContentOffset() * 2;
}
});
return slots;
}
@Override
public void loadExtra(NBTTagCompound nbt) {
value = InfoStack.parseNBT(nbt);
}
@Override
public void saveExtra(NBTTagCompound nbt) {
if (value != null)
value.writeToNBT(nbt);
}
@Override
public boolean contains(String search) {
if (!super.contains(search)) {
if (value != null) | // Path: src/main/java/com/creativemd/igcm/api/segments/ValueSegment.java
// public abstract class ValueSegment<T> extends ConfigSegment implements ICommandSupport {
//
// public T defaultValue;
//
// public T value;
//
// public ValueSegment(String title, T defaultValue) {
// super(title);
// this.value = defaultValue;
// this.defaultValue = defaultValue;
// }
//
// @Override
// public void initDefault() {
// value = defaultValue;
// super.initDefault();
// }
//
// @Override
// public boolean contains(String search) {
// if (title != null && title.toLowerCase().contains(search))
// return true;
// if (value != null && value.toString().toLowerCase().contains(search))
// return true;
// return getKey().toLowerCase().contains(search);
// }
//
// public abstract void set(T newValue);
//
// @Override
// public boolean hasCommandSupport() {
// return CommandParser.canParseObject(value.getClass());
// }
//
// @Override
// public void parseValue(String arg) throws CommandException {
// set((T) CommandParser.parseObject(arg, value.getClass()));
// }
//
// @Override
// public String printValue() {
// return CommandParser.printObject(value);
// }
//
// @Override
// public String printDefaultValue() {
// return CommandParser.printObject(defaultValue);
// }
//
// @Override
// public String[] getPossibleValues() {
// if (value instanceof Boolean)
// return new String[] { "true", "false" };
// return null;
// }
// }
//
// Path: src/main/java/com/creativemd/igcm/container/controls/InfoSlotControl.java
// public class InfoSlotControl extends SlotControlNoSync {
//
// public InfoStack info;
// public InventoryBasic inventory;
//
// public InfoSlotControl(IInventory inventory, int index, int x, int y, InfoStack info) {
// super(new SlotPreview(inventory, index, x, y));
// this.info = info;
// inventory = (InventoryBasic) slot.inventory;
// if (info != null)
// slot.putStack(info.getItemStack());
// }
//
// public void putInfo(InfoStack info) {
// this.info = info;
// if (info != null)
// slot.putStack(info.getItemStack());
// else
// slot.putStack(ItemStack.EMPTY);
// }
//
// }
//
// Path: src/main/java/com/creativemd/igcm/utils/SearchUtils.java
// public class SearchUtils {
//
// public static boolean canStackBeFound(ItemStack stack, String search) {
// try {
// if (stack.getItem() instanceof ItemBlock)
// if (Block.REGISTRY.getNameForObject(Block.getBlockFromItem(stack.getItem())).toString().toLowerCase().contains(search))
// return true;
// else if (Item.REGISTRY.getNameForObject(stack.getItem()).toString().toLowerCase().contains(search))
// return true;
//
// return stack.getDisplayName().toLowerCase().contains(search);
// } catch (Exception e) {
// return false;
// }
// }
//
// public static boolean canInfoBeFound(InfoStack info, String search) {
// return info == null ? false : canStackBeFound(info.getItemStack(), search);
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/api/segments/advanced/InfoSegment.java
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import com.creativemd.creativecore.common.gui.ContainerControl;
import com.creativemd.creativecore.common.gui.GuiControl;
import com.creativemd.creativecore.common.gui.GuiRenderHelper;
import com.creativemd.creativecore.common.gui.container.SubContainer;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiLabel;
import com.creativemd.creativecore.common.utils.stack.InfoBlock;
import com.creativemd.creativecore.common.utils.stack.InfoContainOre;
import com.creativemd.creativecore.common.utils.stack.InfoFuel;
import com.creativemd.creativecore.common.utils.stack.InfoItem;
import com.creativemd.creativecore.common.utils.stack.InfoItemStack;
import com.creativemd.creativecore.common.utils.stack.InfoMaterial;
import com.creativemd.creativecore.common.utils.stack.InfoName;
import com.creativemd.creativecore.common.utils.stack.InfoOre;
import com.creativemd.creativecore.common.utils.stack.InfoStack;
import com.creativemd.igcm.api.segments.ValueSegment;
import com.creativemd.igcm.container.controls.InfoSlotControl;
import com.creativemd.igcm.utils.SearchUtils;
import com.mojang.realmsclient.gui.ChatFormatting;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
InventoryBasic basic = new InventoryBasic(getKey(), false, 1);
slots.add(new InfoSlotControl(basic, 0, x + 5, y + 5, value) {
@Override
public void putInfo(InfoStack info) {
super.putInfo(info);
label.caption = getLabelText(info);
label.width = GuiRenderHelper.instance.font.getStringWidth(label.caption) + label.getContentOffset() * 2;
}
});
return slots;
}
@Override
public void loadExtra(NBTTagCompound nbt) {
value = InfoStack.parseNBT(nbt);
}
@Override
public void saveExtra(NBTTagCompound nbt) {
if (value != null)
value.writeToNBT(nbt);
}
@Override
public boolean contains(String search) {
if (!super.contains(search)) {
if (value != null) | return SearchUtils.canInfoBeFound(value, search); |
CreativeMD/IGCM | src/main/java/com/creativemd/igcm/client/gui/SubGuiProfile.java | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiButton;
import com.creativemd.creativecore.common.gui.controls.gui.GuiComboBox;
import com.creativemd.creativecore.common.gui.controls.gui.GuiLabel;
import com.creativemd.creativecore.common.gui.controls.gui.GuiTextfield;
import com.creativemd.igcm.IGCMGuiManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString; |
GuiComboBox box = new GuiComboBox("profiles", 5, 5, 100, profiles);
box.caption = current;
controls.add(box);
controls.add(new GuiButton("Remove", 120, 5, 40) {
@Override
public void onClicked(int x, int y, int button) {
GuiComboBox combobox = (GuiComboBox) get("profiles");
if (combobox.lines.size() > 1) {
combobox.lines.remove(combobox.caption);
combobox.caption = combobox.lines.get(0);
}
}
});
controls.add(new GuiTextfield("Name", "", 5, 40, 100, 16));
controls.add(new GuiButton("Add", 120, 40, 40) {
@Override
public void onClicked(int x, int y, int button) {
GuiTextfield field = (GuiTextfield) get("name");
if (!field.text.equals("")) {
GuiComboBox combobox = (GuiComboBox) get("profiles");
if (!combobox.lines.contains(field.text))
combobox.lines.add(field.text);
}
}
});
controls.add(new GuiButton("Cancel", 5, 228, 40) {
@Override
public void onClicked(int x, int y, int button) { | // Path: src/main/java/com/creativemd/igcm/IGCMGuiManager.java
// public class IGCMGuiManager extends CustomGuiHandler {
//
// public static void openConfigGui(EntityPlayer player) {
// openConfigGui(player, "root");
// }
//
// public static void openConfigGui(EntityPlayer player, String path) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 0);
// nbt.setString("path", path);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// public static void openProfileGui(EntityPlayer player) {
// NBTTagCompound nbt = new NBTTagCompound();
// nbt.setInteger("gui", 1);
// nbt.setInteger("index", 0);
// GuiHandler.openGui(IGCM.guiID, nbt, player);
// }
//
// @Override
// public SubContainer getContainer(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubContainerConfigSegment(player, ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubContainerProfile(player);
// case 2:
// return new SubContainerAdvancedWorkbench(player);
// }
// return null;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public SubGui getGui(EntityPlayer player, NBTTagCompound nbt) {
// int gui = nbt.getInteger("gui");
// String name = nbt.getString("path");
// switch (gui) {
// case 0:
// return new SubGuiConfigSegement(ConfigTab.getSegmentByPath(name));
// case 1:
// return new SubGuiProfile();
// case 2:
// return new SubGuiAdvancedWorkbench();
// }
// return null;
// }
//
// }
// Path: src/main/java/com/creativemd/igcm/client/gui/SubGuiProfile.java
import java.util.ArrayList;
import java.util.List;
import com.creativemd.creativecore.common.gui.container.SubGui;
import com.creativemd.creativecore.common.gui.controls.gui.GuiButton;
import com.creativemd.creativecore.common.gui.controls.gui.GuiComboBox;
import com.creativemd.creativecore.common.gui.controls.gui.GuiLabel;
import com.creativemd.creativecore.common.gui.controls.gui.GuiTextfield;
import com.creativemd.igcm.IGCMGuiManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
GuiComboBox box = new GuiComboBox("profiles", 5, 5, 100, profiles);
box.caption = current;
controls.add(box);
controls.add(new GuiButton("Remove", 120, 5, 40) {
@Override
public void onClicked(int x, int y, int button) {
GuiComboBox combobox = (GuiComboBox) get("profiles");
if (combobox.lines.size() > 1) {
combobox.lines.remove(combobox.caption);
combobox.caption = combobox.lines.get(0);
}
}
});
controls.add(new GuiTextfield("Name", "", 5, 40, 100, 16));
controls.add(new GuiButton("Add", 120, 40, 40) {
@Override
public void onClicked(int x, int y, int button) {
GuiTextfield field = (GuiTextfield) get("name");
if (!field.text.equals("")) {
GuiComboBox combobox = (GuiComboBox) get("profiles");
if (!combobox.lines.contains(field.text))
combobox.lines.add(field.text);
}
}
});
controls.add(new GuiButton("Cancel", 5, 228, 40) {
@Override
public void onClicked(int x, int y, int button) { | IGCMGuiManager.openConfigGui(getPlayer()); |
marmelo/chili | chili/src/test/java/me/defying/chili/mix/MixTestService.java | // Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
| import me.defying.chili.Log;
import me.defying.chili.Memoize;
import me.defying.chili.Timeout;
import me.defying.chili.memoize.Wrap; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.mix;
/**
* Test service for multiple annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MixTestService {
@Log
@Memoize
@Timeout | // Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
// Path: chili/src/test/java/me/defying/chili/mix/MixTestService.java
import me.defying.chili.Log;
import me.defying.chili.Memoize;
import me.defying.chili.Timeout;
import me.defying.chili.memoize.Wrap;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.mix;
/**
* Test service for multiple annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MixTestService {
@Log
@Memoize
@Timeout | public Wrap simple(final String x) { |
marmelo/chili | chili/src/main/java/me/defying/chili/timeout/TimeoutInterceptor.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
| import me.defying.chili.Timeout;
import me.defying.chili.module.ChiliException;
import me.defying.chili.util.InvocationUtils;
import java.util.concurrent.Callable;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.timeout;
/**
* Guice interceptor for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutInterceptor implements MethodInterceptor {
/**
* Constructs an instance of <code>TimeoutInterceptor</code>.
*/
public TimeoutInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// get annotation, class, method and arguments | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
// Path: chili/src/main/java/me/defying/chili/timeout/TimeoutInterceptor.java
import me.defying.chili.Timeout;
import me.defying.chili.module.ChiliException;
import me.defying.chili.util.InvocationUtils;
import java.util.concurrent.Callable;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.timeout;
/**
* Guice interceptor for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutInterceptor implements MethodInterceptor {
/**
* Constructs an instance of <code>TimeoutInterceptor</code>.
*/
public TimeoutInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// get annotation, class, method and arguments | final Timeout annotation = InvocationUtils.getAnnotation(invocation, Timeout.class); |
marmelo/chili | chili/src/main/java/me/defying/chili/timeout/TimeoutInterceptor.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
| import me.defying.chili.Timeout;
import me.defying.chili.module.ChiliException;
import me.defying.chili.util.InvocationUtils;
import java.util.concurrent.Callable;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.timeout;
/**
* Guice interceptor for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutInterceptor implements MethodInterceptor {
/**
* Constructs an instance of <code>TimeoutInterceptor</code>.
*/
public TimeoutInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// get annotation, class, method and arguments
final Timeout annotation = InvocationUtils.getAnnotation(invocation, Timeout.class);
// do nothing
if (annotation.time() <= 0) {
return invocation.proceed();
}
final TimeLimiter limiter = new SimpleTimeLimiter();
// underlying method invoker
final Callable<Object> invoker = new TimeoutInvoker(invocation);
try {
return limiter.callWithTimeout(invoker, annotation.time(), annotation.unit(), true);
} catch (UncheckedTimeoutException ex) {
throw new TimeoutException(ex); | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
// Path: chili/src/main/java/me/defying/chili/timeout/TimeoutInterceptor.java
import me.defying.chili.Timeout;
import me.defying.chili.module.ChiliException;
import me.defying.chili.util.InvocationUtils;
import java.util.concurrent.Callable;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.timeout;
/**
* Guice interceptor for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutInterceptor implements MethodInterceptor {
/**
* Constructs an instance of <code>TimeoutInterceptor</code>.
*/
public TimeoutInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// get annotation, class, method and arguments
final Timeout annotation = InvocationUtils.getAnnotation(invocation, Timeout.class);
// do nothing
if (annotation.time() <= 0) {
return invocation.proceed();
}
final TimeLimiter limiter = new SimpleTimeLimiter();
// underlying method invoker
final Callable<Object> invoker = new TimeoutInvoker(invocation);
try {
return limiter.callWithTimeout(invoker, annotation.time(), annotation.unit(), true);
} catch (UncheckedTimeoutException ex) {
throw new TimeoutException(ex); | } catch (ChiliException ex) { |
marmelo/chili | chili-example/src/main/java/me/defying/chili/example/MemoizeExample.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliModule.java
// public class ChiliModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Log.class), new LogInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Memoize.class), new MemoizeInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Timeout.class), new TimeoutInterceptor());
// bindInterceptor(Matchers.annotatedWith(ToString.class), new ToStringMatcher(), new ToStringInterceptor());
// }
// }
| import com.google.inject.Guice;
import com.google.inject.Injector;
import me.defying.chili.module.ChiliModule; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.example;
/**
* Example of {@code Memoize} annotation.
*
* <p>Please refer to {@code MemoizeTestService} for further examples.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeExample {
/**
* The entry point.
*
* @param args the command line arguments.
*/
public static void main(final String[] args) {
// create the injector | // Path: chili/src/main/java/me/defying/chili/module/ChiliModule.java
// public class ChiliModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Log.class), new LogInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Memoize.class), new MemoizeInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Timeout.class), new TimeoutInterceptor());
// bindInterceptor(Matchers.annotatedWith(ToString.class), new ToStringMatcher(), new ToStringInterceptor());
// }
// }
// Path: chili-example/src/main/java/me/defying/chili/example/MemoizeExample.java
import com.google.inject.Guice;
import com.google.inject.Injector;
import me.defying.chili.module.ChiliModule;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.example;
/**
* Example of {@code Memoize} annotation.
*
* <p>Please refer to {@code MemoizeTestService} for further examples.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeExample {
/**
* The entry point.
*
* @param args the command line arguments.
*/
public static void main(final String[] args) {
// create the injector | final Injector injector = Guice.createInjector(new ChiliModule()); |
marmelo/chili | chili/src/main/java/me/defying/chili/log/LogInterceptor.java | // Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
| import org.slf4j.LoggerFactory;
import me.defying.chili.Log;
import me.defying.chili.util.InvocationUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.log;
/**
* Guice interceptor for {@code Log} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class LogInterceptor implements MethodInterceptor {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);
/**
* Constructs an instance of <code>LogInterceptor</code>.
*/
public LogInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// get annotation, class, method and arguments | // Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
// Path: chili/src/main/java/me/defying/chili/log/LogInterceptor.java
import org.slf4j.LoggerFactory;
import me.defying.chili.Log;
import me.defying.chili.util.InvocationUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.log;
/**
* Guice interceptor for {@code Log} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class LogInterceptor implements MethodInterceptor {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);
/**
* Constructs an instance of <code>LogInterceptor</code>.
*/
public LogInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
// get annotation, class, method and arguments | final Log annotation = InvocationUtils.getAnnotation(invocation, Log.class); |
marmelo/chili | chili/src/test/java/me/defying/chili/ToStringTest.java | // Path: chili/src/test/java/me/defying/chili/tostring/BasicModifiersClass.java
// @ToString
// public class BasicModifiersClass {
// final int _default = 1;
// public final int _public = 2;
// private final int _private = 3;
// protected final int _protected = 4;
// transient final int _transient = 5;
// volatile int _volatile = 6;
// static final int _static = 7;
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/BasicTypesClass.java
// @ToString
// public class BasicTypesClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/EmptyClass.java
// @ToString
// public class EmptyClass {
// // empty
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/RestrictedFieldsClass.java
// @ToString(fields = { "c", "l", "s" })
// public class RestrictedFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/SimilarMethodsClass.java
// @ToString
// public class SimilarMethodsClass {
//
// public String someMethod() {
// return "someMethod";
// }
//
// public String toString(boolean arg) {
// return "toString";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/ToStringClass.java
// @ToString
// public class ToStringClass {
//
// @Override
// public String toString() {
// return "this will not be returned";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/UnknownFieldsClass.java
// @ToString(fields = { "c", "unknown", "i", "", "random" })
// public class UnknownFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import me.defying.chili.util.ChiliTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.inject.Inject;
import me.defying.chili.tostring.BasicModifiersClass;
import me.defying.chili.tostring.BasicTypesClass;
import me.defying.chili.tostring.EmptyClass;
import me.defying.chili.tostring.RestrictedFieldsClass;
import me.defying.chili.tostring.SimilarMethodsClass;
import me.defying.chili.tostring.ToStringClass;
import me.defying.chili.tostring.UnknownFieldsClass; | /*
* The MIT License (MIT)
* Copyright (c) 2018 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code ToString} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class ToStringTest extends ChiliTest {
@Inject | // Path: chili/src/test/java/me/defying/chili/tostring/BasicModifiersClass.java
// @ToString
// public class BasicModifiersClass {
// final int _default = 1;
// public final int _public = 2;
// private final int _private = 3;
// protected final int _protected = 4;
// transient final int _transient = 5;
// volatile int _volatile = 6;
// static final int _static = 7;
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/BasicTypesClass.java
// @ToString
// public class BasicTypesClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/EmptyClass.java
// @ToString
// public class EmptyClass {
// // empty
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/RestrictedFieldsClass.java
// @ToString(fields = { "c", "l", "s" })
// public class RestrictedFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/SimilarMethodsClass.java
// @ToString
// public class SimilarMethodsClass {
//
// public String someMethod() {
// return "someMethod";
// }
//
// public String toString(boolean arg) {
// return "toString";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/ToStringClass.java
// @ToString
// public class ToStringClass {
//
// @Override
// public String toString() {
// return "this will not be returned";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/UnknownFieldsClass.java
// @ToString(fields = { "c", "unknown", "i", "", "random" })
// public class UnknownFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/ToStringTest.java
import me.defying.chili.util.ChiliTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.inject.Inject;
import me.defying.chili.tostring.BasicModifiersClass;
import me.defying.chili.tostring.BasicTypesClass;
import me.defying.chili.tostring.EmptyClass;
import me.defying.chili.tostring.RestrictedFieldsClass;
import me.defying.chili.tostring.SimilarMethodsClass;
import me.defying.chili.tostring.ToStringClass;
import me.defying.chili.tostring.UnknownFieldsClass;
/*
* The MIT License (MIT)
* Copyright (c) 2018 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code ToString} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class ToStringTest extends ChiliTest {
@Inject | private EmptyClass emptyClass; |
marmelo/chili | chili/src/test/java/me/defying/chili/ToStringTest.java | // Path: chili/src/test/java/me/defying/chili/tostring/BasicModifiersClass.java
// @ToString
// public class BasicModifiersClass {
// final int _default = 1;
// public final int _public = 2;
// private final int _private = 3;
// protected final int _protected = 4;
// transient final int _transient = 5;
// volatile int _volatile = 6;
// static final int _static = 7;
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/BasicTypesClass.java
// @ToString
// public class BasicTypesClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/EmptyClass.java
// @ToString
// public class EmptyClass {
// // empty
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/RestrictedFieldsClass.java
// @ToString(fields = { "c", "l", "s" })
// public class RestrictedFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/SimilarMethodsClass.java
// @ToString
// public class SimilarMethodsClass {
//
// public String someMethod() {
// return "someMethod";
// }
//
// public String toString(boolean arg) {
// return "toString";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/ToStringClass.java
// @ToString
// public class ToStringClass {
//
// @Override
// public String toString() {
// return "this will not be returned";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/UnknownFieldsClass.java
// @ToString(fields = { "c", "unknown", "i", "", "random" })
// public class UnknownFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import me.defying.chili.util.ChiliTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.inject.Inject;
import me.defying.chili.tostring.BasicModifiersClass;
import me.defying.chili.tostring.BasicTypesClass;
import me.defying.chili.tostring.EmptyClass;
import me.defying.chili.tostring.RestrictedFieldsClass;
import me.defying.chili.tostring.SimilarMethodsClass;
import me.defying.chili.tostring.ToStringClass;
import me.defying.chili.tostring.UnknownFieldsClass; | /*
* The MIT License (MIT)
* Copyright (c) 2018 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code ToString} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class ToStringTest extends ChiliTest {
@Inject
private EmptyClass emptyClass;
@Inject | // Path: chili/src/test/java/me/defying/chili/tostring/BasicModifiersClass.java
// @ToString
// public class BasicModifiersClass {
// final int _default = 1;
// public final int _public = 2;
// private final int _private = 3;
// protected final int _protected = 4;
// transient final int _transient = 5;
// volatile int _volatile = 6;
// static final int _static = 7;
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/BasicTypesClass.java
// @ToString
// public class BasicTypesClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/EmptyClass.java
// @ToString
// public class EmptyClass {
// // empty
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/RestrictedFieldsClass.java
// @ToString(fields = { "c", "l", "s" })
// public class RestrictedFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/SimilarMethodsClass.java
// @ToString
// public class SimilarMethodsClass {
//
// public String someMethod() {
// return "someMethod";
// }
//
// public String toString(boolean arg) {
// return "toString";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/ToStringClass.java
// @ToString
// public class ToStringClass {
//
// @Override
// public String toString() {
// return "this will not be returned";
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/tostring/UnknownFieldsClass.java
// @ToString(fields = { "c", "unknown", "i", "", "random" })
// public class UnknownFieldsClass {
// private final boolean b = true;
// private final char c = 'a';
// private final int i = 1;
// private final long l = 2L;
// private final float f = 3.0f;
// private final double d = 4.0;
// private final String s = "string";
// private final List<String> list = ImmutableList.of("a", "b", "c");
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/ToStringTest.java
import me.defying.chili.util.ChiliTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.google.inject.Inject;
import me.defying.chili.tostring.BasicModifiersClass;
import me.defying.chili.tostring.BasicTypesClass;
import me.defying.chili.tostring.EmptyClass;
import me.defying.chili.tostring.RestrictedFieldsClass;
import me.defying.chili.tostring.SimilarMethodsClass;
import me.defying.chili.tostring.ToStringClass;
import me.defying.chili.tostring.UnknownFieldsClass;
/*
* The MIT License (MIT)
* Copyright (c) 2018 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code ToString} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class ToStringTest extends ChiliTest {
@Inject
private EmptyClass emptyClass;
@Inject | private BasicTypesClass basicTypesClass; |
marmelo/chili | chili/src/main/java/me/defying/chili/memoize/MemoizeInterceptor.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
| import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.defying.chili.Memoize;
import me.defying.chili.module.ChiliException;
import me.defying.chili.util.InvocationUtils;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import com.google.common.base.Optional;
import com.google.common.cache.Cache; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.memoize;
/**
* Guice interceptor for {@code Memoize} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeInterceptor implements MethodInterceptor {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(MemoizeInterceptor.class);
/**
* The cache.
*/
private final LoadingCache<Method, Cache<Object, Optional<Object>>> caches = CacheBuilder
.newBuilder()
.build(new MemoizeCacheLoader());
/**
* Constructs an instance of <code>MemoizeInterceptor</code>.
*/
public MemoizeInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
final Object result;
// get annotation, class, method and arguments | // Path: chili/src/main/java/me/defying/chili/module/ChiliException.java
// public class ChiliException extends Exception {
//
// /**
// * Creates a new instance of <code>ChiliException</code> without detail
// * message.
// */
// public ChiliException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public ChiliException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>ChiliException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public ChiliException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/main/java/me/defying/chili/util/InvocationUtils.java
// public final class InvocationUtils {
//
// /**
// * Prevent instantiation of utility class.
// */
// private InvocationUtils() {
// // emtpy
// }
//
// /**
// * Returns the annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the annotation for the specified annotation type
// */
// public static <T extends Annotation> T getAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getMethod().getAnnotation(annotation);
// }
//
// /**
// * Returns the class annotation for the specified annotation type.
// *
// * @param <T> the annotation type
// * @param invocation the method invocation
// * @param annotation the type of annotation
// * @return the class annotation for the specified annotation type
// */
// public static <T extends Annotation> T getClassAnnotation(final MethodInvocation invocation, final Class<T> annotation) {
// return invocation.getThis().getClass().getSuperclass().getAnnotation(annotation);
// }
//
// /**
// * Returns the class being invoked.
// *
// * @param invocation the method invocation
// * @return the class being invoked
// */
// public static Class getClass(final MethodInvocation invocation) {
// return invocation.getThis().getClass().getSuperclass();
// }
//
// /**
// * Returns the method being invoked.
// *
// * @param invocation the method invocation
// * @return the method being invoked
// */
// public static Method getMethod(final MethodInvocation invocation) {
// return invocation.getMethod();
// }
//
// /**
// * Returns the arguments of the method invocation.
// *
// * @param invocation the method invocation
// * @return the arguments of the method invocation
// */
// public static List<Object> getArguments(final MethodInvocation invocation) {
// // get method arguments
// final List<Object> arguments = new ArrayList(Arrays.asList(invocation.getArguments()));
//
// // if the method contains a varargs then the last parameter must be flattened
// if (invocation.getMethod().isVarArgs() && !arguments.isEmpty()) {
// final int last = arguments.size() - 1;
// final Object varargs = arguments.remove(last);
// arguments.addAll(convert(varargs));
// }
//
// return arguments;
// }
//
// /**
// * Converts an {@code Object} array into a {@code List}.
// *
// * @param array the array of objects
// * @return the list of objects
// */
// private static List<Object> convert(final Object array) {
// final List<Object> result = new ArrayList<>();
// final int length = Array.getLength(array);
//
// for (int i = 0; i < length; ++i) {
// result.add(Array.get(array, i));
// }
//
// return result;
// }
// }
// Path: chili/src/main/java/me/defying/chili/memoize/MemoizeInterceptor.java
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.LoadingCache;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.defying.chili.Memoize;
import me.defying.chili.module.ChiliException;
import me.defying.chili.util.InvocationUtils;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import com.google.common.base.Optional;
import com.google.common.cache.Cache;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.memoize;
/**
* Guice interceptor for {@code Memoize} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeInterceptor implements MethodInterceptor {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(MemoizeInterceptor.class);
/**
* The cache.
*/
private final LoadingCache<Method, Cache<Object, Optional<Object>>> caches = CacheBuilder
.newBuilder()
.build(new MemoizeCacheLoader());
/**
* Constructs an instance of <code>MemoizeInterceptor</code>.
*/
public MemoizeInterceptor() {
// empty
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
final Object result;
// get annotation, class, method and arguments | final Memoize annotation = InvocationUtils.getAnnotation(invocation, Memoize.class); |
marmelo/chili | chili/src/test/java/me/defying/chili/MemoizeTest.java | // Path: chili/src/test/java/me/defying/chili/memoize/MemoizeTestService.java
// public class MemoizeTestService {
//
// @Memoize
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3)
// public Wrap keep3(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3, time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep3for1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap statistics(final String x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap exception(final String x) throws Exception {
// throw new IOException();
// }
//
// @Memoize
// public Wrap noArgs() {
// return new Wrap(null);
// }
//
// @Memoize
// public Wrap twoArgs(final String x, final String y) {
// return new Wrap(x + y);
// }
//
// @Memoize
// public Wrap varArgs(final String... x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap mixedVarArgs(final String x, final String... y) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap primitiveVarArgs(final int... x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap nullResult(final String x) {
// return null;
// }
//
// @Memoize
// public Wrap array(final String[] x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import me.defying.chili.memoize.MemoizeTestService;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.util.ChiliTest;
import java.io.IOException;
import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Memoize} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeTest extends ChiliTest {
@Inject | // Path: chili/src/test/java/me/defying/chili/memoize/MemoizeTestService.java
// public class MemoizeTestService {
//
// @Memoize
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3)
// public Wrap keep3(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3, time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep3for1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap statistics(final String x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap exception(final String x) throws Exception {
// throw new IOException();
// }
//
// @Memoize
// public Wrap noArgs() {
// return new Wrap(null);
// }
//
// @Memoize
// public Wrap twoArgs(final String x, final String y) {
// return new Wrap(x + y);
// }
//
// @Memoize
// public Wrap varArgs(final String... x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap mixedVarArgs(final String x, final String... y) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap primitiveVarArgs(final int... x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap nullResult(final String x) {
// return null;
// }
//
// @Memoize
// public Wrap array(final String[] x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/MemoizeTest.java
import me.defying.chili.memoize.MemoizeTestService;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.util.ChiliTest;
import java.io.IOException;
import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Memoize} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeTest extends ChiliTest {
@Inject | private MemoizeTestService service; |
marmelo/chili | chili/src/test/java/me/defying/chili/MemoizeTest.java | // Path: chili/src/test/java/me/defying/chili/memoize/MemoizeTestService.java
// public class MemoizeTestService {
//
// @Memoize
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3)
// public Wrap keep3(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3, time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep3for1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap statistics(final String x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap exception(final String x) throws Exception {
// throw new IOException();
// }
//
// @Memoize
// public Wrap noArgs() {
// return new Wrap(null);
// }
//
// @Memoize
// public Wrap twoArgs(final String x, final String y) {
// return new Wrap(x + y);
// }
//
// @Memoize
// public Wrap varArgs(final String... x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap mixedVarArgs(final String x, final String... y) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap primitiveVarArgs(final int... x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap nullResult(final String x) {
// return null;
// }
//
// @Memoize
// public Wrap array(final String[] x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import me.defying.chili.memoize.MemoizeTestService;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.util.ChiliTest;
import java.io.IOException;
import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Memoize} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeTest extends ChiliTest {
@Inject
private MemoizeTestService service;
/**
* Test simple memoization, without any arguments.
*/
@Test
public void simpleTest() {
// different arguments yield different results | // Path: chili/src/test/java/me/defying/chili/memoize/MemoizeTestService.java
// public class MemoizeTestService {
//
// @Memoize
// public Wrap simple(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3)
// public Wrap keep3(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(size = 3, time = 1, unit = TimeUnit.SECONDS)
// public Wrap keep3for1Sec(final String x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap statistics(final String x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap exception(final String x) throws Exception {
// throw new IOException();
// }
//
// @Memoize
// public Wrap noArgs() {
// return new Wrap(null);
// }
//
// @Memoize
// public Wrap twoArgs(final String x, final String y) {
// return new Wrap(x + y);
// }
//
// @Memoize
// public Wrap varArgs(final String... x) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap mixedVarArgs(final String x, final String... y) {
// return new Wrap(x);
// }
//
// @Memoize
// public Wrap primitiveVarArgs(final int... x) {
// return new Wrap(x);
// }
//
// @Memoize(statistics = true)
// public Wrap nullResult(final String x) {
// return null;
// }
//
// @Memoize
// public Wrap array(final String[] x) {
// return new Wrap(x);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/memoize/Wrap.java
// public class Wrap {
// private final Object value;
//
// public Wrap(final Object value) {
// this.value = value;
// }
//
// public Object getValue() {
// return value;
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/MemoizeTest.java
import me.defying.chili.memoize.MemoizeTestService;
import me.defying.chili.memoize.Wrap;
import me.defying.chili.util.ChiliTest;
import java.io.IOException;
import com.google.inject.Inject;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Memoize} annotation.
*
* @author Rafael Marmelo
* @since 1.0
*/
public class MemoizeTest extends ChiliTest {
@Inject
private MemoizeTestService service;
/**
* Test simple memoization, without any arguments.
*/
@Test
public void simpleTest() {
// different arguments yield different results | final Wrap a = service.simple("a"); |
marmelo/chili | chili/src/test/java/me/defying/chili/TimeoutTest.java | // Path: chili/src/main/java/me/defying/chili/timeout/TimeoutException.java
// public class TimeoutException extends RuntimeException {
//
// /**
// * Constructs an instance of <code>TimeoutException</code> without detail
// * message.
// */
// public TimeoutException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public TimeoutException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public TimeoutException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/timeout/TimeoutTestService.java
// public class TimeoutTestService {
//
// public void noTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout
// public void emptyTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout(time = 100)
// public void wait100Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 1, unit = TimeUnit.SECONDS)
// public void wait200Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 200)
// public void exceptionTimeout() throws Exception {
// throw new IOException();
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import java.io.IOException;
import com.google.inject.Inject;
import org.junit.Test;
import me.defying.chili.timeout.TimeoutException;
import me.defying.chili.timeout.TimeoutTestService;
import me.defying.chili.util.ChiliTest; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutTest extends ChiliTest {
@Inject | // Path: chili/src/main/java/me/defying/chili/timeout/TimeoutException.java
// public class TimeoutException extends RuntimeException {
//
// /**
// * Constructs an instance of <code>TimeoutException</code> without detail
// * message.
// */
// public TimeoutException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public TimeoutException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public TimeoutException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/timeout/TimeoutTestService.java
// public class TimeoutTestService {
//
// public void noTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout
// public void emptyTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout(time = 100)
// public void wait100Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 1, unit = TimeUnit.SECONDS)
// public void wait200Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 200)
// public void exceptionTimeout() throws Exception {
// throw new IOException();
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/TimeoutTest.java
import java.io.IOException;
import com.google.inject.Inject;
import org.junit.Test;
import me.defying.chili.timeout.TimeoutException;
import me.defying.chili.timeout.TimeoutTestService;
import me.defying.chili.util.ChiliTest;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutTest extends ChiliTest {
@Inject | private TimeoutTestService service; |
marmelo/chili | chili/src/test/java/me/defying/chili/TimeoutTest.java | // Path: chili/src/main/java/me/defying/chili/timeout/TimeoutException.java
// public class TimeoutException extends RuntimeException {
//
// /**
// * Constructs an instance of <code>TimeoutException</code> without detail
// * message.
// */
// public TimeoutException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public TimeoutException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public TimeoutException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/timeout/TimeoutTestService.java
// public class TimeoutTestService {
//
// public void noTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout
// public void emptyTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout(time = 100)
// public void wait100Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 1, unit = TimeUnit.SECONDS)
// public void wait200Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 200)
// public void exceptionTimeout() throws Exception {
// throw new IOException();
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
| import java.io.IOException;
import com.google.inject.Inject;
import org.junit.Test;
import me.defying.chili.timeout.TimeoutException;
import me.defying.chili.timeout.TimeoutTestService;
import me.defying.chili.util.ChiliTest; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutTest extends ChiliTest {
@Inject
private TimeoutTestService service;
/**
* Test timeout with default arguments (never timeout).
* @throws java.lang.InterruptedException
*/
@Test
public void emptyTimeoutTest() throws InterruptedException {
service.emptyTimeout();
}
/**
* Test timeout failure (timeouts at 100ms but work only takes 50ms).
* @throws java.lang.InterruptedException
*/
@Test
public void failureTimeoutTest() throws InterruptedException {
service.wait100Timeout(50);
}
/**
* Test timeout success (timeouts at 100ms and work takes 200ms).
* @throws InterruptedException
*/ | // Path: chili/src/main/java/me/defying/chili/timeout/TimeoutException.java
// public class TimeoutException extends RuntimeException {
//
// /**
// * Constructs an instance of <code>TimeoutException</code> without detail
// * message.
// */
// public TimeoutException() {
// // empty
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified detail message.
// *
// * @param message the detail message.
// */
// public TimeoutException(final String message) {
// super(message);
// }
//
// /**
// * Constructs an instance of <code>TimeoutException</code> with the
// * specified cause.
// *
// * @param cause the cause.
// */
// public TimeoutException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/timeout/TimeoutTestService.java
// public class TimeoutTestService {
//
// public void noTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout
// public void emptyTimeout() throws InterruptedException {
// Thread.sleep(100);
// }
//
// @Timeout(time = 100)
// public void wait100Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 1, unit = TimeUnit.SECONDS)
// public void wait200Timeout(final long sleep) throws InterruptedException {
// Thread.sleep(sleep);
// }
//
// @Timeout(time = 200)
// public void exceptionTimeout() throws Exception {
// throw new IOException();
// }
// }
//
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
// public abstract class ChiliTest {
//
// // output stream that will hold log entries
// protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
//
// // pattern format to be compared with log entries
// protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
//
// @BeforeClass
// public static void setUpBeforeClass() {
// // logs produced will be in the format "LEVEL Message."
// System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
// System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
// System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
//
// // redefine error output stream to something we may read
// // slf4j-simple logger writes log to System.err by default
// System.setErr(new PrintStream(LOG));
// }
//
// @Before
// public void setUp() {
// final Injector injector = Guice.createInjector(new ChiliModule());
// injector.injectMembers(this);
//
// // reset log before test
// LOG.reset();
// }
//
// //
// // helpers
// //
//
// /**
// * Asserts that a string matches a regular expression.
// * If it doesn't it throws an AssertionError without a message.
// *
// * @param pattern the regular expression
// * @param string the string to be checked against the pattern
// */
// protected void assertMatches(final String pattern, final String string) {
// assertTrue(pattern.matches(string));
// }
// }
// Path: chili/src/test/java/me/defying/chili/TimeoutTest.java
import java.io.IOException;
import com.google.inject.Inject;
import org.junit.Test;
import me.defying.chili.timeout.TimeoutException;
import me.defying.chili.timeout.TimeoutTestService;
import me.defying.chili.util.ChiliTest;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Test class for {@code Timeout} annotation.
*
* @author Rafael Marmelo
* @since 1.1
*/
public class TimeoutTest extends ChiliTest {
@Inject
private TimeoutTestService service;
/**
* Test timeout with default arguments (never timeout).
* @throws java.lang.InterruptedException
*/
@Test
public void emptyTimeoutTest() throws InterruptedException {
service.emptyTimeout();
}
/**
* Test timeout failure (timeouts at 100ms but work only takes 50ms).
* @throws java.lang.InterruptedException
*/
@Test
public void failureTimeoutTest() throws InterruptedException {
service.wait100Timeout(50);
}
/**
* Test timeout success (timeouts at 100ms and work takes 200ms).
* @throws InterruptedException
*/ | @Test(expected = TimeoutException.class) |
marmelo/chili | chili/src/main/java/me/defying/chili/Log.java | // Path: chili/src/main/java/me/defying/chili/log/LogLevel.java
// public enum LogLevel {
// TRACE, DEBUG, INFO, WARNING, ERROR
// }
| import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import me.defying.chili.log.LogLevel; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Indicates that a method invocation is logged.
*
* @author Rafael Marmelo
* @since 1.0
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
/**
* Returns the log level.
*
* @return the log level.
*/ | // Path: chili/src/main/java/me/defying/chili/log/LogLevel.java
// public enum LogLevel {
// TRACE, DEBUG, INFO, WARNING, ERROR
// }
// Path: chili/src/main/java/me/defying/chili/Log.java
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import me.defying.chili.log.LogLevel;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili;
/**
* Indicates that a method invocation is logged.
*
* @author Rafael Marmelo
* @since 1.0
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
/**
* Returns the log level.
*
* @return the log level.
*/ | LogLevel level() default LogLevel.DEBUG; |
marmelo/chili | chili/src/test/java/me/defying/chili/util/ChiliTest.java | // Path: chili/src/main/java/me/defying/chili/module/ChiliModule.java
// public class ChiliModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Log.class), new LogInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Memoize.class), new MemoizeInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Timeout.class), new TimeoutInterceptor());
// bindInterceptor(Matchers.annotatedWith(ToString.class), new ToStringMatcher(), new ToStringInterceptor());
// }
// }
| import me.defying.chili.module.ChiliModule;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass; | /*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.util;
/**
* Abstract class to be used by Chili project tests.
*
* @author Rafael Marmelo
* @since 1.0
*/
public abstract class ChiliTest {
// output stream that will hold log entries
protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
// pattern format to be compared with log entries
protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
@BeforeClass
public static void setUpBeforeClass() {
// logs produced will be in the format "LEVEL Message."
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
// redefine error output stream to something we may read
// slf4j-simple logger writes log to System.err by default
System.setErr(new PrintStream(LOG));
}
@Before
public void setUp() { | // Path: chili/src/main/java/me/defying/chili/module/ChiliModule.java
// public class ChiliModule extends AbstractModule {
//
// @Override
// protected void configure() {
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Log.class), new LogInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Memoize.class), new MemoizeInterceptor());
// bindInterceptor(Matchers.any(), Matchers.annotatedWith(Timeout.class), new TimeoutInterceptor());
// bindInterceptor(Matchers.annotatedWith(ToString.class), new ToStringMatcher(), new ToStringInterceptor());
// }
// }
// Path: chili/src/test/java/me/defying/chili/util/ChiliTest.java
import me.defying.chili.module.ChiliModule;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import com.google.inject.Guice;
import com.google.inject.Injector;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
/*
* The MIT License (MIT)
* Copyright (c) 2015 Rafael Marmelo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.defying.chili.util;
/**
* Abstract class to be used by Chili project tests.
*
* @author Rafael Marmelo
* @since 1.0
*/
public abstract class ChiliTest {
// output stream that will hold log entries
protected static final ByteArrayOutputStream LOG = new ByteArrayOutputStream();
// pattern format to be compared with log entries
protected final String format = "^DEBUG Invoked %s\\(%s\\) => %s in [0-9]+ ms\\.$";
@BeforeClass
public static void setUpBeforeClass() {
// logs produced will be in the format "LEVEL Message."
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
System.setProperty("org.slf4j.simpleLogger.showThreadName", "false");
System.setProperty("org.slf4j.simpleLogger.showLogName", "false");
// redefine error output stream to something we may read
// slf4j-simple logger writes log to System.err by default
System.setErr(new PrintStream(LOG));
}
@Before
public void setUp() { | final Injector injector = Guice.createInjector(new ChiliModule()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.