repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
BeYkeRYkt/LightAPI
craftbukkit-nms-v1_15_R1/src/main/java/ru/beykerykt/minecraft/lightapi/bukkit/internal/handler/craftbukkit/nms/v1_15_R1/VanillaNMSHandler.java
[ "public class BukkitPlatformImpl implements IPlatformImpl, IBukkitExtension {\n\n private static final String DEFAULT_IMPL_NAME = \"craftbukkit\";\n /**\n * CONFIG\n */\n private final String CONFIG_TITLE = \"general\";\n private final String CONFIG_DEBUG = CONFIG_TITLE + \".debug\";\n private final String CONFIG_ENABLE_METRICS = CONFIG_TITLE + \".enable-metrics\";\n private final String CONFIG_ENABLE_COMPATIBILITY_MODE = CONFIG_TITLE + \".enable-compatibility-mode\";\n private final String CONFIG_FORCE_ENABLE_LEGACY = CONFIG_TITLE + \".force-enable-legacy\";\n private final String CONFIG_SPECIFIC_HANDLER_PATH = CONFIG_TITLE + \".specific-handler-path\";\n private final String CONFIG_HANDLERS_TITLE = CONFIG_TITLE + \".handlers\";\n private final int BSTATS_ID = 13051;\n private final BukkitPlugin mPlugin;\n private boolean DEBUG = false;\n private boolean isInit = false;\n private boolean forceLegacy = false;\n private boolean compatibilityMode = false;\n private IHandler mHandler;\n private IChunkObserver mChunkObserver;\n private ILightEngine mLightEngine;\n private IBackgroundService mBackgroundService;\n private IExtension mExtension;\n private UUID mUUID;\n\n public BukkitPlatformImpl(BukkitPlugin plugin) {\n this.mPlugin = plugin;\n }\n\n public void toggleDebug() {\n DEBUG = !DEBUG;\n log(\"Debug mode is \" + (DEBUG ? \"en\" : \"dis\") + \"abled\");\n }\n\n private FileConfiguration getConfig() {\n return getPlugin().getConfig();\n }\n\n private void generateConfig() {\n // create config\n try {\n File file = new File(getPlugin().getDataFolder(), \"config.yml\");\n if (!file.exists()) {\n getConfig().set(CONFIG_DEBUG, false);\n getConfig().set(CONFIG_ENABLE_METRICS, true);\n getConfig().set(CONFIG_ENABLE_COMPATIBILITY_MODE, false);\n if (Build.API_VERSION == Build.PREVIEW) { // only for PREVIEW build\n getConfig().set(CONFIG_FORCE_ENABLE_LEGACY, true);\n } else {\n getConfig().set(CONFIG_FORCE_ENABLE_LEGACY, false);\n }\n getPlugin().saveConfig();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private boolean upgradeConfig() {\n boolean needSave = false;\n if (getConfig().isSet(\"general.specific-storage-provider\")) {\n getConfig().set(\"general.specific-storage-provider\", null);\n needSave = true;\n }\n if (getConfig().isSet(\"handler.specific-handler-path\")) {\n getConfig().set(\"handler.specific-handler-path\", null);\n needSave = true;\n }\n if (getConfig().isSet(\"handler.craftbukkit.factory-path\")) {\n getConfig().set(\"handler.craftbukkit.factory-path\", null);\n needSave = true;\n }\n if (needSave) {\n getConfig().set(\"handler\", null);\n }\n return needSave;\n }\n\n private void checkAndSetDefaults() {\n boolean needSave = upgradeConfig();\n if (!getConfig().isSet(CONFIG_ENABLE_COMPATIBILITY_MODE)) {\n getConfig().set(CONFIG_ENABLE_COMPATIBILITY_MODE, false);\n needSave = true;\n }\n if (!getConfig().isSet(CONFIG_SPECIFIC_HANDLER_PATH)) {\n getConfig().set(CONFIG_SPECIFIC_HANDLER_PATH, \"none\");\n needSave = true;\n }\n if (!getConfig().isSet(CONFIG_HANDLERS_TITLE + \".\" + DEFAULT_IMPL_NAME + \".factory-path\")) {\n getConfig().set(CONFIG_HANDLERS_TITLE + \".\" + DEFAULT_IMPL_NAME + \".factory-path\",\n \"ru.beykerykt.minecraft.lightapi.bukkit.internal.handler.\" + DEFAULT_IMPL_NAME + \".HandlerFactory\");\n needSave = true;\n }\n if (needSave) {\n getPlugin().saveConfig();\n }\n }\n\n private void initHandler() throws Exception {\n checkAndSetDefaults();\n // load specific handler if available\n String specificPkg = getConfig().getString(CONFIG_SPECIFIC_HANDLER_PATH);\n if (specificPkg != null && !specificPkg.equalsIgnoreCase(\"none\")) {\n info(\"Initial load specific handler\");\n mHandler = (IHandler) Class.forName(specificPkg).getConstructor().newInstance();\n info(\"Custom handler is loaded: \" + mHandler.getClass().getName());\n return;\n }\n\n // compatibility mode (1.17+)\n compatibilityMode = getConfig().getBoolean(CONFIG_ENABLE_COMPATIBILITY_MODE);\n if (compatibilityMode) {\n if (VersionUtil.compareBukkitVersionTo(\"1.17\") >= 0) {\n info(\"Compatibility mode is enabled\");\n mHandler = new CompatibilityHandler();\n mHandler.onInitialization(this);\n return;\n } else {\n error(\"Compatibility mode can only work on versions > 1.17\");\n }\n }\n\n // First, check Bukkit server implementation, since Bukkit is only an API, and there\n // may be several implementations (for example: Spigot, Paper, Glowstone and etc)\n String implName = Bukkit.getName().toLowerCase();\n debug(\"Server implementation name: \" + implName);\n\n String modFactoryPath = getConfig().getString(CONFIG_HANDLERS_TITLE + \".\" + implName + \".factory-path\");\n try {\n Class.forName(modFactoryPath);\n } catch (Exception ex) {\n debug(\"Specific HandlerFactory for \" + implName + \" is not detected. Switch to default: \"\n + DEFAULT_IMPL_NAME);\n implName = DEFAULT_IMPL_NAME;\n modFactoryPath = getConfig().getString(CONFIG_HANDLERS_TITLE + \".\" + implName + \".factory-path\");\n }\n IHandlerFactory factory = (IHandlerFactory) Class.forName(modFactoryPath).getConstructor().newInstance();\n mHandler = factory.createHandler(this);\n debug(\"Handler is loaded: \" + mHandler.getClass().getName());\n }\n\n private void enableMetrics() {\n boolean enableMetrics = getConfig().getBoolean(CONFIG_ENABLE_METRICS);\n if (enableMetrics) {\n Metrics metrics = new Metrics(getPlugin(), BSTATS_ID);\n }\n info(\"Metrics is \" + (enableMetrics ? \"en\" : \"dis\") + \"abled!\");\n }\n\n @Override\n public int prepare() {\n // general default config\n generateConfig();\n\n // debug mode\n this.DEBUG = getConfig().getBoolean(CONFIG_DEBUG);\n return ResultCode.SUCCESS;\n }\n\n @Override\n public int initialization() {\n // enable force legacy\n forceLegacy = getConfig().getBoolean(CONFIG_FORCE_ENABLE_LEGACY);\n if (forceLegacy) {\n info(\"Force legacy is enabled\");\n }\n\n // init handler\n try {\n initHandler();\n mHandler.onInitialization(this);\n } catch (Exception e) {\n e.printStackTrace();\n return ResultCode.FAILED;\n }\n\n // init background service\n mBackgroundService = new BukkitBackgroundServiceImpl(this, getHandler());\n mBackgroundService.onStart();\n\n // init chunk observer\n mChunkObserver = new BukkitScheduledChunkObserverImpl(this, getBackgroundService(), getHandler());\n mChunkObserver.onStart();\n\n // init light engine\n mLightEngine = new BukkitScheduledLightEngineImpl(this, getBackgroundService(), getHandler());\n mLightEngine.onStart();\n\n // init extension\n mExtension = this;\n\n isInit = true;\n\n // enable metrics\n enableMetrics();\n\n return ResultCode.SUCCESS;\n }\n\n @Override\n public void shutdown() {\n mLightEngine.onShutdown();\n mChunkObserver.onShutdown();\n mBackgroundService.onShutdown();\n mHandler.onShutdown(this);\n mHandler = null;\n isInit = false;\n }\n\n @Override\n public boolean isInitialized() {\n return isInit;\n }\n\n @Override\n public void log(String msg) {\n StringBuilder builder = new StringBuilder(ChatColor.AQUA + \"<LightAPI>: \");\n builder.append(ChatColor.WHITE).append(msg);\n mPlugin.getServer().getConsoleSender().sendMessage(builder.toString());\n }\n\n @Override\n public void info(String msg) {\n log(\"[INFO] \" + msg);\n }\n\n @Override\n public void debug(String msg) {\n if (DEBUG) {\n log(ChatColor.YELLOW + \"[DEBUG] \" + msg);\n }\n }\n\n @Override\n public void error(String msg) {\n log(ChatColor.RED + \"[ERROR] \" + msg);\n }\n\n @Override\n public PlatformType getPlatformType() {\n return getHandler().getPlatformType();\n }\n\n @Override\n public ILightEngine getLightEngine() {\n return mLightEngine;\n }\n\n @Override\n public IChunkObserver getChunkObserver() {\n return mChunkObserver;\n }\n\n @Override\n public IBackgroundService getBackgroundService() {\n return mBackgroundService;\n }\n\n @Override\n public IExtension getExtension() {\n return mExtension;\n }\n\n @Override\n public boolean isWorldAvailable(String worldName) {\n return getPlugin().getServer().getWorld(worldName) != null;\n }\n\n /* @hide */\n public int sendCmdLocked(int cmdId, Object... args) {\n int resultCode = ResultCode.SUCCESS;\n // handle internal codes\n switch (cmdId) {\n case InternalCode.UPDATE_UUID:\n mUUID = (UUID) args[0];\n break;\n default:\n resultCode = getHandler().sendCmd(cmdId, args);\n break;\n }\n return resultCode;\n }\n\n @Override\n public int sendCmd(int cmdId, Object... args) {\n return sendCmdLocked(cmdId, args);\n }\n\n @Override\n public UUID getUUID() {\n return mUUID;\n }\n\n public BukkitPlugin getPlugin() {\n return mPlugin;\n }\n\n @Override\n public IHandler getHandler() {\n return mHandler;\n }\n\n @Override\n public int getLightLevel(World world, int blockX, int blockY, int blockZ) {\n return getLightLevel(world, blockX, blockY, blockZ, LightFlag.BLOCK_LIGHTING);\n }\n\n @Override\n public int getLightLevel(World world, int blockX, int blockY, int blockZ, int lightFlags) {\n return getLightEngine().getLightLevel(world.getName(), blockX, blockY, blockZ, lightFlags);\n }\n\n @Override\n public int setLightLevel(World world, int blockX, int blockY, int blockZ, int lightLevel) {\n return setLightLevel(world, blockX, blockY, blockZ, lightLevel, LightFlag.BLOCK_LIGHTING, EditPolicy.DEFERRED,\n SendPolicy.DEFERRED, null);\n }\n\n @Override\n public int setLightLevel(World world, int blockX, int blockY, int blockZ, int lightLevel, int lightFlags) {\n return setLightLevel(world, blockX, blockY, blockZ, lightLevel, lightFlags, EditPolicy.DEFERRED,\n SendPolicy.DEFERRED, null);\n }\n\n @Override\n public int setLightLevel(World world, int blockX, int blockY, int blockZ, int lightLevel, int lightFlags,\n ICallback callback) {\n return setLightLevel(world, blockX, blockY, blockZ, lightLevel, lightFlags, EditPolicy.DEFERRED,\n SendPolicy.DEFERRED, callback);\n }\n\n @Override\n public int setLightLevel(World world, int blockX, int blockY, int blockZ, int lightLevel, int lightFlags,\n EditPolicy editPolicy, SendPolicy sendPolicy, ICallback callback) {\n return getLightEngine().setLightLevel(world.getName(), blockX, blockY, blockZ, lightLevel, lightFlags,\n editPolicy, sendPolicy, callback);\n }\n\n @Override\n public boolean isBackwardAvailable() {\n boolean flag = Build.API_VERSION == Build.PREVIEW;\n try {\n Class.forName(\"ru.beykerykt.lightapi.LightAPI\");\n return forceLegacy ? true : (flag & true);\n } catch (ClassNotFoundException ex) {\n return false;\n }\n }\n\n @Override\n public boolean isCompatibilityMode() {\n return compatibilityMode;\n }\n}", "public abstract class BaseNMSHandler implements IHandler {\n\n private BukkitPlatformImpl mPlatformImpl;\n\n @Override\n public void onInitialization(BukkitPlatformImpl impl) throws Exception {\n this.mPlatformImpl = impl;\n }\n\n protected BukkitPlatformImpl getPlatformImpl() {\n return mPlatformImpl;\n }\n\n @Override\n public PlatformType getPlatformType() {\n return PlatformType.CRAFTBUKKIT;\n }\n\n @Override\n public boolean isMainThread() {\n return Bukkit.isPrimaryThread();\n }\n}", "public class ResultCode {\n\n /**\n * N/A\n */\n public static final int MOVED_TO_DEFERRED = 1;\n\n /**\n * The task has been successfully completed\n */\n public static final int SUCCESS = 0;\n\n /**\n * The task has been failed\n */\n public static final int FAILED = -1;\n\n /**\n * Current world is not available\n */\n public static final int WORLD_NOT_AVAILABLE = -2;\n\n /**\n * (1.14+) No lighting changes in current world\n */\n public static final int RECALCULATE_NO_CHANGES = -3;\n\n /**\n * (1.14+) SkyLight data is not available in current world\n */\n public static final int SKYLIGHT_DATA_NOT_AVAILABLE = -4;\n\n /**\n * (1.14+) BlockLight data is not available in current world\n */\n public static final int BLOCKLIGHT_DATA_NOT_AVAILABLE = -5;\n\n /**\n * Current function is not implemented\n */\n public static final int NOT_IMPLEMENTED = -6;\n\n /**\n * Chunk is not loaded\n */\n public static final int CHUNK_NOT_LOADED = -7;\n}", "public class LightFlag {\n\n /**\n * N/A\n */\n public static final int NONE = 0;\n\n /**\n * A flag for editing block light layer\n */\n public static final int BLOCK_LIGHTING = 1;\n\n /**\n * A flag for editing sky light layer\n */\n public static final int SKY_LIGHTING = 2;\n\n /**\n * A flag for storing the light level in the storage provider\n */\n @Deprecated\n public static final int USE_STORAGE_PROVIDER = 4;\n}", "public interface IChunkData {\n\n /**\n * @return World name\n */\n String getWorldName();\n\n /**\n * @return Chunk X Coordinate\n */\n int getChunkX();\n\n /**\n * @return Chunk Z Coordinate\n */\n int getChunkZ();\n\n /**\n * N/A\n */\n void markSectionForUpdate(int lightFlags, int sectionY);\n\n /**\n * N/A\n */\n void clearUpdate();\n\n /**\n * N/A\n */\n void setFullSections();\n}", "public class IntChunkData extends ChunkData {\n\n public static final int FULL_MASK = 0x1ffff;\n\n protected int skyLightUpdateBits;\n protected int blockLightUpdateBits;\n\n public IntChunkData(String worldName, int chunkX, int chunkZ, int skyLightUpdateBits, int blockLightUpdateBits) {\n super(worldName, chunkX, chunkZ);\n this.skyLightUpdateBits = skyLightUpdateBits;\n this.blockLightUpdateBits = blockLightUpdateBits;\n }\n\n public int getSkyLightUpdateBits() {\n return skyLightUpdateBits;\n }\n\n public int getBlockLightUpdateBits() {\n return blockLightUpdateBits;\n }\n\n @Override\n public void markSectionForUpdate(int lightFlags, int sectionY) {\n if (FlagUtils.isFlagSet(lightFlags, LightFlag.SKY_LIGHTING)) {\n skyLightUpdateBits |= 1 << sectionY + 1;\n }\n\n if (FlagUtils.isFlagSet(lightFlags, LightFlag.BLOCK_LIGHTING)) {\n blockLightUpdateBits |= 1 << sectionY + 1;\n }\n }\n\n @Override\n public void clearUpdate() {\n this.skyLightUpdateBits = 0;\n this.blockLightUpdateBits = 0;\n }\n\n @Override\n public void setFullSections() {\n this.skyLightUpdateBits = FULL_MASK;\n this.blockLightUpdateBits = FULL_MASK;\n }\n\n @Override\n public String toString() {\n return \"IntChunkData{\" + \"worldName=\" + getWorldName() + \", chunkX=\" + getChunkX() + \", chunkZ=\" + getChunkZ()\n + \", skyLightUpdateBits=\" + skyLightUpdateBits + \", blockLightUpdateBits=\" + blockLightUpdateBits + '}';\n }\n}", "public enum LightEngineType {\n UNKNOWN(0), VANILLA(1), STARLIGHT(2), COMPATIBILITY(3);\n\n private final int id;\n\n LightEngineType(int id) {\n this.id = id;\n }\n\n public int getId() {\n return id;\n }\n}", "public enum LightEngineVersion {\n\n /**\n * N/A\n */\n UNKNOWN(0),\n\n /**\n * Minecraft version is before 1.14. For update lighting in client-side, need send full chunk.\n */\n V1(1),\n\n /**\n * Minecraft version is equals or after 1.14. For update lighting in client-side, need send only\n * light update packet.\n */\n V2(2);\n\n private final int id;\n\n LightEngineVersion(int id) {\n this.id = id;\n }\n\n public int getId() {\n return id;\n }\n}", "public class FlagUtils {\n\n /**\n * N/A\n */\n public static int addFlag(int flags, int targetFlag) {\n return flags |= targetFlag;\n }\n\n /**\n * N/A\n */\n public static int removeFlag(int flags, int targetFlag) {\n return flags &= ~targetFlag;\n }\n\n /**\n * N/A\n */\n public static boolean isFlagSet(int flags, int targetFlag) {\n return (flags & targetFlag) == targetFlag;\n }\n}" ]
import com.google.common.collect.Lists; import net.minecraft.server.v1_15_R1.BlockPosition; import net.minecraft.server.v1_15_R1.Chunk; import net.minecraft.server.v1_15_R1.ChunkCoordIntPair; import net.minecraft.server.v1_15_R1.EntityPlayer; import net.minecraft.server.v1_15_R1.EnumSkyBlock; import net.minecraft.server.v1_15_R1.LightEngineBlock; import net.minecraft.server.v1_15_R1.LightEngineGraph; import net.minecraft.server.v1_15_R1.LightEngineLayer; import net.minecraft.server.v1_15_R1.LightEngineSky; import net.minecraft.server.v1_15_R1.LightEngineStorage; import net.minecraft.server.v1_15_R1.LightEngineThreaded; import net.minecraft.server.v1_15_R1.PacketPlayOutLightUpdate; import net.minecraft.server.v1_15_R1.SectionPosition; import net.minecraft.server.v1_15_R1.ThreadedMailbox; import net.minecraft.server.v1_15_R1.WorldServer; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.craftbukkit.v1_15_R1.CraftWorld; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import ru.beykerykt.minecraft.lightapi.bukkit.internal.BukkitPlatformImpl; import ru.beykerykt.minecraft.lightapi.bukkit.internal.handler.craftbukkit.nms.BaseNMSHandler; import ru.beykerykt.minecraft.lightapi.common.api.ResultCode; import ru.beykerykt.minecraft.lightapi.common.api.engine.LightFlag; import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IChunkData; import ru.beykerykt.minecraft.lightapi.common.internal.chunks.data.IntChunkData; import ru.beykerykt.minecraft.lightapi.common.internal.engine.LightEngineType; import ru.beykerykt.minecraft.lightapi.common.internal.engine.LightEngineVersion; import ru.beykerykt.minecraft.lightapi.common.internal.utils.FlagUtils;
// ThreadedMailbox is closing. The light engine mailbox may also stop processing tasks. // The light engine mailbox can be close due to server shutdown or unloading (closing) the world. // I am not sure is it unsafe to process our tasks while the world is closing is closing, // but will try it (one can throw exception here if it crashes the server). if (timeToWait == -1) { // Try to wait 3 seconds until light engine mailbox is busy. timeToWait = System.currentTimeMillis() + 3 * 1000; getPlatformImpl().debug("ThreadedMailbox is closing. Will wait..."); } else if (System.currentTimeMillis() >= timeToWait) { throw new RuntimeException("Failed to enter critical section while ThreadedMailbox is closing"); } try { Thread.sleep(50); } catch (InterruptedException ignored) { } } } try { // ##### STEP 2: Safely running the task while the mailbox process is stopped. ##### task.run(); } finally { // STEP 3: ##### Continue light engine mailbox to process its tasks. ##### // Firstly: Clearing busy flag to allow ThreadedMailbox to use it for running light engine tasks. while (!stateFlags.compareAndSet(flags = stateFlags.get(), flags & ~2)) ; // Secondly: IMPORTANT! The main loop of ThreadedMailbox was broken. Not completed tasks may still be // in the queue. Therefore, it is important to start the loop again to process tasks from the queue. // Otherwise, the main server thread may be frozen due to tasks stuck in the queue. threadedMailbox_DoLoopStep.invoke(threadedMailbox); } } catch (InvocationTargetException e) { throw toRuntimeException(e.getCause()); } catch (IllegalAccessException e) { throw toRuntimeException(e); } } private void lightEngineLayer_a(LightEngineLayer<?, ?> les, BlockPosition var0, int var1) { try { LightEngineStorage<?> ls = (LightEngineStorage<?>) lightEngineLayer_c.get(les); lightEngineStorage_d.invoke(ls); lightEngineGraph_a.invoke(les, 9223372036854775807L, var0.asLong(), 15 - var1, true); } catch (InvocationTargetException e) { throw toRuntimeException(e.getCause()); } catch (IllegalAccessException e) { throw toRuntimeException(e); } } private IChunkData createIntChunkData(String worldName, int chunkX, int chunkZ, int sectionMaskSky, int sectionMaskBlock) { return new IntChunkData(worldName, chunkX, chunkZ, sectionMaskSky, sectionMaskBlock); } @Override public void onInitialization(BukkitPlatformImpl impl) throws Exception { super.onInitialization(impl); try { threadedMailbox_DoLoopStep = ThreadedMailbox.class.getDeclaredMethod("f"); threadedMailbox_DoLoopStep.setAccessible(true); threadedMailbox_State = ThreadedMailbox.class.getDeclaredField("c"); threadedMailbox_State.setAccessible(true); lightEngine_ThreadedMailbox = LightEngineThreaded.class.getDeclaredField("b"); lightEngine_ThreadedMailbox.setAccessible(true); lightEngineLayer_c = LightEngineLayer.class.getDeclaredField("c"); lightEngineLayer_c.setAccessible(true); lightEngineStorage_d = LightEngineStorage.class.getDeclaredMethod("d"); lightEngineStorage_d.setAccessible(true); lightEngineGraph_a = LightEngineGraph.class.getDeclaredMethod("a", long.class, long.class, int.class, boolean.class); lightEngineGraph_a.setAccessible(true); impl.info("Handler initialization is done"); } catch (Exception e) { throw toRuntimeException(e); } } @Override public void onShutdown(BukkitPlatformImpl impl) { } @Override public LightEngineType getLightEngineType() { return LightEngineType.VANILLA; } @Override public void onWorldLoad(WorldLoadEvent event) { } @Override public void onWorldUnload(WorldUnloadEvent event) { } @Override public boolean isLightingSupported(World world, int lightFlags) { WorldServer worldServer = ((CraftWorld) world).getHandle(); LightEngineThreaded lightEngine = worldServer.getChunkProvider().getLightEngine(); if (FlagUtils.isFlagSet(lightFlags, LightFlag.SKY_LIGHTING)) { return lightEngine.a(EnumSkyBlock.SKY) instanceof LightEngineSky; } else if (FlagUtils.isFlagSet(lightFlags, LightFlag.BLOCK_LIGHTING)) { return lightEngine.a(EnumSkyBlock.BLOCK) instanceof LightEngineBlock; } return false; } @Override public LightEngineVersion getLightEngineVersion() { return LightEngineVersion.V2; } @Override public int setRawLightLevel(World world, int blockX, int blockY, int blockZ, int lightLevel, int flags) { WorldServer worldServer = ((CraftWorld) world).getHandle(); final BlockPosition position = new BlockPosition(blockX, blockY, blockZ); final LightEngineThreaded lightEngine = worldServer.getChunkProvider().getLightEngine(); final int finalLightLevel = lightLevel < 0 ? 0 : Math.min(lightLevel, 15); if (!worldServer.getChunkProvider().isChunkLoaded(blockX >> 4, blockZ >> 4)) {
return ResultCode.CHUNK_NOT_LOADED;
2
Kaysoro/KaellyBot
src/main/java/commands/classic/AlignmentCommand.java
[ "public abstract class FetchCommand extends AbstractCommand {\n\n protected DiscordException tooMuchServers;\n protected DiscordException notFoundServer;\n\n protected FetchCommand(String name, String pattern) {\n super(name, pattern);\n tooMuchServers = new TooMuchDiscordException(\"server\", true);\n notFoundServer = new NotFoundDiscordException(\"server\");\n }\n\n /**\n * Renvoie True si la liste ne contient pas un seul élément et jette une DiscordException, sinon renvoie False.\n * @param list List d'ojbets à vérifier\n * @param tooMuch Exception à jeter si la liste a plus d'un objet\n * @param notFound Exception à jeter si la liste est vide\n * @param message Message d'origine provoquant l'appel de la commande\n * @param lg Langue utilisée par la guilde\n * @param <T> Type de la liste passé en paramètre; non utilisé\n * @return True si la liste contient un seul élément; jette une DiscordException et renvoie faux le cas échéant\n */\n protected <T> boolean checkData(List<T> list, DiscordException tooMuch, DiscordException notFound, Message message, Language lg){\n if (list.size() > 1){\n tooMuch.throwException(message, this, lg);\n return true;\n }\n else if(list.isEmpty()){\n notFound.throwException(message, this, lg);\n return true;\n }\n return false;\n }\n}", "public class Guild {\n\n private final static Logger LOG = LoggerFactory.getLogger(Guild.class);\n private static Map<String, Guild> guilds;\n private String id;\n private String name;\n private Map<String, CommandForbidden> commands;\n private String prefix;\n private ServerDofus server;\n private Language language;\n\n public Guild(String id, String name, Language lang){\n this(id, name, Constants.prefixCommand, lang, null);\n }\n\n private Guild(String id, String name, String prefix, Language lang, String serverDofus){\n this.id = id;\n this.name = name;\n this.prefix = prefix;\n commands = CommandForbidden.getForbiddenCommands(this);\n this.language = lang;\n this.server = ServerDofus.getServersMap().get(serverDofus);\n }\n\n public synchronized void addToDatabase(){\n if (! getGuilds().containsKey(id)){\n getGuilds().put(id, this);\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement request = connection.prepareStatement(\"INSERT INTO\"\n + \" Guild(id, name, prefixe, lang) VALUES (?, ?, ?, ?);\");\n request.setString(1, id);\n request.setString(2, name);\n request.setString(3, prefix);\n request.setString(4, language.getAbrev());\n request.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n }\n\n public synchronized void removeToDatabase() {\n if (getGuilds().containsKey(id)) {\n getGuilds().remove(id);\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement request = connection.prepareStatement(\"DELETE FROM Guild WHERE ID = ?;\");\n request.setString(1, id);\n request.executeUpdate();\n\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n }\n\n public synchronized void setName(String name){\n this.name = name;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET name = ? WHERE id = ?;\");\n preparedStatement.setString(1, name);\n preparedStatement.setString(2, id);\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized void setPrefix(String prefix){\n this.prefix = prefix;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET prefixe = ? WHERE id = ?;\");\n preparedStatement.setString(1, prefix);\n preparedStatement.setString(2, id);\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized void setServer(ServerDofus server){\n this.server = server;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET server_dofus = ? WHERE id = ?;\");\n if (server != null) preparedStatement.setString(1, server.getName());\n else preparedStatement.setNull(1, Types.VARCHAR);\n preparedStatement.setString(2, id);\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized void setLanguage(Language lang){\n this.language = lang;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"UPDATE Guild SET lang = ? WHERE id = ?;\");\n preparedStatement.setString(1, lang.getAbrev());\n preparedStatement.setString(2, id);\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n\n public synchronized static Map<String, Guild> getGuilds(){\n if (guilds == null){\n guilds = new ConcurrentHashMap<>();\n String id;\n String name;\n String prefix;\n String server;\n String lang;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement query = connection.prepareStatement(\"SELECT id, name, prefixe, server_dofus, lang FROM Guild\");\n ResultSet resultSet = query.executeQuery();\n\n while (resultSet.next()) {\n id = resultSet.getString(\"id\");\n name = resultSet.getString(\"name\");\n prefix = resultSet.getString(\"prefixe\");\n server = resultSet.getString(\"server_dofus\");\n lang = resultSet.getString(\"lang\");\n\n guilds.put(id, new Guild(id, name, prefix, Language.valueOf(lang), server));\n }\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(e.getMessage());\n }\n }\n return guilds;\n }\n\n public static Guild getGuild(discord4j.core.object.entity.Guild guild){\n return getGuild(guild, true);\n }\n\n public synchronized static Guild getGuild(discord4j.core.object.entity.Guild discordGuild, boolean forceCache){\n Guild guild = getGuilds().get(discordGuild.getId().asString());\n\n if (guild == null && forceCache){\n guild = new Guild(discordGuild.getId().asString(), discordGuild.getName(), Constants.defaultLanguage);\n guild.addToDatabase();\n }\n\n return guild;\n }\n\n public String getId(){\n return id;\n }\n\n public String getName(){\n return name;\n }\n\n public String getPrefix(){ return prefix; }\n\n public Language getLanguage() {\n return language;\n }\n\n public Map<String, CommandForbidden> getForbiddenCommands(){\n return commands;\n }\n\n public ServerDofus getServerDofus() {\n return server;\n }\n}", "public class OrderUser extends ObjectUser {\n\n private final static Logger LOG = LoggerFactory.getLogger(OrderUser.class);\n private static final String ORDER_PREFIX = \"align\";\n private static MultiKeySearch<OrderUser> orders;\n private static final int NUMBER_FIELD = 4;\n private static final int LEVEL_MAX = 100;\n private City city;\n private Order order;\n\n public OrderUser(long idUser, ServerDofus server, City city, Order order, int level){\n this.city = city;\n this.order = order;\n if (level > LEVEL_MAX)\n level = LEVEL_MAX;\n this.level = level;\n this.idUser = idUser;\n this.server = server;\n }\n\n public synchronized void setLevel(int level){\n if (level > LEVEL_MAX)\n level = LEVEL_MAX;\n this.level = level;\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement;\n if (level > 0) {\n preparedStatement = connection.prepareStatement(\n \"UPDATE Order_User SET level = ?\"\n + \"WHERE name_city = ? AND name_order = ? AND id_user = ? AND server_dofus = ?;\");\n preparedStatement.setInt(1, level);\n preparedStatement.setString(2, city.getName());\n preparedStatement.setString(3, order.getName());\n preparedStatement.setString(4, String.valueOf(idUser));\n preparedStatement.setString(5, server.getName());\n }\n else {\n preparedStatement = connection.prepareStatement(\n \"DELETE FROM Order_User \"\n + \"WHERE name_city = ? AND name_order = ? AND id_user = ? AND server_dofus = ?;\");\n preparedStatement.setString(1, city.getName());\n preparedStatement.setString(2, order.getName());\n preparedStatement.setString(3, String.valueOf(idUser));\n preparedStatement.setString(4, server.getName());\n getOrders().remove(idUser, server, city, order);\n }\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n LOG.error(\"setLevel\", e);\n }\n }\n\n /**\n * Ajoute à la base de donnée l'objet si celui-ci n'y est pas déjà.\n */\n public synchronized void addToDatabase(){\n if (! getOrders().containsKeys(idUser, server, city, order) && level > 0) {\n getOrders().add(this, idUser, server, city, order);\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement preparedStatement = connection.prepareStatement(\n \"INSERT INTO Order_User(id_user, server_dofus, name_city, name_order, level) \"\n + \"VALUES(?, ?, ?, ?, ?);\");\n preparedStatement.setString(1, String.valueOf(idUser));\n preparedStatement.setString(2, server.getName());\n preparedStatement.setString(3, city.getName());\n preparedStatement.setString(4, order.getName());\n preparedStatement.setInt(5, level);\n\n preparedStatement.executeUpdate();\n } catch (SQLException e) {\n LOG.error(\"addToDatabase\", e);\n }\n }\n }\n\n private City getCity() {\n return city;\n }\n\n private Order getOrder() {\n return order;\n }\n\n @Override\n protected String displayLine(discord4j.core.object.entity.Guild guild, Language lg) {\n Optional<Member> member = guild.getMemberById(Snowflake.of(idUser)).blockOptional();\n\n if (member.isPresent()) {\n return city.getLogo() + \" \" + order.getLabel(lg) + \", \" + level + \" : **\"\n + member.get().getDisplayName() + \"**\\n\";\n }\n return \"\";\n }\n\n private static synchronized MultiKeySearch<OrderUser> getOrders(){\n if(orders == null){\n orders = new MultiKeySearch<>(NUMBER_FIELD);\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement query = connection.prepareStatement(\n \"SELECT id_user, server_dofus, name_city, name_order, level FROM Order_User;\");\n ResultSet resultSet = query.executeQuery();\n\n while (resultSet.next()) {\n Long idUser = resultSet.getLong(\"id_user\");\n ServerDofus server = ServerDofus.getServersMap().get(resultSet.getString(\"server_dofus\"));\n City city = City.getCity(resultSet.getString(\"name_city\"));\n Order order = Order.getOrder(resultSet.getString(\"name_order\"));\n int level = resultSet.getInt(\"level\");\n orders.add(new OrderUser(idUser, server, city, order, level), idUser, server, city, order);\n }\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(\"getOrders\", e);\n }\n }\n return orders;\n }\n\n /**\n * if JobUser instance contains keys\n * @param user User id\n * @param server Dofus server\n * @param city City (eg. BONTA or BRAKMAR)\n * @param order Order (eg. HEART, SPIRIT, EYES)\n * @return true if it contains\n */\n public static boolean containsKeys(long user, ServerDofus server, City city, Order order){\n return getOrders().containsKeys(user, server, city, order);\n }\n\n /**\n * getData with all the keys\n * @param user User id\n * @param server Dofus server\n * @param city City (eg. BONTA or BRAKMAR)\n * @param order Order (eg. HEART, SPIRIT, EYES)\n * @return List of JobUser\n */\n public static List<OrderUser> get(long user, ServerDofus server, City city, Order order){\n return getOrders().get(user, server, city, order);\n }\n\n /**\n * @param user Joueur de la guilde\n * @param server Serveur dofus\n * @return Liste des résultats de la recherche\n */\n public static List<EmbedCreateSpec> getOrdersFromUser(Member user, ServerDofus server, Language lg){\n List<OrderUser> result = getOrders().get(user.getId().asLong(), server, null, null);\n result.sort(OrderUser::compare);\n\n EmbedCreateSpec.Builder builder = EmbedCreateSpec.builder()\n .title(Translator.getLabel(lg, \"align.user\").replace(\"{user}\", user.getDisplayName()))\n .thumbnail(user.getAvatarUrl());\n\n if (! result.isEmpty()) {\n StringBuilder st = new StringBuilder();\n for (OrderUser orderUser : result)\n st.append(orderUser.city.getLogo()).append(orderUser.order.getLabel(lg)).append(\" : \")\n .append(orderUser.level).append(\"\\n\");\n builder.addField(Translator.getLabel(lg, \"align.aligns\"), st.toString(), true);\n }\n else\n builder.description(Translator.getLabel(lg, \"align.empty\"));\n builder.footer(server.getLabel(lg), null);\n\n return Arrays.asList(builder.build());\n }\n\n /**\n * @param users Joueurs de la guilde\n * @param server Serveur dofus\n * @param level Niveau pallier\n * @return Liste des résultats de la recherche\n */\n public static List<EmbedCreateSpec> getOrdersFromLevel(List<Member> users, ServerDofus server, int level,\n discord4j.core.object.entity.Guild guild, Language lg){\n List<OrderUser> result = new ArrayList<>();\n for(Member user : users)\n if (! user.isBot()){\n List<OrderUser> potentials = getOrders().get(user.getId().asLong(), server, null, null);\n for(OrderUser order : potentials)\n if (order.getLevel() >= level)\n result.add(order);\n }\n result.sort(OrderUser::compare);\n return getPlayersList(result, guild, server, lg, ORDER_PREFIX);\n }\n\n /**\n * @param users Joueurs de la guilde\n * @param server Serveur dofus\n * @param city Cité (Brakmar ou Bonta)\n * @param order Ordre (coeur, oeil, esprit)\n * @return Liste des résultats de la recherche\n */\n public static List<EmbedCreateSpec> getOrdersFromCityOrOrder(List<Member> users, ServerDofus server, City city,\n Order order, discord4j.core.object.entity.Guild guild, Language lg){\n List<OrderUser> result = new ArrayList<>();\n for(Member user : users)\n if (! user.isBot()){\n List<OrderUser> potentials = getOrders().get(user.getId().asLong(), server, city, order);\n result.addAll(potentials);\n }\n result.sort(OrderUser::compare);\n return getPlayersList(result, guild, server, lg, ORDER_PREFIX);\n }\n\n private static int compare(OrderUser o1, OrderUser o2) {\n return Comparator.comparingInt(OrderUser::getLevel).reversed()\n .thenComparing(OrderUser::getCity)\n .thenComparing(OrderUser::getOrder)\n .compare(o1, o2);\n }\n}", "public class ServerDofus {\n\n private final static Logger LOG = LoggerFactory.getLogger(ServerDofus.class);\n private static List<ServerDofus> servers;\n private static Map<String, ServerDofus> serversMap;\n private static boolean initialized = false;\n private String name;\n private String id;\n private Map<Language, String> labels;\n private Game game;\n\n public ServerDofus(String name, String id, Game game) {\n this.name = name;\n this.id = id;\n this.game = game;\n this.labels = new HashMap<>();\n }\n\n private synchronized static void initialize(){\n initialized = true;\n servers = new ArrayList<>();\n serversMap = new HashMap<>();\n\n Connexion connexion = Connexion.getInstance();\n Connection connection = connexion.getConnection();\n\n try {\n PreparedStatement query = connection.prepareStatement(\"SELECT name, id_dofus, game FROM Server\");\n ResultSet resultSet = query.executeQuery();\n\n while (resultSet.next()) {\n ServerDofus sd = new ServerDofus(resultSet.getString(\"name\"),\n resultSet.getString(\"id_dofus\"),\n Game.valueOf(resultSet.getString(\"game\")));\n servers.add(sd);\n serversMap.put(sd.getName(), sd);\n }\n\n query = connection.prepareStatement(\"SELECT server, language, label FROM Server_Label\");\n resultSet = query.executeQuery();\n while (resultSet.next()) {\n ServerDofus sd = serversMap.get(resultSet.getString(\"server\"));\n sd.labels.put(Language.valueOf(resultSet.getString(\"language\")), resultSet.getString(\"label\"));\n }\n\n } catch (SQLException e) {\n Reporter.report(e);\n LOG.error(\"initialize\", e);\n }\n }\n\n public synchronized static Map<String, ServerDofus> getServersMap(){\n if (! initialized)\n initialize();\n return serversMap;\n }\n\n public synchronized static List<ServerDofus> getServersDofus(){\n if (! initialized)\n initialize();\n return servers;\n }\n\n public String getLabel(Language lang){\n return Optional.ofNullable(labels.get(lang)).orElse(getName());\n }\n\n public String getName() {\n return name;\n }\n\n public String getId() {\n return id;\n }\n\n public Game getGame(){\n return game;\n }\n\n @Override\n public String toString(){\n return getName();\n }\n}", "public enum City {\n\n BONTA(\"city.bonta\", \"<:bonta:411236938771857431>\"), BRAKMAR(\"city.brakmar\", \"<:brakmar:411237228736675860>\");\n\n private static Map<String, City> cities;\n private String name;\n private String logo;\n\n City(String name, String logo){ this.name = name; this.logo = logo;}\n\n public String getName(){\n return name;\n }\n\n public String getLogo(){\n return logo;\n }\n\n public String getLabel(Language lg){\n return Translator.getLabel(lg, getName());\n }\n\n public static City getCity(String name){\n if (cities == null){\n cities = new HashMap<>();\n for(City city : City.values())\n cities.put(city.getName(), city);\n }\n\n if (cities.containsKey(name))\n return cities.get(name);\n throw new IllegalArgumentException(\"No city found for \\\"\" + name + \"\\\".\");\n }\n}", "public enum Language {\n\n FR(\"Français\", \"FR\"), EN(\"English\", \"EN\"), ES(\"Español\", \"ES\");\n\n private String name;\n private String abrev;\n\n Language(String name, String abrev){\n this.name = name;\n this.abrev = abrev;\n }\n\n public String getName() {\n return name;\n }\n\n public String getAbrev() {\n return abrev;\n }\n\n @Override\n public String toString(){\n return name;\n }\n}", "public enum Order {\n\n COEUR(\"order.heart\", \":heart:\"), ESPRIT(\"order.spirit\", \":ghost:\"), OEIL(\"order.eye\", \":eye:\");\n\n private static Map<String, Order> orders;\n private String name;\n private String logo;\n\n Order(String name, String logo){ this.name = name; this.logo = logo;}\n\n public String getName(){\n return name;\n }\n\n public String getLogo(){\n return logo;\n }\n\n public String getLabel(Language lg){\n return Translator.getLabel(lg, getName());\n }\n\n public static Order getOrder(String name){\n if (orders == null){\n orders = new HashMap<>();\n for(Order order : Order.values())\n orders.put(order.getName(), order);\n }\n\n if (orders.containsKey(name))\n return orders.get(name);\n throw new IllegalArgumentException(\"Aucun ordre trouvé pour \\\"\" + name + \"\\\".\");\n }\n}", "public final class ServerUtils {\n\n private static final DiscordException TOO_MANY_SERVERS = new TooMuchDiscordException(\"server\");\n private static final DiscordException NOT_FOUND_SERVER = new NotFoundDiscordException(\"server\");\n private static final DiscordException WRONG_BOT_USED = new WrongBotUsedDiscordException();\n\n\n public static ServerDofus getDofusServerFrom(Guild guild, MessageChannel channel){\n return Optional.ofNullable(ChannelServer.getChannelServers().get(channel.getId().asLong()))\n .map(ChannelServer::getServer)\n .orElse(guild.getServerDofus());\n }\n\n @NotNull\n public static ServerQuery getServerDofusFromName(String proposedServer, Language language){\n ServerQuery result = new ServerQuery();\n final String PROPOSED_SERVER = Normalizer.normalize(proposedServer, Normalizer.Form.NFD)\n .replaceAll(\"\\\\p{InCombiningDiacriticalMarks}+\", \"\")\n .replaceAll(\"\\\\W+\", \"\").toLowerCase().trim();\n\n List<ServerDofus> allServers = ServerDofus.getServersDofus().stream()\n .filter(server -> Normalizer.normalize(server.getLabel(language), Normalizer.Form.NFD)\n .replaceAll(\"\\\\p{InCombiningDiacriticalMarks}+\", \"\")\n .replaceAll(\"\\\\W+\", \"\").toLowerCase().trim()\n .startsWith(PROPOSED_SERVER))\n .collect(Collectors.toList());\n\n List<ServerDofus> serverDofusList = allServers.stream()\n .filter(server -> server.getGame() == Game.DOFUS)\n .collect(Collectors.toList());\n\n // Check if the server name is exactly the good one\n List<ServerDofus> exactMatchDofusServer = serverDofusList.stream()\n .filter(server -> Normalizer.normalize(server.getLabel(language), Normalizer.Form.NFD)\n .replaceAll(\"\\\\p{InCombiningDiacriticalMarks}+\", \"\")\n .replaceAll(\"\\\\W+\", \"\").toLowerCase().trim()\n .equals(PROPOSED_SERVER))\n .collect(Collectors.toList());\n\n if (exactMatchDofusServer.size() == 1)\n serverDofusList = exactMatchDofusServer;\n\n if (!serverDofusList.isEmpty()) {\n result.serversFound = serverDofusList;\n if (serverDofusList.size() > 1)\n result.exceptions.add(TOO_MANY_SERVERS);\n else\n result.server = serverDofusList.get(0);\n }\n else if (!allServers.isEmpty()) {\n result.serversFound = allServers;\n result.exceptions.add(WRONG_BOT_USED);\n }\n else\n result.exceptions.add(NOT_FOUND_SERVER);\n return result;\n }\n\n public static final class ServerQuery {\n private ServerDofus server;\n private List<ServerDofus> serversFound;\n private List<DiscordException> exceptions;\n\n private ServerQuery(){\n serversFound = new ArrayList<>();\n exceptions = new ArrayList<>();\n }\n\n public ServerDofus getServer(){\n return server;\n }\n\n public boolean hasSucceed(){\n return exceptions.isEmpty();\n }\n\n public List<ServerDofus> getServersFound(){\n return serversFound;\n }\n\n public List<DiscordException> getExceptions(){\n return exceptions;\n }\n }\n}", "public class Translator {\n\n private final static Logger LOG = LoggerFactory.getLogger(Translator.class);\n private static final int MAX_MESSAGES_READ = 100;\n private static final int MAX_CHARACTER_ACCEPTANCE = 20;\n private static Map<Language, Properties> labels;\n private static LanguageDetector languageDetector;\n\n private static LanguageDetector getLanguageDetector(){\n if (languageDetector == null){\n try {\n List<String> languages = new ArrayList<>();\n for(Language lg : Language.values())\n languages.add(lg.getAbrev().toLowerCase());\n\n List<LanguageProfile> languageProfiles = new LanguageProfileReader().read(languages);\n languageDetector = LanguageDetectorBuilder.create(NgramExtractors.standard())\n .withProfiles(languageProfiles).build();\n }\n catch (IOException e) {\n LOG.error(\"Translator.getLanguageDetector\", e);\n }\n }\n return languageDetector;\n }\n\n /**\n * Fournit la langue utilisée dans un salon textuel\n * @param channel Salon textuel\n * @return Langue de la guilde ou du salon si précisé\n */\n public static Language getLanguageFrom(MessageChannel channel){\n Language result = Constants.defaultLanguage;\n if (channel instanceof GuildMessageChannel) {\n\n Guild guild = Guild.getGuild(((GuildMessageChannel) channel).getGuild().block());\n result = guild.getLanguage();\n ChannelLanguage channelLanguage = ChannelLanguage.getChannelLanguages().get(channel.getId().asLong());\n if (channelLanguage != null)\n result = channelLanguage.getLang();\n }\n return result;\n }\n public static Language getLanguageFrom(RestChannel channel) {\n Guild guild = Guild.getGuilds().get(channel.getData().block().guildId().get().asString());\n Language result = guild.getLanguage();\n\n ChannelLanguage channelLanguage = ChannelLanguage.getChannelLanguages().get(channel.getData().block().id().asLong());\n if (channelLanguage != null)\n result = channelLanguage.getLang();\n\n return result;\n }\n\n /**\n * Génère une liste de source formatée à partir d'un salon textuel\n * @param channel Salon d'origine\n * @return Liste de message éligibles à une reconnaissance de langue\n */\n private static List<String> getReformatedMessages(MessageChannel channel){\n List<String> result = new ArrayList<>();\n\n if (channel != null) {\n try {\n List<Message> messages = channel.getMessagesBefore(Snowflake.of(Instant.now()))\n .take(MAX_MESSAGES_READ).collectList().blockOptional().orElse(Collections.emptyList());\n for (Message message : messages) {\n String content = message.getContent().replaceAll(\":\\\\w+:\", \"\").trim();\n if (content.length() > MAX_CHARACTER_ACCEPTANCE)\n result.add(content);\n }\n } catch (Exception e){\n LOG.warn(\"Impossible to gather data from \" + channel.getId().asString());\n }\n }\n return result;\n }\n\n private static List<String> getReformatedMessages(RestChannel channel){\n List<String> result = new ArrayList<>();\n\n if (channel != null) {\n try {\n List<MessageData> messages = channel.getMessagesBefore(Snowflake.of(Instant.now()))\n .take(MAX_MESSAGES_READ).collectList().blockOptional().orElse(Collections.emptyList());\n for (MessageData message : messages) {\n String content = message.content().replaceAll(\":\\\\w+:\", \"\").trim();\n if (content.length() > MAX_CHARACTER_ACCEPTANCE)\n result.add(content);\n }\n } catch (Exception e){\n LOG.warn(\"Impossible to gather data from rest channel\");\n }\n }\n return result;\n }\n\n /**\n * Détermine une langue à partir d'une source textuelle\n * @param source Source textuelle\n * @return Langue majoritaire détectée au sein de la source\n */\n private static Language getLanguageFrom(String source){\n TextObject textObject = CommonTextObjectFactories.forDetectingOnLargeText().forText(source);\n LdLocale lang = getLanguageDetector().detect(textObject)\n .or(LdLocale.fromString(Constants.defaultLanguage.getAbrev().toLowerCase()));\n\n for(Language lg : Language.values())\n if(lang.getLanguage().equals(lg.getAbrev().toLowerCase()))\n return lg;\n return Constants.defaultLanguage;\n }\n\n /**\n * Détecte la langue majoritaire utilisée dans un salon textuel\n * @param channel Salon textuel à étudier\n * @return Langue majoritaire (ou Constants.defaultLanguage si non trouvée)\n */\n public static Language detectLanguage(GuildMessageChannel channel){\n Language result = Constants.defaultLanguage;\n Map<Language, LanguageOccurrence> languages = new HashMap<>();\n for(Language lang : Language.values())\n languages.put(lang, LanguageOccurrence.of(lang));\n\n List<String> sources = getReformatedMessages(channel);\n for (String source : sources)\n languages.get(getLanguageFrom(source)).increment();\n\n int longest = languages.values().stream()\n .mapToInt(LanguageOccurrence::getOccurrence)\n .max()\n .orElse(-1);\n\n if (longest > 0){\n List<Language> languagesSelected = languages.values().stream()\n .filter(lo -> lo.getOccurrence() == longest)\n .map(LanguageOccurrence::getLanguage)\n .collect(Collectors.toList());\n if (! languagesSelected.contains(result))\n return languagesSelected.get(0);\n }\n\n return result;\n }\n\n /**\n * Fournit un libellé dans la langue choisi, pour un code donné\n * @param lang Language du libellé\n * @param property code du libellé\n * @return Libellé correspondant au code, dans la langue choisie\n */\n public synchronized static String getLabel(Language lang, String property){\n if (labels == null){\n labels = new ConcurrentHashMap<>();\n\n for(Language language : Language.values())\n try(InputStream file = Translator.class.getResourceAsStream(\"/label_\" + language.getAbrev())) {\n Properties prop = new Properties();\n prop.load(new BufferedReader(new InputStreamReader(file, StandardCharsets.UTF_8)));\n labels.put(language, prop);\n } catch (IOException e) {\n LOG.error(\"Translator.getLabel\", e);\n }\n }\n\n String value = labels.get(lang).getProperty(property);\n if (value == null || value.trim().isEmpty())\n if (Constants.defaultLanguage != lang) {\n LOG.warn(\"Missing label in \" + lang.getAbrev() + \" : \" + property);\n return getLabel(Constants.defaultLanguage, property);\n }\n else\n return property;\n return value;\n }\n\n /**\n * Classe dédiée à la détection de la langue la plus utilisée au sein d'un salon textuel\n */\n private static class LanguageOccurrence {\n private final static LanguageOccurrence DEFAULT_LANGUAGE = of(Constants.defaultLanguage);\n private final static int DEFAULT_VALUE = 0;\n private Language language;\n private int occurrence;\n\n private LanguageOccurrence(Language language, int occurrence){\n this.language = language;\n this.occurrence = occurrence;\n }\n\n private static LanguageOccurrence of(Language language){\n return new LanguageOccurrence(language, DEFAULT_VALUE);\n }\n\n public Language getLanguage(){\n return language;\n }\n\n private int getOccurrence(){\n return occurrence;\n }\n\n private void increment(){\n occurrence++;\n }\n\n public boolean equals(LanguageOccurrence lgo){\n return language.equals(lgo.language);\n }\n }\n}" ]
import commands.model.FetchCommand; import data.Guild; import data.OrderUser; import data.ServerDofus; import discord4j.common.util.Snowflake; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.object.entity.Member; import discord4j.core.object.entity.Message; import discord4j.core.spec.EmbedCreateSpec; import enums.City; import enums.Language; import enums.Order; import exceptions.*; import util.ServerUtils; import util.Translator; import java.text.Normalizer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern;
package commands.classic; /** * Created by steve on 08/02/2018 */ public class AlignmentCommand extends FetchCommand { private DiscordException notFoundFilter; private DiscordException tooMuchFilters; private DiscordException tooMuchCities; private DiscordException notFoundCity; private DiscordException tooMuchOrders; private DiscordException notFoundOrder; public AlignmentCommand(){ super("align", "(.*)"); setUsableInMP(false); notFoundFilter = new NotFoundDiscordException("filter"); tooMuchFilters = new TooMuchDiscordException("filter"); tooMuchCities = new TooMuchDiscordException("city", true); notFoundCity = new NotFoundDiscordException("city"); tooMuchOrders = new TooMuchDiscordException("order", true); notFoundOrder = new NotFoundDiscordException("order"); } @Override public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) { String content = m.group(1).trim(); Optional<discord4j.core.object.entity.Guild> guild = message.getGuild().blockOptional(); Optional<Member> user = message.getAuthorAsMember().blockOptional(); // Initialisation du Filtre City city = null; Order order = null; if (guild.isPresent() && user.isPresent()){ ServerDofus server = ServerUtils.getDofusServerFrom(Guild.getGuild(guild.get()), message.getChannel().block()); // Consultation filtré par niveau if ((m = Pattern.compile(">\\s+(\\d{1,3})(\\s+.+)?").matcher(content)).matches()){ int level = Integer.parseInt(m.group(1)); if (m.group(2) != null) { ServerUtils.ServerQuery serverQuery = ServerUtils.getServerDofusFromName(m.group(2), lg); if (serverQuery.hasSucceed()) server = serverQuery.getServer(); else { serverQuery.getExceptions() .forEach(e -> e.throwException(message, this, lg, serverQuery.getServersFound())); return; } } else if (server == null){ notFoundServer.throwException(message, this, lg); return; }
List<EmbedCreateSpec> embeds = OrderUser.getOrdersFromLevel(guild.get().getMembers()
2
MagicMicky/HabitRPGJavaAPI
HabitRPGJavaAPI/src/com/magicmicky/habitrpglibrary/onlineapi/ReviveUser.java
[ "public abstract class HabitItem {\n\tprivate String id;\n\tprivate String notes;\n\tprivate Integer priority;\n\tprivate String text;\n\tprivate double value;\n\tprivate String attribute;\n\tprivate List<String> tagsId;\n\t/**\n\t * Create a new HabitItem from what is necessary\n\t * @param id the id of the habit\n\t * @param notes the notes associated to a habit\n\t * @param priority the priority of the habit\n\t * @param text the text of the habit\n\t * @param value the value (points) of the habit\n\t */\n\tpublic HabitItem(String id, String notes, Integer priority, String text, double value) {\n\t\tthis.setId(id);\n\t\tthis.setNotes(notes);\n\t\tthis.setPriority(priority);\n\t\tthis.setText(text);\n\t\tthis.setValue(value);\n\t\tthis.tagsId=new ArrayList<String>();\n\n\t}\n\tpublic HabitItem() {\n\t\tthis(\"\",\"\",1,\"\",0);\n\t}\n\t/**\n\t * @return the id\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\t/**\n\t * @return the notes\n\t */\n\tpublic String getNotes() {\n\t\treturn notes;\n\t}\n\t/**\n\t * @param notes the notes to set\n\t */\n\tpublic void setNotes(String notes) {\n\t\tthis.notes = notes;\n\t}\n\t/**\n\t * @return the priority\n\t */\n\tpublic Integer getPriority() {\n\t\treturn priority;\n\t}\n\t/**\n\t * @param i the priority to set\n\t */\n\tpublic void setPriority(Integer i) {\n\t\tthis.priority = i;\n\t}\n\t/**\n\t * @return the text\n\t */\n\tpublic String getText() {\n\t\treturn text;\n\t}\n\t/**\n\t * @param text the text to set\n\t */\n\tpublic void setText(String text) {\n\t\tthis.text = text;\n\t}\n\t/**\n\t * @return the value\n\t */\n\tpublic double getValue() {\n\t\treturn value;\n\t}\n\t/**\n\t * @param value the value to set\n\t */\n\tpublic void setValue(double value) {\n\t\tthis.value = value;\n\t}\n\t\n\t/**\n\t * @return the tagsId\n\t */\n\tpublic List<String> getTagsId() {\n\t\treturn tagsId;\n\t}\n\t/**\n\t * @param tagsId the tagsId to set\n\t */\n\tpublic void setTagsId(List<String> tagsId) {\n\t\tthis.tagsId = tagsId;\n\t}\n\t\n\tpublic boolean isTagged(List<String> tags) {\n\t\tif(this.getTagsId()==null) {\n\t\t\tSystem.out.println(\"getTags is null!!!\");\n\t\t}\n\t\tif(this.getTagsId() != null && this.getTagsId().containsAll(tags))\n\t\t\treturn true;\n\t\t\n\t\treturn false;\n\t}\n\t/**\n\t * Returns a string of the type of the HabitItem\n\t * @return the string of the Item type\n\t */\n\tprotected abstract String getType();\n\t/**\n\t * Returns a JSONString of the current HabitItem\n\t * @return the Item in json (ready to send as POST)\n\t */\n\tpublic abstract String getJSONString();\n\n\t/**\n\t * Creates a JSON String for this HabitItem using the basic information.<br>\n\t * Doesn't have the necessary open and close brackets to create an item.\n\t * @return\n\t */\n\tprotected String getJSONBaseString() {\n\t\tStringBuilder json = new StringBuilder();\n\t\tif(this.getId()!=null)\n\t\t\tjson.append(\"\\\"id\\\":\").append(JSONObject.quote(this.getId())).append(\",\");\n\t\tjson\n\t\t\t.append(\"\\\"type\\\":\\\"\").append(this.getType()).append(\"\\\",\" )\n\t\t\t.append(\"\\\"text\\\":\").append(JSONObject.quote(this.getText())).append(\",\" );\n\t\t\tif(this.getPriority()!=null)\n\t\t\t\tjson.append(\"\\\"priority\\\":\").append(this.getPriority()).append(\",\");\n\t\t\tif(this.getNotes()!=null && !this.getNotes().contentEquals(\"\"))\n\t\t\t\tjson.append(\"\\\"notes\\\":\").append(JSONObject.quote(this.getNotes())).append(\",\" );\n\t\t\tjson.append(\"\\\"value\\\":\").append(this.getValue()).append(\",\");\n\t\t\tif(this.getTagsId()!=null && this.getTagsId().size()!=0) {\n\t\t\t\tjson.append(\"\\\"tags\\\":{\");\n\t\t\t\tfor(String tagId : this.getTagsId()) {\n\t\t\t\t\tjson.append(\"\").append(JSONObject.quote(tagId)).append(\":\").append(\"true\").append(\",\");\n\t\t\t\t}\n\t\t\t\tjson.deleteCharAt(json.length()-1);\n\t\t\t\tjson.append(\"},\");\n\t\t\t}\n\t\t\tif(this.getAttribute()!=null) {\n\t\t\t\tjson.append(\"\\\"attribute\\\":\\\"\").append(this.getAttribute()).append(\"\\\",\");\n\t\t\t}\n\t\treturn \tjson.toString();\n\t}\n\t/**\n\t * @return the attribute\n\t */\n\tpublic String getAttribute() {\n\t\treturn attribute;\n\t}\n\t/**\n\t * @param attribute the attribute to set\n\t */\n\tpublic void setAttribute(String attribute) {\n\t\tthis.attribute = attribute;\n\t}\n}", "public class User {\n\tprivate List<HabitItem> items;\n\tprivate String name;\n\tprivate double hp,maxHp=0,xp, maxXp=0,gp;\n\tprivate int lvl;\n\tprivate int dayStart;\n\tprivate UserLook look;\n\tprivate Map<String, String> tags;\n\tprivate List<String> pets, mounts, eggs, hatchingPotions, food;\n\tprivate int timeZoneOffset;\n\tprivate String userClass;\n\t/**\n\t * Create a new User\n\t */\n\tpublic User() {\n\t\tthis(new ArrayList<HabitItem>());\n\t}\n\t/**\n\t * Create a new User based on a list of HabitItem\n\t * @param items the user's list of items\n\t */\n\tpublic User(List<HabitItem> items) {\n\t\tthis.setItems(items);\n\t}\n\n\t/**\n\t * Get the tasks of an user, with or without the custom rewards\n\t * @param withCustomRewardsUpgrade whether or not you want the customrewards integrated to the HabitItem list\n\t * @return the list of all the tasks of this user\n\t */\n\tpublic List<HabitItem> getItems(boolean withCustomRewardsUpgrade) {\n\t\tif(withCustomRewardsUpgrade) {\n\t\t\tList<HabitItem> allItems = new ArrayList<HabitItem>(items);\n\t\t/*\tif(getLook() != null && getLook().getItems() != null && getLook().getItems().toRewardsUpgrade()!=null)\n\t\t\t\tallItems.addAll(getLook().getItems().toRewardsUpgrade());*/\n\t\t\treturn allItems;\n\t\t}\n\t\treturn items;\n\t}\n\t/**\n\t * @param items the items to set\n\t */\n\tpublic void setItems(List<HabitItem> items) {\n\t\tthis.items = items;\n\t}\n\t/**\n\t * @return the user's name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t/**\n\t * @param name the name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\t/**\n\t * @return the user's hp\n\t */\n\tpublic double getHp() {\n\t\treturn hp;\n\t}\n\t/**\n\t * @param hp the hp to set\n\t */\n\tpublic void setHp(double hp) {\n\t\tthis.hp = hp;\n\t}\n\t/**\n\t * @return the user's maxHp\n\t */\n\tpublic double getMaxHp() {\n\t\tif(maxHp!=0)\n\t\t\treturn maxHp;\n\t\treturn 50;\n\t}\n\t/**\n\t * @param maxHp the maxHp to set\n\t */\n\tpublic void setMaxHp(double maxHp) {\n\t\tthis.maxHp = maxHp;\n\t}\n\t/**\n\t * @return the user's xp\n\t */\n\tpublic double getXp() {\n\t\treturn xp;\n\t}\n\t/**\n\t * @param d the xp to set\n\t */\n\tpublic void setXp(double d) {\n\t\tthis.xp = d;\n\t}\n\t/**\n\t * @return the user's maxXp\n\t */\n\tpublic double getMaxXp() {\n\t\tif(maxXp != 0) {\n\t\t\treturn maxXp;\n\t\t}\n\t\treturn Math.round(((Math.pow(this.getLvl(), 2) * 0.25) + (10 * this.getLvl()) + 139.75) / 10)*10;\n\t}\n\t/**\n\t * @param maxXp the maxXp to set\n\t */\n\tpublic void setMaxXp(double maxXp) {\n\t\tthis.maxXp = maxXp;\n\t}\n\t/**\n\t * @return the user's lvl\n\t */\n\tpublic int getLvl() {\n\t\treturn lvl;\n\t}\n\t/**\n\t * @param lvl the lvl to set\n\t */\n\tpublic void setLvl(int lvl) {\n\t\tthis.lvl = lvl;\n\t}\n\t/**\n\t * @return the user's gp\n\t */\n\tpublic double getGp() {\n\t\treturn gp;\n\t}\n\t/**\n\t * @param gp the gp to set\n\t */\n\tpublic void setGp(double gp) {\n\t\tthis.gp = gp;\n\t}\n\t/**\n\t * @return the look\n\t */\n\tpublic UserLook getLook() {\n\t\treturn look;\n\t}\n\t/**\n\t * @param look the look to set\n\t */\n\tpublic void setLook(UserLook look) {\n\t\tthis.look = look;\n\t}\n\t/**\n\t * @param task the task to add to this user\n\t */\n\tpublic void addTask(HabitItem task) {\n\t\tthis.items.add(task);\n\t}\n\t\n\t\n\tpublic void editTask(HabitItem task) {\n\t\tboolean flag=false;\n\t\tint i=0;\n\t\twhile(i<this.items.size() && flag!=true) {\n\t\t\tif(this.items.get(i).getId().equals(task.getId())) {\n\t\t\t\tflag=true;\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tif(flag) {\n\t\t\tthis.items.set(i, task);\n\t\t}\n\t}\n\t/**\n\t * \n\t */\n\tpublic void deleteTask(HabitItem task) {\n\t\tif(this.items.contains(task)) {\n\t\t\tthis.items.remove(task);\n\t\t\tSystem.out.println(\"NO need for search\");\n\t\t} else {\n\t\t\tboolean flag=false;\n\t\t\tint i=0;\n\t\t\twhile(i<this.items.size() && flag!=true) {\n\t\t\t\tif(this.items.get(i).getId().equals(task.getId())) {\n\t\t\t\t\tflag=true;\n\t\t\t\t} else {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(flag) {\n\t\t\t\tthis.items.remove(i);\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t/**\n\t * @return the dayStart\n\t */\n\tpublic int getDayStart() {\n\t\treturn dayStart;\n\t}\n\t/**\n\t * @param dayStart the dayStart to set\n\t */\n\tpublic void setDayStart(int dayStart) {\n\t\tthis.dayStart = dayStart;\n\t}\n\t/**\n\t * @return the tags\n\t */\n\tpublic Map<String,String> getTags() {\n\t\treturn tags;\n\t}\n\t/**\n\t * @param tags2 the tags to set\n\t */\n\tpublic void setTags(Map<String, String> tags2) {\n\t\tthis.tags = tags2;\n\t}\n\t/**\n\t * @return the timeZoneOffset\n\t */\n\tpublic int getTimeZoneOffset() {\n\t\treturn timeZoneOffset;\n\t}\n\t/**\n\t * @param timeZoneOffset the timeZoneOffset to set\n\t */\n\tpublic void setTimeZoneOffset(int timeZoneOffset) {\n\t\tthis.timeZoneOffset = timeZoneOffset;\n\t}\n\t\n\t/**\n\t * @return true if the user is dead, false otherwise\n\t */\n\tpublic boolean isUserDead() {\n\t\treturn this.getHp()<=0;\n\t}\n\t/**\n\t * sets the class of the user\n\t * @param userClass\n\t */\n\tpublic void setUserClass(String userClass) {\n\t\tthis.userClass = userClass;\n\t}\n\t/**\n\t * @return the class of the user\n\t */\n\tpublic String getUserClass() {\n\t\treturn this.userClass;\n\t}\n\t/**\n\t * @return the pets\n\t */\n\tpublic List<String> getPets() {\n\t\treturn pets;\n\t}\n\t/**\n\t * @param pets the pets to set\n\t */\n\tpublic void setPets(List<String> pets) {\n\t\tthis.pets = pets;\n\t}\n\t/**\n\t * @return the mounts\n\t */\n\tpublic List<String> getMounts() {\n\t\treturn mounts;\n\t}\n\t/**\n\t * @param mounts the mounts to set\n\t */\n\tpublic void setMounts(List<String> mounts) {\n\t\tthis.mounts = mounts;\n\t}\n\t/**\n\t * @return the eggs\n\t */\n\tpublic List<String> getEggs() {\n\t\treturn eggs;\n\t}\n\t/**\n\t * @param eggs the eggs to set\n\t */\n\tpublic void setEggs(List<String> eggs) {\n\t\tthis.eggs = eggs;\n\t}\n\t/**\n\t * @return the hatchingPotions\n\t */\n\tpublic List<String> getHatchingPotions() {\n\t\treturn hatchingPotions;\n\t}\n\t/**\n\t * @param hatchingPotions the hatchingPotions to set\n\t */\n\tpublic void setHatchingPotions(List<String> hatchingPotions) {\n\t\tthis.hatchingPotions = hatchingPotions;\n\t}\n\t/**\n\t * @return the food\n\t */\n\tpublic List<String> getFood() {\n\t\treturn food;\n\t}\n\t/**\n\t * @param food the food to set\n\t */\n\tpublic void setFood(List<String> food) {\n\t\tthis.food = food;\n\t}\n}", "public abstract class Answer {\n\tprivate JSONObject object;\n\tprotected OnHabitsAPIResult callback;\n\t/**\n\t * Create a new Answer based on the object to parse, and the callback to call after.\n\t * @param obj the object to parse\n\t * @param callback the callback to call after parsing\n\t */\n\tpublic Answer(JSONObject obj, OnHabitsAPIResult callback) {\n\t\tthis.setObject(obj);\n\t\tthis.callback =callback;\n\t}\n\t/**\n\t * Parse the {@code object}\n\t */\n\tpublic abstract void parse();\n\n\t/**\n\t * @return the object\n\t */\n\tprotected JSONObject getObject() {\n\t\treturn object;\n\t}\n\n\t/**\n\t * @param object the object to set\n\t */\n\tprotected void setObject(JSONObject object) {\n\t\tthis.object = object;\n\t}\n}", "public class ParseErrorException extends HabitRPGException {\n\tpublic static final int HABITRPG_PARSING_ERROR_REGISTRATION=100;\n\tpublic static final int HABITRPG_PARSING_ERROR_AUTH = 101;\n\tpublic static final int JSON_DAILY_UNPARSABLE = 102;\n\tpublic static final int JSON_TODO_UNPARSABLE = 103;\n\tpublic static final int JSON_HABIT_UNPARSABLE = 104;\n\tpublic static final int JSON_REWARD_UNPARSABLE = 105;\n\tpublic static final int JSON_USER_INFO_NOT_FOUND = 106;\n\tpublic static final int JSON_USER_LOOK_NOT_FOUND = 107;\n\tpublic static final int JSON_USER_TAGS_NOT_FOUND = 108;\n\tpublic static final int HABITRPG_DIRECTION_ANSWER_UNPARSABLE = 109;\n\tpublic static final int JSON_CHECKLIST_UNPARSABLE = 110;\n\tpublic static final int JSON_USER_HAS_NO_TASKS_TAGS = 120;\n\tpublic static final int JSON_USER_HAS_NO_DAILIES_TAGS = 121;\n\tpublic static final int JSON_USER_HAS_NO_TODOS_TAGS = 122;\n\tpublic static final int JSON_USER_HAS_NO_HABITS_TAGS = 123;\n\tpublic static final int JSON_USER_HAS_NO_REWARDS_TAGS = 124;\n\tpublic static final int JSON_USER_HAS_NO_ITEMS = 125;\n\tpublic static final int JSON_USER_PREFS_ERROR = 130;\n\n\tpublic static final int TASK_NOT_DELETED = 200;\n\t\n\tpublic ParseErrorException(int id, String message) {\n\t\tsuper(id, message);\n\t}\n\tpublic ParseErrorException(int id) {\n\t\tthis(id, errorToString(id));\n\t}\n\t\n\tprivate static String errorToString(int id) {\n\t\tString details=null;\n\t\tswitch(id) {\n\t\tcase HABITRPG_PARSING_ERROR_REGISTRATION:\n\t\t\tdetails=\"Error while registering!\";\n\t\t\tbreak;\n\t\tcase HABITRPG_PARSING_ERROR_AUTH:\n\t\t\tdetails=\"Error while authentication\";\n\t\t\tbreak;\n\t\tcase JSON_DAILY_UNPARSABLE:\n\t\t\tdetails=\"Error: your dailies couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_TODO_UNPARSABLE:\n\t\t\tdetails=\"Error: your Todos couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_HABIT_UNPARSABLE:\n\t\t\tdetails=\"Error: your Habits couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_REWARD_UNPARSABLE:\n\t\t\tdetails=\"Error: your Rewards couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_USER_INFO_NOT_FOUND:\n\t\t\tdetails=\"Error: your User's information couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_USER_LOOK_NOT_FOUND:\n\t\t\tdetails=\"Error: your user's look couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_USER_TAGS_NOT_FOUND:\n\t\t\tdetails=\"Error: your tags couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase HABITRPG_DIRECTION_ANSWER_UNPARSABLE:\n\t\t\tdetails=\"Error: HabitRPG's answer couldn't be parsed\";\n\t\t\tbreak;\n\t\tcase JSON_USER_HAS_NO_TASKS_TAGS:\n\t\t\tdetails=\"Error: you have no tasks tag\";\n\t\t\tbreak;\n\t\tcase JSON_USER_HAS_NO_DAILIES_TAGS:\n\t\t\tdetails=\"Error: you have no dailies tag\";\n\t\t\tbreak;\n\t\tcase JSON_USER_HAS_NO_TODOS_TAGS:\n\t\t\tdetails=\"Error: you have no todos tag\";\n\t\t\tbreak;\n\t\tcase JSON_USER_HAS_NO_HABITS_TAGS:\n\t\t\tdetails=\"Error: you have no habits tag\";\n\t\t\tbreak;\n\t\tcase JSON_USER_HAS_NO_REWARDS_TAGS:\n\t\t\tdetails=\"Error: you have no dailies tag\";\n\t\tcase TASK_NOT_DELETED:\n\t\t\tdetails=\"Unable to delete the task\";\n\t\t\tbreak;\n\t\t\t\n\t\t}\n\t\treturn details;\n\t}\n}", "public class ParserHelper {\n\tprivate final static String TAG_ERR=\"err\";\n\n\tprivate final static String TAG_AUTH_API_TOKEN=\"token\";\n\tprivate final static String TAG_AUTH_USER_TOKEN=\"id\";\n\tprivate final static String TAG_REG_API_TOKEN=\"apiToken\";\n\tprivate final static String TAG_REG_USER_TOKEN=\"id\";\n\n\t\n\tprivate static final String TAG_habitData = \"habitRPGData\";\n\tprivate static final String TAG_DAILIESID = \"dailyIds\";\n\tprivate static final String TAG_HABITSID = \"habitIds\";\n\tprivate static final String TAG_TODOIDS = \"todoIds\";\n\tprivate static final String TAG_REWARDIDS = \"rewardIds\";\n\tprivate static final String TAG_TAGS = \"tags\";\n\t\tprivate static final String TAG_TAGS_ID = \"id\";\n\t\tprivate static final String TAG_TAGS_NAME = \"name\";\n\tprivate static final String TAG_STATS = \"stats\";\n\t\tprivate static final String TAG_STATS_CLASS = \"class\";\n\t\tprivate static final String TAG_XP = \"exp\";\n\t\tprivate static final String TAG_GP = \"gp\";\n\t\tprivate static final String TAG_HP = \"hp\";\n\t\tprivate static final String TAG_LVL=\"lvl\";\n\t\tprivate static final String TAG_XP_MAX=\"toNextLevel\";\n\t\tprivate static final String TAG_HP_MAX = \"maxHealth\";\n\tprivate static final String TAG_TASKS = \"tasks\";\n\t\tprivate static final String TAG_TASK_TYPE = \"type\";\n\t\tprivate static final String TAG_TASK_ID = \"id\";\n\t\tprivate static final String TAG_TASK_DATE = \"date\";\n\t\tprivate static final String TAG_TASK_NOTES = \"notes\";\n\t\tprivate static final String TAG_TASK_PRIORITY = \"priority\";\n\t\tprivate static final String TAG_TASK_TEXT = \"text\";\n\t\tprivate static final String TAG_TASK_VALUE = \"value\";\n\t\tprivate static final String TAG_TASK_ATTRIBUTE=\"attribute\";\n\t\tprivate static final String TAG_TASK_COMPLETED = \"completed\";\n\t\tprivate static final String TAG_TASK_UP = \"up\";\n\t\tprivate static final String TAG_TASK_DOWN = \"down\";\n\t\tprivate static final String TAG_TASK_REPEAT = \"repeat\";\n\t\tprivate static final String TAG_TASK_STREAK=\"streak\";\n\t\tprivate static final String TAG_TASK_TAGS = \"tags\";\n\t\tprivate static final String TAG_TASK_HISTORY=\"history\";\n\t\t\tprivate static final String TAG_TASK_HISTORY_DATE = \"date\";\n\tprivate static final String TAG_CHECKLIST= \"checklist\";\n\t\tprivate static final String TAG_CHECKLIST_ID = \"id\";\n\t\tprivate static final String TAG_CHECKLIST_TEXT = \"text\";\n\t\tprivate static final String TAG_CHECKLIST_COMPLETED = \"completed\";\n\tprivate static final String TAG_PROFILE = \"profile\";\n\t\tprivate static final String TAG_PROFILE_NAME=\"name\";\n\tprivate static final String TAG_PREFS = \"preferences\";\n\t\tprivate static final String TAG_PREFS_COSTUME=\"costume\";\n\t\tprivate static final String TAG_PREFS_SKIN = \"skin\";\n\t\tprivate static final String TAG_PREFS_SHIRT=\"shirt\";\n\t\tprivate static final String TAG_PREFS_HAIR = \"hair\";\n\t\t\tprivate static final String TAG_PREFS_HAIR_MUSTACHE=\"mustache\";\n\t\t\tprivate static final String TAG_PREFS_HAIR_BEARD=\"beard\";\n\t\t\tprivate static final String TAG_PREFS_HAIR_BANGS=\"bangs\";\n\t\t\tprivate static final String TAG_PREFS_HAIR_BASE=\"base\";\n\t\t\tprivate static final String TAG_PREFS_HAIR_COLOR=\"color\";\n\t\tprivate static final String TAG_PREFS_SIZE=\"size\";\n\t\tprivate static final String TAG_PREFS_DAYSTART = \"dayStart\";\n\t\tprivate static final String TAG_PREFS_TIMEZONEOFFSET =\"timezoneOffset\";\n\tprivate static final String TAG_ITEMS = \"items\";\n\t\tprivate static final String TAG_ITEMS_PETS = \"pets\";\n\t\tprivate static final String TAG_ITEMS_MOUNTS=\"mounts\";\n\t\tprivate static final String TAG_ITEMS_EGGS=\"eggs\";\n\t\tprivate static final String TAG_ITEMS_HATCHING_POTIONS=\"hatchingPotions\";\n\t\tprivate static final String TAG_ITEMS_FOOD=\"food\";\n\t\tprivate static final String TAG_ITEMS_GEAR=\"gear\";\n\t\tprivate static final String TAG_ITEMS_GEAR_EQUIPPED=\"equipped\";\n\t\tprivate static final String TAG_ITEMS_GEAR_COSTUME = \"costume\";\n\t\t\tprivate static final String TAG_ITEMS_ARMOR = \"armor\";\n\t\t\tprivate static final String TAG_ITEMS_HEAD = \"head\";\n\t\t\tprivate static final String TAG_ITEMS_SHIELD = \"shield\";\n\t\t\tprivate static final String TAG_ITEMS_WEAPON = \"weapon\";\n\n\t\t//TODO:private static final String TAG_ITEMS_PETS = \"pets\";\n\t\tprivate static final String TAG_NOWXP = \"exp\";\n\t\tprivate static final String TAG_NOWGP = \"gp\";\n\t\tprivate static final String TAG_NOWHP = \"hp\";\n\t\tprivate static final String TAG_DELTA = \"delta\";\n\n\t\tprivate static final String TAG_TASK_DELETED = \"task_deleted\";\n\t\t\n\t\t//Hotfix\n\t\tprivate static final String TAG_DAILIES=\"dailys\";\n\t\tprivate static final String TAG_HABITS=\"habits\";\n\t\tprivate static final String TAG_TODOS=\"todos\";\n\t\tprivate static final String TAG_REWARDS=\"rewards\";\n\t\n\tpublic static User parseUser(JSONObject obj) throws ParseErrorException{\n\t\tparseError(obj);\n\t\tif(obj.has(TAG_habitData)) {\n\t\t\ttry {\n\t\t\t\tobj = obj.getJSONObject(TAG_habitData);\n\t\t\t} catch (JSONException e1) {\n\t\t\t\t// Can't happen\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tUser user = new User();\n\t\t/*\n\t\t * Parse tasks\n\t\t */\n\t\t\tuser.setItems(parseTasks(obj));\n\t\t\n\t\t/*\n\t\t * Parse User infos\n\t\t */\n\t\ttry {\n\t\t\tparseUserInfos(obj, user);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\t//exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_INFO_NOT_FOUND));\n\t\t}\n\t\t/*\n\t\t * Parse user look\n\t\t */\n\t\ttry {\n\t\t\tuser.setLook(parseUserLook(obj));\n\t\t} catch (ParseErrorException e) {\n\t\t\te.printStackTrace();\n\t\t\t//TODO:\n\t\t\t//exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_LOOK_NOT_FOUND));\n\n\t\t}\n\t\t/*\n\t\t * Parse user tags.\n\t\t */\n\t\ttry {\n\t\t\tuser.setTags(parseUserTags(obj.getJSONArray(TAG_TAGS)));\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\t//exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_TAGS_NOT_FOUND));\n\t\t}\n\t\ttry {\n\t\t\tparseUserInventory(obj.getJSONObject(TAG_ITEMS), user);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\t//exceptions.add(new ParseErrorException(ParseErrorException.JSON_USER_TAGS_NOT_FOUND));\n\t\t}\n\n\t\treturn user;\n\t\t\n\t}\n\tprivate static void parseUserInventory(JSONObject obj, User user) {\n\t\tList<String> pets, mounts, eggs, hatchingPotions, food;\n\t\t//Pets:\n\t\ttry {\n\t\t\tJSONObject pets_json = obj.getJSONObject(TAG_ITEMS_PETS);\n\n\t\t\tJSONArray pets_array = pets_json.names();\n\t\t\tpets = new ArrayList<String>();\n\t\t\tif(pets_array != null && pets_array.length()>0) {\n\t\t\t\tfor(int i = 0;i<pets_array.length()-1;i++) {\n\t\t\t\t\tif(pets_json.getInt(pets_array.getString(i))>=1)\n\t\t\t\t\t\tpets.add(pets_array.getString(i));\n\t\t\t\t}\n\t\t\t}\n\t\t\tuser.setPets(pets);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t/*Mounts\n\t\tJSONArray mounts_array = obj.getJSONArray(TAG_ITEMS_MOUNTS);*/\n\t\ttry {\n\t\t\t//Eggs\n\t\t\tJSONObject eggs_json = obj.getJSONObject(TAG_ITEMS_EGGS);\n\t\t\tJSONArray eggs_array = eggs_json.names();\n\t\t\teggs = new ArrayList<String>();\n\t\t\t\tif(eggs_array != null && eggs_array.length()>0) {\n\t\t\t\tfor(int i = 0;i<eggs_array.length()-1;i++) {\n\t\t\t\t\tif(eggs_json.getInt(eggs_array.getString(i))>=1)\n\t\t\t\t\t\teggs.add(eggs_array.getString(i));\n\t\t\t\t}\n\t\t\t}\n\t\t\tuser.setEggs(eggs);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\t//hatching potions\n\t\t\tJSONObject pot_json = obj.getJSONObject(TAG_ITEMS_HATCHING_POTIONS);\n\t\t\tJSONArray pot_array = pot_json.names();\n\t\t\thatchingPotions = new ArrayList<String>();\n\t\t\tif(pot_array!=null && pot_array.length() > 0) {\n\t\t\t\tfor(int i = 0;i<pot_array.length()-1;i++) {\n\t\t\t\t\tif(pot_json.getInt(pot_array.getString(i))>=1)\n\t\t\t\t\t\thatchingPotions.add(pot_array.getString(i));\n\t\t\t\t}\n\t\t\t}\n\t\t\tuser.setHatchingPotions(hatchingPotions);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\t//food\n\t\t\tJSONObject food_json = obj.getJSONObject(TAG_ITEMS_FOOD);\n\t\t\tJSONArray food_array = food_json.names();\n\t\t\tfood = new ArrayList<String>();\n\t\t\tif(food_array!=null && food_array.length()>0) {\n\t\t\t\tfor(int i = 0;i<food_array.length()-1;i++) {\n\t\t\t\t\tif(food_json.getInt(food_array.getString(i))>=1)\n\t\t\t\t\t\tfood.add(food_array.getString(i));\n\t\t\t\t}\n\t\t\t}\n\t\t\tuser.setFood(food);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\n\t}\n\t/**\n\t * Parses the tags from the user\n\t * @param obj the JSONArray containing the tags\n\t * @return a map of {@code <TagId, TagName>}\n\t */\n\tprivate static Map<String, String> parseUserTags(JSONArray obj) {\n\t\tMap<String,String> tags = new HashMap<String,String>();\n\t\ttry {\n\t\t\tfor(int i=0;i<obj.length();i++) {\n\t\t\t\tJSONObject tag_obj = obj.getJSONObject(i);\n\t\t\t\ttags.put(tag_obj.getString(TAG_TAGS_ID), tag_obj.getString(TAG_TAGS_NAME));\n\t\t\t}\n\t\t} catch(JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn tags;\n\t}\n\n\tpublic static UserLook parseUserLook(JSONObject obj) throws ParseErrorException {\n\t\tUserLook look = new UserLook();\n\t\tif(obj.has(TAG_PREFS)) {\n\t\t\ttry {\n\t\t\t\tJSONObject prefs;\n\t\t\t\tprefs = obj.getJSONObject(TAG_PREFS);\n\t\t\t\tif(prefs.has(TAG_PREFS_COSTUME)) {\n\t\t\t\t\tlook.setCostume(prefs.getBoolean(TAG_PREFS_COSTUME));\n\t\t\t\t}\n\t\t\t\tif(prefs.has(TAG_PREFS_SIZE))\n\t\t\t\t\tlook.setSize(prefs.getString(TAG_PREFS_SIZE));\n\t\t\t\tif(prefs.has(TAG_PREFS_SHIRT)) \n\t\t\t\t\tlook.setShirtColor(prefs.getString(TAG_PREFS_SHIRT));\n\t\t\t\tif(prefs.has(TAG_PREFS_SKIN))\n\t\t\t\t\tlook.setSkin(prefs.getString(TAG_PREFS_SKIN));\n\t\t\t\tif(prefs.has(TAG_PREFS_HAIR)) {\n\t\t\t\t\tJSONObject hair = prefs.getJSONObject(TAG_PREFS_HAIR);\n\t\t\t\t\tint mustache = hair.getInt(TAG_PREFS_HAIR_MUSTACHE);\n\t\t\t\t\tint beard = hair.getInt(TAG_PREFS_HAIR_BEARD);\n\t\t\t\t\tint bangs = hair.getInt(TAG_PREFS_HAIR_BANGS);\n\t\t\t\t\tint base = hair.getInt(TAG_PREFS_HAIR_BASE);\n\t\t\t\t\tString color = hair.getString(TAG_PREFS_HAIR_COLOR);\n\t\t\t\t\t//UserHair user_hair = new UserHair(mustache, beard, bangs, base, color);\n\t\t\t\t\tUserHair user_hair = new UserHair(mustache, beard,bangs,base, color);\n\t\t\t\t\tlook.setHair(user_hair);\n\n\t\t\t\t}\n\t\t\t}catch(JSONException e) {\n\t\t\t\tthrow new ParseErrorException(ParseErrorException.JSON_USER_PREFS_ERROR);\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tlook.setItems(parseUserItems(obj.getJSONObject(TAG_ITEMS).getJSONObject(TAG_ITEMS_GEAR).getJSONObject(TAG_ITEMS_GEAR_EQUIPPED)));\n\t\t} catch(JSONException e) {\n\t\t\tthrow new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_ITEMS);\n\t\t}\n\t\ttry {\n\t\t\tlook.setCostumeItems(parseUserItems(obj.getJSONObject(TAG_ITEMS).getJSONObject(TAG_ITEMS_GEAR).getJSONObject(TAG_ITEMS_GEAR_COSTUME)));\n\t\t} catch(JSONException e) {\n\t\t\tthrow new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_ITEMS);\n\t\t}\n\n\t\treturn look;\n\t}\n\tpublic static UserLook.UserItems parseUserItems(JSONObject obj) throws ParseErrorException {\n\t\tparseError(obj);\n\t\tString armor = null, head = null, shield = null, weapon = null;\n\t\ttry {\n\t\t\tif(obj.has(TAG_ITEMS_ARMOR))\n\t\t\t\tarmor = (obj.getString(TAG_ITEMS_ARMOR));\n\t\t\tif(obj.has(TAG_ITEMS_HEAD))\n\t\t\t\thead = (obj.getString(TAG_ITEMS_HEAD));\n\t\t\tif(obj.has(TAG_ITEMS_SHIELD))\n\t\t\t\tshield = (obj.getString(TAG_ITEMS_SHIELD));\n\t\t\tif(obj.has(TAG_ITEMS_WEAPON))\n\t\t\t\tweapon = (obj.getString(TAG_ITEMS_WEAPON));\n\t\t} catch (JSONException e){\n\t\t\te.printStackTrace();\n\t\t\t//Should never happen\n\t\t}\n\t\treturn new UserLook.UserItems(armor, head, shield, weapon);\n\t}\n\tprivate static void parseUserInfos(JSONObject obj, User user) throws JSONException {\n\t\tif(obj.has(TAG_STATS)) {\n\t\t\tJSONObject stats = obj.getJSONObject(TAG_STATS);\n\t\t\tif(stats.has(TAG_LVL))\n\t\t\t\tuser.setLvl(stats.getInt(TAG_LVL));\n\t\t\tif(stats.has(TAG_XP))\n\t\t\t\tuser.setXp(stats.getDouble(TAG_XP));\n\t\t\tif(stats.has(TAG_XP_MAX))\n\t\t\t\tuser.setMaxXp(stats.getDouble(TAG_XP_MAX));\n\t\t\tif(stats.has(TAG_HP))\n\t\t\t\tuser.setHp(stats.getDouble(TAG_HP));\n\t\t\tif(stats.has(TAG_HP_MAX))\n\t\t\t\tuser.setMaxHp(stats.getDouble(TAG_HP_MAX));\n\t\t\tif(stats.has(TAG_GP))\n\t\t\t\tuser.setGp(stats.getDouble(TAG_GP));\n\t\t\tif(stats.has(TAG_STATS_CLASS))\n\t\t\t\tuser.setUserClass(stats.getString(TAG_STATS_CLASS));\n\t\t}\n\t\tif(obj.has(TAG_PREFS)) {\n\t\t\tJSONObject prefs = obj.getJSONObject(TAG_PREFS);\n\t\t\tif(prefs.has(TAG_PREFS_DAYSTART))\n\t\t\t\tuser.setDayStart(prefs.getInt(TAG_PREFS_DAYSTART));\n\t\t\telse\n\t\t\t\tuser.setDayStart(0);\n\t\t\tif(prefs.has(TAG_PREFS_TIMEZONEOFFSET))\n\t\t\t\tuser.setTimeZoneOffset(prefs.getInt(TAG_PREFS_TIMEZONEOFFSET));\n\t\t}\n\t\tif(obj.has(TAG_PROFILE)) {\n\t\t\tJSONObject profile = obj.getJSONObject(TAG_PROFILE);\n\t\t\t\tuser.setName(profile.getString(TAG_PROFILE_NAME));\n\t\t}\n\t\t\n\n\t}\n\t/**\n\t * Parse all the tasks of the user\n\t * @param obj the json object of the user\n\t * @return the list of all the tasks of the user\n\t * @throws ParseErrorException when something isn't found.\n\t */\n\tpublic static List<HabitItem> parseTasks(JSONObject obj) throws ParseErrorException {\n\t\tparseError(obj);\n\t\tList<HabitItem> items = new ArrayList<HabitItem>();\n\t\t//First, parse the TASKS tag to find all tasks.\n\t\tJSONObject tasks;\n\t\t//try {\n\t\t\ttry {\n\t\t\t\tJSONArray h = obj.getJSONArray(TAG_HABITS);\n\t\t\t\tfor(int i=0;i<h.length();i++) {\n\t\t\t\t\titems.add(parseHabit(h.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\tJSONArray d = obj.getJSONArray(TAG_DAILIES);\n\t\n\t\t\t\tfor(int i=0;i<d.length();i++) {\n\t\t\t\t\titems.add(parseDaily(d.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\tJSONArray r = obj.getJSONArray(TAG_REWARDS);\n\t\t\t\tfor(int i=0;i<r.length();i++) {\n\t\t\t\t\titems.add(parseReward(r.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\tJSONArray t = obj.getJSONArray(TAG_TODOS);\n\t\t\t\tfor(int i=0;i<t.length();i++) {\n\t\t\t\t\titems.add(parseTodo(t.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t} catch (JSONException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\t\n\n\t\t\t//tasks = obj.getJSONObject(TAG_TASKS);\n\t\t\n\t\t\n\t\t/*\n\t\t * Then parse DAILISES tag to find dailies id\n\t\t * and loop through them to find it in the TASKS tags\n\t\t */\n\t\t/*try {\n\t\t\tJSONArray dailies = obj.getJSONArray(TAG_DAILIESID);\n\t\t\tfor(int i=0;i<dailies.length();i++) {\n\t\t\t\tif(tasks.has(dailies.getString(i))) {\n\n\t\t\t\t\titems.add(parseDaily(tasks.getJSONObject(dailies.getString(i))));\n\t\t\t\t\t//TODO: it Throws exception when stuff not found, but we still want to continue if this happens.\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_DAILIES_TAGS);\n\t\t\tthrow(ex);\n\t\t}\n\n\t\ttry {\n\t\t\tJSONArray todos = obj.getJSONArray(TAG_TODOIDS);\n\t\t\tfor(int i=0;i<todos.length();i++) {\n\t\t\t\tif(tasks.has(todos.getString(i))) {\n\t\t\t\t\titems.add(parseTodo(tasks.getJSONObject(todos.getString(i))));\n\t\t\t\t}\n\t\t\t}\t\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_TODOS_TAGS);\n\t\t\tthrow(ex);\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tJSONArray habits = obj.getJSONArray(TAG_HABITSID);\n\t\t\tfor(int i=0;i<habits.length();i++) {\n\t\t\t\tif(tasks.has(habits.getString(i))) {\n\t\t\t\t\titems.add(parseHabit(tasks.getJSONObject(habits.getString(i))));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_HABITS_TAGS);\n\t\t\tthrow(ex);\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tJSONArray rewards = obj.getJSONArray(TAG_REWARDIDS);\n\t\t\tfor(int i=0;i<rewards.length();i++) {\n\t\t\t\tif(tasks.has(rewards.getString(i))) {\n\t\t\t\t\titems.add(parseReward(tasks.getJSONObject(rewards.getString(i))));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_REWARDS_TAGS);\n\t\t\tthrow(ex);\n\t\t}\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\t//tasks = obj.getJSONObject(key)\n\t\t\t\n\t\t\ttry {\n\t\t\t\tJSONArray h = obj.getJSONArray(TAG_HABITS);\n\t\t\t\tfor(int i=0;i<h.length();i++) {\n\t\t\t\t\titems.add(parseHabit(h.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\tJSONArray d = obj.getJSONArray(TAG_DAILIES);\n\t\n\t\t\t\tfor(int i=0;i<d.length();i++) {\n\t\t\t\t\titems.add(parseDaily(d.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\tJSONArray r = obj.getJSONArray(TAG_TODOS);\n\t\t\t\tfor(int i=0;i<r.length();i++) {\n\t\t\t\t\titems.add(parseReward(r.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\tJSONArray t = obj.getJSONArray(TAG_TODOS);\n\t\t\t\tfor(int i=0;i<t.length();i++) {\n\t\t\t\t\titems.add(parseTodo(t.getJSONObject(i)));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t} catch (JSONException e1) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te1.printStackTrace();\n\t\t\t}\t*/\n\t\t\t\n\t\t\n\t\t\t//private static final String TAG_HABITS=\"habits\";\n\t\t\t//private static final String TAG_TODOS=\"todos\";\n\t\t\t//private static final String TAG_REWARDS=\"rewards\";\n\n\t\t\t//ParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_USER_HAS_NO_TASKS_TAGS);\n\t\t\t//throw(ex);\n\t\t//}\n\t\treturn items;\n\t\t\n\t}\n\n\n\tpublic static HabitItem parseHabitItem(JSONObject obj) throws ParseErrorException {\n\t\tparseError(obj);\n\t\ttry {\n\t\t\tif(obj.getString(TAG_TASK_TYPE).equals(\"reward\")) {\n\t\t\t\treturn parseReward(obj);\n\t\t\t}\n\t\t\telse if(obj.getString(TAG_TASK_TYPE).equals(\"habit\")) {\n\t\t\t\treturn parseHabit(obj);\n\t\t\t} else if(obj.getString(TAG_TASK_TYPE).equals(\"daily\")) {\n\t\t\t\treturn parseDaily(obj);\n\t\t\t} else if(obj.getString(TAG_TASK_TYPE).equals(\"todo\")) {\n\t\t\t\treturn parseTodo(obj);\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t\n\t}\n\n\tpublic static double[] parseDirectionAnswer(JSONObject obj) throws ParseErrorException {\n\t\ttry {\n\t\t\tdouble xp = 0,hp = 0,gold = 0,lvl = 0,delta = 0;\n\t\t\t if(obj.has(TAG_NOWXP))\n\t\t\t\t xp = obj.getDouble(TAG_NOWXP);\n\t\t\t if(obj.has(TAG_NOWHP))\n\t\t\t\t hp = obj.getDouble(TAG_NOWHP);\n\t\t\t if(obj.has(TAG_NOWGP))\n\t\t\t\t gold = obj.getDouble(TAG_NOWGP);\n\t\t\t if(obj.has(TAG_LVL))\n\t\t\t\t lvl = obj.getDouble(TAG_LVL);\n\t\t\t if(obj.has(TAG_DELTA))\n\t\t\t\t delta = obj.getDouble(TAG_DELTA);\n\t\t\t double[] res = {xp,hp,gold,lvl,delta};\n\t\t\t return res;\n\t\t} catch (JSONException e) {\n\t\t\t e.printStackTrace();\n\t\t\tthrow(new ParseErrorException(ParseErrorException.HABITRPG_DIRECTION_ANSWER_UNPARSABLE));\n\t\t}\n\n\t}\n\n\tprivate static Habit parseHabit(JSONObject obj) throws ParseErrorException {\n\t\ttry {\n\t\t\t\tHabit it = new Habit();\n\t\t\t\tparseBase(it, obj);\n\t\t\t\tit.setUp(obj.has(TAG_TASK_UP) ? obj.getBoolean(TAG_TASK_UP) : false);\n\t\t\t\tit.setDown(obj.has(TAG_TASK_DOWN) ? obj.getBoolean(TAG_TASK_DOWN) : false);\n\t\t\t\treturn it;\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_HABIT_UNPARSABLE);\n\t\t\tthrow(ex);\n\t\t}\n\t}\n\tprivate static Daily parseDaily(JSONObject obj) throws ParseErrorException {\n\t\ttry {\n\t\t\tDaily it;\n\t\t\tString lastday=\"\";\n\t\t\t\n\t\t\tif(obj.has(TAG_TASK_HISTORY)) {\n\t\t\t\tJSONArray history = obj.getJSONArray(TAG_TASK_HISTORY);\n\t\t\t\tif(history.length()>=1) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tlastday = history.getJSONObject(history.length()-1).getString(TAG_TASK_HISTORY_DATE);\n\t\t\t\t\t} catch(JSONException e) {\n\t\t\t\t\t\tSimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n\t\t\t\t\t\tlastday=format.format(new Date(history.getJSONObject(history.length()-1).getLong(TAG_TASK_HISTORY_DATE)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} \n\t\t\tboolean[] repeats = {false,false,false,false,false,false,false};\n\t\t\tif(obj.has(TAG_TASK_REPEAT)) {\n\t\t\t\tJSONObject repeatTag = obj.getJSONObject(TAG_TASK_REPEAT);\n\t\t\t\tfor(int j=0;j<7;j++) {\n\t\t\t\t\tif(repeatTag.has(whatDay(j))) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\trepeats[j] = repeatTag.getBoolean(whatDay(j));\n\t\t\t\t\t\t} catch(JSONException e) {\n\t\t\t\t\t\t\trepeats[j] = repeatTag.getInt(whatDay(j)) >= 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tit = new Daily();\n\t\t\tparseBase(it, obj);\n\t\t\tit.setCompleted(obj.has(TAG_TASK_COMPLETED) ? obj.getBoolean(TAG_TASK_COMPLETED) : false);\n\t\t\tit.setRepeat(repeats);\n\t\t\tit.setStreak(obj.has(TAG_TASK_STREAK) ? obj.getInt(TAG_TASK_STREAK) : 0);\n\t\t\tit.setLastCompleted(lastday);\n\t\t\tif(obj.has(TAG_CHECKLIST)){\n\t\t\t\tJSONArray clArray = obj.getJSONArray(TAG_CHECKLIST);\n\t\t\t\tif(clArray.length()>0) {\n\t\t\t\t\tChecklist cl = parseChecklist(clArray);\n\t\t\t\t\tit.setChecklist(cl);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn it;\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_DAILY_UNPARSABLE);\n\t\t\tthrow(ex);\n\t\t}\n\t}\n\tprivate static ToDo parseTodo(JSONObject obj) throws ParseErrorException {\n\t\ttry {\n\t\t\tToDo it= new ToDo();\n\t\t\tparseBase(it, obj);\n\t\t\tit.setCompleted(obj.has(TAG_TASK_COMPLETED) ? obj.getBoolean(TAG_TASK_COMPLETED) : false);\n\t\t\tit.setDate(obj.has(TAG_TASK_DATE) ? obj.getString(TAG_TASK_DATE) : null);\n\t\t\tif(obj.has(TAG_CHECKLIST)){\n\t\t\t\tJSONArray clArray = obj.getJSONArray(TAG_CHECKLIST);\n\t\t\t\tif(clArray.length()>0) {\n\t\t\t\t\tChecklist cl = parseChecklist(clArray);\n\t\t\t\t\tit.setChecklist(cl);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn it;\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_TODO_UNPARSABLE);\n\t\t\tthrow(ex);\n\t\t}\n\t}\n\tprivate static Reward parseReward(JSONObject obj) throws ParseErrorException {\n\t\ttry {\n\t\t\tReward it = new Reward();\n\t\t\tparseBase(it, obj);\n\t\t\treturn it;\n\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_REWARD_UNPARSABLE);\n\t\t\tthrow(ex);\n\t\t}\n\t}\n\t\n\tprivate static Checklist parseChecklist(JSONArray obj) throws ParseErrorException {\n\t\tChecklist cl = new Checklist();\n\t\ttry {\n\t\t\tfor(int i=0;i<obj.length();i++) {\n\t\t\t\tJSONObject current_item = obj.getJSONObject(i);\n\t\t\t\tString id = current_item.getString(TAG_CHECKLIST_ID);\n\t\t\t\tString text = current_item.getString(TAG_CHECKLIST_TEXT);\n\t\t\t\tboolean cmplt = current_item.getBoolean(TAG_CHECKLIST_COMPLETED);\n\t\t\t\tChecklistItem it = new ChecklistItem(id, text,cmplt);\n\t\t\t\tcl.addItem(it);\n\t\t\t}\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t\tParseErrorException ex = new ParseErrorException(ParseErrorException.JSON_CHECKLIST_UNPARSABLE);\n\t\t\tthrow(ex);\n\t\t}\n\t\t\n\t\treturn cl;\n\t}\n\t\n\tprivate static <T extends HabitItem> void parseBase(T it, JSONObject habit) throws JSONException {\n\t\tif(habit.has(TAG_TASK_ID))\n\t\t\tit.setId(habit.getString(TAG_TASK_ID));\n\t\tif(habit.has(TAG_TASK_NOTES))\n\t\t\tit.setNotes(habit.getString(TAG_TASK_NOTES));\n\t\tif(habit.has(TAG_TASK_PRIORITY))\n\t\t\tit.setPriority(habit.getInt(TAG_TASK_PRIORITY));\n\t\tif(habit.has(TAG_TASK_TEXT))\n\t\t\tit.setText(habit.getString(TAG_TASK_TEXT));\n\t\tif(habit.has(TAG_TASK_VALUE))\n\t\t\tit.setValue(habit.getDouble(TAG_TASK_VALUE));\n\t\tif(habit.has(TAG_TASK_ATTRIBUTE))\n\t\t\tit.setAttribute(habit.getString(TAG_TASK_ATTRIBUTE));\n\t\tif(habit.has(TAG_TASK_TAGS) && !habit.isNull(TAG_TASK_TAGS)) {\n\t\t\ttry {\n\t\t\t\tJSONObject tagsJSON = habit.getJSONObject(TAG_TASK_TAGS);\n\t\t\t\tList<String> tags = parseTaskTags(tagsJSON);\n\t\t\t\tit.setTagsId(tags);\n\n\t\t\t} catch(JSONException error) {\n\t\t\t\terror.printStackTrace(); \n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static List<String> parseTaskTags(JSONObject tagsJSON) throws JSONException {\n\t\tList<String> tagsIds = new ArrayList<String>();\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tIterator<String> it = tagsJSON.keys();\n\t\twhile(it.hasNext()) {\n\t\t\tString tag = it.next();\n\t\t\tif(tagsJSON.getBoolean(tag))\n\t\t\t\ttagsIds.add(tag);\n\t\t}\n\t\t\n\t\treturn tagsIds;\n\t}\n\t\n\t\n\t/**\n\t * Throws an exception if an error is detected\n\t * @param obj\n\t * @throws ParseErrorException\n\t */\n\tpublic static void parseError(JSONObject obj) throws ParseErrorException{\n\t\tif(obj.has(TAG_ERR)) {\n\t\t\ttry {\n\t\t\t\tthrow(new ParseErrorException(ParseErrorException.HABITRPG_REGISTRATION_ERROR, obj.getString(TAG_ERR)));\n\t\t\t} catch (JSONException e1) {\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t}\n\tpublic static String[] parseAuthenticationAnswer(JSONObject obj) throws ParseErrorException {\n\t\tparseError(obj);\n\t\tString api_t = null;\n\t\tString user_t = null;\n\t\ttry {\n\t\t\tapi_t = obj.getString(TAG_AUTH_API_TOKEN);\n\t\t\tuser_t = obj.getString(TAG_AUTH_USER_TOKEN);\n\t\t\t//callback.onUserConnected(api_t, user_t);\n\t\t} catch (JSONException e) {\n\t\t\tthrow(new ParseErrorException(ParseErrorException.HABITRPG_PARSING_ERROR_AUTH));\n\t\t}\n\t\tString[] res = {api_t, user_t};\n\t\treturn res;\n\t}\n\tpublic static String[] parseRegistrationAnswer(JSONObject obj) throws ParseErrorException {\n\t\tparseError(obj);\n\t\tString api_t = null;\n\t\tString user_t = null;\n\t\ttry {\n\t\t\tapi_t = obj.getString(TAG_REG_API_TOKEN);\n\t\t\tuser_t = obj.getString(TAG_REG_USER_TOKEN);\n\t\t\tString[] res = {api_t, user_t};\n\t\t\treturn res;\n\t\t} catch (JSONException e) {\n\t\t\tthrow(new ParseErrorException(ParseErrorException.HABITRPG_PARSING_ERROR_REGISTRATION));\n\t\t}\n\t}\n\n\t/**\n\t * returns the day string depending on the number\n\t * @param j the number\n\t * @return the first/two first letter of the day\n\t */\n\tpublic static String whatDay(int j) {\n\t\tif(j==0)\n\t\t\treturn \"m\";\n\t\telse if(j==1)\n\t\t\treturn \"t\";\n\t\telse if(j==2)\n\t\t\treturn \"w\";\n\t\telse if(j==3)\n\t\t\treturn \"th\";\n\t\telse if(j==4)\n\t\t\treturn \"f\";\n\t\telse if(j==5)\n\t\t\treturn \"s\";\n\t\telse if(j==6)\n\t\t\treturn \"su\";\n\t\treturn \"su\";\n\t}\n\tpublic static boolean parseDeletedTask(JSONObject obj) throws ParseErrorException {\n\t\tparseError(obj);\n\t\tif(obj.length()==0) {\n \t\t\treturn true;\n\t\t} else {\n\t\t\tthrow new ParseErrorException(ParseErrorException.TASK_NOT_DELETED);\n\t\t}\n\t\t\n\t}\n\t\n\t\n}" ]
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.json.JSONObject; import com.magicmicky.habitrpglibrary.habits.HabitItem; import com.magicmicky.habitrpglibrary.habits.User; import com.magicmicky.habitrpglibrary.onlineapi.WebServiceInteraction.Answer; import com.magicmicky.habitrpglibrary.onlineapi.helper.ParseErrorException; import com.magicmicky.habitrpglibrary.onlineapi.helper.ParserHelper;
package com.magicmicky.habitrpglibrary.onlineapi; public class ReviveUser extends WebServiceInteraction { private static final String CMD = "user/revive"; public ReviveUser(OnHabitsAPIResult callback, HostConfig config) { super(CMD, callback, config); } @Override protected HttpRequestBase getRequest() { return new HttpPost(); } @Override protected Answer findAnswer(JSONObject answer) { return new ReviveData(answer,this.getCallback()); } private class ReviveData extends Answer { public ReviveData(JSONObject obj, OnHabitsAPIResult callback) { super(obj, callback); } public void parse() { try {
User us=ParserHelper.parseUser(this.getObject());
4
LyashenkoGS/analytics4github
src/main/java/com/rhcloud/analytics4github/service/CommitsService.java
[ "public enum GitHubApiEndpoints {\n COMMITS, STARGAZERS\n}", "@ApiModel\npublic class RequestFromFrontendDto {\n @ApiParam(required = true, example = \"mewo2\", value = \"a repository author. Example: mewo2\")\n private String author;\n @ApiParam(required = true, example = \"terrain\", value = \"a repository author. Example: terrain\")\n private String repository;\n @ApiParam(required = true, example = \"2016-08-10\", value = \"a data to start analyze from. Example: 2016-08-10\")\n @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\n private LocalDate startPeriod;\n @ApiParam(required = true, example = \"2016-08-17\", value = \"a data until analyze. Example: 2016-08-17\")\n @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\n private LocalDate endPeriod;\n\n public RequestFromFrontendDto() {\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public String getRepository() {\n return repository;\n }\n\n public void setRepository(String repository) {\n this.repository = repository;\n }\n\n public LocalDate getStartPeriod() {\n return startPeriod;\n }\n\n public void setStartPeriod(LocalDate startPeriod) {\n this.startPeriod = startPeriod;\n }\n\n public LocalDate getEndPeriod() {\n return endPeriod;\n }\n\n public void setEndPeriod(LocalDate endPeriod) {\n this.endPeriod = endPeriod;\n }\n}", "@ApiModel\npublic class ResponceForFrontendDto {\n private String name;\n private int requestsLeft;\n private List<Integer> data;\n public ResponceForFrontendDto() {\n }\n\n public ResponceForFrontendDto(String name, List<Integer> data) {\n this.name = name;\n this.data = data;\n }\n\n public ResponceForFrontendDto(String name, List<Integer> data, int requestsLeft) {\n this.name = name;\n this.data = data;\n this.requestsLeft = requestsLeft;\n }\n\n @Override\n public String toString() {\n return \"ResponceForFrontendDto{\" +\n \"name='\" + name + '\\'' +\n \", requestsLeft=\" + requestsLeft +\n \", data=\" + data +\n '}';\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public List<Integer> getData() {\n return data;\n }\n\n public void setData(List<Integer> data) {\n this.data = data;\n }\n\n public Integer getRequestsLeft() {\n return requestsLeft;\n }\n\n public void setRequestsLeft(Integer requestsLeft) {\n this.requestsLeft = requestsLeft;\n }\n}", "public class GitHubRESTApiException extends Exception {\n\n public GitHubRESTApiException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public class GitHubApiIterator implements Iterator<JsonNode> {\n private static Logger LOG = LoggerFactory.getLogger(GitHubApiIterator.class);\n\n private final int numberOfPages;\n private final String projectName;\n private final GitHubApiEndpoints githubEndpoint;\n private final RestTemplate restTemplate;\n private final ExecutorService executor = Executors.newFixedThreadPool(5);\n private Instant since = null;\n private Instant until = null;\n private String author;\n private volatile AtomicInteger counter = new AtomicInteger();\n public static int requestsLeft;\n\n public GitHubApiIterator(String projectName, RestTemplate restTemplate, GitHubApiEndpoints endpoint\n ) throws URISyntaxException, GitHubRESTApiException {\n this.restTemplate = restTemplate;\n this.projectName = projectName;\n this.githubEndpoint = endpoint;\n this.numberOfPages = getLastPageNumber(projectName);\n this.counter.set(numberOfPages);\n }\n\n public GitHubApiIterator(String projectName, String author, RestTemplate restTemplate, GitHubApiEndpoints endpoint\n ) throws URISyntaxException, GitHubRESTApiException {\n this.author = author;\n this.restTemplate = restTemplate;\n this.projectName = projectName;\n this.githubEndpoint = endpoint;\n this.numberOfPages = getLastPageNumber(projectName);\n this.counter.set(numberOfPages);\n }\n\n public GitHubApiIterator(String projectName, RestTemplate restTemplate, GitHubApiEndpoints endpoint,\n Instant since, Instant until) throws URISyntaxException, GitHubRESTApiException {\n this.since = since;\n this.until = until;\n this.restTemplate = restTemplate;\n this.projectName = projectName;\n this.githubEndpoint = endpoint;\n this.numberOfPages = getLastPageNumber(projectName);\n this.counter.set(numberOfPages);\n }\n\n public int getNumberOfPages() {\n return numberOfPages;\n }\n\n public String getProjectName() {\n return projectName;\n }\n\n public int getLastPageNumber(String projectName) throws URISyntaxException, GitHubRESTApiException {\n return Utils.getLastPageNumber(projectName, restTemplate, githubEndpoint, author, since, until);\n }\n\n public synchronized boolean hasNext() {\n return counter.get() > 0;\n }\n\n /**\n * Performs side efects (parsing a header and updating the static field\n * @return JsonNode that represents a stargazers list\n *\n */\n public JsonNode next() {\n if (counter.get() > 0) {\n String basicURL = \"https://api.github.com/repos/\" + projectName + \"/\" + githubEndpoint.toString().toLowerCase();\n UriComponents page;\n\n if (since != null && until!=null) {\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .queryParam(\"since\", since)\n .queryParam(\"until\",until)\n .build();\n } else if (since != null){\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .queryParam(\"since\", since)\n .build();\n } else if (author != null) {\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .queryParam(\"author\", author)\n .build();\n } else {\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .build();\n }\n String URL = page.encode().toUriString();\n LOG.debug(URL);\n //sent request\n HttpEntity entity = restTemplate.getForEntity(URL, JsonNode.class);\n initializeRequestsLeft(restTemplate);\n JsonNode node = new ObjectMapper().convertValue(entity.getBody(), JsonNode.class);\n LOG.debug(node.toString());\n return node;\n } else throw new IndexOutOfBoundsException(\"there is no next element\");\n }\n\n public static void initializeRequestsLeft(RestTemplate restTemplate){\n try{\n HttpEntity entity = restTemplate.getForEntity(\"https://api.github.com/users/whatever\", JsonNode.class);\n HttpHeaders headers = entity.getHeaders();\n GitHubApiIterator.requestsLeft = Integer.parseInt(headers.get(\"X-RateLimit-Remaining\").get(0));\n } catch (Exception e){\n LOG.debug(e.getMessage());\n }\n }\n\n /**\n * @param batchSize number of numberOfPages to return\n * @return list of stargazer numberOfPages according to batchSize\n * @throws IndexOutOfBoundsException if there is no elements left to return\n */\n public List<JsonNode> next(int batchSize) throws ExecutionException, InterruptedException {\n int reliableBatchSize = batchSize;\n if (batchSize > counter.get()) {\n LOG.warn(\"batch size is bigger then number of elements left, decrease batch size to \" + counter);\n reliableBatchSize = counter.get();\n }\n\n List<CompletableFuture<JsonNode>> completableFutures = IntStream.range(0, reliableBatchSize)\n .mapToObj(\n e -> CompletableFuture\n .supplyAsync(this::next, executor)\n ).collect(Collectors.toList());\n\n CompletableFuture<List<JsonNode>> result = CompletableFuture\n .allOf(completableFutures\n .toArray(new CompletableFuture[completableFutures.size()]))\n .thenApply(v -> completableFutures.stream()\n .map(CompletableFuture::join)\n .collect(Collectors.toList()));//compose all in one task\n List<JsonNode> jsonNodes = result.get();//\n LOG.debug(\"batch completed, counter:\" + counter.get());\n return jsonNodes;\n }\n\n /**\n * invoke explicitly after every class usage to close ThreadPool correctly\n */\n public void close() {\n this.executor.shutdown();\n }\n}", "public class Utils {\n static String HTTPS_API_GITHUB_COM_REPOS = \"https://api.github.com/repos/\";\n private static Logger LOG = LoggerFactory.getLogger(Utils.class);\n private Utils() {\n }\n\n /**\n * Assert that given Date is in the range from current monday to sunday\n * include border values.\n * Must return true for all days from this week include monday and sunday.\n */\n public static boolean isWithinThisWeekRange(LocalDate timestamp) {\n LOG.debug(\"Check is the \" + timestamp + \" is within this week range\");\n LocalDate today = LocalDate.now();\n LocalDate monday = today.with(previousOrSame(MONDAY));\n LocalDate sunday = today.with(nextOrSame(SUNDAY));\n boolean isWithinThisWeekRange = (timestamp.isAfter(monday.minusDays(1))) && timestamp.isBefore(sunday.plusDays(1));\n LOG.debug(String.valueOf(isWithinThisWeekRange));\n return isWithinThisWeekRange;\n }\n\n /**\n *\n * @param timestamp String representing date and time in ISO 8601 YYYY-MM-DDTHH:MM:SSZ\n * @param requestFromFrontendDto DTO came from frontend\n * @return if commit is withing analitics period\n */\n public static boolean isWithinThisMonthRange(LocalDate timestamp, RequestFromFrontendDto requestFromFrontendDto) {\n LOG.debug(\"Check is the \" + timestamp + \" is within this month range\");\n LocalDate monthStart = requestFromFrontendDto.getStartPeriod();\n LocalDate monthEnd = requestFromFrontendDto.getEndPeriod();\n\n boolean isWithinThisMonthRange = (timestamp.isAfter(monthStart) || timestamp.isEqual(monthStart))\n && (timestamp.isBefore(monthEnd) || timestamp.isEqual(monthEnd));\n LOG.debug(String.valueOf(isWithinThisMonthRange));\n return isWithinThisMonthRange;\n }\n\n /**\n * @param timestamp String representing date and time in ISO 8601 YYYY-MM-DDTHH:MM:SSZ\n * @return LocalDate parsed from the given @param. Example (2007-12-03)\n */\n public static LocalDate parseTimestamp(String timestamp) {\n return LocalDate.parse(timestamp, DateTimeFormatter.ISO_DATE_TIME);\n }\n\n public static Instant getThisMonthBeginInstant() {\n LocalDateTime localDate = LocalDateTime.now().withSecond(0).withHour(0).withMinute(0)\n .with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.SECONDS);\n return localDate.toInstant(ZoneOffset.UTC);\n }\n\n public static Instant getPeriodInstant(LocalDate localDate) {\n LocalDateTime localDateTime = localDate.atStartOfDay();\n return localDateTime.toInstant(ZoneOffset.UTC);\n }\n\n public static Instant getThisWeekBeginInstant() {\n LocalDateTime localDate = LocalDateTime.now().withSecond(0).withHour(0).withMinute(0)\n .with((MONDAY)).truncatedTo(ChronoUnit.SECONDS);\n return localDate.toInstant(ZoneOffset.UTC);\n }\n\n public static ResponceForFrontendDto buildJsonForFrontend(List<Integer> stargazersFrequencyList) throws IOException, ClassNotFoundException {\n ResponceForFrontendDto outputDto = new ResponceForFrontendDto();\n outputDto.setName(\"Stars\");\n outputDto.setData(stargazersFrequencyList);\n return outputDto;\n }\n\n public static List<Integer> parseWeekStargazersMapFrequencyToWeekFrequencyList(TreeMap<LocalDate, Integer> weekStargazersFrequenyMap) {\n LOG.debug(\"parseWeekStargazersMapFrequencyToWeekFrequencyList\");\n List<Integer> output = new ArrayList<>();\n for (DayOfWeek dayOfWeek : DayOfWeek.values()) {\n LOG.debug(dayOfWeek.toString());\n Optional<LocalDate> optional = weekStargazersFrequenyMap.keySet().stream()\n .filter(e -> DayOfWeek.from(e).equals(dayOfWeek))\n .findFirst();\n if (optional.isPresent()) {\n LOG.debug(\"match \" + optional.get() + \" with frequency \" + weekStargazersFrequenyMap.get(optional.get()));\n output.add(weekStargazersFrequenyMap.get(optional.get()));\n } else {\n LOG.debug(\"no match from \" + weekStargazersFrequenyMap.keySet());\n LOG.debug(\"add 0\");\n output.add(0);\n }\n\n }\n LOG.debug(\"Output is\" + output.toString());\n return output;\n }\n\n public static List<Integer> parseMonthFrequencyMapToFrequencyLIst(TreeMap<LocalDate, Integer> mockWeekStargazersFrequencyMap) throws IOException {\n int lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();\n LOG.debug(String.valueOf(lastDayOfMonth));\n List<Integer> monthStargazersFrequency = new ArrayList<>(lastDayOfMonth);\n for (int dayOfMonth = 1; dayOfMonth < lastDayOfMonth + 1; dayOfMonth++) {\n LOG.debug(\"day of month: \" + dayOfMonth);\n Optional<Integer> frequency = Optional.empty();\n for (LocalDate localDate : mockWeekStargazersFrequencyMap.keySet()) {\n if (dayOfMonth == localDate.getDayOfMonth()) {\n frequency = Optional.of(mockWeekStargazersFrequencyMap.get(localDate));\n }\n }\n if (frequency.isPresent()) {\n monthStargazersFrequency.add(frequency.get());\n } else {\n monthStargazersFrequency.add(0);\n }\n LOG.debug(monthStargazersFrequency.toString());\n }\n return monthStargazersFrequency;\n }\n\n\n public static TreeMap<LocalDate, Integer> buildStargazersFrequencyMap(List<LocalDate> stargazersList) throws IOException, URISyntaxException, ExecutionException, InterruptedException {\n //temporary set\n Set<LocalDate> stargazersDateSet = new HashSet<>(stargazersList);\n Map<LocalDate, Integer> stargazersFrequencyMap = stargazersDateSet.stream().collect(Collectors\n .toMap(Function.identity(), e -> Collections.frequency(stargazersList, e)));\n TreeMap<LocalDate, Integer> localDateIntegerNavigableMap = new TreeMap<>(stargazersFrequencyMap);\n LOG.debug(\"stargazers week/month frequency map:\" + localDateIntegerNavigableMap.toString());\n return localDateIntegerNavigableMap;\n }\n\n public static int getLastPageNumber(String repository, RestTemplate restTemplate, GitHubApiEndpoints githubEndpoint, String author, Instant since, Instant until) throws GitHubRESTApiException{\n String url;\n try {\n if (since != null) {\n url = UriComponentsBuilder.fromHttpUrl(HTTPS_API_GITHUB_COM_REPOS)\n .path(repository).path(\"/\" + githubEndpoint.toString().toLowerCase())\n .queryParam(\"since\", since)\n .queryParam(\"until\", until)\n .build().encode()\n .toUriString();\n } else if (author != null) {\n url = UriComponentsBuilder.fromHttpUrl(HTTPS_API_GITHUB_COM_REPOS)\n .path(repository).path(\"/\" + githubEndpoint.toString().toLowerCase())\n .queryParam(\"author\", author)\n .queryParam(\"until\", until)\n .build().encode()\n .toUriString();\n } else {\n url = UriComponentsBuilder.fromHttpUrl(HTTPS_API_GITHUB_COM_REPOS)\n .path(repository).path(\"/\" + githubEndpoint.toString().toLowerCase())\n .build().encode()\n .toUriString();\n }\n LOG.debug(\"URL to get the last commits page number:\" + url);\n HttpHeaders headers = restTemplate.headForHeaders(url);\n String link = headers.getFirst(\"Link\");\n LOG.debug(\"Link: \" + link);\n LOG.debug(\"parse link by regexp\");\n Pattern p = Pattern.compile(\"page=(\\\\d*)>; rel=\\\"last\\\"\");\n int lastPageNum = 0;\n try {\n Matcher m = p.matcher(link);\n if (m.find()) {\n lastPageNum = Integer.valueOf(m.group(1));\n LOG.debug(\"parse result: \" + lastPageNum);\n }\n } catch (NullPointerException npe) {\n // npe.printStackTrace();\n LOG.info(\"Propably \" + repository + \"commits consists from only one page\");\n return 1;\n }\n return lastPageNum;\n } catch (Exception e) {\n throw new GitHubRESTApiException(\" Can't access GitHub REST \", e);\n }\n }\n}" ]
import com.fasterxml.jackson.databind.JsonNode; import com.rhcloud.analytics4github.config.GitHubApiEndpoints; import com.rhcloud.analytics4github.dto.RequestFromFrontendDto; import com.rhcloud.analytics4github.dto.ResponceForFrontendDto; import com.rhcloud.analytics4github.exception.GitHubRESTApiException; import com.rhcloud.analytics4github.util.GitHubApiIterator; import com.rhcloud.analytics4github.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.net.URISyntaxException; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.LinkedList; import java.util.List; import java.util.TreeMap; import java.util.concurrent.ExecutionException;
package com.rhcloud.analytics4github.service; /** * @author lyashenkogs. */ @Service public class CommitsService { private static Logger LOG = LoggerFactory.getLogger(CommitsService.class); @Autowired private RestTemplate template; public List<LocalDate> getCommitsList(RequestFromFrontendDto requestFromFrontendDto) throws URISyntaxException, ExecutionException, InterruptedException, GitHubRESTApiException { List<LocalDate> thisMonthCommitsDateList = new LinkedList<>(); GitHubApiIterator iterator = new GitHubApiIterator(requestFromFrontendDto.getAuthor() + "/" + requestFromFrontendDto.getRepository(), template,
GitHubApiEndpoints.COMMITS, Utils.getPeriodInstant(requestFromFrontendDto.getStartPeriod()),
5
kinnla/eniac
src/eniac/menu/action/OpenSkin.java
[ "public class Manager {\n\n\t/*\n\t * ========================= applet lifecycle states =======================\n\t */\n\n\tpublic enum LifeCycle {\n\n\t\t/**\n\t\t * Default lifecycle state on startup\n\t\t */\n\t\tDEFAULT,\n\n\t\t/**\n\t\t * Livecycle state indicating a successful initialization\n\t\t */\n\t\tINITIALIZED,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is running and the\n\t\t * gui expects input.\n\t\t */\n\t\tRUNNING,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is running but the\n\t\t * gui is blocked.\n\t\t */\n\t\tBLOCKED,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is stopped.\n\t\t */\n\t\tSTOPPED,\n\n\t\t/**\n\t\t * Lifecycle state indicating that the application is destroyed.\n\t\t */\n\t\tDESTROYED,\n\t}\n\n\t/*\n\t * =============================== fields ==================================\n\t */\n\n\t// flag indicating, whether we have privileged local file access\n\tprivate boolean _ioAccess;\n\n\t// reference to the applet. Stays null, if started as application.\n\tprivate Applet _applet = null;\n\n\t/*\n\t * ========================== singleton stuff ==============================\n\t */\n\n\tprivate Manager() {\n\t\t// empty constructor\n\t}\n\n\t// singleton self reference\n\tprivate static Manager instance = null;\n\n\tpublic static Manager getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new Manager();\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/*\n\t * =================== lifecycle state transitions =========================\n\t */\n\n\t/**\n\t * creates and initializes all instances\n\t */\n\tpublic void init() {\n\t\tStatus.initValues();\n\t\tDictionaryIO.loadDefaultLanguage();\n\t\tSkinIO.loadDefaultSkin();\n\t\tStatus.LIFECYCLE.setValue(LifeCycle.INITIALIZED);\n\t}\n\n\tpublic void start() {\n\n\t\t// loading the configuration may open an input dialog for the user.\n\t\t// as the java-plugin may expect this method to return quickly,\n\t\t// we start a new thread.\n\t\tSwingUtilities.invokeLater(new Runnable() {\n\t\t\tpublic void run() {\n\n\t\t\t\t// load types\n\t\t\t\tTypeHandler.loadTypes();\n\n\t\t\t\t// load default configuration\n\t\t\t\tConfigIO.loadDefaultConfiguration();\n\n\t\t\t\t// check, if we haven't been interrupted\n\t\t\t\tif (Status.LIFECYCLE.getValue() == LifeCycle.INITIALIZED) {\n\n\t\t\t\t\t// open eframe and adjust runlevel\n\t\t\t\t\tEFrame.getInstance().toScreen();\n\t\t\t\t\tLogWindow.getInstance();\n\t\t\t\t\tStatus.LIFECYCLE.setValue(LifeCycle.RUNNING);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic void stop() {\n\n\t\t// TODO: check, if we need to block first\n\n\t\t// dispose configuration\n\t\tConfiguration config = (Configuration) Status.CONFIGURATION.getValue();\n\t\tif (config != null) {\n\t\t\tconfig.dispose();\n\t\t}\n\t\tStatus.CONFIGURATION.setValue(null);\n\n\t\t// announce that applet is shutting down\n\t\tStatus.LIFECYCLE.setValue(LifeCycle.STOPPED);\n\t}\n\n\tpublic void destroy() {\n\n\t\t// check that we haven't been destroyed before\n\t\tif (Status.LIFECYCLE.getValue() != LifeCycle.STOPPED) {\n\t\t\treturn;\n\t\t}\n\n\t\t// run finalization.\n\t\t// Though it probably has no effect, the purpose provides good fortune.\n\t\tSystem.runFinalization();\n\n\t\t// announce that applet is destroyed\n\t\tStatus.LIFECYCLE.setValue(LifeCycle.DESTROYED);\n\t}\n\n\t/*\n\t * ============================== methods ==================================\n\t */\n\n\tpublic void setApplet(Applet applet) {\n\t\t_applet = applet;\n\t}\n\n\tpublic void makeDialog(DialogPanel content, String title) {\n\t\t// create dialog. Add listener and set content pane\n\t\tfinal JDialog dialog = new JDialog(Progressor.getInstance(), title, true);\n\t\tdialog.addWindowListener(new WindowAdapter() {\n\t\t\tpublic void windowClosing(WindowEvent e) {\n\t\t\t\t((DialogPanel) dialog.getContentPane()).performCancelAction();\n\t\t\t}\n\t\t});\n\t\tdialog.setContentPane(content);\n\n\t\t// bring it to the screen.\n\t\tdialog.pack();\n\t\tdialog.setLocationRelativeTo(Progressor.getInstance());\n\t\tcontent.setWindow(dialog);\n\t\tdialog.setVisible(true);\n\t}\n\n\t/*\n\t * public boolean isPrivileged() { // if we are started as an application,\n\t * we have all privileges if (!isApplet()) { return true; } // check, if we\n\t * already tried to set our SecurityManager if (_privileged != null) {\n\t * return _privileged.booleanValue(); } // This is an applet. Ask for\n\t * priviliges. try { // anonymous security manager granting any permission\n\t * new SecurityManager() { public void checkPermission(Permission\n\t * permission) { // grant any permission }\n\t * \n\t * public void checkPermission(Permission permission, Object obj) { // grant\n\t * any permission } }; // user allowed the signed applet. Set flag.\n\t * _privileged = new Boolean(true); return true; } catch\n\t * (AccessControlException ace) { // User didn't allow the signed applet. //\n\t * Reset flag and display message. // ace.printStackTrace();\n\t * Log.log(LogWords.NO_PRIVILEGES_GRANTED, JOptionPane.INFORMATION_MESSAGE,\n\t * ace.getMessage(), true); _privileged = new Boolean(false); return false;\n\t * } }\n\t */\n\t// indicates whether this program is started as applet or as application.\n\t// private boolean isApplet() {\n\t// return getAppletContext() == null;\n\t// }\n\tpublic void block() {\n\t\tif (Status.LIFECYCLE.getValue() == LifeCycle.RUNNING) {\n\t\t\tStatus.LIFECYCLE.setValue(LifeCycle.BLOCKED);\n\t\t}\n\t}\n\n\tpublic void unblock() {\n\t\tif (Status.LIFECYCLE.getValue() == LifeCycle.BLOCKED) {\n\t\t\tStatus.LIFECYCLE.setValue(LifeCycle.RUNNING);\n\t\t}\n\t}\n\n\t// ============================ io methods //===============================\n\n\t/**\n\t * Opens an <code>inputStream</code> to the specified resource.\n\t * \n\t * @param name\n\t * a <code>string</code> specifying the resource to load\n\t * @return an <code>inputStream</code> if the resource could be found, <br>\n\t * or <code>null</code> otherwise\n\t */\n\tpublic InputStream getResourceAsStream(String name) {\n\t\treturn Manager.class.getClassLoader().getResourceAsStream(name);\n\t}\n\n\tpublic void setIOAccess(boolean ioAccess) {\n\t\t_ioAccess = ioAccess;\n\t}\n\n\tpublic boolean hasIOAccess() {\n\t\treturn _ioAccess;\n\t}\n}", "public class Proxy extends EnumMap<Proxy.Tag, String> {\n\n\t/**\n\t * Enumeration of all tags that are understood by the proxy handler\n\t * \n\t * @author till\n\t * \n\t * TODO\n\t */\n\tpublic enum Tag {\n\n\t\t/**\n\t\t * the proxy tag. data outside this section will be ignored. Any tag\n\t\t * inside this section shall be registered as enum constant in Proxy.Tag\n\t\t */\n\t\tPROXY,\n\n\t\t/**\n\t\t * the author of a skin\n\t\t */\n\t\tAUTHOR,\n\n\t\t/**\n\t\t * the email address of the author of a skin\n\t\t */\n\t\tEMAIL,\n\n\t\t/**\n\t\t * number of LODs in a skin (should be 2) TODO: refactor, we don't need\n\t\t * it\n\t\t */\n\t\tNUMBER_OF_LODS,\n\n\t\t/**\n\t\t * the number of descriptors in a skin TODO: do we need this any more?\n\t\t */\n\t\tNUMBER_OF_DESCRIPTORS,\n\n\t\t/**\n\t\t * zoom steps for the user to zoom in & out\n\t\t */\n\t\tZOOM_STEPS,\n\n\t\t/**\n\t\t * path to a preview image of the skin\n\t\t */\n\t\tPREVIEW,\n\n\t\t/**\n\t\t * name of a configuration or language\n\t\t */\n\t\tNAME,\n\n\t\t/**\n\t\t * description of the configuration or language\n\t\t */\n\t\tDESCRIPTION,\n\n\t\t/**\n\t\t * string-key of the language, as the 2-letter locale\n\t\t */\n\t\tKEY,\n\t}\n\n\tprivate String _path;\n\n\tpublic Proxy() {\n\t\tsuper(Proxy.Tag.class);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn get(Tag.NAME); // need this to be displayed in a jlist\n\t}\n\n\tpublic void setPath(String path) {\n\t\t_path = path;\n\t}\n\n\tpublic String getPath() {\n\t\treturn _path;\n\t}\n\n\tpublic void appendTags(List<String> l, int indent) {\n\n\t\t// append comment line and open tag\n\t\tXMLUtil.appendCommentLine(l, indent, Tag.PROXY.toString());\n\t\tl.add(XMLUtil.TABS[indent] + XMLUtil.wrapOpenTag(Tag.PROXY.toString()));\n\n\t\t// append child tags\n\t\tString tabs = XMLUtil.TABS[indent + 1];\n\t\tfor (Map.Entry<Proxy.Tag, String> entry : entrySet()) {\n\t\t\tString open = XMLUtil.wrapOpenTag(entry.getKey().toString().toLowerCase());\n\t\t\tString close = XMLUtil.wrapCloseTag(entry.getKey().toString().toLowerCase());\n\t\t\tl.add(tabs + open + entry.getValue() + close);\n\t\t}\n\n\t\t// append close tags\n\t\tl.add(XMLUtil.TABS[indent] + XMLUtil.wrapCloseTag(Tag.PROXY.toString()));\n\t}\n}", "public enum Dictionary {\n\n\t/**\n\t * Name of the \"Open-Skin\" command.\n\t */\n\tOPEN_SKIN_NAME,\n\n\t/**\n\t * Short description of the \"Open-Skin\" command.\n\t */\n\tOPEN_SKIN_SHORT,\n\n\t/**\n\t * Name of the \"Open Configuration\" command.\n\t */\n\tOPEN_CONFIGURATION_NAME,\n\n\t/**\n\t * Short description of the \"Open configuration\" command.\n\t */\n\tOPEN_CONFIGURATION_SHORT,\n\n\t/**\n\t * Name of the \"Save Configuration\" command.\n\t */\n\tSAVE_CONFIGURATION_NAME,\n\n\t/**\n\t * Short description of the \"Save configuration\" command.\n\t */\n\tSAVE_CONFIGURATION_SHORT,\n\n\t/**\n\t * Name of the \"Zoom in\" command.\n\t */\n\tZOOM_IN_NAME,\n\n\t/**\n\t * Short description of the \"Zoom in\" command.\n\t */\n\tZOOM_IN_SHORT,\n\n\t/**\n\t * Name of the \"Zoom out\" command.\n\t */\n\tZOOM_OUT_NAME,\n\n\t/**\n\t * Short description of the \"Zoom out\" command.\n\t */\n\tZOOM_OUT_SHORT,\n\n\t/**\n\t * Title of the \"Confirm overwrite\" dialog.\n\t */\n\tCONFIRM_OVERWRITE_TITLE,\n\n\t/**\n\t * Text at the \"Confirm overwrite\" dialog.\n\t */\n\tCONFIRM_OVERWRITE_TEXT,\n\n\t/**\n\t * Name of the \"Change Language\" command.\n\t */\n\tCHANGE_LANGUAGE_NAME,\n\n\t/**\n\t * Short description of the \"Change Language\" command.\n\t */\n\tCHANGE_LANGUAGE_SHORT,\n\n\t/**\n\t * Name of the \"Show log-window\" dialog.\n\t */\n\tSHOW_LOG_NAME,\n\n\t/**\n\t * Short description of the \"Show log-window\" command.\n\t */\n\tSHOW_LOG_SHORT,\n\n\t/**\n\t * Name of the \"Show Overview-window\" command.\n\t */\n\tSHOW_OVERVIEW_NAME,\n\n\t/**\n\t * Short description of the \"Show Overview-window\" command.\n\t */\n\tSHOW_OVERVIEW_SHORT,\n\n\t/**\n\t * Name of the \"Fit zoom to height\" command.\n\t */\n\tZOOM_FIT_HEIGHT_NAME,\n\n\t/**\n\t * Short description of the \"Fit zoom to height\" command.\n\t */\n\tZOOM_FIT_HEIGHT_SHORT,\n\n\t/**\n\t * Name of the \"Fit zoom to width\" command.\n\t */\n\tZOOM_FIT_WIDTH_NAME,\n\n\t/**\n\t * Short description of the \"Fit zoom to width\" command.\n\t */\n\tZOOM_FIT_WIDTH_SHORT,\n\n\t/**\n\t * Text at the \"Open configuration\" dialog.\n\t */\n\tCHOOSE_WEB_LOCATION,\n\n\t/**\n\t * Text at the \"Open configuration\" dialog.\n\t */\n\tCHOOSE_FILE,\n\n\t/**\n\t * Text at the \"Open configuration\" dialog.\n\t */\n\tLOAD_FROM_FILE,\n\n\t/**\n\t * The word for \"value\".\n\t */\n\tVALUE,\n\n\t/**\n\t * Title of the Main-frame.\n\t */\n\tMAIN_FRAME_TITLE,\n\n\t/**\n\t * Title of the Overview-window.\n\t */\n\tOVERVIEW_WINDOW_TITLE,\n\n\t/**\n\t * Title of the \"Log window\".\n\t */\n\tLOG_WINDOW_TITLE,\n\n\t/**\n\t * The word for \"properties\".\n\t */\n\tPROPERTIES,\n\n\t/**\n\t * The word for \"ok\".\n\t */\n\tOK,\n\n\t/**\n\t * The word for \"cancel\".\n\t */\n\tCANCEL,\n\n\t/**\n\t * Message in the blocking-dialog that we are scanning for configurations.\n\t */\n\tCONFIGURATION_SCANNING,\n\n\t/**\n\t * Description of the file filter at File-Chooser-Dialogs.\n\t */\n\tFILE_FILTER_DESCRIPTION,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading a dictionary.\n\t */\n\tDICTIONARY_LOADING,\n\n\t/**\n\t * Message in the blocking-dialog that we are scanning for Dictionaries.\n\t */\n\tDICTIONARY_SCANNING,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading the menu.\n\t */\n\tMENU_LOADING,\n\n\t/**\n\t * Message in the blocking-dialog that we are scanning for skin files.\n\t */\n\tSKIN_SCANNING,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading a skin file.\n\t */\n\tSKIN_LOADING,\n\n\t/**\n\t * Polite busy message.\n\t */\n\tPLEASE_WAIT,\n\n\t/**\n\t * Title of the \"Save Configuration\" dialog.\n\t */\n\tSAVE_CONFIGURATION_TITLE,\n\n\t/**\n\t * The word for \"write\".\n\t */\n\tWRITE,\n\n\t/**\n\t * The word for \"next\".\n\t */\n\tNEXT,\n\n\t/**\n\t * Enter details before saving a configuration.\n\t */\n\tENTER_DETAILS,\n\n\t/**\n\t * The word for \"name\".\n\t */\n\tNAME,\n\n\t/**\n\t * The word for \"description\".\n\t */\n\tDESCRIPTION,\n\n\t/**\n\t * The title of the (floating) toolbar.\n\t */\n\tTOOLBAR_TITLE,\n\n\t/**\n\t * The word for \"file\".\n\t */\n\tFILE,\n\n\t/**\n\t * The word for \"window\" (not: windows).\n\t */\n\tWINDOW,\n\n\t/**\n\t * The word for \"view\".\n\t */\n\tVIEW,\n\n\t/**\n\t * The word for \"zoom\".\n\t */\n\tZOOM,\n\n\t/**\n\t * The word for \"help\".\n\t */\n\tHELP,\n\n\t/**\n\t * The name of the \"Hightlight pule\" command.\n\t */\n\tHIGHLIGHT_PULSE_NAME,\n\n\t/**\n\t * Short description of the \"Highlight pulse\" command.\n\t */\n\tHIGHLIGHT_PULSE_SHORT,\n\n\t/**\n\t * Name of the \"About this program\" command.\n\t */\n\tABOUT_NAME,\n\n\t/**\n\t * Short description of the \"About this program\" command.\n\t */\n\tABOUT_SHORT,\n\n\t/**\n\t * Text of the \"About this program\" dialog.\n\t */\n\tABOUT_TEXT,\n\n\t/**\n\t * Name of the \"faq\" command.\n\t */\n\tFAQ_NAME,\n\n\t/**\n\t * Short description of the \"faq\" command.\n\t */\n\tFAQ_SHORT,\n\n\t/**\n\t * Text of the \"faq\" dialog.\n\t */\n\tFAQ_TEXT,\n\n\t/**\n\t * Name of the \"settings\" command.\n\t */\n\tSETTINGS_NAME,\n\n\t/**\n\t * Short description of the \"settings\" command.\n\t */\n\tSETTINGS_SHORT,\n\n\t/**\n\t * Text at the \"save settings\" dialog.\n\t */\n\tSAVE_SETTINGS_TEXT,\n\n\t/**\n\t * Title of the \"Save settings\" dialog.\n\t */\n\tSAVE_SETTINGS_TITLE,\n\n\t/**\n\t * Message in the blocking-dialog that we are initializing.\n\t */\n\tINITIALIZING,\n\n\t/**\n\t * Message in the blocking-dialog that we are loading a configuration.\n\t */\n\tCONFIGURATION_LOADING,\n\n\t/**\n\t * Message in the blocking-dialog that we are writing a configuration.\n\t */\n\tCONFIGURATION_WRITING;\n\n\t/**\n\t * Looks for the words associated with the given key. If the key is invalid,\n\t * the key itself is returned.\n\t * \n\t * @param sid\n\t * a <code>string</code> to identify the words we are looking\n\t * for.\n\t * @return the value of the static field with the uppercased name of 'key'\n\t * or the value of key itself, if there is no field.\n\t */\n\n\tprivate EnumMap<Dictionary, String> _map = null;\n\n\tpublic void checkInit() {\n\n\t\t// if already initialized, just return.\n\t\tif (_map != null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// create new dictionary map\n\t\t_map = new EnumMap<>(Dictionary.class);\n\n\t\t// Init special fields with predefined values. These are those words\n\t\t// displayed before the language data is loaded.\n\t\t_map.put(INITIALIZING, \"Eniac simulation is starting up. Please wait.\"); //$NON-NLS-1$\n\t\t_map.put(DICTIONARY_LOADING, \"loading language file\"); //$NON-NLS-1$\n\t\t_map.put(DICTIONARY_SCANNING, \"scanning for language files\"); //$NON-NLS-1$\n\t\t_map.put(PLEASE_WAIT, \"Please wait\"); //$NON-NLS-1$\n\t}\n\n\tpublic String getText() {\n\t\tcheckInit();\n\t\treturn _map.get(this);\n\t}\n\n\tpublic void setText(String text) {\n\t\tcheckInit();\n\t\t_map.put(this, text);\n\t}\n\n\tpublic enum Tag {\n\t\tENTRY, KEY\n\t}\n\n//\n// try {\n// Field field = Dictionary.class.getField(sid.toUpperCase());\n// return (String) field.get(null);\n// } catch (Exception e) {\n// // unknown key. return key as value.\n// // TODO: log this\n// return sid;\n// }\n// }\n\n}", "public class OpenSkinPanel extends DialogPanel {\n\n\t// configurationProxies the user can choose from\n\tprivate List<Proxy> _proxies;\n\n\tprivate Proxy _selectedProxy = null;\n\n\tprivate JPanel _jpanel;\n\n\tJList<Proxy> _jlist;\n\n\tprivate JScrollPane _listPane;\n\n\tprivate ImagePanel _imagePanel;\n\n\t// Actions\n\tprivate Action _cancelAction;\n\n\tprivate Action _okAction;\n\n\tpublic OpenSkinPanel(List<Proxy> proxies) {\n\t\tsuper(new GridBagLayout());\n\t\t_proxies = proxies;\n\t}\n\n\t/**\n\t * Initializes this openConfigurationPanel\n\t */\n\tpublic void init() {\n\n\t\t// ========================== actions\n\t\t// ===================================\n\n\t\t// create and add okAction\n\t\t_okAction = new AbstractAction() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tperformOkAction();\n\t\t\t}\n\t\t};\n\t\t_okAction.setEnabled(false);\n\t\t_okAction.putValue(Action.NAME, Dictionary.OK.getText());\n\t\tgetActionMap().put(_okAction.getValue(Action.NAME), _okAction);\n\n\t\t// create and add cancelAction\n\t\t_cancelAction = new AbstractAction() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tperformCancelAction();\n\t\t\t}\n\t\t};\n\t\t_cancelAction.putValue(Action.NAME, Dictionary.CANCEL.getText());\n\t\tgetActionMap().put(_cancelAction.getValue(Action.NAME), _cancelAction);\n\n\t\t// ============================ jpanel\n\t\t// ==================================\n\n\t\t_jpanel = new JPanel(new GridBagLayout());\n\t\t_imagePanel = new ImagePanel();\n\n\t\t// create and init _jlist and _listPane\n\t\t_jlist = new JList<>(new Vector<>(_proxies));\n\t\t_jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n\t\t_listPane = new JScrollPane(_jlist);\n\n\t\t// add mouseListener to _jlist for receiving double-clicks\n\t\t_jlist.addMouseListener(new MouseAdapter() {\n\t\t\tpublic void mouseClicked(MouseEvent e) {\n\t\t\t\tif (e.getClickCount() == 2) {\n\t\t\t\t\tperformOkAction();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t// add itemListener to _jlist for display preview image\n\t\t_jlist.addListSelectionListener(new ListSelectionListener() {\n\t\t\tpublic void valueChanged(ListSelectionEvent e) {\n\t\t\t\tperformUpdate();\n\t\t\t}\n\t\t});\n\n\t\t// ========================= layout components\n\t\t// ==========================\n\n\t\t// add components\n\t\t_jpanel.add(_listPane, new GridBagConstraints(0, 0, 1, 1, 0.5, 0.5, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\t\t_jpanel.add(_imagePanel, new GridBagConstraints(1, 0, 1, 1, 0.5, 0.5, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// add jpanel\n\t\tadd(_jpanel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// ============================= buttons\n\t\t// ================================\n\n\t\t// create and init buttons\n\t\tJButton okButton = new JButton(_okAction);\n\t\tJButton cancelButton = new JButton(_cancelAction);\n\n\t\t// layout components\n\t\tadd(okButton, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\t\tadd(cancelButton, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER,\n\t\t\t\tGridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));\n\n\t\t// ============================= add keystrokes\n\t\t// =========================\n\n\t\t// fill actionMap\n\t\tgetActionMap().put(_okAction.getValue(Action.NAME), _okAction);\n\t\tgetActionMap().put(_cancelAction.getValue(Action.NAME), _cancelAction);\n\n\t\t// fill inputMap\n\t\tgetInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),\n\t\t\t\t_okAction.getValue(Action.NAME));\n\t\tgetInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),\n\t\t\t\t_cancelAction.getValue(Action.NAME));\n\n\t\t// adjust inputMaps of buttons\n\t\tcancelButton.getActionMap().setParent(getActionMap());\n\t\tcancelButton.getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),\n\t\t\t\t_cancelAction.getValue(Action.NAME));\n\t}\n\n\t// this is called, when the panel already was added to the dialog.\n\t// so we can set our selection here.\n\t// note: if set selection without having a window as ancestor,\n\t// there will be a NuPoExc\n\tpublic void setWindow(Window window) {\n\t\tsuper.setWindow(window);\n\t\tif (_jlist.getModel().getSize() > 0) {\n\t\t\t_jlist.setSelectedIndex(0);\n\t\t}\n\t}\n\n\t// ========================= event processing\n\t// ===============================\n\n\tvoid performUpdate() {\n\n\t\t// set image to imagePanel\n\t\t_selectedProxy = _jlist.getSelectedValue();\n\t\tif (_selectedProxy == null) {\n\t\t\t_imagePanel.setImage(null);\n\t\t}\n\t\telse {\n\t\t\tString path = _selectedProxy.get(Proxy.Tag.PREVIEW);\n\t\t\tImage img = EFrame.getInstance().getResourceAsImage(path);\n\t\t\t_imagePanel.setImage(img);\n\t\t}\n\n\t\t// resize window\n\t\tWindow window = SwingUtilities.windowForComponent(this);\n\t\twindow.pack();\n\n\t\t// enable or disable okButton\n\t\t_okAction.setEnabled(_selectedProxy != null);\n\t}\n\n\tpublic void performCancelAction() {\n\t\t_selectedProxy = null;\n\t\tSwingUtilities.windowForComponent(OpenSkinPanel.this).dispose();\n\t}\n\n\tvoid performOkAction() {\n\t\tif (_selectedProxy != null) {\n\t\t\tSwingUtilities.windowForComponent(OpenSkinPanel.this).dispose();\n\t\t}\n\t}\n\n\tpublic Proxy getSelectedProxy() {\n\t\treturn _selectedProxy;\n\t}\n\n\t// ======================= inner class ImagePanel\n\t// ===========================\n\n\tclass ImagePanel extends JPanel {\n\n\t\tprivate Image _preview;\n\n\t\tpublic void setImage(Image preview) {\n\t\t\t_preview = preview;\n\t\t\trepaint();\n\t\t}\n\n\t\tpublic Dimension getPreferredSize() {\n\t\t\treturn StringConverter.toDimension(EProperties.getInstance().getProperty(\"PREVIEW_SIZE\"));\n\t\t\t// if (_preview == null) {\n\t\t\t// return new Dimension(0, 0);\n\t\t\t// }\n\t\t\t// int width = _preview.getWidth(this);\n\t\t\t// int height = _preview.getHeight(this);\n\t\t\t// return new Dimension(width, height);\n\t\t}\n\n\t\tpublic void paint(Graphics g) {\n\t\t\tif (_preview == null) {\n\t\t\t\tg.clearRect(0, 0, getWidth(), getHeight());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tg.drawImage(_preview, 0, 0, getWidth(), getHeight(), this);\n\t\t\t}\n\t\t}\n\t}\n\n}", "public final class SkinIO {\n\n\tprivate SkinIO() {\n\t\t// empty\n\t}\n\n\tpublic static List<Proxy> loadProxies() {\n\t\tString path = getSkinPathWithoutIndex();\n\t\tint max = StringConverter.toInt(EProperties.getInstance().getProperty(\"MAX_NUMBER_OF_SKINS\"));\n\t\tString text = Dictionary.SKIN_SCANNING.getText();\n\t\treturn IOUtil.loadProxies(path, max, text);\n\t}\n\n\tpublic static void loadSkin(Proxy proxy) {\n\n\t\tString path = proxy.getPath();\n\t\tInputStream in = Manager.getInstance().getResourceAsStream(path);\n\t\tSkin skin = new Skin(proxy);\n\t\tSkinHandler handler = new SkinHandler(skin);\n\t\ttry {\n\t\t\tIOUtil.parse(in, handler);\n\n\t\t\t// check, if all images could be loaded.\n\t\t\t// if not, announce this to the user\n\t\t\tif (handler.hasMissingImages()) {\n\t\t\t\tLog.log(LogWords.MISSING_IMAGES, JOptionPane.INFORMATION_MESSAGE, true);\n\t\t\t}\n\n\t\t\t// TODO: this should be done at another place\n\t\t\t// iterate on types\n\t\t\tfor (EType type : EType.values()) {\n\t\t\t\t// set descriptors to etypes\n\t\t\t\thandler.setDescriptorsToType(type);\n\t\t\t}\n\t\t\t// set new skin\n\t\t\tStatus.SKIN.setValue(skin);\n\t\t} catch (IOException e) {\n\t\t\tLog.log(LogWords.LOADING_OF_SKIN_FAILED, JOptionPane.ERROR_MESSAGE, true);\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static void loadDefaultSkin() {\n\t\tString path = getSkinPathWithoutIndex();\n\t\tint index = StringConverter.toInt(EProperties.getInstance().getProperty(\"INDEX_OF_DEFAULT_SKIN\"));\n\t\tString skinPath = IOUtil.addIndex(path, index);\n\t\tProxy proxy = IOUtil.loadProxy(skinPath);\n\t\tif (proxy == null) {\n\t\t\tLog.log(\"skin loading: proxy is null\");\n\t\t\t// System.out.println(\"skin loading: proxy is null\");\n\t\t\treturn;\n\t\t}\n\t\tloadSkin(proxy);\n\t}\n\n\tprivate static String getSkinPathWithoutIndex() {\n\t\tString folder = EProperties.getInstance().getProperty(\"SKIN_FOLDER\");\n\t\tString file = EProperties.getInstance().getProperty(\"SKIN_FILE_WITHOUT_INDEX\");\n\t\treturn folder + \"/\" + file; //$NON-NLS-1$\n\t}\n}" ]
import java.awt.event.ActionEvent; import java.util.List; import eniac.Manager; import eniac.io.Proxy; import eniac.lang.Dictionary; import eniac.menu.action.gui.OpenSkinPanel; import eniac.skin.SkinIO;
/******************************************************************************* * Copyright (c) 2003-2005, 2013 Till Zoppke. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Till Zoppke - initial API and implementation ******************************************************************************/ /* * Created on 23.02.2004 */ package eniac.menu.action; /** * @author zoppke */ public class OpenSkin extends EAction implements Runnable { public void actionPerformed(ActionEvent evt) { Thread t = new Thread(this); t.start(); } /** * @param e * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void run() { // announce that we are working Manager.getInstance().block(); // scan for proxies List<Proxy> proxies = SkinIO.loadProxies(); // create dialog that user can choose a configDescriptor OpenSkinPanel panel = new OpenSkinPanel(proxies); panel.init();
Manager.getInstance().makeDialog(panel, Dictionary.OPEN_SKIN_NAME.getText());
2
aw20/MongoWorkBench
src/org/aw20/mongoworkbench/eclipse/view/wizard/AggregateWizard.java
[ "public enum Event {\n\n\tDOCUMENT_VIEW,\n\tELEMENT_VIEW,\n\t\n\tWRITERESULT,\n\t\n\tEXCEPTION, \n\t\n\tTOWIZARD\n\t\n}", "public class EventWorkBenchManager extends Object {\n\tprivate static EventWorkBenchManager thisInst;\n\t\n\tpublic static synchronized EventWorkBenchManager getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new EventWorkBenchManager();\n\n\t\treturn thisInst;\n\t}\n\n\tprivate Set<EventWorkBenchListener>\tlisteners;\n\t\n\tprivate EventWorkBenchManager(){\n\t\tlisteners\t= new HashSet<EventWorkBenchListener>();\n\t}\n\t\n\tpublic void registerListener(EventWorkBenchListener listener){\n\t\tlisteners.add(listener);\n\t}\n\t\n\tpublic void deregisterListener(EventWorkBenchListener listener){\n\t\tlisteners.remove(listener);\n\t}\n\n\tpublic void onEvent( final Event event, final Object data ){\n\t\t\n\t\tnew Thread(\"EventWorkBenchEventFire\"){ \n\t\t\tpublic void run(){\n\t\t\t\tIterator<EventWorkBenchListener>\tit\t= listeners.iterator();\n\t\t\t\twhile ( it.hasNext() ){\n\t\t\t\t\ttry{\n\t\t\t\t\t\tit.next().onEventWorkBench(event, data);\n\t\t\t\t\t}catch(Exception e){\n\t\t\t\t\t\tSystem.out.println(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\n\t}\n\t\n}", "public class MongoFactory extends Thread {\n\n\tprivate static MongoFactory\tthisInst = null;\n\t\n\tpublic static synchronized MongoFactory getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new MongoFactory();\n\n\t\treturn thisInst;\n\t}\n\t\n\tprivate Map<String,MongoClient>\tmongoMap;\n\t\n\tprivate Set<MongoCommandListener>\tmongoListeners;\n\tprivate Set<MDocumentView>\tdocumentViewListeners;\n\t\n\tprivate List<MongoCommand>\tcommandQueue;\n\tprivate Map<String, Class>\tcommandMap;\n\tprivate boolean bRun = true;\n\n\t\n\tprivate String activeServer = null, activeDB = null, activeCollection = null;\n\t\n\tpublic MongoFactory(){\n\t\tmongoMap\t\t\t\t\t\t\t= new HashMap<String,MongoClient>();\n\t\tcommandQueue\t\t\t\t\t=\tnew ArrayList<MongoCommand>(); \n\t\tmongoListeners\t\t\t\t= new HashSet<MongoCommandListener>();\n\t\tdocumentViewListeners\t= new HashSet<MDocumentView>();\n\t\tcommandMap\t\t\t\t\t\t= new HashMap<String,Class>();\n\n\t\t// Register the Commands\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.find\\\\(.*\", FindMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.findOne\\\\(.*\", FindOneMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.save\\\\(.*\", SaveMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.update\\\\(.*\", UpdateMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.remove\\\\(.*\", RemoveMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.group\\\\(.*\", GroupMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.aggregate\\\\(.*\", AggregateMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.mapReduce\\\\(.*\", MapReduceMongoCommand.class);\n\t\tcommandMap.put(\"^use\\\\s+.*\", UseMongoCommand.class);\n\t\tcommandMap.put(\"^show dbs\", ShowDbsMongoCommand.class);\n\t\tcommandMap.put(\"^show collections\", ShowCollectionsMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.serverStatus\\\\(.*\", DBserverStatsMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.getStats\\\\(.*\", DBStatsMongoCommand.class);\n\n\t\tsetName( \"MongoFactory\" );\n\t\tstart();\n\t}\n\t\n\tpublic void registerListener(MongoCommandListener listener){\n\t\tif ( listener instanceof MDocumentView )\n\t\t\tdocumentViewListeners.add( (MDocumentView)listener );\n\t\telse\n\t\t\tmongoListeners.add(listener);\n\t}\n\t\n\tpublic void deregisterListener(MongoCommandListener listener){\n\t\tif ( listener instanceof MDocumentView )\n\t\t\tdocumentViewListeners.remove( (MDocumentView)listener );\n\t\telse\n\t\t\tmongoListeners.remove(listener);\n\t}\n\t\t\n\tpublic void removeMongo(String sName){\n\t\tMongoClient\tmclient\t= mongoMap.remove(sName);\n\t\tif ( mclient != null )\n\t\t\tmclient.close();\n\t}\n\t\n\t\n\tpublic MongoClient getMongo(String sName) {\n\t\tactiveServer = sName;\n\t\t\n\t\tif ( mongoMap.containsKey(sName) )\n\t\t\treturn mongoMap.get(sName);\n\t\telse{\n\t\t\ttry {\n\t\t\t\tMongoClient mc\t= Activator.getDefault().getMongoClient(sName);\n\t\t\t\tmongoMap.put( sName, mc );\n\t\t\t\treturn mc;\n\t\t\t} catch (UnknownHostException e) {\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( org.aw20.mongoworkbench.Event.EXCEPTION, e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void destroy(){\n\t\tbRun = false;\n\t}\n\t\n\tpublic String getActiveServer(){\n\t\treturn activeServer;\n\t}\n\t\n\tpublic String getActiveDB(){\n\t\treturn activeDB;\n\t}\n\t\n\tpublic void setActiveDB(String db){\n\t\tthis.activeDB = db;\n\t}\n\t\n\tpublic MongoCommand\tcreateCommand( String cmd ) throws Exception {\n\t\t\n\t\t// remove line breaks\n\t\tcmd = cmd.replaceAll(\"(\\\\r|\\\\n)\", \"\");\n\t\tcmd = cmd.replaceAll(\"\\\\t+\", \" \");\n\t\tcmd\t= cmd.trim();\n\n\t\tIterator p = commandMap.keySet().iterator();\n\t\twhile (p.hasNext()) {\n\t\t\tString patternStr = (String) p.next();\n\t\t\tif (cmd.matches(patternStr)) {\n\t\t\t\tClass clazz = (Class) commandMap.get(patternStr);\n\t\t\t\ttry {\n\t\t\t\t\tMongoCommand mcmd = (MongoCommand)clazz.newInstance();\n\t\t\t\t\tmcmd.setConnection(activeServer, activeDB);\n\t\t\t\t\tmcmd.setCommandStr( cmd );\n\t\t\t\t\tmcmd.parseCommandStr();\n\t\t\t\t\treturn mcmd;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Determine if this is a command\n\t\tif ( cmd.startsWith(\"db.\") || cmd.startsWith(\"sh.\") || cmd.startsWith(\"rs.\") ){\n\t\t\tMongoCommand mcmd = new PassThruMongoCommand();\n\t\t\tmcmd.setConnection(activeServer, activeDB);\n\t\t\tmcmd.setCommandStr(cmd);\n\t\t\treturn mcmd;\n\t\t}\n\t\t\t\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic void submitExecution( MongoCommand mcmd ){\n\t\tsynchronized(commandQueue){\n\t\t\tcommandQueue.add(mcmd);\n\t\t\tcommandQueue.notify();\n\t\t}\n\t}\n\n\tpublic MongoClient getMongoActive() {\n\t\treturn mongoMap.get(activeServer);\n\t}\n\n\tpublic DB getMongoActiveDB() {\n\t\treturn mongoMap.get(activeServer).getDB(activeDB);\n\t}\n\t\n\tpublic void run(){\n\t\tMongoCommand\tcmd;\n\t\t\n\t\twhile (bRun){\n\t\t\t\n\t\t\twhile ( commandQueue.size() == 0 ){\n\t\t\t\tsynchronized (commandQueue) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommandQueue.wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tbRun = false;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tsynchronized(commandQueue){\n\t\t\t\tcmd\t= commandQueue.remove(0);\n\t\t\t\tif ( cmd == null )\n\t\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\t// Now let the listeners know we are about to start\n\t\t\talertDocumentViewsOnMongoCommandStart(cmd);\n\t\t\talertListenersOnMongoCommandStart(cmd);\n\t\t\t\n\t\t\t// Execute the command\n\t\t\tlong startTime\t= System.currentTimeMillis();\n\t\t\ttry{\n\t\t\t\tcmd.execute();\n\t\t\t}catch(Throwable t){\n\t\t\t\tt.printStackTrace();\n\t\t\t}finally{\n\t\t\t\tcmd.setExecTime( System.currentTimeMillis() - startTime );\n\t\t\t\tcmd.hasRun();\n\t\t\t}\n\n\t\t\tif ( cmd.getCollection() != null )\n\t\t\t\tactiveCollection = cmd.getCollection();\n\t\t\t\n\n\t\t\t// Now let the listeners know we have finished\n\t\t\talertDocumentViewsOnMongoCommandFinished(cmd);\n\t\t\talertListenersOnMongoCommandFinished(cmd);\n\t\t}\n\t}\n\n\tpublic void setActiveServerDB(String name, String db) {\n\t\tactiveServer = name;\n\t\tactiveDB = db;\n\t}\n\n\tpublic String getActiveCollection() {\n\t\treturn activeCollection;\n\t}\n\t\n\t\n\tprivate void alertListenersOnMongoCommandStart( MongoCommand cmd ){\n\t\tIterator<MongoCommandListener>\tit\t= mongoListeners.iterator();\n\t\twhile ( it.hasNext() ){\n\t\t\ttry{\n\t\t\t\tit.next().onMongoCommandStart(cmd);\n\t\t\t}catch(Exception e){\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void alertListenersOnMongoCommandFinished( MongoCommand cmd ){\n\t\tIterator<MongoCommandListener>\tit\t= mongoListeners.iterator();\n\t\twhile ( it.hasNext() ){\n\t\t\ttry{\n\t\t\t\tit.next().onMongoCommandFinished(cmd);\n\t\t\t}catch(Exception e){\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\tprivate void alertDocumentViewsOnMongoCommandStart( MongoCommand cmd ){}\n\t\n\tprivate void alertDocumentViewsOnMongoCommandFinished( MongoCommand cmd ){\n\t\tif ( !cmd.hasQueryData() )\n\t\t\treturn;\n\t\t\n\t\tfindDocumentView(cmd);\n\t}\n\t\n\tprivate void findDocumentView(final MongoCommand cmd){\n\t\tIterator<MDocumentView>\tit\t= documentViewListeners.iterator();\n\t\t\n\t\tfinal String id\t= ( cmd.getDB() != null ? cmd.getDB() : \"DB\" ) + \"-\" + ( cmd.getCollection() != null ? cmd.getCollection() : \"Output\" );\n\t\t\n\t\twhile ( it.hasNext() ){\n\t\t\tMDocumentView view = it.next();\n\t\t\t\n\t\t\tif ( view.getViewTitle().equals(id) ){\n\t\t\t\tfinal MDocumentView finalView = view;\n\t\t\t\tActivator.getDefault().getShell().getDisplay().asyncExec(new Runnable() {\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tActivator.getDefault().showView(\"org.aw20.mongoworkbench.eclipse.view.MDocumentView\", id );\n\t\t\t\t\t\t((MDocumentView)finalView).onMongoCommandFinished(cmd);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t/* Need to create a new one */\n\t\tActivator.getDefault().getShell().getDisplay().asyncExec(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tObject view = Activator.getDefault().showView(\"org.aw20.mongoworkbench.eclipse.view.MDocumentView\", id );\n\t\t\t\tif ( view != null && view instanceof MDocumentView )\n\t\t\t\t\t((MDocumentView)view).onMongoCommandFinished(cmd);\n\t\t\t}\n\t\t});\n\t\t\n\t}\n}", "public class AggregateMongoCommand extends GroupMongoCommand {\n\n\t@Override\n\tpublic void execute() throws Exception {\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\t\n\t\tDB db\t= mdb.getDB(sDb);\n\t\tBasicDBObject cmdMap\t= parseMongoCommandString(db, cmd);\n\t\t\n\t\tif ( !cmdMap.containsField(\"aggregateArg\") )\n\t\t\tthrow new Exception(\"no aggregate document\");\n\n\t\t// Execute the command\n\t\tObject result\t= db.eval(cmd, (Object[])null );\n\t\t\n\t\tif ( result == null )\n\t\t\tthrow new Exception(\"null returned\");\n\t\tif ( !(result instanceof BasicDBObject ) )\n\t\t\tthrow new Exception(\"not correct type returned: \" + result.getClass().getName() );\n\n\t\tBasicDBObject dbo = (BasicDBObject)result;\n\t\tif ( dbo.containsField(\"result\") ){\n\t\t\tdbListResult\t= (BasicDBList)dbo.get(\"result\");\n\t\t\tsetMessage(\"# rows=\" + dbListResult.size() );\n\t\t} else {\n\t\t\tsetMessage(\"# rows=0\" );\n\t\t}\n\t}\n\t\n\t\n\t@Override\n\tpublic void parseCommandStr() throws Exception {\n\t\tsColl = getCollNameFromAction(cmd, \"aggregate\");\n\t\t\n\t\tif ( sColl == null || sColl.length() == 0 )\n\t\t\tthrow new Exception(\"failed to determine collection from command\");\n\t}\n}", "public abstract class MongoCommand extends Object {\n\n\tpublic static String KEY_NAME = \"_name\";\n\n\tpublic static String KEY_COUNT = \"_count\";\n\n\tprotected String sName = null, sDb = null, sColl = null, rteMessage = \"\", cmd = null;\n\n\tprotected Exception lastException = null;\n\n\tprotected boolean hasRun = false;\n\n\tprivate long execTime = -1;\n\n\t/**\n\t * Sets the connection details to which this command pertains to\n\t * \n\t * @param mongoName\n\t * @param database\n\t * @param collection\n\t */\n\tpublic MongoCommand setConnection(String mongoName, String database, String collection) {\n\t\tthis.sName = mongoName;\n\t\tthis.sDb = database;\n\t\tthis.sColl = collection;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(String mongoName, String database) {\n\t\tthis.sName = mongoName;\n\t\tthis.sDb = database;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(String mongoName) {\n\t\tthis.sName = mongoName;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(MongoCommand mcmd) {\n\t\tthis.sName = mcmd.sName;\n\t\tthis.sDb = mcmd.sDb;\n\t\tthis.sColl = mcmd.sColl;\n\t\treturn this;\n\t}\n\n\tpublic boolean isSuccess() {\n\t\treturn lastException == null;\n\t}\n\t\n\tpublic boolean hasQueryData(){\n\t\treturn false;\n\t}\n\n\tpublic boolean hasRun() {\n\t\treturn hasRun;\n\t}\n\n\tpublic void markAsRun() {\n\t\thasRun = true;\n\t}\n\n\tpublic Exception getException() {\n\t\treturn lastException;\n\t}\n\n\tpublic void setException(Exception e) {\n\t\tlastException = e;\n\t}\n\n\tpublic String getExceptionMessage() {\n\t\tif (lastException == null)\n\t\t\treturn \"\";\n\n\t\tif (lastException instanceof MongoException) {\n\t\t\tString e = lastException.getMessage();\n\t\t\tif (e.startsWith(\"command failed [$eval]: {\") && e.endsWith(\"}\")) {\n\t\t\t\ttry {\n\t\t\t\t\tMap m = (Map) JSON.parse(e.substring(e.indexOf(\"{\")));\n\t\t\t\t\treturn (String) m.get(\"errmsg\");\n\t\t\t\t} catch (Exception ee) {\n\t\t\t\t\treturn lastException.getMessage();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lastException.getMessage();\n\t}\n\n\tpublic long getExecTime() {\n\t\treturn execTime;\n\t}\n\n\tprotected void setMessage(String string) {\n\t\trteMessage = string;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn rteMessage;\n\t}\n\n\tpublic String getName() {\n\t\treturn sName;\n\t}\n\n\tpublic String getDB() {\n\t\treturn sDb;\n\t}\n\n\tpublic String getCollection() {\n\t\treturn sColl;\n\t}\n\n\t/**\n\t * Override this function to provide the body of the command\n\t */\n\tpublic abstract void execute() throws Exception;\n\n\tpublic String getCommandString() {\n\t\treturn this.cmd;\n\t}\n\n\tpublic void setExecTime(long l) {\n\t\texecTime = l;\n\t}\n\n\tpublic void setCommandStr(String cmd) {\n\t\tthis.cmd = cmd;\n\t}\n\n\tpublic void parseCommandStr() throws Exception {}\n\n\tpublic String getMatchIgnoreCase(String patternStr, String target) {\n\t\tPattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);\n\t\tMatcher matcher = pattern.matcher(target);\n\t\tif (matcher.find()) {\n\t\t\tif (matcher.groupCount() > 0) {\n\t\t\t\treturn matcher.group(1);\n\t\t\t} else {\n\t\t\t\treturn target.substring(matcher.start(), matcher.end());\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\t\n\tpublic BasicDBObject parse() throws Exception{\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\t\n\t\tDB db\t= mdb.getDB(sDb);\n\t\treturn parseMongoCommandString(db, cmd);\n\t}\n\t\n\t\n\tprotected BasicDBObject parseMongoCommandString(DB db, String cmd) throws Exception {\n\t\t\n\t\tString newCmd = cmd.replaceFirst(\"db.\" + sColl, \"a\");\n\t\tString jsStr = StreamUtil.readToString( this.getClass().getResourceAsStream(\"parseCommand.txt\") ); \n\t\tjsStr = StringUtil.tokenReplace(jsStr, new String[]{\"//_QUERY_\"}, new String[]{newCmd} );\n\n\t\tBasicDBObject cmdMap = (BasicDBObject)db.eval(jsStr, (Object[])null);\n\t\t\n\t\t/*\n\t\t * Using JavaScript Engine\n\t\tContext cx = Context.enter();\n\t\tcx.setLanguageVersion(Context.VERSION_1_7);\n\t\tScriptable scope = cx.initStandardObjects();\n\t\tObject returnObj = cx.evaluateString(scope, jsStr, \"CustomJS\", 1, null);\n\t\t\n\t\tMap cmdMap = (Map) jsConvert2cfData( (IdScriptableObject)returnObj );\n\t\t*/\n\t\t\n\t\t// Remove the helper methods\n\t\tcmdMap.remove(\"find\");\n\t\tcmdMap.remove(\"findOne\");\n\t\tcmdMap.remove(\"group\");\n\t\tcmdMap.remove(\"aggregate\");\n\t\tcmdMap.remove(\"save\");\n\t\tcmdMap.remove(\"mapReduce\");\n\t\tcmdMap.remove(\"update\");\n\t\tcmdMap.remove(\"remove\");\n\t\tcmdMap.remove(\"limit\");\n\t\tcmdMap.remove(\"skip\");\n\t\tcmdMap.remove(\"sort\");\n\t\t\n\t\treturn new BasicDBObject( cmdMap );\n\t}\n\n\t\n\tpublic static Object jsConvert2cfData(IdScriptableObject obj) throws Exception {\n\n\t\tif (obj instanceof NativeObject) {\n\t\t\tMap struct = new HashMap();\n\n\t\t\tNativeObject nobj = (NativeObject) obj;\n\t\t\tObject[] elements = nobj.getAllIds();\n\n\t\t\tObject cfdata;\n\t\t\t\n\t\t\tfor (int x = 0; x < elements.length; x++) {\n\t\t\t\tObject jsObj = nobj.get(elements[x]);\n\n\t\t\t\tif (jsObj == null)\n\t\t\t\t\tcfdata = null;\n\t\t\t\telse if (jsObj instanceof NativeObject || jsObj instanceof NativeArray)\n\t\t\t\t\tcfdata = jsConvert2cfData((IdScriptableObject) jsObj);\n\t\t\t\telse\n\t\t\t\t\tcfdata = jsObj;\n\n\t\t\t\tstruct.put((String) elements[x], cfdata);\n\t\t\t}\n\n\t\t\treturn struct;\n\t\t} else if (obj instanceof NativeArray) {\n\t\t\tList array = new ArrayList();\n\n\t\t\tNativeArray nobj = (NativeArray) obj;\n\t\t\tObject cfdata;\n\t\t\tint len = (int) nobj.getLength();\n\n\t\t\tfor (int x = 0; x < len; x++) {\n\t\t\t\tObject jsObj = nobj.get(x);\n\n\t\t\t\tif (jsObj == null)\n\t\t\t\t\tcfdata = null;\n\t\t\t\telse if (jsObj instanceof NativeObject || jsObj instanceof NativeArray)\n\t\t\t\t\tcfdata = jsConvert2cfData((IdScriptableObject) jsObj);\n\t\t\t\telse\n\t\t\t\t\tcfdata = jsObj;\n\t\t\t\t\n\t\t\t\tarray.add(cfdata);\n\t\t\t}\n\n\t\t\treturn array;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t\n\tprotected BasicDBObject\tfixNumbers( BasicDBObject dbo ){\n\t\tIterator<String> it\t= dbo.keySet().iterator();\n\t\twhile (it.hasNext()){\n\t\t\tString field\t= it.next();\n\t\t\tObject o\t= dbo.get(field);\n\t\t\tif ( o instanceof Double ){\n\t\t\t\tdbo.put(field, NumberUtil.fixDouble( (Double)o) );\n\t\t\t}else if ( o instanceof BasicDBObject ){\n\t\t\t\tdbo.put(field, fixNumbers((BasicDBObject)o) );\n\t\t\t}else if ( o instanceof BasicDBList ){\n\t\t\t\tdbo.put(field, fixNumbers((BasicDBList)o) );\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dbo;\n\t}\n\t\n\t\n\tprotected BasicDBList\tfixNumbers( BasicDBList dbo ){\n\t\tfor ( int x=0; x < dbo.size(); x++ ){\n\t\t\tObject o =\tdbo.get(x);\n\t\t\t\n\t\t\tif ( o instanceof Double ){\n\t\t\t\tdbo.set(x, NumberUtil.fixDouble( (Double)o) );\n\t\t\t}else if ( o instanceof BasicDBObject ){\n\t\t\t\tdbo.set(x, fixNumbers((BasicDBObject)o) );\n\t\t\t}else if ( o instanceof BasicDBList ){\n\t\t\t\tdbo.set(x, fixNumbers((BasicDBList)o) );\n\t\t\t}\n\t\t}\n\n\t\treturn dbo;\n\t}\n}", "public interface WizardParentI {\n\n\t/**\n\t * Returns the active DB\n\t * @return\n\t */\n\tpublic String getActiveDB();\n\t\n\t/**\n\t * Returns the active collection\n\t * @return\n\t */\n\tpublic String getActiveCollection();\n\t\n}", "public class JSONFormatter extends Object {\n\n\tprivate StringBuilder sb;\n\tprivate String tab;\n\tprivate String nl = System.getProperty(\"line.separator\");\n\n\tpublic static String format( Object object ){\n\t\treturn new JSONFormatter().parseObject(object);\n\t}\n\t\n\tpublic JSONFormatter() {\n\t\tthis(\" \");\n\t}\n\t\n\tpublic JSONFormatter(String _tab) {\n\t\tthis.tab = _tab;\n\t}\n\t\n\t/**\n\t * Treats a List, Map, String, Integer, Long, Float, Double, or Boolean as a JSON Object and formats it in JSON format.\n\t * \n\t * Unrecognized Object Types will be marked \"binary-object\"\n\t * \n\t * @param _o A valid object to be parsed may be a Boolean, Integer, Float, String, or Map or List containing any of the other object\n\t * @return Formatted Json\n\t */\n\tpublic String parseObject(Object _o) {\n\t\tsb = new StringBuilder(256);\n\t\tparseValue(_o);\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate void parseValue(Object _o) {\n\t\tparseValue(_o, 0);\n\t}\n\t\n\tprivate void parseValue(Object _o, int _depth) {\n\t\t\n\t\tif ( _o instanceof String || _o instanceof Character ){\n\t\t\tsb.append(\"\\\"\" + _o.toString() + \"\\\"\");\n\t\t} else if (_o instanceof Map) {\n\t\t\tsb.append(\"{\");\n\t\t\tparseObject((Map<String, Object>)_o, _depth + 1);\n\t\t\tsb.append(\"}\");\n\t\t} else if (_o instanceof List) {\n\t\t\tsb.append(\"[\");\n\t\t\tparseArray((List)_o, _depth + 1);\n\t\t\tsb.append(\"]\");\n\t\t} else if (_o instanceof Float || _o instanceof Double) {\n\t\t\tString d = String.valueOf(_o);\n\t\t\tif ( d.endsWith(\".0\") )\n\t\t\t\tsb.append(d.substring(0,d.length()-2));\n\t\t\telse\n\t\t\t\tsb.append(d);\n\t\t} else if (_o instanceof Integer || _o instanceof Long || _o instanceof Boolean) {\n\t\t\tsb.append(_o.toString());\n\t\t} else if (_o == null) {\n\t\t\tsb.append(\"null\");\n\t\t} else if ( _o instanceof Date ){\n\t\t\tsb.append( \"ISODate(\\\"\" );\n\t\t\tsb.append( DateUtil.getDateString( (Date)_o, \"yyyy-MM-dd'T'HH:mm:ss.SSS\") );\n\t\t\tsb.append( \"Z\\\")\");\n\t\t} else if ( _o instanceof ObjectId ){\n\t\t\tsb.append( \"ObjectId(\\\"\" );\n\t\t\tsb.append( (ObjectId)_o );\n\t\t\tsb.append( \"\\\")\");\n\t\t} else if ( _o instanceof Pattern ){\n\t\t\tsb.append( \"/\" );\n\t\t\tsb.append( (Pattern)_o );\n\t\t\tsb.append( \"/\");\n\t\t} else if ( _o instanceof byte[] ){\t\n\t\t\tsb.append( \"BinData(0,\\\"\" );\n\t\t\tsb.append( Base64.encodeBytes((byte[])_o) );\n\t\t\tsb.append( \"\\\")\");\n\t\t} else {\n\t\t\tsb.append( _o.getClass().getName() );\n\t\t}\n\t}\n\t\n\tprivate void parseObject(Map<String, Object> _map, int _depth) {\n\t\tString margin = getMargin(_depth);\n\t\t\n\t\tString[] keyArr = (String[])_map.keySet().toArray(new String[0]);\n\t\tArrays.sort(keyArr);\n\t\tfor ( String key : keyArr ){\n\t\t\tObject value = _map.get(key);\n\t\t\t\n\t\t\t// Write out this key/value pair\n\t\t\tsb.append(nl)\n\t\t\t\t.append(margin)\n\t\t\t\t.append(\"\\\"\")\n\t\t\t\t.append( key )\n\t\t\t\t.append(\"\\\" : \");\n\t\t\tparseValue(value, _depth);\n\t\t\tsb.append(\",\");\n\t\t}\n\t\t\n\t\t// Remove final comma\n\t\tif ( sb.charAt(sb.length()-1) == ','){\n\t\t\tsb.delete(sb.length() - 1, sb.length());\n\t\t\tsb.append(nl).append(getMargin(_depth - 1));\n\t\t} else {\n\t\t\tsb.append(\" \");\n\t\t}\n\t}\n\t\n\tprivate void parseArray(List _list, int _depth) {\n\t\t\n\t\t// Parse through an array\n\t\tboolean empty = true;\n\t\tfor( Object o : _list) {\n\t\t\tempty = false;\n\t\t\tparseValue(o, _depth);\n\t\t\tsb.append(\", \");\n\t\t}\n\n\t\t// Remove final comma\n\t\tif (!empty)\n\t\t\tsb.delete(sb.length() - 2, sb.length());\n\t\telse\n\t\t\tsb.append(\" \");\n\t}\n\t\n\t// Gets the margin for the specified _depth level\n\tprivate String getMargin(int _depth) {\n\t\tStringBuilder margin = new StringBuilder(32);\n\t\tfor (int i = 0; i < _depth; i++)\n\t\t\tmargin.append(this.tab);\n\t\t\n\t\treturn margin.toString();\n\t}\n}", "public class MSwtUtil extends Object {\n\n\tpublic static Text createText( Composite comp ){\n\t\tText txt = new Text(comp, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);\n\t\ttxt.setFont(SWTResourceManager.getFont(\"Courier New\", 9, SWT.NORMAL));\n\t\ttxt.setTabs(2);\n\t\treturn txt;\n\t}\n\t\n\tpublic static void addListenerToMenuItems(Menu menu, Listener listener) {\n\t\tMenuItem[] itemArray = menu.getItems();\n\t\tfor (int i = 0; i < itemArray.length; ++i) {\n\t\t\titemArray[i].addListener(SWT.Selection, listener);\n\t\t}\n\t}\n\n\tpublic static void copyToClipboard(String s) {\n\t\tDisplay display = Display.findDisplay(Thread.currentThread());\n\t\tClipboard clipboard = new Clipboard(display);\n\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\tclipboard.setContents(new Object[] { s }, new Transfer[] { textTransfer });\n\t\tclipboard.dispose();\n\t}\n\n\tpublic static Image getImage(Device device, String imageFileName) {\n\t\tInputStream in = null;\n\t\ttry {\n\t\t\tin = StreamUtil.getResourceStream(\"org/aw20/mongoworkbench/eclipse/resources/\" + imageFileName);\n\t\t\tImageData imageData = new ImageData(in);\n\t\t\treturn new Image(device, imageData);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tStreamUtil.closeStream(in);\n\t\t}\n\t}\n\t\n}" ]
import java.io.IOException; import org.aw20.mongoworkbench.Event; import org.aw20.mongoworkbench.EventWorkBenchManager; import org.aw20.mongoworkbench.MongoFactory; import org.aw20.mongoworkbench.command.AggregateMongoCommand; import org.aw20.mongoworkbench.command.MongoCommand; import org.aw20.mongoworkbench.eclipse.view.WizardParentI; import org.aw20.util.JSONFormatter; import org.aw20.util.MSwtUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject;
/* * MongoWorkBench is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * Free Software Foundation,version 3. * * MongoWorkBench is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * If not, see http://www.gnu.org/licenses/ * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining * it with any of the JARS listed in the README.txt (or a modified version of * (that library), containing parts covered by the terms of that JAR, the * licensors of this Program grant you additional permission to convey the * resulting work. * * https://github.com/aw20/MongoWorkBench * Original fork: https://github.com/Kanatoko/MonjaDB * */ package org.aw20.mongoworkbench.eclipse.view.wizard; public class AggregateWizard extends Composite implements WizardCommandI { private String HELPURL = "http://docs.mongodb.org/manual/reference/method/db.collection.aggregate"; private Text textPipe; private TabFolder tabFolder; private Button btnRemovePipe; private WizardParentI wizardparent; public AggregateWizard(WizardParentI wizardparent, Composite parent, int style) { super(parent, style); this.wizardparent = wizardparent; setLayout(new GridLayout(5, false)); tabFolder = new TabFolder(this, SWT.NONE); tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1)); TabItem tbtmPipe = new TabItem(tabFolder, SWT.NONE); tbtmPipe.setText("Pipe#1");
textPipe = MSwtUtil.createText( tabFolder );
7
oantajames/mdb-android-application
app/src/main/java/mdb/com/view/moviesgrid/MoviesGridActivity.java
[ "public class MovieEntity implements Parcelable {\n\n @SerializedName(\"vote_count\")\n @Expose\n public Integer voteCount;\n @SerializedName(\"id\")\n @Expose\n public Integer id;\n @SerializedName(\"video\")\n @Expose\n public Boolean video;\n @SerializedName(\"vote_average\")\n @Expose\n public Double voteAverage;\n @SerializedName(\"title\")\n @Expose\n public String title;\n @SerializedName(\"popularity\")\n @Expose\n public Double popularity;\n @SerializedName(\"poster_path\")\n @Expose\n public String posterPath;\n @SerializedName(\"original_language\")\n @Expose\n public String originalLanguage;\n @SerializedName(\"original_title\")\n @Expose\n public String originalTitle;\n @SerializedName(\"backdrop_path\")\n @Expose\n public String backdropPath;\n @SerializedName(\"adult\")\n @Expose\n public Boolean adult;\n @SerializedName(\"overview\")\n @Expose\n public String overview;\n @SerializedName(\"release_date\")\n @Expose\n public String releaseDate;\n\n public MovieEntity() {\n }\n\n public MovieEntity(Cursor cursor) {\n this.id = getColumnInt(cursor, MovieEntry._ID);\n this.title = getColumnString(cursor, MovieEntry.TITLE);\n this.posterPath = getColumnString(cursor, MovieEntry.POSTER_PATH);\n this.adult = getColumnInt(cursor, MovieEntry.IS_ADULT) == 1;\n this.backdropPath = getColumnString(cursor, MovieEntry.BACKDROP_PATH);\n this.originalLanguage = getColumnString(cursor, MovieEntry.ORIGINAL_LANGUAGE);\n this.overview = getColumnString(cursor, MovieEntry.OVERVIEW);\n this.popularity = getColumnDouble(cursor, MovieEntry.POPULARITY);\n this.originalTitle = getColumnString(cursor, MovieEntry.ORIGINAL_TITLE);\n this.releaseDate = getColumnString(cursor, MovieEntry.RELEASE_DATE);\n this.video = getColumnInt(cursor, MovieEntry.HAS_VIDEO) == 1;\n this.voteAverage = getColumnDouble(cursor, MovieEntry.VOTE_AVERAGE);\n this.voteCount = getColumnInt(cursor, MovieEntry.VOTE_COUNT);\n }\n\n protected MovieEntity(Parcel in) {\n if (in.readByte() == 0) {\n voteCount = null;\n } else {\n voteCount = in.readInt();\n }\n if (in.readByte() == 0) {\n id = null;\n } else {\n id = in.readInt();\n }\n byte tmpVideo = in.readByte();\n video = tmpVideo == 0 ? null : tmpVideo == 1;\n if (in.readByte() == 0) {\n voteAverage = null;\n } else {\n voteAverage = in.readDouble();\n }\n title = in.readString();\n if (in.readByte() == 0) {\n popularity = null;\n } else {\n popularity = in.readDouble();\n }\n posterPath = in.readString();\n originalLanguage = in.readString();\n originalTitle = in.readString();\n backdropPath = in.readString();\n byte tmpAdult = in.readByte();\n adult = tmpAdult == 0 ? null : tmpAdult == 1;\n overview = in.readString();\n releaseDate = in.readString();\n byte tmpIsFavorite = in.readByte();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n if (voteCount == null) {\n dest.writeByte((byte) 0);\n } else {\n dest.writeByte((byte) 1);\n dest.writeInt(voteCount);\n }\n if (id == null) {\n dest.writeByte((byte) 0);\n } else {\n dest.writeByte((byte) 1);\n dest.writeInt(id);\n }\n dest.writeByte((byte) (video == null ? 0 : video ? 1 : 2));\n if (voteAverage == null) {\n dest.writeByte((byte) 0);\n } else {\n dest.writeByte((byte) 1);\n dest.writeDouble(voteAverage);\n }\n dest.writeString(title);\n if (popularity == null) {\n dest.writeByte((byte) 0);\n } else {\n dest.writeByte((byte) 1);\n dest.writeDouble(popularity);\n }\n dest.writeString(posterPath);\n dest.writeString(originalLanguage);\n dest.writeString(originalTitle);\n dest.writeString(backdropPath);\n dest.writeByte((byte) (adult == null ? 0 : adult ? 1 : 2));\n dest.writeString(overview);\n dest.writeString(releaseDate);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator<MovieEntity> CREATOR = new Creator<MovieEntity>() {\n @Override\n public MovieEntity createFromParcel(Parcel in) {\n return new MovieEntity(in);\n }\n\n @Override\n public MovieEntity[] newArray(int size) {\n return new MovieEntity[size];\n }\n };\n\n public ContentValues convertToContentValues() {\n ContentValues movieContent = new ContentValues();\n movieContent.put(MovieEntry._ID, id);\n movieContent.put(MovieEntry.TITLE, title);\n movieContent.put(MovieEntry.POSTER_PATH, posterPath);\n movieContent.put(MovieEntry.IS_ADULT, adult);\n movieContent.put(MovieEntry.BACKDROP_PATH, backdropPath);\n movieContent.put(MovieEntry.ORIGINAL_LANGUAGE, originalLanguage);\n movieContent.put(MovieEntry.OVERVIEW, overview);\n movieContent.put(MovieEntry.POPULARITY, popularity);\n movieContent.put(MovieEntry.ORIGINAL_TITLE, originalTitle);\n movieContent.put(MovieEntry.RELEASE_DATE, releaseDate);\n movieContent.put(MovieEntry.HAS_VIDEO, video);\n movieContent.put(MovieEntry.VOTE_AVERAGE, voteAverage);\n movieContent.put(MovieEntry.VOTE_COUNT, voteCount);\n return movieContent;\n }\n\n public static MovieEntity fromCursor(Cursor cursor) {\n MovieEntity movie = new MovieEntity();\n movie.setId(getColumnInt(cursor, MovieEntry._ID));\n movie.setTitle(getColumnString(cursor, MovieEntry.TITLE));\n movie.setPosterPath(getColumnString(cursor, MovieEntry.POSTER_PATH));\n movie.setAdult(getColumnInt(cursor, MovieEntry.IS_ADULT) == 1);\n movie.setBackdropPath(getColumnString(cursor, MovieEntry.BACKDROP_PATH));\n movie.setOriginalLanguage(getColumnString(cursor, MovieEntry.ORIGINAL_LANGUAGE));\n movie.setOverview(getColumnString(cursor, MovieEntry.OVERVIEW));\n movie.setPopularity(getColumnDouble(cursor, MovieEntry.POPULARITY));\n movie.setOriginalTitle(getColumnString(cursor, MovieEntry.ORIGINAL_TITLE));\n movie.setReleaseDate(getColumnString(cursor, MovieEntry.RELEASE_DATE));\n movie.setVideo(getColumnInt(cursor, MovieEntry.HAS_VIDEO) == 1);\n movie.setVoteAverage(getColumnDouble(cursor, MovieEntry.VOTE_AVERAGE));\n movie.setVoteCount(getColumnInt(cursor, MovieEntry.VOTE_COUNT));\n return movie;\n }\n\n public Integer getVoteCount() {\n return voteCount;\n }\n\n public void setVoteCount(Integer voteCount) {\n this.voteCount = voteCount;\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Boolean getVideo() {\n return video;\n }\n\n public void setVideo(Boolean video) {\n this.video = video;\n }\n\n public Double getVoteAverage() {\n return voteAverage;\n }\n\n public void setVoteAverage(Double voteAverage) {\n this.voteAverage = voteAverage;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public Double getPopularity() {\n return popularity;\n }\n\n public void setPopularity(Double popularity) {\n this.popularity = popularity;\n }\n\n public String getPosterPath() {\n return posterPath;\n }\n\n public void setPosterPath(String posterPath) {\n this.posterPath = posterPath;\n }\n\n public String getOriginalLanguage() {\n return originalLanguage;\n }\n\n public void setOriginalLanguage(String originalLanguage) {\n this.originalLanguage = originalLanguage;\n }\n\n public String getOriginalTitle() {\n return originalTitle;\n }\n\n public void setOriginalTitle(String originalTitle) {\n this.originalTitle = originalTitle;\n }\n\n public String getBackdropPath() {\n return backdropPath;\n }\n\n public void setBackdropPath(String backdropPath) {\n this.backdropPath = backdropPath;\n }\n\n public Boolean getAdult() {\n return adult;\n }\n\n public void setAdult(Boolean adult) {\n this.adult = adult;\n }\n\n public String getOverview() {\n return overview;\n }\n\n public void setOverview(String overview) {\n this.overview = overview;\n }\n\n public String getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(String releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n public static Creator<MovieEntity> getCREATOR() {\n return CREATOR;\n }\n\n}", "public interface HasComponent<C> {\n C getComponent();\n}", "@PerActivity\n@Component(dependencies = ApplicationComponent.class, modules = {MoviesGridModule.class})\npublic interface MoviesGridComponent {\n\n //where\n void inject(MoviesGridActivity moviesGridActivity);\n\n void inject(FragmentMoviesList fragmentMoviesList);\n\n void inject(MoviesGridAdapter.ViewHolder viewHolder);\n\n}", "@Module\npublic class MoviesGridModule {\n\n @Provides\n @PerActivity\n SharedPreferences providesSharedPreferences(Context application) {\n return PreferenceManager.getDefaultSharedPreferences(application);\n }\n\n @Provides\n public MoviesRepository providesMoviesService(Context context, mdb.com.data.api.MoviesService theMovieDbService) {\n return new MoviesRepository(context, theMovieDbService);\n }\n\n}", "public class DisposableManager {\n\n private DisposableManager() {\n }\n\n private static CompositeDisposable compositeDisposable;\n\n public static void add(Disposable disposable) {\n getCompositeDisposable().add(disposable);\n }\n\n public static CompositeDisposable getCompositeDisposable() {\n if (compositeDisposable == null || compositeDisposable.isDisposed()) {\n compositeDisposable = new CompositeDisposable();\n }\n return compositeDisposable;\n }\n\n public static void dispose() {\n getCompositeDisposable().dispose();\n }\n\n}", "public enum Sort {\n\n MOST_POPULAR(\"popular\"),\n TOP_RATED(\"top_rated\"),\n FAVORITES(\"favorites\");\n\n private String value;\n\n Sort(String sort) {\n value = sort;\n }\n\n public static Sort fromString(@NonNull String string) {\n for (Sort sort : Sort.values()) {\n if (string.equals(sort.toString())) {\n return sort;\n }\n }\n throw new IllegalArgumentException(\"No constant with text \" + string + \" found.\");\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n}", "public abstract class BaseActivity extends Activity {\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getApplicationComponent().inject(this);\n }\n\n protected ApplicationComponent getApplicationComponent() {\n return ((MdbApplication) getApplication()).getApplicationComponent();\n }\n\n}", "public class MovieDetailsActivity extends BaseActivity implements MovieReviewsAdapter.UpdateReviewsView, MovieTrailersAdapter.UpdateTrailersView {\n\n public static final String EXTRA_MOVIE_IMAGE_TRANSITION = \"movieImageTransition\";\n\n private static final int TRAILERS_LOADER = 1;\n private static final int REVIEWS_LOADER = 2;\n\n @Bind(R.id.header)\n SimpleDraweeView movieHeader;\n @Bind(R.id.backdrop_gradient_view)\n ImageView backdropGradient;\n @Bind(R.id.movie_release_year)\n TextView movieReleaseYear;\n @Bind(R.id.movie_rating)\n TextView movieRating;\n @Bind(R.id.movie_title)\n TextView movieTitle;\n @Bind(R.id.movie_poster)\n ImageView moviePoster;\n @Bind(R.id.movie_description)\n FlowTextView movieDescription;\n @Bind(R.id.main_background)\n LinearLayout mainBackground;\n @Bind(R.id.trailer_recycler_view)\n RecyclerView trailersRecyclerView;\n @Bind(R.id.reviews_recycler_view)\n RecyclerView reviewsRecyclerView;\n @Bind(R.id.favorites_button)\n ImageView favoritesButton;\n @Bind(R.id.back_button)\n ImageView backButton;\n @Bind(R.id.scroll_view)\n ScrollView scrollView;\n @Bind(R.id.no_reviews)\n TextView noReviewsView;\n @Bind(R.id.no_trailers)\n TextView noTrailersView;\n\n\n @Inject\n FavoritesRepository favoritesRepository;\n @Inject\n MovieDetailsRepository movieDetailsRepository;\n\n private MovieTrailersAdapter movieTrailersAdapter;\n private MovieReviewsAdapter reviewsAdapter;\n private MovieEntity movieEntity;\n\n private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n if (action.equals(MovieDetailsRepository.BROADCAST_ON_COMPLETE_TRAILERS)) {\n if (!intent.getBooleanExtra(MovieDetailsRepository.SUCCESSFUL_UPDATED, true)) {\n showError();\n }\n } else if (action.equals(MovieDetailsRepository.BROADCAST_ON_COMPLETE_REVIEWS)) {\n if (!intent.getBooleanExtra(MovieDetailsRepository.SUCCESSFUL_UPDATED, true)) {\n showError();\n }\n }\n }\n };\n\n private void showError() {\n Snackbar.make(scrollView, R.string.error_failed_to_update_movies,\n Snackbar.LENGTH_LONG)\n .show();\n }\n\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n inject();\n setContentView(R.layout.activity_movie_details);\n ButterKnife.bind(this);\n setFlowTextViewAppearance();\n movieEntity = getIntent().getExtras().getParcelable(MoviesGridActivity.MOVIE_ENTITY);\n getLoaderManager().initLoader(TRAILERS_LOADER, null, trailersCallback);\n getLoaderManager().initLoader(REVIEWS_LOADER, null, reviewsCallback);\n setFavoritesButtonView();\n movieTrailersAdapter = new MovieTrailersAdapter(null, this);\n reviewsAdapter = new MovieReviewsAdapter(null, this);\n bindViews(movieEntity);\n scrollView.smoothScrollTo(0, 0);\n }\n\n\n @Override\n protected void onResume() {\n super.onResume();\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(MovieDetailsRepository.BROADCAST_ON_COMPLETE_REVIEWS);\n intentFilter.addAction(MovieDetailsRepository.BROADCAST_ON_COMPLETE_TRAILERS);\n LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter);\n movieDetailsRepository.retrieveTrailers(movieEntity);\n movieDetailsRepository.retrieveReviews(movieEntity);\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);\n }\n\n @Override\n protected void onDestroy() {\n DisposableManager.dispose();\n super.onDestroy();\n }\n\n\n private void setFavoritesButtonView() {\n if (favoritesRepository.isFavorite(movieEntity)) {\n favoritesButton.setSelected(true);\n } else {\n favoritesButton.setSelected(false);\n }\n }\n\n private void setFlowTextViewAppearance() {\n movieDescription.setTextColor(Color.WHITE);\n movieDescription.setTextSize(60);\n }\n\n private void inject() {\n DaggerMovieDetailsComponent movieDetailsComponent = (DaggerMovieDetailsComponent) DaggerMovieDetailsComponent.builder()\n .applicationComponent(getApplicationComponent())\n .movieDetailsModule(new MovieDetailsModule())\n .build();\n movieDetailsComponent.inject(this);\n }\n\n @OnClick(R.id.favorites_button)\n public void onFavoritesClick(View v) {\n if (v.isSelected()) {\n favoritesRepository.removeFromFavorites(movieEntity);\n v.setSelected(false);\n } else {\n favoritesRepository.addToFavorites(movieEntity);\n v.setSelected(true);\n }\n }\n\n @OnClick(R.id.back_button)\n public void onBackButtonClicked() {\n super.onBackPressed();\n }\n\n public void bindViews(MovieEntity entity) {\n movieTitle.setText(entity.getTitle());\n movieReleaseYear.setText(getYearOfRelease(entity.getReleaseDate()));\n movieRating.setText(String.valueOf(entity.getVoteAverage()));\n movieDescription.setText(entity.getOverview());\n Window window = getWindow();\n window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);\n window.setStatusBarColor(Color.BLACK);\n setGradientViews(Color.BLACK);\n moviePoster.setBackgroundColor(Color.BLACK);\n mainBackground.setBackgroundColor(Color.BLACK);\n SharedPreferencesUtil.saveInt(SharedPreferencesUtil.MOVIE_DETAILS_MAIN_COLOR, (Color.BLACK), this);\n setMoviePosterTransition();\n Glide.with(this)\n .load(Uri.parse(BASE_BACKDROP_URL + entity.getBackdropPath()))\n .placeholder(Color.GRAY)\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .centerCrop()\n .crossFade()\n .into(movieHeader);\n\n Glide.with(this)\n .load(Uri.parse(BASE_IMAGE_URL + entity.getPosterPath()))\n .placeholder(Color.GRAY)\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .centerCrop()\n .crossFade()\n .into(moviePoster);\n initTrailersView();\n initReviewsView();\n }\n\n private void initTrailersView() {\n movieTrailersAdapter.setOnItemClickListener((itemView, position) -> onMovieVideoClicked(position));\n trailersRecyclerView.setAdapter(movieTrailersAdapter);\n trailersRecyclerView.setItemAnimator(new DefaultItemAnimator());\n LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);\n trailersRecyclerView.setLayoutManager(layoutManager);\n }\n\n private void initReviewsView() {\n reviewsRecyclerView.setAdapter(reviewsAdapter);\n reviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());\n LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);\n reviewsRecyclerView.setLayoutManager(layoutManager);\n }\n\n private void setMoviePosterTransition() {\n Bundle extras = getIntent().getExtras();\n final String transition;\n if (extras != null) {\n transition = extras.getString(EXTRA_MOVIE_IMAGE_TRANSITION);\n moviePoster.setTransitionName(transition);\n }\n }\n\n private String getYearOfRelease(String releaseDate) {\n String[] parts = releaseDate.split(\"-\");\n return parts[0];\n }\n\n private void setGradientViews(int colorCode) {\n GradientDrawable bottomToTopGradient = new GradientDrawable(\n GradientDrawable.Orientation.BOTTOM_TOP,\n new int[]{colorCode, Color.TRANSPARENT});\n backdropGradient.setBackground(bottomToTopGradient);\n }\n\n private void onMovieVideoClicked(int position) {\n MovieTrailerEntity video = movieTrailersAdapter.getItem(position);\n if (video != null) {\n Intent intent = new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"http://www.youtube.com/watch?v=\" + video.getKey()));\n startActivity(intent);\n }\n }\n\n private final LoaderManager.LoaderCallbacks<Cursor> trailersCallback = new LoaderManager.LoaderCallbacks<Cursor>() {\n @Override\n public Loader<Cursor> onCreateLoader(int id, Bundle args) {\n return new CursorLoader(getApplicationContext(), ContentUris.withAppendedId(MoviesContract.TrailersEntry.CONTENT_URI, movieEntity.getId())\n , null, null, null, null);\n }\n\n @Override\n public void onLoadFinished(Loader<Cursor> loader, Cursor data) {\n if (data != null && data.getCount() == 0) {\n trailersRecyclerView.setVisibility(View.GONE);\n noTrailersView.setVisibility(View.VISIBLE);\n } else {\n noTrailersView.setVisibility(View.GONE);\n trailersRecyclerView.setVisibility(View.VISIBLE);\n movieTrailersAdapter.changeCursor(data);\n\n }\n }\n\n @Override\n public void onLoaderReset(Loader<Cursor> loader) {\n movieTrailersAdapter.changeCursor(null);\n }\n };\n\n\n private final LoaderManager.LoaderCallbacks<Cursor> reviewsCallback = new LoaderManager.LoaderCallbacks<Cursor>() {\n @Override\n public Loader<Cursor> onCreateLoader(int id, Bundle args) {\n return new CursorLoader(getApplicationContext(), ContentUris.withAppendedId(MoviesContract.ReviewsEntry.CONTENT_URI, movieEntity.getId())\n , null, null, null, null);\n }\n\n @Override\n public void onLoadFinished(Loader<Cursor> loader, Cursor data) {\n if (data != null && data.getCount() == 0) {\n reviewsRecyclerView.setVisibility(View.GONE);\n noReviewsView.setVisibility(View.VISIBLE);\n } else {\n noReviewsView.setVisibility(View.GONE);\n reviewsRecyclerView.setVisibility(View.VISIBLE);\n reviewsAdapter.changeCursor(data);\n\n }\n }\n\n @Override\n public void onLoaderReset(Loader<Cursor> loader) {\n reviewsAdapter.changeCursor(null);\n }\n };\n\n @Override\n public void updateReviewsViewForEmptyData() {\n // hotfix\n// noReviewsView.setVisibility(View.VISIBLE);\n }\n\n @Override\n public void updateTrailersViewForEmptyData() {\n // hotfix\n// noTrailersView.setVisibility(View.VISIBLE);\n }\n}", "public interface OnItemSelectedListener {\n void onItemSelected(MovieEntity movie);\n}" ]
import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.PersistableBundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import mdb.com.R; import mdb.com.data.api.entity.MovieEntity; import mdb.com.di.HasComponent; import mdb.com.di.component.DaggerMoviesGridComponent; import mdb.com.di.component.MoviesGridComponent; import mdb.com.di.module.MoviesGridModule; import mdb.com.util.rx.DisposableManager; import mdb.com.util.Sort; import mdb.com.view.base.BaseActivity; import mdb.com.view.moviedetails.MovieDetailsActivity; import mdb.com.view.moviesgrid.util.OnItemSelectedListener; import java.util.ArrayList; import java.util.List;
package mdb.com.view.moviesgrid; public class MoviesGridActivity extends BaseActivity implements HasComponent<MoviesGridComponent>, OnItemSelectedListener { public static Intent getCallingIntent(Context context) { return new Intent(context, MoviesGridActivity.class); } public static String MOVIE_ENTITY = "movie_entity"; @Bind(R.id.viewpager) ViewPager viewPager; @Bind(R.id.tabs) TabLayout tabLayout; private DaggerMoviesGridComponent moviesGridComponent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); setTabLayoutListener(); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); initTabIcons(); //default position viewPager.setCurrentItem(1); } @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); inject(); } @Override protected void onDestroy() { DisposableManager.dispose(); super.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); } private void inject() { moviesGridComponent = (DaggerMoviesGridComponent) DaggerMoviesGridComponent.builder() .applicationComponent(getApplicationComponent())
.moviesGridModule(new MoviesGridModule())
3
gjhutchison/pixelhorrorjam2016
core/src/com/kowaisugoi/game/rooms/RoomHallway.java
[ "public class AudioManager implements Disposable {\n private static final Map<SoundId, Sound> _soundMap = new HashMap<SoundId, Sound>();\n private static final Map<MusicId, Music> _musicMap = new HashMap<MusicId, Music>();\n\n private static MusicId _currentSong = MusicId.NONE;\n\n public static void initSounds() {\n _soundMap.put(SoundId.DOOR_CREAK, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/door.mp3\")));\n _soundMap.put(SoundId.DOOR_LOCKED, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/door_locked.mp3\")));\n _soundMap.put(SoundId.SNOW_CRUNCH, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/snowsteps_2.mp3\")));\n _soundMap.put(SoundId.FLOOR_STEP, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/footsteps_floor.mp3\")));\n _soundMap.put(SoundId.CLICK, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/caclick.mp3\")));\n _soundMap.put(SoundId.UNCLE_GASP, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/uncleNoise.mp3\")));\n _soundMap.put(SoundId.ENGINE_START, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/car_ignition.mp3\")));\n _soundMap.put(SoundId.SCARE, Gdx.audio.newSound(Gdx.files.internal(\"audio/effects/jump-scare.mp3\")));\n\n\n _musicMap.put(MusicId.MAIN_MENU, Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/bensound-betterdays.mp3\")));\n\n Music dark = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/244961__patricklieberkind__dark-ambience.mp3\"));\n dark.setLooping(true);\n _musicMap.put(MusicId.DARK, dark);\n\n Music drone = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/144921__thesoundcatcher__deepdrone.mp3\"));\n drone.setLooping(true);\n _musicMap.put(MusicId.DRONE, drone);\n\n Music bedroom = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/simpleloops/bedroom.mp3\"));\n bedroom.setLooping(true);\n _musicMap.put(MusicId.BEDROOM, bedroom);\n\n Music cozy = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/fireplace.mp3\"));\n cozy.setLooping(true);\n _musicMap.put(MusicId.COZY, cozy);\n\n Music crawlspace = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/simpleloops/crawlspace.mp3\"));\n crawlspace.setLooping(true);\n _musicMap.put(MusicId.CRAWLSPACE, crawlspace);\n\n Music howl = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/simpleloops/howl.mp3\"));\n howl.setLooping(true);\n _musicMap.put(MusicId.HOWL, howl);\n\n Music wind = Gdx.audio.newMusic(Gdx.files.internal(\"audio/music/simpleloops/wind.mp3\"));\n wind.setLooping(true);\n _musicMap.put(MusicId.WIND, wind);\n }\n\n public static void playSound(SoundId id) {\n if (id == null) {\n return;\n }\n\n if (_soundMap.containsKey(id)) {\n _soundMap.get(id).play();\n }\n }\n\n public static void playMusic(MusicId id, boolean restart) {\n if (id == null) {\n return;\n }\n if (_currentSong == id && !restart) {\n return;\n }\n\n stopSong(_currentSong);\n _musicMap.get(id).play();\n _currentSong = id;\n }\n\n public static void playMusic(MusicId id) {\n playMusic(id, true);\n }\n\n public static void stopSong(MusicId id) {\n if (_currentSong != MusicId.NONE) {\n _musicMap.get(id).stop();\n _currentSong = MusicId.NONE;\n }\n }\n\n public static void stopMusic() {\n for (MusicId id : _musicMap.keySet()) {\n if (_musicMap.get(id).isPlaying()) {\n _musicMap.get(id).stop();\n _currentSong = MusicId.NONE;\n return;\n }\n }\n }\n\n @Override\n public void dispose() {\n for (SoundId id : _soundMap.keySet()) {\n _soundMap.get(id).dispose();\n }\n }\n}", "public enum MusicId {\n NONE, MAIN_MENU, DARK, DRONE, BEDROOM, COZY, CRAWLSPACE, HOWL, WIND\n}", "public enum SoundId {\n DOOR_CREAK, DOOR_LOCKED, SNOW_CRUNCH, FLOOR_STEP, CLICK, UNCLE_GASP,\n ENGINE_START, SCARE\n}", "public class DirectionalPassage implements Passage {\n private LinkedList<InteractionListener> _listeners = new LinkedList<InteractionListener>();\n protected Rectangle _interactionBox;\n protected Rectangle _silentInteractionBox;\n private RoomId _source, _destination;\n protected Direction _direction;\n private boolean _release = true;\n\n private FlagId _travelFlag;\n\n private SoundId _soundId;\n\n private Sprite _transitionSprite;\n\n private float _travelSpeed = SlideTransition.DEFAULT_SPEED;\n\n private Map<ItemId, String> _itemInteractionMessages;\n\n public DirectionalPassage(RoomId src, RoomId dest, Rectangle interactionBox, Direction direction) {\n _source = src;\n _destination = dest;\n _interactionBox = interactionBox;\n _silentInteractionBox = interactionBox;\n _direction = direction;\n\n _itemInteractionMessages = new HashMap<ItemId, String>();\n }\n\n public DirectionalPassage(RoomId src, RoomId dest, Rectangle interactionBox, Rectangle silentInteractionBox, Direction direction) {\n _source = src;\n _destination = dest;\n _interactionBox = interactionBox;\n _silentInteractionBox = silentInteractionBox;\n _direction = direction;\n\n _itemInteractionMessages = new HashMap<ItemId, String>();\n }\n\n @Override\n public RoomId getDestination() {\n return _destination;\n }\n\n @Override\n public Rectangle getInteractionBox() {\n return _interactionBox;\n }\n\n @Override\n public void roomTransition() {\n PlayGame.getPlayer().enterRoom(_destination);\n }\n\n @Override\n public void transitionComplete() {\n if (PlayGame.getFlagManager().getFlag(FlagId.FLAG_KEYS_MISSING).getState()) {\n Timer.schedule(new Timer.Task() {\n @Override\n public void run() {\n if (_release) {\n PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NORMAL);\n }\n }\n }\n , 0.65f // Initial delay\n , 0 // Fire every X seconds\n , 1 // Number of times to fire\n );\n } else {\n Timer.schedule(new Timer.Task() {\n @Override\n public void run() {\n if (_release) {\n PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NORMAL);\n }\n }\n }\n , 0.4f // Initial delay\n , 0 // Fire every X seconds\n , 1 // Number of times to fire\n );\n }\n }\n\n @Override\n public void setTransitionImage(Sprite sprite) {\n _transitionSprite = sprite;\n }\n\n @Override\n public void setTravelFlag(FlagId flag) {\n _travelFlag = flag;\n }\n\n @Override\n public void setTravelSpeed(float speed) {\n _travelSpeed = speed;\n }\n\n @Override\n public void draw(SpriteBatch batch) {\n }\n\n public void setAutoRelease(boolean release) {\n _release = release;\n }\n\n @Override\n public void draw(ShapeRenderer renderer) {\n if (PlayGame.getDebug()) {\n if (PlayGame.getPlayer().getInteractionMode() == Player.InteractionMode.NORMAL) {\n renderer.setColor(0, 1, 0, 0.25f);\n } else if (PlayGame.getPlayer().getInteractionMode() == Player.InteractionMode.ITEM_INTERACTION) {\n renderer.setColor(0, 0, 1, 0.25f);\n } else {\n renderer.setColor(1, 0, 0, 0.25f);\n }\n renderer.rect(_interactionBox.x, _interactionBox.y, _interactionBox.width, _interactionBox.height);\n }\n }\n\n @Override\n public boolean click(float curX, float curY) {\n if (_interactionBox.contains(curX, curY) || _silentInteractionBox.contains(curX, curY)) {\n notifyListeners();\n\n PlayGame.getPlayer().setInteractionMode(Player.InteractionMode.NONE);\n PlayGame.playTransition(_transitionSprite == null ?\n new SlideTransition(this, _direction) :\n new SlideTransition(this, _direction, _transitionSprite, _travelSpeed));\n\n AudioManager.playSound(_soundId);\n\n if (_travelFlag != null && !PlayGame.getFlagManager().getFlag(_travelFlag).getState()) {\n PlayGame.getFlagManager().toggleFlag(_travelFlag);\n }\n\n return true;\n }\n return false;\n }\n\n @Override\n public void beautifyCursor(float curX, float curY) {\n if (_interactionBox.contains(curX, curY)) {\n switch (_direction) {\n case UP:\n PlayGame.getPlayer().setCursor(Player.CursorType.UP_ARROW);\n break;\n case DOWN:\n PlayGame.getPlayer().setCursor(Player.CursorType.DOWN_ARROW);\n break;\n case LEFT:\n PlayGame.getPlayer().setCursor(Player.CursorType.LEFT_ARROW);\n break;\n case RIGHT:\n PlayGame.getPlayer().setCursor(Player.CursorType.RIGHT_ARROW);\n break;\n }\n }\n }\n\n @Override\n public void update(float delta) {\n }\n\n @Override\n public void registerListener(InteractionListener lis) {\n _listeners.push(lis);\n }\n\n @Override\n public void setSoundEffect(SoundId soundId) {\n _soundId = soundId;\n }\n\n @Override\n public String getItemInteractionMessage(ItemId id) {\n if (_itemInteractionMessages.containsKey(id)) {\n return _itemInteractionMessages.get(id);\n }\n return \"\";\n }\n\n @Override\n public void setItemInteractionMessage(ItemId id, String message) {\n _itemInteractionMessages.put(id, message);\n }\n\n @Override\n public boolean isItemInteractable() {\n return false;\n }\n\n @Override\n public boolean itemInteract(ItemId id) {\n return false;\n }\n\n private void notifyListeners() {\n for (InteractionListener listener : _listeners) {\n listener.notifyListener();\n }\n }\n\n @Override\n public boolean checkInteraction(float curX, float curY) {\n return _interactionBox.contains(curX, curY);\n }\n}", "public interface Passage extends Interactable {\n public RoomId getDestination();\n\n public void roomTransition();\n\n public void transitionComplete();\n\n public void setTransitionImage(Sprite sprite);\n\n public void setTravelFlag(FlagId flag);\n\n public void setTravelSpeed(float speed);\n}", "public class PlayGame implements Screen {\n // 640x360\n public static final float GAME_WIDTH = 160;\n public static final float GAME_HEIGHT = 90;\n\n private OrthographicCamera _camera;\n private Viewport _viewport;\n private SpriteBatch _batch;\n private ShapeRenderer _shapeRenderer;\n private static boolean _debug = false;\n private static boolean _placing = false;\n private static Transition _transition;\n\n // Global state\n private static Player _player;\n private static RoomManager _roomManager;\n private static FlagManager _flagManager;\n private static boolean _paused;\n\n public static Player getPlayer() {\n return _player;\n }\n\n public static RoomManager getRoomManager() {\n return _roomManager;\n }\n\n public static FlagManager getFlagManager() {\n return _flagManager;\n }\n\n @Override\n public void show() {\n _roomManager = new RoomManager();\n _flagManager = new FlagManager();\n\n SlideTransition.setTransitionSpeed(SlideTransition.DEFAULT_SPEED);\n\n PlayerInventory inventory = new PlayerInventory();\n\n _batch = new SpriteBatch();\n _shapeRenderer = new ShapeRenderer();\n _camera = new OrthographicCamera();\n _camera.translate(GAME_WIDTH / 2, GAME_HEIGHT / 2);\n _viewport = new StretchViewport(GAME_WIDTH, GAME_HEIGHT, _camera);\n\n _player = new Player(this, inventory);\n _player.startGame(RoomId.CAR);\n\n Gdx.input.setInputProcessor(_player);\n }\n\n public static void setPaused(boolean paused) {\n _paused = paused;\n }\n\n public static boolean getPaused() {\n return _paused;\n }\n\n public void renderPauseDialog() {\n // Fade to black\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n _shapeRenderer.setColor(0.05f, 0.05f, 0.05f, 0.5f);\n _shapeRenderer.rect(0, 0, GAME_WIDTH, GAME_HEIGHT);\n _shapeRenderer.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n\n _batch.begin();\n // TODO: Factor this out (at the very least)\n FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(\"font/raleway/Raleway-Medium.ttf\"));\n FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();\n parameter.size = 32;\n BitmapFont bfont = generator.generateFont(parameter);\n GlyphLayout layout = new GlyphLayout();\n bfont.getData().setScale(0.12f, 0.12f);\n\n float x_pos = GAME_WIDTH / 2;\n float y_pos = 20 / 2;\n\n bfont.setColor(1.0f, 1.0f, 1.0f, 0.5f);\n\n layout.setText(bfont, Messages.getText(\"system.exit\"));\n\n x_pos -= layout.width / 2;\n y_pos += layout.height / 2;\n\n bfont.draw(_batch, layout, x_pos, y_pos);\n _batch.end();\n }\n\n @Override\n public void render(float delta) {\n _camera.update();\n _batch.setProjectionMatrix(_camera.combined);\n _shapeRenderer.setProjectionMatrix(_camera.combined);\n\n if (_paused) {\n renderPauseDialog();\n return;\n }\n\n updateGame(delta);\n renderGame();\n }\n\n private void updateGame(float delta) {\n Vector3 position = screenToWorldPosition(Gdx.input.getX(), Gdx.input.getY());\n getPlayer().updateCursor(position);\n getPlayer().update(delta);\n\n if (_transition != null) {\n _transition.update(delta);\n }\n }\n\n private void renderCurrentRoom() {\n Gdx.gl.glClearColor(1, 0, 0, 1);\n Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n\n // Draw room sprites\n _batch.begin();\n getPlayer().getCurrentRoom().draw(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n\n // Draw room shapes\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n getPlayer().getCurrentRoom().draw(_shapeRenderer);\n _shapeRenderer.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderFX() {\n // Draw room FX\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_DST_COLOR, GL20.GL_ONE);\n _batch.begin();\n getPlayer().getCurrentRoom().drawFx(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderInventory() {\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n\n // Draw inventory bag\n _batch.begin();\n getPlayer().getInventory().drawInventory(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderSelectedItem() {\n _batch.begin();\n getPlayer().getInventory().drawSelectedItemSprite(_batch);\n _batch.end();\n }\n\n private void renderTransitions() {\n // Draw transitions, if applicable\n if (_transition == null) {\n return;\n }\n\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n _transition.draw(_shapeRenderer);\n _shapeRenderer.end();\n _batch.begin();\n _transition.draw(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderHUD() {\n // Draw player thoughts over everything\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n getPlayer().getThought().draw(_shapeRenderer);\n _shapeRenderer.end();\n _batch.begin();\n getPlayer().getThought().draw(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderPlacementHelper() {\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n _player.getPlacementRectangle().draw(_shapeRenderer);\n _shapeRenderer.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n /**\n * Breaks down rendering of game world into different layers\n */\n private void renderGame() {\n renderCurrentRoom();\n renderFX();\n renderInventory();\n renderPlacementHelper();\n\n // Draw inventory, if applicable\n if (getPlayer().getInteractionMode() == ITEM_INTERACTION) {\n renderSelectedItem();\n }\n\n renderTransitions();\n renderHUD();\n }\n\n @Override\n public void resize(int width, int height) {\n _viewport.update(width, height);\n }\n\n @Override\n public void pause() {\n // TODO Auto-generated method stub\n\n }\n\n @Override\n public void resume() {\n // TODO Auto-generated method stub\n\n }\n\n @Override\n public void hide() {\n // TODO Auto-generated method stub\n }\n\n @Override\n public void dispose() {\n }\n\n public Vector3 screenToWorldPosition(int screenX, int screenY) {\n Vector3 vecCursorPos = new Vector3(screenX, screenY, 0);\n _camera.unproject(vecCursorPos);\n return vecCursorPos;\n }\n\n /**\n * Play transition animation on transition layer\n *\n * @param t The transition animation to play\n */\n public static void playTransition(Transition t) {\n _transition = t;\n _transition.play();\n }\n\n public static void setDebug(boolean debug) {\n _debug = debug;\n }\n\n public static boolean getDebug() {\n return _debug;\n }\n\n public static void setPlacementMode(boolean mode) {\n _player.think(\"Placement mode: \" + (mode ? \"ON\" : \"OFF\"));\n _placing = mode;\n }\n\n public static boolean getPlacementMode() {\n return _placing;\n }\n}", "public class GameUtil {\n public enum Direction {\n UP, DOWN, LEFT, RIGHT\n }\n\n public static boolean isNotNullOrEmpty(String s) {\n return !(s == null || \"\".equals(s));\n }\n}", "public enum FlagId {\n FLAG_BODY_FOUND,\n FLAG_CAR_FOUND,\n FLAG_CAR_SNOWREMOVED,\n FLAG_SHED_OPENED,\n FLAG_NIGHT_TIME,\n FLAG_BOARDS_REMOVED,\n FLAG_TORCH_PLACED,\n FLAG_ENTERED_BATHROOM,\n FLAG_KEYS_MISSING,\n FLAG_KEYS_APPEARED,\n FLAG_KEYS_FOUND,\n FLAG_HALLWAY_SCARE,\n FLAG_HALLWAY_SCARE_OVER\n}" ]
import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.kowaisugoi.game.audio.AudioManager; import com.kowaisugoi.game.audio.MusicId; import com.kowaisugoi.game.audio.SoundId; import com.kowaisugoi.game.interactables.passages.DirectionalPassage; import com.kowaisugoi.game.interactables.passages.Passage; import com.kowaisugoi.game.screens.PlayGame; import com.kowaisugoi.game.system.GameUtil; import static com.kowaisugoi.game.control.flags.FlagId.*;
package com.kowaisugoi.game.rooms; public class RoomHallway extends StandardRoom { private static final String ROOM_URL = "rooms/hallway/hallway.png"; private static final String ROOM_URL2 = "rooms/hallway/hallway_night.png"; private static final String OH_HI = "rooms/hallway/hallway_hai.png"; private final Sprite _roomSprite1 = new Sprite(new Texture(ROOM_URL)); private final Sprite _roomSprite2 = new Sprite(new Texture(ROOM_URL2)); private final Sprite _hiSprite = new Sprite(new Texture(OH_HI)); public RoomHallway() { super(new Sprite(new Texture(ROOM_URL))); _hiSprite.setSize(PlayGame.GAME_WIDTH, PlayGame.GAME_HEIGHT); Passage passageMainRoom = new DirectionalPassage(RoomId.HALLWAY, RoomId.MAIN_HALL, new Rectangle(51, 0, 54, 10),
GameUtil.Direction.DOWN) {
6
mgilangjanuar/GoSCELE
app/src/main/java/com/mgilangjanuar/dev/goscele/modules/main/presenter/HomePresenter.java
[ "public class BasePresenter {\n}", "public class HomeRecyclerViewAdapter extends BaseRecyclerViewAdapter<HomeRecyclerViewAdapter.ViewHolder> {\n\n private List<HomeModel> list;\n\n public HomeRecyclerViewAdapter(List<HomeModel> list) {\n this.list = list;\n }\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n return new ViewHolder(createView(parent));\n }\n\n @Override\n public int findLayout() {\n return R.layout.layout_home_post;\n }\n\n @Override\n public List<?> findList() {\n return list;\n }\n\n @Override\n public void initialize(ViewHolder holder, int position) {\n final HomeModel model = list.get(position);\n holder.model = model;\n\n holder.title.setText(model.title);\n holder.author.setText(model.author);\n holder.info.setText(model.date);\n\n holder.content.setHtml(model.content, new HtmlHttpImageGetter(holder.content));\n holder.layout.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(v.getContext(), ForumDetailActivity.class).putExtra(Constant.URL, model.url);\n v.getContext().startActivity(intent);\n }\n });\n holder.menuMore.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n buildMenuView(v.getContext(), model);\n }\n });\n }\n\n private void buildMenuView(Context context, final HomeModel model) {\n Builder alertDialog = new Builder(context);\n alertDialog.setTitle(model.title);\n\n LinearLayout container = new LinearLayout(context);\n container.setPadding(0, 40, 0, 0);\n container.setOrientation(LinearLayout.VERTICAL);\n LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);\n\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);\n\n View divider = new View(context);\n divider.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));\n divider.setBackgroundColor(container.getResources().getColor(android.R.color.darker_gray));\n\n Button btnShare = new Button(context);\n btnShare.setText(context.getString(R.string.share));\n btnShare.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);\n btnShare.setPadding(50, 0, 50, 0);\n btnShare.setAllCaps(false);\n btnShare.setBackgroundResource(typedValue.resourceId);\n btnShare.setLayoutParams(params);\n\n View divider1 = new View(context);\n divider1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));\n divider1.setBackgroundColor(container.getResources().getColor(android.R.color.darker_gray));\n\n Button btnCopy = new Button(context);\n btnCopy.setText(context.getString(R.string.copy_url));\n btnCopy.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);\n btnCopy.setPadding(50, 0, 50, 0);\n btnCopy.setAllCaps(false);\n btnCopy.setBackgroundResource(typedValue.resourceId);\n btnCopy.setLayoutParams(params);\n\n container.addView(divider);\n container.addView(btnCopy);\n container.addView(divider1);\n container.addView(btnShare);\n\n alertDialog.setView(container);\n final android.app.AlertDialog alert = alertDialog.create();\n\n btnShare.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ShareContentUtil.share(v.getContext(), model.title + \"\\n(\" + model.author + \" - \" + model.date + \")\\n\\n\" + model.url);\n alert.dismiss();\n }\n });\n btnCopy.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ClipboardManager clipboardManager = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);\n clipboardManager.setPrimaryClip(ClipData.newPlainText(Constant.LABEL, model.url));\n Toast.makeText(v.getContext(), v.getContext().getString(R.string.url_copied), Toast.LENGTH_SHORT).show();\n alert.dismiss();\n }\n });\n\n alert.show();\n }\n\n public class ViewHolder extends BaseViewHolder {\n\n @BindView(R.id.title_home)\n TextView title;\n\n @BindView(R.id.author_home)\n TextView author;\n\n @BindView(R.id.info_home)\n TextView info;\n\n @BindView(R.id.content_home)\n HtmlTextView content;\n\n @BindView(R.id.main_layout_home)\n LinearLayout layout;\n\n @BindView(R.id.menu_more_home)\n ImageButton menuMore;\n\n private HomeModel model;\n\n public ViewHolder(View itemView) {\n super(itemView);\n }\n }\n\n}", "public interface HomeListener {\n void onRetrieve(HomeRecyclerViewAdapter adapter);\n\n void onError();\n}", "@Table(name = \"post_home\")\npublic class HomeModel extends BaseModel {\n\n @Column(name = \"url\")\n public String url;\n\n @Column(name = \"title\")\n public String title;\n\n @Column(name = \"author\")\n public String author;\n\n @Column(name = \"date\")\n public String date;\n\n @Column(name = \"content\")\n public String content;\n\n public HomeModel() {\n super();\n }\n}", "public class HomeProvider extends BaseProvider {\n\n private HomeListener listener;\n\n public HomeProvider(HomeListener listener) {\n this.listener = listener;\n }\n\n @Override\n public void run() {\n execute(\".forumpost\");\n }\n\n @Override\n public String url() {\n return Constant.BASE_URL;\n }\n\n @Override\n public Map<String, String> cookies() {\n return CookieModel.getCookiesMap();\n }\n\n @Override\n protected void onPostExecute(List<Elements> elementses) {\n super.onPostExecute(elementses);\n try {\n Elements elements = elementses.get(0);\n\n for (Model e: new HomeModel().find().execute()) e.delete();\n\n List<HomeModel> list = new ArrayList<>();\n for (Element e : elements) {\n String url = e.select(\".link > a\").attr(\"href\");\n String title = e.select(\".subject\").text();\n String author = e.select(\".author a\").text();\n String date = e.select(\".author\").text().replace(\"by \" + author + \" - \", \"\");\n String content = e.select(\".posting\").html();\n\n HomeModel model = new HomeModel();\n model.url = url;\n model.title = title;\n model.author = author;\n model.date = date;\n model.content = content;\n model.save();\n\n list.add(model);\n }\n listener.onRetrieve(new HomeRecyclerViewAdapter(list));\n } catch (Exception e) {\n listener.onError();\n }\n }\n}" ]
import com.mgilangjanuar.dev.goscele.base.BasePresenter; import com.mgilangjanuar.dev.goscele.modules.main.adapter.HomeRecyclerViewAdapter; import com.mgilangjanuar.dev.goscele.modules.main.listener.HomeListener; import com.mgilangjanuar.dev.goscele.modules.main.model.HomeModel; import com.mgilangjanuar.dev.goscele.modules.main.provider.HomeProvider; import java.util.List;
package com.mgilangjanuar.dev.goscele.modules.main.presenter; /** * Created by mgilangjanuar ([email protected]) * * @since 2017 */ public class HomePresenter extends BasePresenter { private HomeListener listener; public HomePresenter(HomeListener listener) { this.listener = listener; } public void runProvider(boolean force) { List<HomeModel> models = new HomeModel().find().execute(); if (!force && models.size() > 0) { listener.onRetrieve(new HomeRecyclerViewAdapter(models)); } else {
new HomeProvider(listener).run();
4
SamuelGjk/GComic
app/src/main/java/moe/yukinoneko/gcomic/module/download/tasks/DownloadTasksPresenter.java
[ "public abstract class BasePresenter<T extends IBaseView> {\n protected CompositeSubscription mCompositeSubscription;\n protected Context mContext;\n protected T iView;\n\n public BasePresenter(Context context, T iView) {\n this.mContext = context;\n this.iView = iView;\n }\n\n public void init() {\n iView.init();\n }\n\n public void release() {\n if (this.mCompositeSubscription != null) {\n this.mCompositeSubscription.unsubscribe();\n }\n }\n\n public void addSubscription(Subscription s) {\n if (this.mCompositeSubscription == null) {\n this.mCompositeSubscription = new CompositeSubscription();\n }\n this.mCompositeSubscription.add(s);\n }\n}", "public class ComicData {\n public int id;\n public String islong;\n public int direction;\n public String title;\n @Json(name = \"is_dmzj\") public int isDmzj;\n public String cover;\n public String description;\n @Json(name = \"last_updatetime\") public int lastUpdatetime;\n public int copyright;\n @Json(name = \"first_letter\") public String firstLetter;\n @Json(name = \"hot_num\") public int hotNum;\n public Object uid;\n @Json(name = \"subscribe_num\") public int subscribeNum;\n public CommentBean comment;\n public List<TypesBean> types;\n public List<AuthorsBean> authors;\n public List<StatusBean> status;\n public List<ChaptersBean> chapters;\n\n public List<Integer> downloadedChapters = new ArrayList<>();\n\n public ReadHistoryModel readHistory;\n\n public static class CommentBean {\n @Json(name = \"comment_count\") public int commentCount;\n @Json(name = \"latest_comment\") public List<LatestCommentBean> latestComment;\n\n public static class LatestCommentBean {\n @Json(name = \"comment_id\") public int commentId;\n public int uid;\n public String content;\n public int createtime;\n public String nickname;\n @Json(name = \"avatar_url\") public String avatarUrl;\n }\n }\n\n public static class TypesBean {\n @Json(name = \"tag_id\") public int tagId;\n @Json(name = \"tag_name\") public String tagName;\n }\n\n public static class AuthorsBean {\n @Json(name = \"tag_id\") public int tagId;\n @Json(name = \"tag_name\") public String tagName;\n }\n\n public static class StatusBean {\n @Json(name = \"tag_id\") public int tagId;\n @Json(name = \"tag_name\") public String tagName;\n }\n\n public static class ChaptersBean {\n public String title;\n public List<ChapterBean> data;\n\n public static class ChapterBean implements Parcelable {\n @Json(name = \"chapter_id\") public int chapterId;\n @Json(name = \"chapter_title\") public String chapterTitle;\n public int updatetime;\n public long filesize;\n @Json(name = \"chapter_order\") public int chapterOrder;\n\n public boolean isDownloaded;\n\n public ChapterBean() {\n\n }\n\n protected ChapterBean(Parcel in) {\n chapterId = in.readInt();\n chapterTitle = in.readString();\n updatetime = in.readInt();\n filesize = in.readLong();\n chapterOrder = in.readInt();\n }\n\n public static final Creator<ChapterBean> CREATOR = new Creator<ChapterBean>() {\n @Override\n public ChapterBean createFromParcel(Parcel in) {\n return new ChapterBean(in);\n }\n\n @Override\n public ChapterBean[] newArray(int size) {\n return new ChapterBean[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(chapterId);\n dest.writeString(chapterTitle);\n dest.writeInt(updatetime);\n dest.writeLong(filesize);\n dest.writeInt(chapterOrder);\n }\n }\n }\n}", "public class GComicDB {\n\n private static final String DB_NAME = \"gcomic.db\";\n\n private static GComicDB mInstance;\n\n private final LiteOrm liteOrm;\n\n public static GComicDB getInstance(Context context) {\n if (mInstance == null) {\n synchronized (GComicDB.class) {\n if (mInstance == null) {\n mInstance = new GComicDB(context.getApplicationContext());\n }\n }\n }\n return mInstance;\n }\n\n private GComicDB(Context context) {\n liteOrm = LiteOrm.newSingleInstance(context, DB_NAME);\n liteOrm.setDebugged(true);\n }\n\n /**\n * 插入一条记录\n *\n * @param t 实体类对象\n */\n public <T> Observable<Long> insert(final T t) {\n return Observable.defer(new Func0<Observable<Long>>() {\n @Override\n public Observable<Long> call() {\n return Observable.just(liteOrm.insert(t, ConflictAlgorithm.Abort));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 插入所有记录\n *\n * @param list 实体类对象list\n */\n public <T> Observable<Integer> insertAll(final List<T> list) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.insert(list, ConflictAlgorithm.Abort));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 查询所有\n *\n * @param cls 要查询的对象类型\n * @return 查询结果集合\n */\n public <T> Observable<ArrayList<T>> queryAll(final Class<T> cls) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(cls));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 查询所有并按照指定列的值降序排列\n */\n public <T> Observable<ArrayList<T>> queryAllDesc(final Class<T> cls, final String column) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(new QueryBuilder<>(cls).appendOrderDescBy(column)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 查询 指定字段 的值并去除重复\n *\n * @param cls 要查询的对象类型\n * @param columns 字段名称\n * @return 查询结果集合\n */\n public <T> Observable<ArrayList<T>> querySpecificColumnsAndDistinct(final Class<T> cls, final String[] columns) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(new QueryBuilder<>(cls).columns(columns).distinct(true)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 查询 某字段 等于 value 的值\n *\n * @param cls 要查询的对象类型\n * @param where 字段名称\n * @param value 字段的值\n * @return 查询结果集合\n */\n public <T> Observable<ArrayList<T>> queryByWhere(final Class<T> cls, final String where, final String[] value) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(new QueryBuilder<>(cls).where(where + \"=?\", value)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 查询 某字段 等于 value 的值并按照指定列的值升序排列\n */\n public <T> Observable<ArrayList<T>> queryByWhereAsc(final Class<T> cls, final String where, final String[] value, final String column) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(new QueryBuilder<>(cls).where(where + \"=?\", value).appendOrderAscBy(column)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n public <T> Observable<ArrayList<T>> queryByLike(final Class<T> cls, final String where, final String[] value) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(new QueryBuilder<>(cls).where(where + \" LIKE ?\", value)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 查询 某字段 等于 value 的值 可以指定从1-20,就是分页\n */\n public <T> Observable<ArrayList<T>> queryByWhereLength(final Class<T> cls, final String where, final String[] value, final int start, final int length) {\n return Observable.defer(new Func0<Observable<ArrayList<T>>>() {\n @Override\n public Observable<ArrayList<T>> call() {\n return Observable.just(liteOrm.query(new QueryBuilder<T>(cls).where(where + \"=?\", value).limit(start, length)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 删除一条记录\n */\n public <T> Observable<Integer> delete(final T t) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.delete(t));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 删除所有 某字段 等于 vlaue 的值\n */\n public <T> Observable<Integer> deleteWhere(final Class<T> cls, final String where, final String[] value) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.delete(new WhereBuilder(cls).where(where + \"=?\", value)));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n public <T> Observable<Integer> deleteAll(final List<T> list) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.delete(list));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 删除所有\n */\n public <T> Observable<Integer> deleteAll(final Class<T> cls) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.deleteAll(cls));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 更新一条记录\n */\n public <T> Observable<Integer> update(final T t) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.update(t));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 更新多条记录\n */\n public <T> Observable<Integer> updateAll(final List<T> list) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.update(list));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 保存(插入 or 更新)一条记录\n */\n public <T> Observable<Long> save(final T t) {\n return Observable.defer(new Func0<Observable<Long>>() {\n @Override\n public Observable<Long> call() {\n return Observable.just(liteOrm.save(t));\n }\n }).subscribeOn(Schedulers.io());\n }\n\n /**\n * 保存(插入 or 更新)多条记录\n */\n public <T> Observable<Integer> saveAll(final List<T> list) {\n return Observable.defer(new Func0<Observable<Integer>>() {\n @Override\n public Observable<Integer> call() {\n return Observable.just(liteOrm.save(list));\n }\n }).subscribeOn(Schedulers.io());\n }\n}", "@Table(\"gcomic_download\")\npublic class DownloadTaskModel {\n\n @PrimaryKey(AssignType.BY_MYSELF)\n public int id;\n\n public int comicId;\n public String comicTitle;\n public String comicCover;\n\n public int chapterId;\n public String chapterTitle;\n\n public String firstLetter;\n\n public int position;\n public int chaptersSize;\n\n public String url;\n public String path;\n\n public DownloadTaskModel(int id, int comicId, String comicTitle, String comicCover, int chapterId, String chapterTitle, String firstLetter, int position, int chaptersSize, String url, String path) {\n this.id = id;\n this.comicId = comicId;\n this.comicTitle = comicTitle;\n this.comicCover = comicCover;\n this.chapterId = chapterId;\n this.chapterTitle = chapterTitle;\n this.firstLetter = firstLetter;\n this.position = position;\n this.chaptersSize = chaptersSize;\n this.url = url;\n this.path = path;\n }\n}", "@Table(\"gcomic_read_history\")\npublic class ReadHistoryModel {\n\n @PrimaryKey(AssignType.BY_MYSELF)\n public int comicId;\n\n public int chapterId;\n\n public int browsePosition;\n\n public ReadHistoryModel(int comicId, int chapterId, int browsePosition) {\n this.comicId = comicId;\n this.chapterId = chapterId;\n this.browsePosition = browsePosition;\n }\n}", "public class DownloadTasksManager {\n\n // @formatter:off\n private static DownloadTasksManager mInstance;\n\n private Context context;\n\n public static DownloadTasksManager getInstance(Context context) {\n if (mInstance == null) {\n synchronized (DownloadTasksManager.class) {\n if (mInstance == null) {\n mInstance = new DownloadTasksManager(context.getApplicationContext());\n }\n }\n }\n return mInstance;\n }\n\n private DownloadTasksManager(Context context) {\n this.context = context;\n }\n\n private SparseArray<BaseDownloadTask> taskSparseArray = new SparseArray<>();\n\n public void addTaskForViewHolder(final BaseDownloadTask task) {\n taskSparseArray.put(task.getId(), task);\n }\n\n public void removeTaskForViewHolder(final int id) {\n taskSparseArray.remove(id);\n }\n\n public void updateViewHolder(final int id, final Object holder) {\n final BaseDownloadTask task = taskSparseArray.get(id);\n if (task == null) {\n return;\n }\n\n task.setTag(holder);\n }\n\n public void releaseTask() {\n taskSparseArray.clear();\n }\n\n public void onDestroy() {\n releaseTask();\n FileDownloader.getImpl().pauseAll();\n FileDownloader.getImpl().unBindService();\n }\n\n public boolean isReady() {\n return FileDownloader.getImpl().isServiceConnected();\n }\n\n public Observable<ArrayList<DownloadTaskModel>> getDownloadedComic() {\n return GComicDB.getInstance(context).querySpecificColumnsAndDistinct(DownloadTaskModel.class, new String[]{ \"comicId\", \"comicTitle\", \"comicCover\" });\n }\n\n public Observable<ArrayList<DownloadTaskModel>> getTasksByComicId(String[] values) {\n return GComicDB.getInstance(context).queryByWhereAsc(DownloadTaskModel.class, \"comicId\", values, \"chapterId\");\n }\n\n public void bindService() {\n FileDownloader.getImpl().bindService();\n }\n\n public void unbindService() {\n FileDownloader.getImpl().unBindService();\n }\n\n public void addServiceConnectListener(FileDownloadConnectListener listener) {\n FileDownloader.getImpl().addServiceConnectListener(listener);\n }\n\n public void removeServiceConnectListener(FileDownloadConnectListener listener) {\n FileDownloader.getImpl().removeServiceConnectListener(listener);\n }\n\n /**\n * @param status Download Status\n * @return has already downloaded\n * @see FileDownloadStatus\n */\n public boolean isDownloaded(final int status) {\n return status == FileDownloadStatus.completed;\n }\n\n public boolean isDownloadedById(final int id) {\n return getStatus(id) == FileDownloadStatus.completed;\n }\n\n public boolean isExist(String path) {\n return new File(path).exists();\n }\n\n public int getStatus(final int id) {\n return FileDownloader.getImpl().getStatus(id);\n }\n\n public long getTotal(final int id) {\n return FileDownloader.getImpl().getTotal(id);\n }\n\n public long getSoFar(final int id) {\n return FileDownloader.getImpl().getSoFar(id);\n }\n\n public Observable<Long> addTask(final DownloadTaskModel model) {\n\n model.path = generatePath(model.url);\n model.id = FileDownloadUtils.generateId(model.url, model.path);\n\n return GComicDB.getInstance(context).insert(model);\n }\n\n public Observable<Integer> addTasks(final List<DownloadTaskModel> models) {\n\n for (DownloadTaskModel model : models) {\n model.path = generatePath(model.url);\n model.id = FileDownloadUtils.generateId(model.url, model.path);\n }\n\n return GComicDB.getInstance(context).insertAll(models);\n }\n\n public void startTask(final DownloadTaskModel model) {\n if (!isReady()) {\n return;\n }\n\n int status = getStatus(model.id);\n if (!(status == FileDownloadStatus.paused || status == FileDownloadStatus.error || status == FileDownloadStatus.INVALID_STATUS || (isDownloaded(status) && !isExist(model.path)))) {\n return;\n }\n\n BaseDownloadTask task = FileDownloader.getImpl()\n .create(model.url)\n .setPath(model.path)\n .addHeader(\"Referer\", GComicApi.REFERER)\n .setCallbackProgressTimes(100)\n .setListener(taskDownloadListener);\n addTaskForViewHolder(task);\n task.start();\n }\n\n // 用于从漫画详情页下载\n public void startTasks(final List<DownloadTaskModel> models) {\n if (!isReady()) {\n return;\n }\n\n // 别问我为什么这样写,大概是疯了\n final FileDownloadQueueSet queueSet = new FileDownloadQueueSet(new FileDownloadSampleListener() {\n\n private ITaskViewHolder checkCurrentHolder(final BaseDownloadTask task) {\n final ITaskViewHolder tag = (ITaskViewHolder) task.getTag();\n if (tag == null || tag.getId() != task.getId()) {\n return null;\n }\n\n return tag;\n }\n\n @Override\n protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {\n super.pending(task, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.pending, soFarBytes, totalBytes);\n }\n\n @Override\n protected void started(BaseDownloadTask task) {\n super.started(task);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.started, 0, 1);\n }\n\n @Override\n protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {\n super.connected(task, etag, isContinue, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.connected, soFarBytes, totalBytes);\n }\n\n @Override\n protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {\n super.progress(task, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.progress, soFarBytes, totalBytes);\n }\n\n @Override\n protected void error(BaseDownloadTask task, Throwable e) {\n super.error(task, e);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateNotDownloaded(FileDownloadStatus.error, task.getLargeFileSoFarBytes(), task.getLargeFileTotalBytes());\n removeTaskForViewHolder(task.getId());\n }\n\n @Override\n protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {\n super.paused(task, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateNotDownloaded(FileDownloadStatus.paused, soFarBytes, totalBytes);\n removeTaskForViewHolder(task.getId());\n }\n\n @Override\n protected void completed(BaseDownloadTask task) {\n super.completed(task);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloaded();\n removeTaskForViewHolder(task.getId());\n }\n });\n\n final List<BaseDownloadTask> tasks = new ArrayList<>();\n for (DownloadTaskModel model : models) {\n int status = getStatus(model.id);\n if (!(status == FileDownloadStatus.paused || status == FileDownloadStatus.error || status == FileDownloadStatus.INVALID_STATUS)) {\n continue;\n }\n tasks.add(FileDownloader.getImpl().create(model.url).setPath(model.path).addHeader(\"Referer\", GComicApi.REFERER));\n }\n\n queueSet.setCallbackProgressTimes(100);\n\n for (BaseDownloadTask task : tasks) {\n addTaskForViewHolder(task);\n }\n\n queueSet.downloadTogether(tasks).start();\n }\n\n public void pauseTask(int downloadId) {\n FileDownloader.getImpl().pause(downloadId);\n }\n\n // 用于下载管理页面\n public void startAllTasks(final List<DownloadTaskModel> taskModels) {\n for (DownloadTaskModel taskModel : taskModels) {\n startTask(taskModel);\n }\n }\n\n public void pauseAllTasks(final List<DownloadTaskModel> taskModels) {\n for (DownloadTaskModel taskModel : taskModels) {\n pauseTask(taskModel.id);\n }\n }\n\n public String generatePath(final String url) {\n if (TextUtils.isEmpty(url)) {\n return null;\n }\n\n return FileDownloadUtils.getDefaultSaveFilePath(url);\n }\n\n private FileDownloadListener taskDownloadListener = new FileDownloadSampleListener() {\n\n private ITaskViewHolder checkCurrentHolder(final BaseDownloadTask task) {\n final ITaskViewHolder tag = (ITaskViewHolder) task.getTag();\n if (tag == null || tag.getId() != task.getId()) {\n return null;\n }\n\n return tag;\n }\n\n @Override\n protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {\n super.pending(task, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.pending, soFarBytes, totalBytes);\n }\n\n @Override\n protected void started(BaseDownloadTask task) {\n super.started(task);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.started, 0, 1);\n }\n\n @Override\n protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {\n super.connected(task, etag, isContinue, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.connected, soFarBytes, totalBytes);\n }\n\n @Override\n protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {\n super.progress(task, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloading(FileDownloadStatus.progress, soFarBytes, totalBytes);\n }\n\n @Override\n protected void error(BaseDownloadTask task, Throwable e) {\n super.error(task, e);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateNotDownloaded(FileDownloadStatus.error, task.getLargeFileSoFarBytes(), task.getLargeFileTotalBytes());\n removeTaskForViewHolder(task.getId());\n }\n\n @Override\n protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {\n super.paused(task, soFarBytes, totalBytes);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateNotDownloaded(FileDownloadStatus.paused, soFarBytes, totalBytes);\n removeTaskForViewHolder(task.getId());\n }\n\n @Override\n protected void completed(BaseDownloadTask task) {\n super.completed(task);\n final ITaskViewHolder tag = checkCurrentHolder(task);\n if (tag == null) {\n return;\n }\n\n tag.updateDownloaded();\n removeTaskForViewHolder(task.getId());\n }\n };\n\n public interface ITaskViewHolder {\n\n int getId();\n\n void updateDownloaded();\n\n void updateNotDownloaded(final int status, final long sofar, final long total);\n\n void updateDownloading(final int status, final long sofar, final long total);\n }\n}", "public class FileUtlis {\n public static Observable<List<byte[]>> readFileContent(final String path) {\n return Observable.defer(new Func0<Observable<List<byte[]>>>() {\n @Override\n public Observable<List<byte[]>> call() {\n List<byte[]> result = new ArrayList<>();\n try {\n ZipFile zf = new ZipFile(path);\n Enumeration<? extends ZipEntry> entries = zf.entries();\n List<String> names = new ArrayList<>();\n while (entries.hasMoreElements()) {\n names.add(entries.nextElement()\n .getName());\n }\n Collections.sort(names, new Comparator<String>() {\n @Override\n public int compare(String lhs, String rhs) {\n if (lhs.length() == rhs.length()) {\n return lhs.compareTo(rhs);\n } else if (lhs.length() < rhs.length()) {\n return -1;\n } else {\n return 1;\n }\n }\n });\n ZipEntry ze;\n for (String name : names) {\n ze = zf.getEntry(name);\n long size = ze.getSize();\n if (size > 0) {\n InputStream zeis = zf.getInputStream(ze);\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int len;\n while ((len = zeis.read(buffer, 0, buffer.length)) != -1) {\n bos.write(buffer, 0, len);\n }\n result.add(bos.toByteArray());\n bos.close();\n zeis.close();\n }\n }\n zf.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return Observable.just(result);\n }\n })\n .subscribeOn(Schedulers.io());\n }\n\n public static void deleteFiles(List<String> paths) {\n for (String path : paths) {\n File file = new File(path);\n if (file.exists()) {\n file.delete();\n }\n }\n }\n\n /**\n * Get a file path from a Uri. This will get the the path for Storage Access\n * Framework Documents, as well as the _data field for the MediaStore and\n * other file-based ContentProviders.<br>\n * <br>\n * Callers should check whether the path is local before assuming it\n * represents a local file.\n *\n * @param context The context.\n * @param uri The Uri to query.\n * @author paulburke\n */\n public static String getPath(final Context context, final Uri uri) {\n\n // DocumentProvider\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {\n // ExternalStorageProvider\n if (isExternalStorageDocument(uri)) {\n final String docId = DocumentsContract.getDocumentId(uri);\n final String[] split = docId.split(\":\");\n final String type = split[0];\n\n if (\"primary\".equalsIgnoreCase(type)) {\n return Environment.getExternalStorageDirectory() + \"/\" + split[1];\n }\n\n // TODO handle non-primary volumes\n }\n // DownloadsProvider\n else if (isDownloadsDocument(uri)) {\n\n final String id = DocumentsContract.getDocumentId(uri);\n final Uri contentUri = ContentUris.withAppendedId(Uri.parse(\"content://downloads/public_downloads\"), Long.valueOf(id));\n\n return getDataColumn(context, contentUri, null, null);\n }\n // MediaProvider\n else if (isMediaDocument(uri)) {\n final String docId = DocumentsContract.getDocumentId(uri);\n final String[] split = docId.split(\":\");\n final String type = split[0];\n\n Uri contentUri = null;\n if (\"image\".equals(type)) {\n contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;\n } else if (\"video\".equals(type)) {\n contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;\n } else if (\"audio\".equals(type)) {\n contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;\n }\n\n final String selection = \"_id=?\";\n final String[] selectionArgs = new String[]{ split[1] };\n\n return getDataColumn(context, contentUri, selection, selectionArgs);\n }\n }\n // MediaStore (and general)\n else if (\"content\".equalsIgnoreCase(uri.getScheme())) {\n\n // Return the remote address\n if (isGooglePhotosUri(uri)) {\n return uri.getLastPathSegment();\n }\n\n return getDataColumn(context, uri, null, null);\n }\n // File\n else if (\"file\".equalsIgnoreCase(uri.getScheme())) {\n return uri.getPath();\n }\n\n return null;\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is ExternalStorageProvider.\n * @author paulburke\n */\n public static boolean isExternalStorageDocument(Uri uri) {\n return \"com.android.externalstorage.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is DownloadsProvider.\n * @author paulburke\n */\n public static boolean isDownloadsDocument(Uri uri) {\n return \"com.android.providers.downloads.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is MediaProvider.\n * @author paulburke\n */\n public static boolean isMediaDocument(Uri uri) {\n return \"com.android.providers.media.documents\".equals(uri.getAuthority());\n }\n\n /**\n * @param uri The Uri to check.\n * @return Whether the Uri authority is Google Photos.\n */\n public static boolean isGooglePhotosUri(Uri uri) {\n return \"com.google.android.apps.photos.content\".equals(uri.getAuthority());\n }\n\n /**\n * Get the value of the data column for this Uri. This is useful for\n * MediaStore Uris, and other file-based ContentProviders.\n *\n * @param context The context.\n * @param uri The Uri to query.\n * @param selection (Optional) Filter used in the query.\n * @param selectionArgs (Optional) Selection arguments used in the query.\n * @return The value of the _data column, which is typically a file path.\n * @author paulburke\n */\n public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {\n\n Cursor cursor = null;\n final String column = \"_data\";\n final String[] projection = { column };\n\n try {\n cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);\n if (cursor != null && cursor.moveToFirst()) {\n final int column_index = cursor.getColumnIndexOrThrow(column);\n return cursor.getString(column_index);\n }\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n return null;\n }\n}", "public class Utils {\n\n public static float dp2px(Context context, float dp) {\n return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());\n }\n\n public static String getFirstCharacter(String str) {\n return str.substring(0, 1);\n }\n\n public static int getNavigationBarHeight(Context context) {\n Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();\n DisplayMetrics dm1 = new DisplayMetrics();\n display.getMetrics(dm1);\n\n DisplayMetrics dm2 = new DisplayMetrics();\n if (Build.VERSION.SDK_INT >= 17) {\n display.getRealMetrics(dm2);\n } else {\n try {\n Class c = Class.forName(\"android.view.Display\");\n Method method = c.getMethod(\"getRealMetrics\", DisplayMetrics.class);\n method.invoke(display, dm2);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n return dm2.heightPixels - dm1.heightPixels;\n }\n\n /**\n * 判断网络是否连接\n */\n public static boolean isConnected(Context context) {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\n if (null != cm) {\n NetworkInfo info = cm.getActiveNetworkInfo();\n if (null != info && info.isConnected()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断是否是 wifi 连接\n */\n public static boolean isWifi(Context context) {\n ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\n return null != cm && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;\n }\n\n public static String getVersionName(Context context) {\n try {\n PackageManager packageManager = context.getPackageManager();\n PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);\n return packageInfo.versionName;\n\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n }\n return \"unknown\";\n }\n\n public static boolean isNightMode(Context context) {\n int uiMode = context.getResources().getConfiguration().uiMode;\n int dayNightUiMode = uiMode & Configuration.UI_MODE_NIGHT_MASK;\n\n return dayNightUiMode == Configuration.UI_MODE_NIGHT_YES;\n }\n}" ]
import moe.yukinoneko.gcomic.utils.FileUtlis; import moe.yukinoneko.gcomic.utils.Utils; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import android.content.Context; import java.util.ArrayList; import java.util.List; import moe.yukinoneko.gcomic.R; import moe.yukinoneko.gcomic.base.BasePresenter; import moe.yukinoneko.gcomic.data.ComicData; import moe.yukinoneko.gcomic.database.GComicDB; import moe.yukinoneko.gcomic.database.model.DownloadTaskModel; import moe.yukinoneko.gcomic.database.model.ReadHistoryModel; import moe.yukinoneko.gcomic.download.DownloadTasksManager; import moe.yukinoneko.gcomic.network.GComicApi;
/* * Copyright (C) 2016 SamuelGjk <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package moe.yukinoneko.gcomic.module.download.tasks; /** * Created by SamuelGjk on 2016/5/13. */ public class DownloadTasksPresenter extends BasePresenter<IDownloadTasksView> { public DownloadTasksPresenter(Context context, IDownloadTasksView iView) { super(context, iView); } void fetchDownloadTasks(int comicId) {
Subscription subscription = DownloadTasksManager.getInstance(mContext)
5
gibffe/fuse
src/main/java/com/sulaco/fuse/FuseServerImpl.java
[ "public interface AnnotationScanner {\n\n public void scan();\n}", "public class RouteFinderActor extends FuseEndpointActor {\r\n\r\n @Autowired protected RoutesConfig routes;\r\n \r\n @Override\r\n protected void onRequest(final FuseRequestMessage message) {\r\n \r\n String uri = message.getRequest().getUri();\r\n \r\n Optional<Route> route = routes.getFuseRoute(uri);\r\n\r\n if (route.isPresent()) {\r\n Route rte = route.get();\r\n\r\n // add route to the message\r\n ((FuseRequestMessageImpl) message).setRoute(rte);\r\n\r\n // pass message to handling actor\r\n rte.getHandler()\r\n .getActor()\r\n .ifPresent(\r\n handler -> {\r\n HttpMethod requested = message.getRequest().getMethod();\r\n HttpMethod supported = rte.getHandler().getHttpMethod();\r\n\r\n if (supported.compareTo(requested) == 0) {\r\n handler.tell(message, getSelf());\r\n }\r\n else {\r\n info(requested +\" not supported by \" + uri.toString());\r\n unhandled(message);\r\n }\r\n }\r\n );\r\n }\r\n else {\r\n unhandled(message);\r\n }\r\n }\r\n\r\n public void setRoutes(RoutesConfig routes) {\r\n this.routes = routes;\r\n }\r\n \r\n}\r", "public class SystemLogActor extends UntypedActor {\r\n\r\n private ConcurrentMap<ActorPath, Logger> loggers;\r\n \r\n public SystemLogActor() {\r\n this.loggers = new ConcurrentHashMap<>();\r\n }\r\n \r\n @Override\r\n public void onReceive(Object message) throws Exception {\r\n \r\n if (message instanceof SystemLogMessage) {\r\n log((SystemLogMessage) message); \r\n }\r\n else {\r\n unhandled(message);\r\n }\r\n }\r\n \r\n protected void log(SystemLogMessage message) {\r\n \r\n // find appropriate logger \r\n Logger logger = findLogger(message.getOrigin());\r\n \r\n // log message\r\n switch (message.getLevel()) {\r\n case DEBUG: {\r\n logger.debug(message.getMessage().get(), message.getException().get());\r\n }\r\n case INFO : {\r\n logger.info(message.getMessage().get(), message.getException().get());\r\n break;\r\n }\r\n default: break;\r\n }\r\n }\r\n \r\n protected Logger findLogger(Optional<ActorPath> origin) {\r\n \r\n ActorPath path = origin.orElse(getContext().parent().path());\r\n \r\n return loggers.computeIfAbsent(\r\n path, \r\n key -> {\r\n return LoggerFactory.getLogger(key.toString());\r\n }\r\n );\r\n }\r\n\r\n}\r", "public interface ConfigSource {\r\n\r\n public void parseLocalConfig();\r\n \r\n public Config getConfig();\r\n \r\n public RoutesConfig getRoutesConfig();\r\n}\r", "public interface ActorFactory extends ActorSystemAware, ApplicationContextAware {\r\n\r\n public Optional<ActorRef> getLocalActor(String actorClass);\r\n \r\n public Optional<ActorRef> getLocalActor(String actorClass, String actorName);\r\n \r\n public Optional<ActorRef> getLocalActor(String ref, String actorClass, int spinCount);\r\n \r\n public Optional<ActorRef> getLocalActor(String ref, String actorClass, String actorName, int spinCount);\r\n \r\n public Optional<ActorRef> getLocalActorByRef(String ref);\r\n\r\n public Optional<ActorSelection> select(String path);\r\n\r\n public Iterable<ActorRef> getRoutees(String ref, Class<?> clazz, int spinCount);\r\n\r\n \r\n}\r", "@Component\r\npublic class FuseChannelInitializer extends ChannelInitializer<SocketChannel> {\r\n\r\n @Autowired ConfigSource configSource;\r\n\r\n protected List<ChannelHandler> channelHandlers;\r\n\r\n protected ActorRef router;\r\n\r\n @Override\r\n protected void initChannel(SocketChannel ch) throws Exception {\r\n\r\n ChannelPipeline pipeline = ch.pipeline();\r\n\r\n // add handlers stack \r\n //\r\n if (channelHandlers != null) {\r\n for (ChannelHandler handler : channelHandlers) {\r\n pipeline.addLast(handler.getClass().getName(), handler);\r\n }\r\n }\r\n else {\r\n addDefaultHandlerStack(pipeline);\r\n }\r\n \r\n // at last , add FUSE channel handler, passing the router actor reference\r\n //\r\n pipeline.addLast(\"handler\", new FuseChannelHandler(this.router));\r\n }\r\n\r\n protected void addDefaultHandlerStack(ChannelPipeline pipeline) {\r\n Config config = configSource.getConfig();\r\n\r\n pipeline.addLast(\"decoder\" , new HttpRequestDecoder());\r\n pipeline.addLast(\"aggregator\" , new HttpObjectAggregator(66560));\r\n pipeline.addLast(\"encoder\" , new HttpResponseEncoder());\r\n pipeline.addLast(\"chunkedWriter\" , new ChunkedWriteHandler());\r\n pipeline.addLast(\"idlehandler\" , new IdleStateHandler(\r\n config.getLong(\"netty.reader.idle.time\"),\r\n config.getLong(\"netty.writer.idle.time\"),\r\n config.getLong(\"netty.either.idle.time\"),\r\n TimeUnit.MILLISECONDS\r\n ));\r\n }\r\n\r\n public void setChannelHandlers(List<ChannelHandler> channelHandlers) {\r\n this.channelHandlers = channelHandlers;\r\n }\r\n\r\n public void setRouter(ActorRef router) {\r\n this.router = router;\r\n }\r\n\r\n}\r" ]
import com.sulaco.fuse.config.AnnotationScanner; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.routing.RoundRobinRouter; import com.sulaco.fuse.akka.actor.RouteFinderActor; import com.sulaco.fuse.akka.syslog.SystemLogActor; import com.sulaco.fuse.config.ConfigSource; import com.sulaco.fuse.config.actor.ActorFactory; import com.sulaco.fuse.netty.FuseChannelInitializer; import com.typesafe.config.Config;
package com.sulaco.fuse; @Component public class FuseServerImpl implements FuseServer, InitializingBean, ApplicationContextAware { protected ExecutorService exe = Executors.newSingleThreadExecutor(); protected ActorSystem actorSystem; protected ApplicationContext appContext;
@Autowired protected ActorFactory actorFactory;
4
cqyijifu/OpenFalcon-SuitAgent
src/main/java/com/yiji/falcon/agent/Agent.java
[ "@Getter\npublic enum AgentConfiguration {\n\n INSTANCE;\n\n //版本不能大于 x.9\n public static final float VERSION = (float) 11.8;\n\n /**\n * quartz配置文件路径\n */\n private String quartzConfPath = null;\n /**\n * push到falcon的地址\n */\n private String agentPushUrl = null;\n\n /**\n * 插件配置的目录\n */\n private String pluginConfPath;\n\n /**\n * 授权配置文件路径\n */\n private String authorizationConfPath;\n\n /**\n * 集成的Falcon文件夹路径\n */\n private String falconDir;\n\n /**\n * Falcon的配置文件目录路径\n */\n private String falconConfDir;\n\n /**\n * 服务配置文件路径\n */\n private String agentConfPath = null;\n private String jmxCommonMetricsConfPath = null;\n\n /**\n * agent监控指标的主体说明\n */\n private String agentEndpoint = \"\";\n\n /**\n * agent启动端口\n */\n private int agentPort = 4518;\n\n /**\n * mock的有效时间\n */\n private int mockValidTime = 10800;\n\n /**\n * agent web 监听端口\n */\n private int agentWebPort = 4519;\n\n /**\n * 是否启用web服务\n */\n private boolean webEnable = true;\n\n /**\n * agent自动发现服务刷新周期\n */\n private int agentFlushTime = 300;\n\n /**\n * agent最大线程数\n */\n private int agentMaxThreadCount = 200;\n\n /**\n * JMX连接是否支持本地连接\n */\n private boolean agentJMXLocalConnect = false;\n\n private String agentUpdateUrl = null;\n\n private String agentHomeDir;\n\n\n private static final String CONF_AGENT_ENDPOINT = \"agent.endpoint\";\n private static final String CONF_AGENT_HOME = \"agent.home.dir\";\n private static final String CONF_AGENT_FLUSH_TIME = \"agent.flush.time\";\n private static final String CONF_AGENT_MAX_THREAD = \"agent.thread.maxCount\";\n\n private static final String CONF_AGENT_FALCON_PUSH_URL = \"agent.falcon.push.url\";\n private static final String CONF_AGENT_PORT = \"agent.port\";\n private static final String CONF_AGENT_WEB_PORT = \"agent.web.port\";\n private static final String CONF_AGENT_WEB_ENABLE = \"agent.web.enable\";\n private static final String CONF_AGENT_MOCK_VALID_TIME = \"agent.mock.valid.time\";\n private static final String AUTHORIZATION_CONF_PATH = \"authorization.conf.path\";\n private static final String FALCON_DIR_PATH = \"agent.falcon.dir\";\n private static final String FALCON_CONF_DIR_PATH = \"agent.falcon.conf.dir\";\n private static final String CONF_AGENT_JMX_LOCAL_CONNECT = \"agent.jmx.localConnectSupport\";\n private static final String CONF_AGENT_UPDATE_URL = \"agent.update.pack.url\";\n\n private Properties agentConf = null;\n\n /**\n * 初始化agent配置\n */\n AgentConfiguration() {\n instance();\n }\n\n private void instance(){\n if(StringUtils.isEmpty(System.getProperty(\"agent.conf.path\"))){\n System.err.println(\"agent agent.properties 配置文件位置读取失败,请确定系统配置项:\" + \"agent.conf.path\");\n System.exit(0);\n }else{\n this.agentConfPath = System.getProperty(\"agent.conf.path\");\n }\n\n if(StringUtils.isEmpty(System.getProperty(CONF_AGENT_HOME))){\n System.err.println(\"agent home dir 读取失败,请确定系统配置项:\" + CONF_AGENT_HOME);\n System.exit(0);\n }else{\n this.agentHomeDir = System.getProperty(CONF_AGENT_HOME);\n }\n\n if(StringUtils.isEmpty(System.getProperty(AUTHORIZATION_CONF_PATH))){\n System.err.println(\"agent authorization.properties 配置文件位置读取失败,请确定系统配置项:\" + AUTHORIZATION_CONF_PATH);\n System.exit(0);\n }else{\n this.authorizationConfPath = System.getProperty(AUTHORIZATION_CONF_PATH);\n }\n\n if(StringUtils.isEmpty(System.getProperty(FALCON_DIR_PATH))){\n System.err.println(\"falcon 目录位置读取失败,请确定系统配置项:\" + FALCON_DIR_PATH);\n System.exit(0);\n }else{\n this.falconDir = System.getProperty(FALCON_DIR_PATH);\n }\n\n if(StringUtils.isEmpty(System.getProperty(FALCON_CONF_DIR_PATH))){\n System.err.println(\"falcon conf 目录位置读取失败,请确定系统配置项:\" + FALCON_CONF_DIR_PATH);\n System.exit(0);\n }else{\n this.falconConfDir = System.getProperty(FALCON_CONF_DIR_PATH);\n }\n\n if(StringUtils.isEmpty(System.getProperty(\"agent.plugin.conf.dir\"))){\n System.err.println(\"agent 配置文件位置读取失败,请确定系统配置项:\" + \"agent.plugin.conf.dir\");\n System.exit(0);\n }else{\n this.pluginConfPath = System.getProperty(\"agent.plugin.conf.dir\");\n }\n\n if(StringUtils.isEmpty(System.getProperty(\"agent.quartz.conf.path\"))){\n System.err.println(\"quartz 配置文件位置读取失败,请确定系统配置项:\" + \"agent.quartz.conf.path\");\n System.exit(0);\n }else{\n this.quartzConfPath = System.getProperty(\"agent.quartz.conf.path\");\n }\n\n agentConf = new Properties();\n try(FileInputStream in = new FileInputStream(this.agentConfPath)){\n agentConf.load(in);\n }catch (IOException e) {\n System.err.println(this.agentConfPath + \" 配置文件读取失败 Agent启动失败\");\n System.exit(0);\n }\n init();\n initJMXCommon();\n }\n\n private void init(){\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_ENDPOINT))){\n this.agentEndpoint = agentConf.getProperty(CONF_AGENT_ENDPOINT);\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_PORT))){\n try {\n this.agentWebPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_WEB_PORT));\n } catch (Exception e) {\n System.err.println(String.format(\"Agent启动失败,端口配置%s无效:%s\", CONF_AGENT_WEB_PORT, agentConf.getProperty(CONF_AGENT_WEB_PORT)));\n System.exit(0);\n }\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_WEB_ENABLE))){\n this.webEnable = \"true\".equals(agentConf.getProperty(CONF_AGENT_WEB_ENABLE));\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME))){\n try {\n this.mockValidTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME));\n } catch (NumberFormatException e) {\n System.err.println(String.format(\"Agent启动失败,mock有效时间配置 %s 无效: %s\", CONF_AGENT_MOCK_VALID_TIME, agentConf.getProperty(CONF_AGENT_MOCK_VALID_TIME)));\n System.exit(0);\n }\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT))){\n this.agentJMXLocalConnect = \"true\".equals(agentConf.getProperty(CONF_AGENT_JMX_LOCAL_CONNECT));\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_UPDATE_URL))){\n this.agentUpdateUrl = agentConf.getProperty(CONF_AGENT_UPDATE_URL);\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_PORT))){\n try {\n this.agentPort = Integer.parseInt(agentConf.getProperty(CONF_AGENT_PORT));\n } catch (NumberFormatException e) {\n System.err.println(String.format(\"Agent启动失败,端口配置%s无效:%s\", CONF_AGENT_PORT, agentConf.getProperty(CONF_AGENT_PORT)));\n System.exit(0);\n }\n }\n\n if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL))){\n System.err.println(\"Agent启动失败,未定义falcon push地址配置:\" + CONF_AGENT_FALCON_PUSH_URL);\n System.exit(0);\n }\n this.agentPushUrl = agentConf.getProperty(CONF_AGENT_FALCON_PUSH_URL);\n\n if(StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_FLUSH_TIME))){\n System.err.println(\"Agent启动失败,未指定配置:\" + CONF_AGENT_FLUSH_TIME);\n System.exit(0);\n }\n try {\n this.agentFlushTime = Integer.parseInt(agentConf.getProperty(CONF_AGENT_FLUSH_TIME));\n if(this.agentFlushTime <= 0){\n System.err.println(String.format(\"Agent启动失败,自动发现服务的刷新周期配置 %s 必须大于0: %s\",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME)));\n System.exit(0);\n }\n } catch (NumberFormatException e) {\n System.err.println(String.format(\"Agent启动失败,自动发现服务的刷新周期配置%s无效:%s\",CONF_AGENT_FLUSH_TIME,agentConf.getProperty(CONF_AGENT_FLUSH_TIME)));\n System.exit(0);\n }\n\n if(!StringUtils.isEmpty(agentConf.getProperty(CONF_AGENT_MAX_THREAD))){\n try {\n this.agentMaxThreadCount = Integer.parseInt(agentConf.getProperty(CONF_AGENT_MAX_THREAD));\n if(this.agentMaxThreadCount <= 5){\n System.err.println(String.format(\"Agent启动失败,最大线程数 %s 必须大于5: %s\",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD)));\n System.exit(0);\n }\n } catch (NumberFormatException e) {\n System.err.println(String.format(\"Agent启动失败,最大线程数%s无效:%s\",CONF_AGENT_MAX_THREAD,agentConf.getProperty(CONF_AGENT_MAX_THREAD)));\n System.exit(0);\n }\n }\n\n }\n\n private void initJMXCommon(){\n String property = System.getProperty(\"agent.jmx.metrics.common.path\");\n if(StringUtils.isEmpty(property)){\n System.err.println(\"jmx 的公共配置系统属性文件未定义:agent.jmx.metrics.common.path\");\n System.exit(0);\n }\n this.jmxCommonMetricsConfPath = property;\n }\n\n}", "@Slf4j\npublic class JMXConnection {\n private static final Map<String,JMXConnectionInfo> connectCacheLibrary = new HashMap<>();//JMX的连接缓存\n private static final Map<String,Integer> serverConnectCount = new HashMap<>();//记录服务应有的JMX连接数\n\n private String serverName;\n\n public JMXConnection(String serverName) {\n this.serverName = serverName;\n }\n\n /**\n * 删除JMX连接池连接\n * @param serverName\n * JMX服务名\n * @param pid\n * 进程id\n */\n public static void removeConnectCache(String serverName,int pid){\n String key = serverName + pid;\n if(connectCacheLibrary.remove(key) != null){\n //删除成功,更新serverConnectCount\n int count = serverConnectCount.get(serverName);\n serverConnectCount.put(serverName,count - 1);\n log.info(\"已清除JMX监控: {} , pid: {}\",serverName,pid);\n }\n }\n\n /**\n * 根据服务名,返回该服务应有的JMX连接数\n * @param serverName\n * @return\n */\n public static int getServerConnectCount(String serverName){\n return serverConnectCount.get(serverName);\n }\n\n /**\n * 获取本地是否已开启指定的JMX服务\n * @param serverName\n * @return\n */\n public static boolean hasJMXServerInLocal(String serverName){\n if(!StringUtils.isEmpty(serverName)){\n List<VirtualMachineDescriptor> vms = VirtualMachine.list();\n for (VirtualMachineDescriptor desc : vms) {\n File file = new File(desc.displayName());\n if(file.exists()){\n //java -jar 形式启动的Java应用\n if(file.toPath().getFileName().toString().equals(serverName)){\n return true;\n }\n }else if(desc.displayName().contains(serverName)){\n return true;\n }\n\n }\n }\n return false;\n }\n\n /**\n *\n * @throws IOException\n */\n public static void closeAll() {\n for (JMXConnectionInfo jmxConnectionInfo : connectCacheLibrary.values()) {\n jmxConnectionInfo.closeJMXConnector();\n }\n }\n\n /**\n * 获取指定服务名的本地JMX VM 描述对象\n * @param serverName\n * @return\n */\n public static List<VirtualMachineDescriptor> getVmDescByServerName(String serverName){\n List<VirtualMachineDescriptor> vmDescList = new ArrayList<>();\n List<VirtualMachineDescriptor> vms = VirtualMachine.list();\n for (VirtualMachineDescriptor desc : vms) {\n File file = new File(desc.displayName());\n if(file.exists()){\n //java -jar 形式启动的Java应用\n if(file.toPath().getFileName().toString().equals(serverName)){\n vmDescList.add(desc);\n }\n }else if(desc.displayName().contains(serverName)){\n vmDescList.add(desc);\n }\n }\n return vmDescList;\n }\n\n\n\n /**\n * 获取JMX连接\n * @return\n * @throws IOException\n */\n public synchronized List<JMXConnectionInfo> getMBeanConnection(){\n if(StringUtils.isEmpty(serverName)){\n log.error(\"获取JMX连接的serverName不能为空\");\n return new ArrayList<>();\n }\n\n List<VirtualMachineDescriptor> vmDescList = getVmDescByServerName(serverName);\n\n List<JMXConnectionInfo> connections = connectCacheLibrary.entrySet().\n stream().\n filter(entry -> NumberUtils.isNumber(entry.getKey().replace(serverName,\"\"))).\n map(Map.Entry::getValue).\n collect(Collectors.toList());\n\n if(connections.isEmpty() || connections.size() < vmDescList.size()){ //JMX连接池为空,进行连接获取\n int count = 0;\n connections.clear();\n clearCache();\n for (VirtualMachineDescriptor desc : vmDescList) {\n JMXConnectUrlInfo jmxConnectUrlInfo = getConnectorAddress(desc);\n if (jmxConnectUrlInfo == null) {\n log.error(\"应用 {} 的JMX连接URL获取失败\",desc.displayName());\n //对应的ServerName的JMX连接获取失败,返回该服务JMX连接失败,用于上报不可用记录\n connections.add(initBadJMXConnect(desc));\n count++;\n continue;\n }\n\n try {\n connections.add(initJMXConnectionInfo(getJMXConnector(jmxConnectUrlInfo),desc));\n log.debug(\"应用 {} JMX 连接已建立\",serverName);\n\n } catch (Exception e) {\n log.error(\"JMX 连接获取异常:{}\",e.getMessage());\n //JMX连接获取失败,添加该服务JMX的不可用记录,用于上报不可用记录\n connections.add(initBadJMXConnect(desc));\n }\n //该服务应有的数量++\n count++;\n }\n\n if(count > 0){\n serverConnectCount.put(serverName,count);\n }else{\n //对应的ServerName的JMX连接获取失败,返回该服务JMX连接失败,用于上报不可用记录\n JMXConnectionInfo jmxConnectionInfo = new JMXConnectionInfo();\n jmxConnectionInfo.setValid(false, JMXUnavailabilityType.connectionFailed);\n connections.add(jmxConnectionInfo);\n serverConnectCount.put(serverName,1);\n }\n }\n\n //若当前应有的服务实例记录值比获取到的记录值小,重新设置\n if(getServerConnectCount(serverName) < vmDescList.size()){\n serverConnectCount.put(serverName,vmDescList.size());\n }\n\n return connections;\n }\n\n private JMXConnector getJMXConnector(JMXConnectUrlInfo jmxConnectUrlInfo) throws Exception {\n JMXServiceURL url = new JMXServiceURL(jmxConnectUrlInfo.getRemoteUrl());\n JMXConnector connector;\n if(jmxConnectUrlInfo.isAuthentication()){\n connector = JMXConnectWithTimeout.connectWithTimeout(url,jmxConnectUrlInfo.getJmxUser()\n ,jmxConnectUrlInfo.getJmxPassword(),10, TimeUnit.SECONDS);\n }else{\n connector = JMXConnectWithTimeout.connectWithTimeout(url,null,null,10, TimeUnit.SECONDS);\n }\n return connector;\n }\n\n /**\n * 清楚连接缓存\n */\n private void clearCache(){\n //清除当前连接池中的连接\n List<String> removeKey = connectCacheLibrary.keySet().stream().filter(key -> NumberUtils.isNumber(key.replace(serverName,\"\"))).collect(Collectors.toList());\n removeKey.forEach(key -> {\n connectCacheLibrary.get(key).closeJMXConnector();\n connectCacheLibrary.remove(key);\n });\n }\n\n /**\n * 重置jmx连接\n * @throws IOException\n */\n public synchronized void resetMBeanConnection() {\n if(StringUtils.isEmpty(serverName)){\n log.error(\"获取JMX连接的serverName不能为空\");\n }\n\n //本地JMX连接中根据指定的服务名命中的VirtualMachineDescriptor\n List<VirtualMachineDescriptor> targetDesc = getVmDescByServerName(serverName);\n\n //若命中的target数量大于或等于该服务要求的JMX连接数,则进行重置连接池中的连接\n if(targetDesc.size() >= getServerConnectCount(serverName)){\n\n //清除当前连接池中的连接\n clearCache();\n\n //重新设置服务应有连接数\n int count = 0;\n //重新构建连接\n for (VirtualMachineDescriptor desc : targetDesc) {\n\n JMXConnectUrlInfo jmxConnectUrlInfo = getConnectorAddress(desc);\n if (jmxConnectUrlInfo == null) {\n log.error(\"应用{}的JMX连接URL获取失败\",serverName);\n //对应的ServerName的JMX连接获取失败,返回该服务JMX连接失败,用于上报不可用记录\n initBadJMXConnect(desc);\n count++;\n continue;\n }\n try {\n initJMXConnectionInfo(getJMXConnector(jmxConnectUrlInfo),desc);\n log.info(\"应用 {} JMX 连接已建立,将在下一周期获取Metrics值时生效\",serverName);\n } catch (Exception e) {\n log.error(\"JMX 连接获取异常:{}\",e);\n //JMX连接获取失败,添加该服务JMX的不可用记录,用于上报不可用记录\n initBadJMXConnect(desc);\n }\n count++;\n }\n serverConnectCount.put(serverName,count);\n }\n\n //若当前应有的服务实例记录值比获取到的记录值小,重新设置\n if(getServerConnectCount(serverName) < targetDesc.size()){\n serverConnectCount.put(serverName,targetDesc.size());\n }\n\n }\n\n\n\n private JMXConnectUrlInfo getConnectorAddress(VirtualMachineDescriptor desc){\n if(AgentConfiguration.INSTANCE.isAgentJMXLocalConnect()){\n String connectorAddress = AbstractJmxCommand.findJMXLocalUrlByProcessId(Integer.parseInt(desc.id()));\n if(connectorAddress != null){\n return new JMXConnectUrlInfo(connectorAddress);\n }\n }\n\n JMXConnectUrlInfo jmxConnectUrlInfo = null;\n try {\n jmxConnectUrlInfo = AbstractJmxCommand.findJMXRemoteUrlByProcessId(Integer.parseInt(desc.id()), InetAddress.getLocalHost().getHostAddress());\n if(jmxConnectUrlInfo != null){\n log.info(\"JMX Remote URL:{}\",jmxConnectUrlInfo);\n }else if(!AgentConfiguration.INSTANCE.isAgentJMXLocalConnect()){\n log.warn(\"应用未配置JMX Remote功能,请给应用配置JMX Remote\");\n }\n } catch (UnknownHostException e) {\n log.error(\"JMX连接本机地址获取失败\",e);\n }\n return jmxConnectUrlInfo;\n }\n\n /**\n * JMXConnectionInfo的初始化动作\n * @param connector\n * @param desc\n * @return\n * @throws IOException\n */\n private JMXConnectionInfo initJMXConnectionInfo(JMXConnector connector,VirtualMachineDescriptor desc) throws IOException {\n JMXConnectionInfo jmxConnectionInfo = new JMXConnectionInfo();\n jmxConnectionInfo.setJmxConnector(connector);\n jmxConnectionInfo.setCacheKeyId(desc.id());\n jmxConnectionInfo.setConnectionServerName(serverName);\n jmxConnectionInfo.setConnectionQualifiedServerName(desc.displayName());\n jmxConnectionInfo.setMBeanServerConnection(connector.getMBeanServerConnection());\n jmxConnectionInfo.setValid(true,null);\n jmxConnectionInfo.setPid(Integer.parseInt(desc.id()));\n\n connectCacheLibrary.put(serverName + desc.id(),jmxConnectionInfo);\n return jmxConnectionInfo;\n }\n\n /**\n * 连接失败的JMX的初始化动作\n * @param desc\n */\n private JMXConnectionInfo initBadJMXConnect(VirtualMachineDescriptor desc){\n JMXConnectionInfo jmxConnectionInfo = new JMXConnectionInfo();\n jmxConnectionInfo.setValid(false,JMXUnavailabilityType.connectionFailed);\n jmxConnectionInfo.setConnectionServerName(serverName);\n jmxConnectionInfo.setConnectionQualifiedServerName(desc.displayName());\n jmxConnectionInfo.setPid(Integer.parseInt(desc.id()));\n connectCacheLibrary.put(serverName + desc.id(),jmxConnectionInfo);\n return jmxConnectionInfo;\n }\n\n}", "@Slf4j\npublic class PluginExecute {\n\n /**\n * 启动插件\n * @throws SchedulerException\n */\n public static void start() throws SchedulerException {\n //根据配置启动自发现功能\n AgentJobHelper.agentFlush();\n run();\n }\n\n /**\n * 运行插件\n */\n public static void run(){\n\n Set<Plugin> jmxPlugins = PluginLibraryHelper.getJMXPlugins();\n Set<Plugin> jdbcPlugins = PluginLibraryHelper.getJDBCPlugins();\n Set<Plugin> snmpv3Plugins = PluginLibraryHelper.getSNMPV3Plugins();\n Set<Plugin> detectPlugins = PluginLibraryHelper.getDetectPlugins();\n\n jmxPlugins.forEach(plugin -> {\n try {\n JMXPlugin jmxPlugin = (JMXPlugin) plugin;\n JobDataMap jobDataMap = new JobDataMap();\n //若jmxServerName有多个值,分别进行job启动\n for (String jmxServerName : ((JMXPlugin) plugin).jmxServerName().split(\",\")) {\n if(!StringUtils.isEmpty(jmxServerName)){\n String pluginName = String.format(\"%s-%s\",jmxPlugin.pluginName(),jmxServerName);\n jobDataMap.put(\"pluginName\",pluginName);\n jobDataMap.put(\"jmxServerName\",jmxServerName);\n jobDataMap.put(\"pluginObject\",jmxPlugin);\n\n AgentJobHelper.pluginWorkForJMX(pluginName,\n jmxPlugin.activateType(),\n jmxPlugin.step(),\n pluginName,\n jmxPlugin.serverName() + \"-\" + jmxServerName,\n jmxServerName,\n jobDataMap);\n }\n }\n } catch (Exception e) {\n log.error(\"插件启动异常\",e);\n }\n });\n snmpv3Plugins.forEach(plugin -> {\n try{\n SNMPV3Plugin snmpv3Plugin = (SNMPV3Plugin) plugin;\n JobDataMap jobDataMap = new JobDataMap();\n String pluginName = String.format(\"%s-%s\",snmpv3Plugin.pluginName(),snmpv3Plugin.serverName());\n jobDataMap.put(\"pluginName\",pluginName);\n jobDataMap.put(\"pluginObject\",snmpv3Plugin);\n// List<SNMPV3UserInfo> jobUsers = new ArrayList<>();\n// Collection<SNMPV3UserInfo> userInfoCollection = snmpv3Plugin.userInfo();\n// StringBuilder sb = new StringBuilder();\n// int count = 1;\n// for (SNMPV3UserInfo snmpv3UserInfo : userInfoCollection) {\n// //每5个SNMP连接为一个job\n// if(jobUsers.size() == 5){\n// jobDataMap.put(\"userInfoList\",jobUsers);\n// AgentJobHelper.pluginWorkForSNMPV3(snmpv3Plugin,pluginName,SNMPPluginJob.class,pluginName + \"-\" + count + \"-\" + sb.toString(),snmpv3Plugin.serverName() + \"-\" + count + \"-\" + sb.toString(),jobDataMap);\n// jobUsers = new ArrayList<>();\n// jobUsers.add(snmpv3UserInfo);\n// sb = new StringBuilder();\n// sb.append(snmpv3UserInfo.getAddress()).append(\" | \");\n// count++;\n// }else{\n// sb.append(snmpv3UserInfo.getAddress()).append(\" | \");\n// jobUsers.add(snmpv3UserInfo);\n// }\n// }\n// jobDataMap.put(\"userInfoList\",jobUsers);\n// AgentJobHelper.pluginWorkForSNMPV3(snmpv3Plugin,pluginName,SNMPPluginJob.class,pluginName + \"-\" + count + \"-\" + sb.toString(),snmpv3Plugin.serverName() + \"-\" + count + \"-\" + sb.toString(),jobDataMap);\n jobDataMap.put(\"userInfoList\",snmpv3Plugin.userInfo());\n AgentJobHelper.pluginWorkForSNMPV3(snmpv3Plugin,pluginName,SNMPPluginJob.class,pluginName,snmpv3Plugin.serverName(),jobDataMap);\n }catch (Exception e){\n log.error(\"插件启动异常\",e);\n }\n });\n\n detectPlugins.forEach(plugin -> {\n try {\n DetectPlugin detectPlugin = (DetectPlugin) plugin;\n JobDataMap jobDataMap = new JobDataMap();\n String pluginName = plugin.pluginName();\n jobDataMap.put(\"pluginName\",pluginName);\n jobDataMap.put(\"pluginObject\",detectPlugin);\n AgentJobHelper.pluginWorkForDetect(detectPlugin,pluginName, DetectPluginJob.class,jobDataMap);\n }catch (Exception e){\n log.error(\"插件启动异常\",e);\n }\n });\n\n //设置JDBC超时为5秒\n DriverManager.setLoginTimeout(5);\n jdbcPlugins.forEach(plugin -> {\n try {\n JDBCPlugin jdbcPlugin = (JDBCPlugin) plugin;\n JobDataMap jobDataMap = new JobDataMap();\n String pluginName = String.format(\"%s-%s\",jdbcPlugin.pluginName(),jdbcPlugin.serverName());\n jobDataMap.put(\"pluginName\",pluginName);\n jobDataMap.put(\"pluginObject\",jdbcPlugin);\n AgentJobHelper.pluginWorkForJDBC(jdbcPlugin,pluginName,JDBCPluginJob.class,pluginName,jdbcPlugin.serverName(),jobDataMap);\n } catch (Exception e) {\n log.error(\"插件启动异常\",e);\n }\n });\n\n }\n\n}", "@Slf4j\npublic class PluginLibraryHelper {\n\n private final static Set<Plugin> plugins = new HashSet<>();\n private final static List<String> pluginNames = new ArrayList<>();\n\n private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n\n /**\n * 获取拥有授权配置的插件\n * @return\n */\n public static Set<Plugin> getPluginsAboutAuthorization(){\n Set<Plugin> targetPlugins = new HashSet<>();\n for (Plugin plugin : plugins) {\n if(hasAuthorizationConf(plugin.authorizationKeyPrefix())){\n targetPlugins.add(plugin);\n }\n }\n\n return targetPlugins;\n }\n\n /**\n * 是否有授权配置\n * @param authorizationKeyPrefix\n * 授权配置的字符串前缀\n * @return\n */\n private static boolean hasAuthorizationConf(String authorizationKeyPrefix){\n Map<String,String> authorizationConf = PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getAuthorizationConfPath());\n for (String key : authorizationConf.keySet()) {\n if(key != null && key.contains(authorizationKeyPrefix)){\n return true;\n }\n }\n return false;\n }\n\n /**\n * 根据配置文件名称查找匹配的插件\n * @param fileName\n * @return\n * 匹配不到返回null\n */\n public static Plugin getPluginByConfigFileName(String fileName){\n Plugin plugin = null;\n if(!StringUtils.isEmpty(fileName)){\n\n for (Plugin plugin1 : plugins) {\n if(fileName.equals(plugin1.configFileName())){\n plugin = plugin1;\n break;\n }\n }\n }\n return plugin;\n }\n\n /**\n * 调用所有注册的Plugin的agentShutdownHook方法\n */\n public static void invokeAgentShutdownHook(){\n plugins.forEach(Plugin::agentShutdownHook);\n }\n\n /**\n * 获取JMX监控服务插件\n * @return\n */\n public static Set<Plugin> getJMXPlugins(){\n return getPluginsByType(JMXPlugin.class);\n }\n\n /**\n * 获取JDBC监控服务插件\n * @return\n */\n public static Set<Plugin> getJDBCPlugins(){\n return getPluginsByType(JDBCPlugin.class);\n }\n\n /**\n * 获取SNMPV3监控服务插件\n * @return\n */\n public static Set<Plugin> getSNMPV3Plugins(){\n return getPluginsByType(SNMPV3Plugin.class);\n }\n\n /**\n * 获取探测监控服务插件\n * @return\n */\n public static Set<Plugin> getDetectPlugins(){\n return getPluginsByType(DetectPlugin.class);\n }\n\n private static Set<Plugin> getPluginsByType(Class type){\n Set<Plugin> targetPlugins = new HashSet<>();\n targetPlugins.addAll(plugins.stream().filter(plugin -> type.isAssignableFrom(plugin.getClass())).collect(Collectors.toSet()));\n return targetPlugins;\n }\n\n /**\n * 获取插件的配置\n * @param plugin\n * @return\n */\n public static Map<String,String> getPluginConfig(Plugin plugin){\n Map<String,String> config = new HashMap<>();\n config.put(\"pluginDir\",AgentConfiguration.INSTANCE.getPluginConfPath());\n if(!StringUtils.isEmpty(plugin.configFileName())){\n //指定了插件名,传入插件配置\n config.putAll(PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getPluginConfPath() + File.separator + plugin.configFileName()));\n }\n String authorizationKeyPrefix = plugin.authorizationKeyPrefix();\n if(!StringUtils.isEmpty(authorizationKeyPrefix)){\n //传入授权配置\n Map<String,String> authorizationConf = PropertiesUtil.getAllPropertiesByFileName(AgentConfiguration.INSTANCE.getAuthorizationConfPath());\n authorizationConf.entrySet().stream().filter(entry -> entry.getKey() != null &&\n entry.getKey().contains(authorizationKeyPrefix)).forEach(entry -> {\n config.put(entry.getKey(), entry.getValue());\n });\n }\n return config;\n }\n\n /**\n * 注册插件\n */\n public synchronized void register(){\n Set<ClassPath.ClassInfo> classInfos;\n try {\n classInfos = ClassPath.from(classLoader).getTopLevelClassesRecursive(\"com.yiji.falcon\");\n for (ClassPath.ClassInfo classInfo : classInfos) {\n String clazzName = classInfo.getName();\n Class clazz = Class.forName(clazzName);\n if(Plugin.class.isAssignableFrom(clazz) &&\n clazz != Plugin.class &&\n clazz != JMXPlugin.class &&\n clazz != JDBCPlugin.class &&\n clazz != SNMPV3Plugin.class &&\n clazz != DetectPlugin.class){\n final Plugin plugin = (Plugin) clazz.newInstance();\n //插件初始化操作\n Map<String,String> config = getPluginConfig(plugin);\n //初始化插件配置\n plugin.init(config);\n\n String avaStr = pluginAvailable(plugin);\n if(avaStr != null){\n log.warn(\"插件 {} 无效 : {}\",clazz.getName(),avaStr);\n continue;\n }\n plugins.add(plugin);\n log.info(\"成功注册插件:{},启动方式:{}\",clazzName,plugin.activateType().getDesc());\n }\n }\n } catch (Exception e) {\n log.error(\"插件注册异常\",e);\n }\n }\n\n /**\n * 插件有效性判断\n * @return\n */\n private String pluginAvailable(Plugin plugin){\n try {\n int step = plugin.step();\n int stepMin = 30;\n int stepMax = 24 * 60 * 60;\n if(step < stepMin || step >= stepMax){\n return String.format(\"step不能小于%d 并且不能大于等于%d\",stepMin,stepMax);\n }\n\n String pluginName = plugin.pluginName();\n if(pluginNames.contains(pluginName)){\n return String.format(\"插件 {%s} 的插件名称 {%s} 重复,请重新执行插件名称\",plugin.getClass().getName(),pluginName);\n }\n pluginNames.add(pluginName);\n\n if(StringUtils.isEmpty(plugin.serverName())){\n return String.format(\"插件 {%s} 的serverName不能为空\",plugin.getClass().getName());\n }\n } catch (Exception e) {\n log.warn(\"插件无效\",e);\n return null;\n }\n\n return null;\n }\n\n}", "@Data\npublic class HttpResult {\n\n /**\n * 状态码\n */\n private int status;\n /**\n * 返回结果\n */\n private String result;\n\n /**\n * 响应时间\n */\n private long responseTime;\n}", "@Slf4j\npublic class ConfDirWatcher extends Thread{\n\n private String confDir;\n\n /**\n * 配置文件目录的监听器\n * @param confDir\n * 配置文件conf目录\n */\n public ConfDirWatcher(String confDir){\n this.confDir = confDir;\n }\n\n @Override\n public void run() {\n WatchService watchService = WatchServiceUtil.watchModify(confDir);\n WatchKey key;\n while (watchService != null){\n try {\n key = watchService.take();\n for (WatchEvent<?> watchEvent : key.pollEvents()) {\n if(watchEvent.kind() == ENTRY_MODIFY){\n String fileName = watchEvent.context() == null ? \"\" : watchEvent.context().toString();\n if(\"authorization.properties\".equals(fileName)){\n log.info(\"检测到授权文件authorization.properties有改动,正在重新配置相关插件配置\");\n Set<Plugin> plugins = PluginLibraryHelper.getPluginsAboutAuthorization();\n for (Plugin plugin : plugins) {\n plugin.init(PluginLibraryHelper.getPluginConfig(plugin));\n log.info(\"已完成插件{}的配置重新加载\",plugin.pluginName());\n }\n }\n }\n }\n key.reset();\n } catch (Exception e) {\n log.error(\"插件配置文件监听异常\",e);\n break;\n }\n }\n }\n}", "@Slf4j\npublic class PluginPropertiesWatcher extends Thread{\n\n private String pluginDir;\n\n /**\n * 插件配置文件的监听器\n * @param pluginDir\n * 插件目录\n */\n public PluginPropertiesWatcher(String pluginDir){\n this.pluginDir = pluginDir;\n }\n\n @Override\n public void run() {\n WatchService watchService = WatchServiceUtil.watchModify(pluginDir);\n WatchKey key;\n while (watchService != null){\n try {\n key = watchService.take();\n for (WatchEvent<?> watchEvent : key.pollEvents()) {\n if(watchEvent.kind() == ENTRY_MODIFY){\n String fileName = watchEvent.context() == null ? \"\" : watchEvent.context().toString();\n Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);\n if(plugin != null){\n plugin.init(PluginLibraryHelper.getPluginConfig(plugin));\n log.info(\"已完成插件{}的配置重新加载\",plugin.pluginName());\n }\n }\n }\n key.reset();\n } catch (Exception e) {\n log.error(\"插件配置文件监听异常\",e);\n break;\n }\n }\n }\n}", "@Slf4j\npublic class HttpServer extends Thread{\n\n private static final String SHUTDOWN_COMMAND = \"/__SHUTDOWN__\";\n private boolean shutdown = false;\n /**\n * 0 : 服务未启动\n * 1 : 服务已启动\n * -1 : 服务正在关闭\n */\n public static int status = 0;\n\n private int port;\n private ServerSocket serverSocket;\n\n public HttpServer(int port) {\n this.port = port;\n }\n\n @Override\n public void run() {\n try {\n startServer();\n } catch (IOException e) {\n log.error(\"web服务启动异常\",e);\n status = 0;\n System.exit(0);\n }\n }\n\n public void startServer() throws IOException {\n serverSocket = new ServerSocket(port, 10, InetAddress.getByName(\"0.0.0.0\"));\n log.info(\"Web服务启动地址:http://{}:{}\",InetAddress.getByName(\"0.0.0.0\").getHostName(),serverSocket.getLocalPort());\n status = 1;\n while (!shutdown) {\n Socket socket;\n InputStream input;\n OutputStream output;\n try {\n socket = serverSocket.accept();\n\n input = socket.getInputStream();\n output = socket.getOutputStream();\n Request request = new Request(input);\n request.parse();\n Response response = new Response(output);\n response.setRequest(request);\n shutdown = SHUTDOWN_COMMAND.equals(request.getUri());\n if(shutdown){\n status = -1;\n response.send(\"Shutdown OK\");\n }else{\n response.doRequest();\n }\n socket.close();\n } catch (Exception e) {\n log.error(\"Web处理异常\",e);\n }\n }\n try {\n close();\n } catch (Exception e) {\n log.error(\"web服务关闭异常\",e);\n }\n }\n\n private void close() throws IOException {\n if(serverSocket != null && !serverSocket.isClosed()){\n serverSocket.close();\n status = 0;\n log.info(\"Web 服务已关闭\");\n }\n }\n\n}" ]
import com.yiji.falcon.agent.config.AgentConfiguration; import com.yiji.falcon.agent.jmx.JMXConnection; import com.yiji.falcon.agent.plugins.util.PluginExecute; import com.yiji.falcon.agent.plugins.util.PluginLibraryHelper; import com.yiji.falcon.agent.util.*; import com.yiji.falcon.agent.vo.HttpResult; import com.yiji.falcon.agent.watcher.ConfDirWatcher; import com.yiji.falcon.agent.watcher.PluginPropertiesWatcher; import com.yiji.falcon.agent.web.HttpServer; import lombok.extern.slf4j.Slf4j; import org.apache.log4j.PropertyConfigurator; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SchedulerFactory; import org.quartz.impl.DirectSchedulerFactory; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Collection;
/* * www.yiji.com Inc. * Copyright (c) 2016 All Rights Reserved */ package com.yiji.falcon.agent; /* * 修订记录: * [email protected] 2016-06-22 17:48 创建 */ /** * agent服务 * @author [email protected] */ @Slf4j public class Agent extends Thread{ public static final PrintStream OUT = System.out; public static final PrintStream ERR = System.err; public static int falconAgentPid = 0; private ServerSocketChannel serverSocketChannel;
private HttpServer httpServer = null;
7
jiang111/ZhiHu-TopAnswer
app/src/main/java/com/jiang/android/zhihu_topanswer/fragment/RecyclerViewFragment.java
[ "public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder> {\n\n\n @Override\n public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n final BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false));\n\n if (clickable()) {\n holder.getConvertView().setClickable(true);\n holder.getConvertView().setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onItemClick(v, holder.getLayoutPosition());\n }\n });\n }\n return holder;\n }\n\n @Override\n public void onBindViewHolder(final BaseViewHolder holder, final int position) {\n\n onBindView(holder, holder.getLayoutPosition());\n\n }\n\n public abstract void onBindView(BaseViewHolder holder, int position);\n\n @Override\n public int getItemViewType(int position) {\n return getLayoutID(position);\n }\n\n\n public abstract int getLayoutID(int position);\n\n public abstract boolean clickable();\n\n public void onItemClick(View v, int position) {\n }\n\n\n}", "public class BaseViewHolder extends RecyclerView.ViewHolder {\n\n protected final SparseArray<View> mViews;\n protected View mConvertView;\n\n\n public BaseViewHolder(View itemView) {\n super(itemView);\n mViews = new SparseArray<>();\n mConvertView = itemView;\n }\n\n\n /**\n * 通过控件的Id获取对应的控件,如果没有则加入mViews,则从item根控件中查找并保存到mViews中\n *\n * @param viewId\n * @return\n */\n public <T extends View> T getView(@IdRes int viewId) {\n View view = mViews.get(viewId);\n if (view == null) {\n view = mConvertView.findViewById(viewId);\n mViews.put(viewId, view);\n }\n return (T) view;\n }\n\n public View getConvertView() {\n return mConvertView;\n }\n\n public BaseViewHolder setBgColor(@IdRes int resID, int color) {\n getView(resID).setBackgroundColor(color);\n return this;\n }\n\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n public BaseViewHolder setBgDrawable(@IdRes int resID, Drawable drawable) {\n getView(resID).setBackground(drawable);\n return this;\n\n }\n\n\n public BaseViewHolder setTextColor(@IdRes int resID, int color) {\n ((TextView) getView(resID)).setTextColor(color);\n return this;\n }\n\n public BaseViewHolder setText(@IdRes int resID, String text) {\n ((TextView) getView(resID)).setText(text);\n return this;\n }\n\n public BaseViewHolder setTextSize(@IdRes int resID, int spSize) {\n ((TextView) getView(resID)).setTextSize(spSize);\n return this;\n }\n\n public BaseViewHolder setVisibility(@IdRes int resID, @Visibility int visibility) {\n switch (visibility) {\n case VISIBLE:\n getView(resID).setVisibility(View.VISIBLE);\n break;\n case INVISIBLE:\n getView(resID).setVisibility(View.INVISIBLE);\n break;\n case GONE:\n getView(resID).setVisibility(View.GONE);\n break;\n\n }\n return this;\n\n }\n\n\n @IntDef({VISIBLE, INVISIBLE, GONE})\n @Retention(RetentionPolicy.SOURCE)\n public @interface Visibility {\n }\n\n public static final int VISIBLE = 0x00000000;\n public static final int INVISIBLE = 0x00000004;\n\n public static final int GONE = 0x00000008;\n\n\n}", "public class L {\n\n private static boolean isDEBUG = true;\n\n\n public static void debug(boolean debug) {\n isDEBUG = debug;\n }\n\n public static void i(String value) {\n if (isDEBUG) {\n LogUtils.i(value);\n }\n }\n\n public static void i(String key, String value) {\n if (isDEBUG) {\n Log.i(key, value);\n }\n }\n\n public static void d(String value) {\n if (isDEBUG) {\n LogUtils.d(value);\n }\n }\n\n\n public static void e(String value) {\n if (isDEBUG) {\n LogUtils.e(value);\n }\n }\n\n public static void v(String value) {\n if (isDEBUG) {\n LogUtils.v(value);\n }\n }\n\n\n /**\n * 打印json\n *\n * @param value\n */\n public static void json(String value) {\n if (isDEBUG) {\n LogUtils.json(value);\n }\n }\n}", "public class LoadMoreRecyclerView extends RecyclerView {\n\n /**\n * 监听到底部的接口\n */\n private OnLoadMoreListener onLoadMoreListener;\n\n /**\n * 正在加载更多\n */\n public static final int STATE_START_LOADMORE = 100;\n\n /**\n * 加载完成\n */\n public static final int STATE_FINISH_LOADMORE = 90;\n /**\n * 加载更多的状态开关\n */\n public boolean canLOADMORE = true;\n\n /**\n * 加载更多时候的状态\n */\n private int loadmore_state;\n\n\n /**\n * layoutManager的类型(枚举)\n */\n protected LAYOUT_MANAGER_TYPE layoutManagerType;\n\n /**\n * 最后一个的位置\n */\n private int[] lastPositions;\n\n /**\n * 最后一个可见的item的位置\n */\n private int lastVisibleItemPosition;\n\n\n /**\n * 当前滑动的状态\n */\n private int currentScrollState = 0;\n\n public static enum LAYOUT_MANAGER_TYPE {\n LINEAR,\n GRID,\n STAGGERED_GRID\n }\n\n\n public LoadMoreRecyclerView(Context context) {\n super(context);\n }\n\n public LoadMoreRecyclerView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public LoadMoreRecyclerView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n }\n\n\n @Override\n public void setOnScrollListener(OnScrollListener listener) {\n super.setOnScrollListener(listener);\n\n }\n\n public boolean isCanLOADMORE() {\n return canLOADMORE;\n }\n\n public void setCanLOADMORE(boolean canLOADMORE) {\n this.canLOADMORE = canLOADMORE;\n }\n\n @Override\n public void onScrolled(int dx, int dy) {\n super.onScrolled(dx, dy);\n\n LayoutManager layoutManager = getLayoutManager(); //拿到layoutmanager用来判断类型,拿到最后一个可见的view\n if (layoutManagerType == null) {\n if (layoutManager instanceof LinearLayoutManager) {\n layoutManagerType = LAYOUT_MANAGER_TYPE.LINEAR;\n } else if (layoutManager instanceof GridLayoutManager) {\n layoutManagerType = LAYOUT_MANAGER_TYPE.GRID;\n } else if (layoutManager instanceof StaggeredGridLayoutManager) {\n layoutManagerType = LAYOUT_MANAGER_TYPE.STAGGERED_GRID;\n } else {\n throw new RuntimeException(\n \"不支持的LayoutManager ,目前只支持 LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager\");\n }\n }\n /**\n * 拿到最后一个可见的view\n */\n switch (layoutManagerType) {\n case LINEAR:\n lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();\n break;\n case GRID:\n lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();\n break;\n case STAGGERED_GRID:\n StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;\n if (lastPositions == null) {\n lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];\n }\n staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);\n lastVisibleItemPosition = findMax(lastPositions);\n break;\n }\n }\n\n @Override\n public void onScrollStateChanged(int state) {\n super.onScrollStateChanged(state);\n if (!canLOADMORE)\n return;\n if (loadmore_state == STATE_START_LOADMORE) //如果正在加载更多, 则直接return\n return;\n currentScrollState = state;\n LayoutManager layoutManager = getLayoutManager();\n int visibleItemCount = layoutManager.getChildCount();\n int totalItemCount = layoutManager.getItemCount();\n if ((visibleItemCount > 0 && currentScrollState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItemPosition) >= totalItemCount - 1)) {\n loadmore_state = STATE_START_LOADMORE;\n onLoadMoreListener.onLoadMore();\n }\n }\n\n\n private int findMax(int[] lastPositions) {\n int max = lastPositions[0];\n for (int value : lastPositions) {\n if (value > max) {\n max = value;\n }\n }\n return max;\n }\n\n public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {\n this.onLoadMoreListener = onLoadMoreListener;\n }\n\n public void setLoadmore_state(int loadmore_state) {\n this.loadmore_state = loadmore_state;\n }\n\n public interface OnLoadMoreListener {\n void onLoadMore();\n }\n}", "public class MultiStateView extends FrameLayout {\n private static final int UNKNOWN_VIEW = -1;\n\n private static final int CONTENT_VIEW = 0;\n\n private static final int ERROR_VIEW = 1;\n\n private static final int EMPTY_VIEW = 2;\n\n private static final int LOADING_VIEW = 3;\n\n public enum ViewState {\n CONTENT,\n LOADING,\n EMPTY,\n ERROR\n }\n\n private LayoutInflater mInflater;\n\n private View mContentView;\n\n private View mLoadingView;\n\n private View mErrorView;\n\n private View mEmptyView;\n\n private ViewState mViewState = ViewState.CONTENT;\n\n public MultiStateView(Context context) {\n this(context, null);\n }\n\n public MultiStateView(Context context, AttributeSet attrs) {\n super(context, attrs);\n init(attrs);\n }\n\n public MultiStateView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n init(attrs);\n }\n\n private void init(AttributeSet attrs) {\n mInflater = LayoutInflater.from(getContext());\n TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MultiStateView);\n\n int loadingViewResId = a.getResourceId(R.styleable.MultiStateView_msv_loadingView, -1);\n if (loadingViewResId > -1) {\n mLoadingView = mInflater.inflate(loadingViewResId, this, false);\n addView(mLoadingView, mLoadingView.getLayoutParams());\n }\n\n int emptyViewResId = a.getResourceId(R.styleable.MultiStateView_msv_emptyView, -1);\n if (emptyViewResId > -1) {\n mEmptyView = mInflater.inflate(emptyViewResId, this, false);\n addView(mEmptyView, mEmptyView.getLayoutParams());\n }\n\n int errorViewResId = a.getResourceId(R.styleable.MultiStateView_msv_errorView, -1);\n if (errorViewResId > -1) {\n mErrorView = mInflater.inflate(errorViewResId, this, false);\n addView(mErrorView, mErrorView.getLayoutParams());\n }\n\n int viewState = a.getInt(R.styleable.MultiStateView_msv_viewState, UNKNOWN_VIEW);\n if (viewState != UNKNOWN_VIEW) {\n switch (viewState) {\n case CONTENT_VIEW:\n mViewState = ViewState.CONTENT;\n break;\n\n case ERROR_VIEW:\n mViewState = ViewState.EMPTY;\n break;\n\n case EMPTY_VIEW:\n mViewState = ViewState.EMPTY;\n break;\n\n case LOADING_VIEW:\n mViewState = ViewState.LOADING;\n break;\n }\n }\n\n a.recycle();\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n if (mContentView == null) throw new IllegalArgumentException(\"Content view is not defined\");\n setView();\n }\n\n /* All of the addView methods have been overridden so that it can obtain the content view via XML\n It is NOT recommended to add views into MultiStateView via the addView methods, but rather use\n any of the setViewForState methods to set views for their given ViewState accordingly */\n @Override\n public void addView(View child) {\n if (isValidContentView(child)) mContentView = child;\n super.addView(child);\n }\n\n @Override\n public void addView(View child, int index) {\n if (isValidContentView(child)) mContentView = child;\n super.addView(child, index);\n }\n\n @Override\n public void addView(View child, int index, ViewGroup.LayoutParams params) {\n if (isValidContentView(child)) mContentView = child;\n super.addView(child, index, params);\n }\n\n @Override\n public void addView(View child, ViewGroup.LayoutParams params) {\n if (isValidContentView(child)) mContentView = child;\n super.addView(child, params);\n }\n\n @Override\n public void addView(View child, int width, int height) {\n if (isValidContentView(child)) mContentView = child;\n super.addView(child, width, height);\n }\n\n @Override\n protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params) {\n if (isValidContentView(child)) mContentView = child;\n return super.addViewInLayout(child, index, params);\n }\n\n @Override\n protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) {\n if (isValidContentView(child)) mContentView = child;\n return super.addViewInLayout(child, index, params, preventRequestLayout);\n }\n\n\n public View getView(ViewState state) {\n switch (state) {\n case LOADING:\n return mLoadingView;\n\n case CONTENT:\n return mContentView;\n\n case EMPTY:\n return mEmptyView;\n\n case ERROR:\n return mErrorView;\n\n default:\n return null;\n }\n }\n\n\n public ViewState getViewState() {\n return mViewState;\n }\n\n\n public void setViewState(ViewState state) {\n if (state != mViewState) {\n mViewState = state;\n setView();\n }\n }\n\n\n private void setView() {\n switch (mViewState) {\n case LOADING:\n if (mLoadingView == null) {\n throw new NullPointerException(\"Loading View\");\n }\n\n mLoadingView.setVisibility(View.VISIBLE);\n if (mContentView != null) mContentView.setVisibility(View.GONE);\n if (mErrorView != null) mErrorView.setVisibility(View.GONE);\n if (mEmptyView != null) mEmptyView.setVisibility(View.GONE);\n break;\n\n case EMPTY:\n if (mEmptyView == null) {\n throw new NullPointerException(\"Empty View\");\n }\n\n mEmptyView.setVisibility(View.VISIBLE);\n if (mLoadingView != null) mLoadingView.setVisibility(View.GONE);\n if (mErrorView != null) mErrorView.setVisibility(View.GONE);\n if (mContentView != null) mContentView.setVisibility(View.GONE);\n break;\n\n case ERROR:\n if (mErrorView == null) {\n throw new NullPointerException(\"Error View\");\n }\n\n mErrorView.setVisibility(View.VISIBLE);\n if (mLoadingView != null) mLoadingView.setVisibility(View.GONE);\n if (mContentView != null) mContentView.setVisibility(View.GONE);\n if (mEmptyView != null) mEmptyView.setVisibility(View.GONE);\n break;\n\n case CONTENT:\n default:\n if (mContentView == null) {\n // Should never happen, the view should throw an exception if no content view is present upon creation\n throw new NullPointerException(\"Content View\");\n }\n\n mContentView.setVisibility(View.VISIBLE);\n if (mLoadingView != null) mLoadingView.setVisibility(View.GONE);\n if (mErrorView != null) mErrorView.setVisibility(View.GONE);\n if (mEmptyView != null) mEmptyView.setVisibility(View.GONE);\n break;\n }\n }\n\n /**\n * Checks if the given {@link View} is valid for the Content View\n *\n * @param view The {@link View} to check\n * @return\n */\n private boolean isValidContentView(View view) {\n if (mContentView != null && mContentView != view) {\n return false;\n }\n\n return view != mLoadingView && view != mErrorView && view != mEmptyView;\n }\n\n\n public void setViewForState(View view, ViewState state, boolean switchToState) {\n switch (state) {\n case LOADING:\n if (mLoadingView != null) removeView(mLoadingView);\n mLoadingView = view;\n addView(mLoadingView);\n break;\n\n case EMPTY:\n if (mEmptyView != null) removeView(mEmptyView);\n mEmptyView = view;\n addView(mEmptyView);\n break;\n\n case ERROR:\n if (mErrorView != null) removeView(mErrorView);\n mErrorView = view;\n addView(mErrorView);\n break;\n\n case CONTENT:\n if (mContentView != null) removeView(mContentView);\n mContentView = view;\n addView(mContentView);\n break;\n }\n\n if (switchToState) setViewState(state);\n }\n\n\n public void setViewForState(View view, ViewState state) {\n setViewForState(view, state, false);\n }\n\n\n public void setViewForState(int layoutRes, ViewState state, boolean switchToState) {\n if (mInflater == null) mInflater = LayoutInflater.from(getContext());\n View view = mInflater.inflate(layoutRes, this, false);\n setViewForState(view, state, switchToState);\n }\n\n\n public void setViewForState(int layoutRes, ViewState state) {\n setViewForState(layoutRes, state, false);\n }\n}", "public class AnswersActivity extends RxAppCompatActivity {\n\n\n public static final String QUESTION_URL = \"question_url\";\n private String mQuestionUrl;\n private RecyclerView mRecyclerView;\n private List<AnswersModel> mLists = new ArrayList<>();\n private SwipeRefreshLayout mRefresh;\n private MultiStateView mStateView;\n private String title;\n private String detail;\n private LinearLayoutManager linearLayoutManager;\n private Toolbar mToolBar;\n private boolean isSaved; //已经收藏了\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_answers);\n mRecyclerView = (RecyclerView) findViewById(R.id.activity_answers_rv);\n mRefresh = (SwipeRefreshLayout) findViewById(R.id.activity_answers_refresh);\n mStateView = (MultiStateView) findViewById(R.id.activity_answers_state);\n mToolBar = (Toolbar) findViewById(R.id.activity_answers_toolbar);\n mQuestionUrl = getIntent().getStringExtra(QUESTION_URL);\n initView();\n initStateView();\n }\n\n\n private void initView() {\n setTitle(false);\n\n\n mToolBar.setNavigationIcon(ContextCompat.getDrawable(this,R.drawable.ic_back));\n setSupportActionBar(mToolBar);\n mToolBar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onBackPressed();\n }\n });\n\n\n mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n\n @Override\n public void onRefresh() {\n initData(false);\n }\n });\n\n initData(true);\n }\n\n private void setTitle(boolean show) {\n if (show) {\n mToolBar.setTitle(title);\n } else {\n mToolBar.setTitle(\"\");\n }\n }\n\n public void initData(final boolean needState) {\n if (needState) {\n mStateView.setViewState(MultiStateView.ViewState.LOADING);\n }\n final String url = mQuestionUrl;\n Observable.create(new Observable.OnSubscribe<Document>() {\n @Override\n public void call(Subscriber<? super Document> subscriber) {\n\n try {\n subscriber.onNext(Jsoup.connect(url + \"#zh-question-collapsed-wrap\").timeout(5000).userAgent(\"Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\").get());\n subscriber.onCompleted();\n } catch (IOException e) {\n e.printStackTrace();\n subscriber.onError(e);\n }\n }\n }).map(new Func1<Document, List<AnswersModel>>() {\n @Override\n public List<AnswersModel> call(Document document) {\n\n List<AnswersModel> list = new ArrayList<>();\n\n\n Element titleLink = document.getElementById(\"zh-question-title\");\n Element detailLink = document.getElementById(\"zh-question-detail\");\n String title = titleLink.select(\"span.zm-editable-content\").text();\n String detailHtml = detailLink.select(\"div.zm-editable-content\").html();\n AnswersActivity.this.title = title;\n detail = detailHtml;\n\n\n Element bodyAnswer = document.getElementById(\"zh-question-answer-wrap\");\n Elements bodys = bodyAnswer.select(\"div.zm-item-answer\");\n Element bodyWrapAnswer = document.getElementById(\"zh-question-collapsed-wrap\");\n bodys.addAll(bodyWrapAnswer.select(\"div.zm-item-answer.zm-item-expanded\"));\n\n if (bodys.iterator().hasNext()) {\n Iterator iterator = bodys.iterator();\n while (iterator.hasNext()) {\n AnswersModel answersModel = new AnswersModel();\n Element element = (Element) iterator.next();\n String url = element.getElementsByTag(\"link\").attr(\"href\");\n String vote = element.select(\"span.count\").text();\n String content = element.select(\"div.zh-summary.summary.clearfix\").text();\n if (content.length() > 4) {\n content = content.substring(0, content.length() - 4);\n }\n String user = element.select(\"a.author-link\").text();\n answersModel.setAuthor(user);\n answersModel.setContent(content);\n answersModel.setUrl(url);\n answersModel.setVote(vote);\n list.add(answersModel);\n\n }\n }\n\n return list;\n }\n }).compose(this.<List<AnswersModel>>bindUntilEvent(ActivityEvent.DESTROY))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Subscriber<List<AnswersModel>>() {\n\n\n @Override\n public void onCompleted() {\n\n if (mStateView.getViewState() != MultiStateView.ViewState.CONTENT) {\n mStateView.setViewState(MultiStateView.ViewState.CONTENT);\n }\n\n mRefresh.setRefreshing(false);\n\n initRecyclerView();\n }\n\n @Override\n public void onError(Throwable e) {\n if (needState) {\n mStateView.setViewState(MultiStateView.ViewState.ERROR);\n }\n mRefresh.setRefreshing(false);\n\n\n }\n\n @Override\n public void onStart() {\n super.onStart();\n }\n\n @Override\n public void onNext(List<AnswersModel> s) {\n mLists.clear();\n mLists.addAll(s);\n\n }\n });\n\n\n }\n\n private void initRecyclerView() {\n if (mRecyclerView.getAdapter() == null) {\n linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);\n mRecyclerView.setLayoutManager(linearLayoutManager);\n mRecyclerView.setAdapter(new BaseAdapter() {\n @Override\n public void onBindView(BaseViewHolder holder, int position) {\n\n if (position == 0) {\n holder.setText(R.id.item_fr_answers_top_title, title)\n .setVisibility(R.id.item_fr_answers_top_body, TextUtils.isEmpty(detail) ? BaseViewHolder.GONE : BaseViewHolder.VISIBLE)\n .setText(R.id.item_fr_answers_top_body, Html.fromHtml(detail).toString())\n .setText(R.id.item_fr_answers_top_count, mLists.size() + \"个回答(只抽取前\" + mLists.size() + \"个)\");\n\n } else {\n AnswersModel answers = mLists.get(position - 1);\n holder.setText(R.id.item_fr_answers_author, TextUtils.isEmpty(answers.getAuthor()) ? \"匿名\" : answers.getAuthor())\n .setText(R.id.item_fr_answers_body, answers.getContent())\n .setText(R.id.item_fr_answers_vote, answers.getVote() + \" 赞同\");\n\n }\n }\n\n @Override\n public int getLayoutID(int position) {\n if (position == 0)\n return R.layout.item_answers_top_activity;\n return R.layout.item_answers_activity;\n }\n\n @Override\n public boolean clickable() {\n return true;\n }\n\n @Override\n public void onItemClick(View v, int position) {\n super.onItemClick(v, position);\n if (position == 0)\n return;\n Intent intent = new Intent(AnswersActivity.this, AnswerDetailActivity.class);\n intent.putExtra(AnswerDetailActivity.URL, mLists.get(position - 1).getUrl());\n intent.putExtra(AnswerDetailActivity.TITLE, title);\n intent.putExtra(AnswerDetailActivity.DETAIL, detail);\n\n startActivity(intent);\n\n }\n\n @Override\n public int getItemCount() {\n return mLists.size() + 1;\n }\n });\n\n mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n if (linearLayoutManager.findFirstVisibleItemPosition() != 0) {\n setTitle(true);\n } else {\n setTitle(false);\n }\n }\n });\n } else {\n mRecyclerView.getAdapter().notifyDataSetChanged();\n }\n }\n\n\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main_answer, menu);\n return true;\n }\n\n\n @Override\n public boolean onPrepareOptionsMenu(final Menu menu) {\n\n CollectionUtils.getInstance().contailItem(mQuestionUrl).compose(this.<Collection>bindUntilEvent(ActivityEvent.DESTROY))\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Action1<Collection>() {\n @Override\n public void call(Collection model) {\n isSaved = true;\n menu.findItem(R.id.save).setIcon(ContextCompat.getDrawable(AnswersActivity.this,R.drawable.ic_save));\n }\n });\n return super.onPrepareOptionsMenu(menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.save:\n if(mLists.size()==0)\n return true;\n saveCurrentItem();\n if(isSaved) {\n item.setIcon(ContextCompat.getDrawable(AnswersActivity.this, R.drawable.ic_save));\n }else{\n item.setIcon(ContextCompat.getDrawable(AnswersActivity.this, R.drawable.ic_save_normal));\n }\n\n break;\n case R.id.web_look:\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(Uri.parse(mQuestionUrl));\n startActivity(intent);\n break;\n\n }\n\n\n return super.onOptionsItemSelected(item);\n }\n\n private void saveCurrentItem() {\n if(isSaved){\n CollectionUtils.getInstance().removeItem(mQuestionUrl);\n toast(\"取消收藏成功\");\n isSaved = false;\n }else{\n isSaved = true;\n Collection model = new Collection();\n model.setId(System.currentTimeMillis());\n model.setTitle(title);\n model.setDetail(detail);\n model.setType(CollectionUtils.TYPE_ANSWERS);\n model.setUrl(mQuestionUrl);\n CollectionUtils.getInstance().saveItem(model);\n toast(\"收藏成功\");\n\n }\n\n\n }\n\n private void initStateView() {\n LinearLayout error = (LinearLayout) mStateView.findViewById(R.id.error_root_layout);\n error.setClickable(true);\n error.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n initData(true);\n }\n });\n }\n\n\n}", "public class TopicAnswers {\n private String url;\n private String title;\n private String img;\n private String vote;\n private String body;\n\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n }\n\n public String getVote() {\n return vote;\n }\n\n public void setVote(String vote) {\n this.vote = vote;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getImg() {\n return img;\n }\n\n public void setImg(String img) {\n this.img = img;\n }\n\n @Override\n public String toString() {\n return \"url:\" + url + \" :title:\" + title + \" :img:\" + img + \" :vote:\" + vote + \" :body:\" + body;\n }\n}", "public class JSoupUtils {\n\n private static final String TAG = \"JSoupUtils\";\n\n\n\n /**\n * 首页获取列表信息\n * @param document\n * @return\n */\n public static List<TopicAnswers> getTopicList(Document document) {\n Elements contentLinks = document.select(\"div.content\");\n List<TopicAnswers> list = new ArrayList<>();\n Iterator iterator = contentLinks.iterator();\n while (iterator.hasNext()) {\n TopicAnswers answers = new TopicAnswers();\n Element body = (Element) iterator.next();\n Elements questionLinks = body.select(\"a.question_link\");\n if (questionLinks.iterator().hasNext()) {\n Element questionLink = questionLinks.iterator().next();\n answers.setTitle(questionLink.text());\n answers.setUrl(\"https://www.zhihu.com\" + questionLink.attr(\"href\"));\n }\n\n\n Elements votes = body.select(\"a.zm-item-vote-count.js-expand.js-vote-count\");\n if (votes.size() > 0) {\n if (votes.iterator().hasNext()) {\n Element aVotes = votes.iterator().next();\n answers.setVote(aVotes.text());\n }\n }\n\n Elements divs = body.select(\"div.zh-summary.summary.clearfix\");\n\n String descBody = divs.text();\n if (descBody.length() > 4) {\n descBody = descBody.substring(0, descBody.length() - 4);\n }\n answers.setBody(descBody);\n if (divs.size() > 0) {\n if (divs.iterator().hasNext()) {\n Element aDiv = divs.iterator().next();\n\n Element img = aDiv.children().first();\n if (img.tagName().equals(\"img\")) {\n String imgUrl = img.attr(\"src\");\n answers.setImg(imgUrl);\n }\n }\n }\n if (!TextUtils.isEmpty(answers.getTitle()) && !TextUtils.isEmpty(answers.getUrl())) {\n L.i(TAG, answers.toString());\n list.add(answers);\n }\n }\n return list;\n }\n\n\n}" ]
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.facebook.drawee.view.SimpleDraweeView; import com.jiang.android.architecture.adapter.BaseAdapter; import com.jiang.android.architecture.adapter.BaseViewHolder; import com.jiang.android.architecture.utils.L; import com.jiang.android.architecture.view.LoadMoreRecyclerView; import com.jiang.android.architecture.view.MultiStateView; import com.jiang.android.zhihu_topanswer.R; import com.jiang.android.zhihu_topanswer.activity.AnswersActivity; import com.jiang.android.zhihu_topanswer.model.TopicAnswers; import com.jiang.android.zhihu_topanswer.utils.JSoupUtils; import com.trello.rxlifecycle.android.FragmentEvent; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers;
package com.jiang.android.zhihu_topanswer.fragment; /** * Created by jiang on 2016/12/23. */ public class RecyclerViewFragment extends BaseFragment { private static final String TAG = "RecyclerViewFragment"; public static final int PAGE_START = 1; private int mPage = PAGE_START; private static final java.lang.String BUNDLE_ID = "bundle_id"; private int mTopic;
private LoadMoreRecyclerView mRecyclerView;
3
CagataySonmez/EdgeCloudSim
src/edu/boun/edgecloudsim/applications/sample_app4/FuzzyExperimentalNetworkModel.java
[ "public class SimManager extends SimEntity {\r\n\tprivate static final int CREATE_TASK = 0;\r\n\tprivate static final int CHECK_ALL_VM = 1;\r\n\tprivate static final int GET_LOAD_LOG = 2;\r\n\tprivate static final int PRINT_PROGRESS = 3;\r\n\tprivate static final int STOP_SIMULATION = 4;\r\n\t\r\n\tprivate String simScenario;\r\n\tprivate String orchestratorPolicy;\r\n\tprivate int numOfMobileDevice;\r\n\tprivate NetworkModel networkModel;\r\n\tprivate MobilityModel mobilityModel;\r\n\tprivate ScenarioFactory scenarioFactory;\r\n\tprivate EdgeOrchestrator edgeOrchestrator;\r\n\tprivate EdgeServerManager edgeServerManager;\r\n\tprivate CloudServerManager cloudServerManager;\r\n\tprivate MobileServerManager mobileServerManager;\r\n\tprivate LoadGeneratorModel loadGeneratorModel;\r\n\tprivate MobileDeviceManager mobileDeviceManager;\r\n\t\r\n\tprivate static SimManager instance = null;\r\n\t\r\n\tpublic SimManager(ScenarioFactory _scenarioFactory, int _numOfMobileDevice, String _simScenario, String _orchestratorPolicy) throws Exception {\r\n\t\tsuper(\"SimManager\");\r\n\t\tsimScenario = _simScenario;\r\n\t\tscenarioFactory = _scenarioFactory;\r\n\t\tnumOfMobileDevice = _numOfMobileDevice;\r\n\t\torchestratorPolicy = _orchestratorPolicy;\r\n\r\n\t\tSimLogger.print(\"Creating tasks...\");\r\n\t\tloadGeneratorModel = scenarioFactory.getLoadGeneratorModel();\r\n\t\tloadGeneratorModel.initializeModel();\r\n\t\tSimLogger.printLine(\"Done, \");\r\n\t\t\r\n\t\tSimLogger.print(\"Creating device locations...\");\r\n\t\tmobilityModel = scenarioFactory.getMobilityModel();\r\n\t\tmobilityModel.initialize();\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\r\n\t\t//Generate network model\r\n\t\tnetworkModel = scenarioFactory.getNetworkModel();\r\n\t\tnetworkModel.initialize();\r\n\t\t\r\n\t\t//Generate edge orchestrator\r\n\t\tedgeOrchestrator = scenarioFactory.getEdgeOrchestrator();\r\n\t\tedgeOrchestrator.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers\r\n\t\tedgeServerManager = scenarioFactory.getEdgeServerManager();\r\n\t\tedgeServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on cloud\r\n\t\tcloudServerManager = scenarioFactory.getCloudServerManager();\r\n\t\tcloudServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on mobile devices\r\n\t\tmobileServerManager = scenarioFactory.getMobileServerManager();\r\n\t\tmobileServerManager.initialize();\r\n\r\n\t\t//Create Client Manager\r\n\t\tmobileDeviceManager = scenarioFactory.getMobileDeviceManager();\r\n\t\tmobileDeviceManager.initialize();\r\n\t\t\r\n\t\tinstance = this;\r\n\t}\r\n\t\r\n\tpublic static SimManager getInstance(){\r\n\t\treturn instance;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Triggering CloudSim to start simulation\r\n\t */\r\n\tpublic void startSimulation() throws Exception{\r\n\t\t//Starts the simulation\r\n\t\tSimLogger.print(super.getName()+\" is starting...\");\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tedgeServerManager.startDatacenters();\r\n\t\tedgeServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tcloudServerManager.startDatacenters();\r\n\t\tcloudServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Mobile Datacenters & Generate VMs\r\n\t\tmobileServerManager.startDatacenters();\r\n\t\tmobileServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\tCloudSim.startSimulation();\r\n\t}\r\n\r\n\tpublic String getSimulationScenario(){\r\n\t\treturn simScenario;\r\n\t}\r\n\r\n\tpublic String getOrchestratorPolicy(){\r\n\t\treturn orchestratorPolicy;\r\n\t}\r\n\t\r\n\tpublic ScenarioFactory getScenarioFactory(){\r\n\t\treturn scenarioFactory;\r\n\t}\r\n\t\r\n\tpublic int getNumOfMobileDevice(){\r\n\t\treturn numOfMobileDevice;\r\n\t}\r\n\t\r\n\tpublic NetworkModel getNetworkModel(){\r\n\t\treturn networkModel;\r\n\t}\r\n\r\n\tpublic MobilityModel getMobilityModel(){\r\n\t\treturn mobilityModel;\r\n\t}\r\n\t\r\n\tpublic EdgeOrchestrator getEdgeOrchestrator(){\r\n\t\treturn edgeOrchestrator;\r\n\t}\r\n\t\r\n\tpublic EdgeServerManager getEdgeServerManager(){\r\n\t\treturn edgeServerManager;\r\n\t}\r\n\t\r\n\tpublic CloudServerManager getCloudServerManager(){\r\n\t\treturn cloudServerManager;\r\n\t}\r\n\t\r\n\tpublic MobileServerManager getMobileServerManager(){\r\n\t\treturn mobileServerManager;\r\n\t}\r\n\r\n\tpublic LoadGeneratorModel getLoadGeneratorModel(){\r\n\t\treturn loadGeneratorModel;\r\n\t}\r\n\t\r\n\tpublic MobileDeviceManager getMobileDeviceManager(){\r\n\t\treturn mobileDeviceManager;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void startEntity() {\r\n\t\tint hostCounter=0;\r\n\r\n\t\tfor(int i= 0; i<edgeServerManager.getDatacenterList().size(); i++) {\r\n\t\t\tList<? extends Host> list = edgeServerManager.getDatacenterList().get(i).getHostList();\r\n\t\t\tfor (int j=0; j < list.size(); j++) {\r\n\t\t\t\tmobileDeviceManager.submitVmList(edgeServerManager.getVmList(hostCounter));\r\n\t\t\t\thostCounter++;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor(int i = 0; i<SimSettings.getInstance().getNumOfCloudHost(); i++) {\r\n\t\t\tmobileDeviceManager.submitVmList(cloudServerManager.getVmList(i));\r\n\t\t}\r\n\r\n\t\tfor(int i=0; i<numOfMobileDevice; i++){\r\n\t\t\tif(mobileServerManager.getVmList(i) != null)\r\n\t\t\t\tmobileDeviceManager.submitVmList(mobileServerManager.getVmList(i));\r\n\t\t}\r\n\t\t\r\n\t\t//Creation of tasks are scheduled here!\r\n\t\tfor(int i=0; i< loadGeneratorModel.getTaskList().size(); i++)\r\n\t\t\tschedule(getId(), loadGeneratorModel.getTaskList().get(i).getStartTime(), CREATE_TASK, loadGeneratorModel.getTaskList().get(i));\r\n\t\t\r\n\t\t//Periodic event loops starts from here!\r\n\t\tschedule(getId(), 5, CHECK_ALL_VM);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime(), STOP_SIMULATION);\r\n\t\t\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void processEvent(SimEvent ev) {\r\n\t\tsynchronized(this){\r\n\t\t\tswitch (ev.getTag()) {\r\n\t\t\tcase CREATE_TASK:\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTaskProperty edgeTask = (TaskProperty) ev.getData();\r\n\t\t\t\t\tmobileDeviceManager.submitTask(edgeTask);\t\t\t\t\t\t\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase CHECK_ALL_VM:\r\n\t\t\t\tint totalNumOfVm = SimSettings.getInstance().getNumOfEdgeVMs();\r\n\t\t\t\tif(EdgeVmAllocationPolicy_Custom.getCreatedVmNum() != totalNumOfVm){\r\n\t\t\t\t\tSimLogger.printLine(\"All VMs cannot be created! Terminating simulation...\");\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase GET_LOAD_LOG:\r\n\t\t\t\tSimLogger.getInstance().addVmUtilizationLog(\r\n\t\t\t\t\t\tCloudSim.clock(),\r\n\t\t\t\t\t\tedgeServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tcloudServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tmobileServerManager.getAvgUtilization());\r\n\t\t\t\t\r\n\t\t\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\t\t\tbreak;\r\n\t\t\tcase PRINT_PROGRESS:\r\n\t\t\t\tint progress = (int)((CloudSim.clock()*100)/SimSettings.getInstance().getSimulationTime());\r\n\t\t\t\tif(progress % 10 == 0)\r\n\t\t\t\t\tSimLogger.print(Integer.toString(progress));\r\n\t\t\t\telse\r\n\t\t\t\t\tSimLogger.print(\".\");\r\n\t\t\t\tif(CloudSim.clock() < SimSettings.getInstance().getSimulationTime())\r\n\t\t\t\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\r\n\t\t\t\tbreak;\r\n\t\t\tcase STOP_SIMULATION:\r\n\t\t\t\tSimLogger.printLine(\"100\");\r\n\t\t\t\tCloudSim.terminateSimulation();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tSimLogger.getInstance().simStopped();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tSimLogger.printLine(getName() + \": unknown event type\");\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void shutdownEntity() {\r\n\t\tedgeServerManager.terminateDatacenters();\r\n\t\tcloudServerManager.terminateDatacenters();\r\n\t\tmobileServerManager.terminateDatacenters();\r\n\t}\r\n}\r", "public class SimSettings {\r\n\tprivate static SimSettings instance = null;\r\n\tprivate Document edgeDevicesDoc = null;\r\n\r\n\tpublic static final double CLIENT_ACTIVITY_START_TIME = 10;\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum VM_TYPES { MOBILE_VM, EDGE_VM, CLOUD_VM }\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum NETWORK_DELAY_TYPES { WLAN_DELAY, MAN_DELAY, WAN_DELAY, GSM_DELAY }\r\n\r\n\t//predifined IDs for the components.\r\n\tpublic static final int CLOUD_DATACENTER_ID = 1000;\r\n\tpublic static final int MOBILE_DATACENTER_ID = 1001;\r\n\tpublic static final int EDGE_ORCHESTRATOR_ID = 1002;\r\n\tpublic static final int GENERIC_EDGE_DEVICE_ID = 1003;\r\n\r\n\t//delimiter for output file.\r\n\tpublic static final String DELIMITER = \";\";\r\n\r\n\tprivate double SIMULATION_TIME; //minutes unit in properties file\r\n\tprivate double WARM_UP_PERIOD; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_VM_LOAD_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_LOCATION_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_AP_DELAY_LOG; //minutes unit in properties file\r\n\tprivate boolean FILE_LOG_ENABLED; //boolean to check file logging option\r\n\tprivate boolean DEEP_FILE_LOG_ENABLED; //boolean to check deep file logging option\r\n\r\n\tprivate int MIN_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MAX_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MOBILE_DEVICE_COUNTER_SIZE;\r\n\tprivate int WLAN_RANGE;\r\n\r\n\tprivate int NUM_OF_EDGE_DATACENTERS;\r\n\tprivate int NUM_OF_EDGE_HOSTS;\r\n\tprivate int NUM_OF_EDGE_VMS;\r\n\tprivate int NUM_OF_PLACE_TYPES;\r\n\r\n\tprivate double WAN_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double GSM_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double LAN_INTERNAL_DELAY; //seconds unit in properties file\r\n\tprivate int BANDWITH_WLAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_MAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_WAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_GSM; //Mbps unit in properties file\r\n\r\n\tprivate int NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\tprivate int NUM_OF_VM_ON_CLOUD_HOST;\r\n\tprivate int CORE_FOR_CLOUD_VM;\r\n\tprivate int MIPS_FOR_CLOUD_VM; //MIPS\r\n\tprivate int RAM_FOR_CLOUD_VM; //MB\r\n\tprivate int STORAGE_FOR_CLOUD_VM; //Byte\r\n\r\n\tprivate int CORE_FOR_VM;\r\n\tprivate int MIPS_FOR_VM; //MIPS\r\n\tprivate int RAM_FOR_VM; //MB\r\n\tprivate int STORAGE_FOR_VM; //Byte\r\n\r\n\tprivate String[] SIMULATION_SCENARIOS;\r\n\tprivate String[] ORCHESTRATOR_POLICIES;\r\n\r\n\tprivate double NORTHERN_BOUND;\r\n\tprivate double EASTERN_BOUND;\r\n\tprivate double SOUTHERN_BOUND;\r\n\tprivate double WESTERN_BOUND;\r\n\r\n\t// mean waiting time (minute) is stored for each place types\r\n\tprivate double[] mobilityLookUpTable;\r\n\r\n\t// following values are stored for each applications defined in applications.xml\r\n\t// [0] usage percentage (%)\r\n\t// [1] prob. of selecting cloud (%)\r\n\t// [2] poisson mean (sec)\r\n\t// [3] active period (sec)\r\n\t// [4] idle period (sec)\r\n\t// [5] avg data upload (KB)\r\n\t// [6] avg data download (KB)\r\n\t// [7] avg task length (MI)\r\n\t// [8] required # of cores\r\n\t// [9] vm utilization on edge (%)\r\n\t// [10] vm utilization on cloud (%)\r\n\t// [11] vm utilization on mobile (%)\r\n\t// [12] delay sensitivity [0-1]\r\n\tprivate double[][] taskLookUpTable = null;\r\n\r\n\tprivate String[] taskNames = null;\r\n\r\n\tprivate SimSettings() {\r\n\t\tNUM_OF_PLACE_TYPES = 0;\r\n\t}\r\n\r\n\tpublic static SimSettings getInstance() {\r\n\t\tif(instance == null) {\r\n\t\t\tinstance = new SimSettings();\r\n\t\t}\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t/**\r\n\t * Reads configuration file and stores information to local variables\r\n\t * @param propertiesFile\r\n\t * @return\r\n\t */\r\n\tpublic boolean initialize(String propertiesFile, String edgeDevicesFile, String applicationsFile){\r\n\t\tboolean result = false;\r\n\t\tInputStream input = null;\r\n\t\ttry {\r\n\t\t\tinput = new FileInputStream(propertiesFile);\r\n\r\n\t\t\t// load a properties file\r\n\t\t\tProperties prop = new Properties();\r\n\t\t\tprop.load(input);\r\n\r\n\t\t\tSIMULATION_TIME = (double)60 * Double.parseDouble(prop.getProperty(\"simulation_time\")); //seconds\r\n\t\t\tWARM_UP_PERIOD = (double)60 * Double.parseDouble(prop.getProperty(\"warm_up_period\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_VM_LOAD_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"vm_load_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_LOCATION_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"location_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_AP_DELAY_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"ap_delay_check_interval\", \"0\")); //seconds\t\t\r\n\t\t\tFILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"file_log_enabled\"));\r\n\t\t\tDEEP_FILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"deep_file_log_enabled\"));\r\n\r\n\t\t\tMIN_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"min_number_of_mobile_devices\"));\r\n\t\t\tMAX_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"max_number_of_mobile_devices\"));\r\n\t\t\tMOBILE_DEVICE_COUNTER_SIZE = Integer.parseInt(prop.getProperty(\"mobile_device_counter_size\"));\r\n\t\t\tWLAN_RANGE = Integer.parseInt(prop.getProperty(\"wlan_range\", \"0\"));\r\n\r\n\t\t\tWAN_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"wan_propagation_delay\", \"0\"));\r\n\t\t\tGSM_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"gsm_propagation_delay\", \"0\"));\r\n\t\t\tLAN_INTERNAL_DELAY = Double.parseDouble(prop.getProperty(\"lan_internal_delay\", \"0\"));\r\n\t\t\tBANDWITH_WLAN = 1000 * Integer.parseInt(prop.getProperty(\"wlan_bandwidth\"));\r\n\t\t\tBANDWITH_MAN = 1000 * Integer.parseInt(prop.getProperty(\"man_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_WAN = 1000 * Integer.parseInt(prop.getProperty(\"wan_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_GSM = 1000 * Integer.parseInt(prop.getProperty(\"gsm_bandwidth\", \"0\"));\r\n\r\n\t\t\tNUM_OF_HOST_ON_CLOUD_DATACENTER = Integer.parseInt(prop.getProperty(\"number_of_host_on_cloud_datacenter\"));\r\n\t\t\tNUM_OF_VM_ON_CLOUD_HOST = Integer.parseInt(prop.getProperty(\"number_of_vm_on_cloud_host\"));\r\n\t\t\tCORE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"core_for_cloud_vm\"));\r\n\t\t\tMIPS_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"mips_for_cloud_vm\"));\r\n\t\t\tRAM_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"ram_for_cloud_vm\"));\r\n\t\t\tSTORAGE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"storage_for_cloud_vm\"));\r\n\r\n\t\t\tRAM_FOR_VM = Integer.parseInt(prop.getProperty(\"ram_for_mobile_vm\"));\r\n\t\t\tCORE_FOR_VM = Integer.parseInt(prop.getProperty(\"core_for_mobile_vm\"));\r\n\t\t\tMIPS_FOR_VM = Integer.parseInt(prop.getProperty(\"mips_for_mobile_vm\"));\r\n\t\t\tSTORAGE_FOR_VM = Integer.parseInt(prop.getProperty(\"storage_for_mobile_vm\"));\r\n\r\n\t\t\tORCHESTRATOR_POLICIES = prop.getProperty(\"orchestrator_policies\").split(\",\");\r\n\r\n\t\t\tSIMULATION_SCENARIOS = prop.getProperty(\"simulation_scenarios\").split(\",\");\r\n\r\n\t\t\tNORTHERN_BOUND = Double.parseDouble(prop.getProperty(\"northern_bound\", \"0\"));\r\n\t\t\tSOUTHERN_BOUND = Double.parseDouble(prop.getProperty(\"southern_bound\", \"0\"));\r\n\t\t\tEASTERN_BOUND = Double.parseDouble(prop.getProperty(\"eastern_bound\", \"0\"));\r\n\t\t\tWESTERN_BOUND = Double.parseDouble(prop.getProperty(\"western_bound\", \"0\"));\r\n\r\n\t\t\t//avg waiting time in a place (min)\r\n\t\t\tdouble place1_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L1_mean_waiting_time\"));\r\n\t\t\tdouble place2_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L2_mean_waiting_time\"));\r\n\t\t\tdouble place3_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L3_mean_waiting_time\"));\r\n\r\n\t\t\t//mean waiting time (minute)\r\n\t\t\tmobilityLookUpTable = new double[]{\r\n\t\t\t\t\tplace1_mean_waiting_time, //ATTRACTIVENESS_L1\r\n\t\t\t\t\tplace2_mean_waiting_time, //ATTRACTIVENESS_L2\r\n\t\t\t\t\tplace3_mean_waiting_time //ATTRACTIVENESS_L3\r\n\t\t\t};\r\n\r\n\r\n\t\t} catch (IOException ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (input != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t\tresult = true;\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tparseApplicationsXML(applicationsFile);\r\n\t\tparseEdgeDevicesXML(edgeDevicesFile);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the parsed XML document for edge_devices.xml\r\n\t */\r\n\tpublic Document getEdgeDevicesDocument(){\r\n\t\treturn edgeDevicesDoc;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * returns simulation time (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getSimulationTime()\r\n\t{\r\n\t\treturn SIMULATION_TIME;\r\n\t}\r\n\r\n\t/**\r\n\t * returns warm up period (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getWarmUpPeriod()\r\n\t{\r\n\t\treturn WARM_UP_PERIOD; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM utilization log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getVmLoadLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_VM_LOAD_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getLocationLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_LOCATION_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getApDelayLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_AP_DELAY_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getDeepFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED && DEEP_FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getWanPropagationDelay()\r\n\t{\r\n\t\treturn WAN_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getGsmPropagationDelay()\r\n\t{\r\n\t\treturn GSM_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns internal LAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getInternalLanDelay()\r\n\t{\r\n\t\treturn LAN_INTERNAL_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WLAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWlanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WLAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getManBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_MAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WAN; \r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getGsmBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_GSM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the minimum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMinNumOfMobileDev()\r\n\t{\r\n\t\treturn MIN_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the maximum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMaxNumOfMobileDev()\r\n\t{\r\n\t\treturn MAX_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of increase on mobile devices\r\n\t * while iterating from min to max mobile device\r\n\t */\r\n\tpublic int getMobileDevCounterSize()\r\n\t{\r\n\t\treturn MOBILE_DEVICE_COUNTER_SIZE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns edge device range in meter\r\n\t */\r\n\tpublic int getWlanRange()\r\n\t{\r\n\t\treturn WLAN_RANGE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeDatacenters()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_DATACENTERS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge hosts running on the datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeHosts()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_HOSTS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge VMs running on the hosts\r\n\t */\r\n\tpublic int getNumOfEdgeVMs()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_VMS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of different place types\r\n\t */\r\n\tpublic int getNumOfPlaceTypes()\r\n\t{\r\n\t\treturn NUM_OF_PLACE_TYPES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud datacenters\r\n\t */\r\n\tpublic int getNumOfCloudHost()\r\n\t{\r\n\t\treturn NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud VMs per Host\r\n\t */\r\n\tpublic int getNumOfCloudVMsPerHost()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the total number of cloud VMs\r\n\t */\r\n\tpublic int getNumOfCloudVMs()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST * NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for cloud VMs\r\n\t */\r\n\tpublic int getCoreForCloudVM()\r\n\t{\r\n\t\treturn CORE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the central cloud VMs\r\n\t */\r\n\tpublic int getMipsForCloudVM()\r\n\t{\r\n\t\treturn MIPS_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the central cloud VMs\r\n\t */\r\n\tpublic int getRamForCloudVM()\r\n\t{\r\n\t\treturn RAM_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the central cloud VMs\r\n\t */\r\n\tpublic int getStorageForCloudVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getRamForMobileVM()\r\n\t{\r\n\t\treturn RAM_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for mobile VMs\r\n\t */\r\n\tpublic int getCoreForMobileVM()\r\n\t{\r\n\t\treturn CORE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getMipsForMobileVM()\r\n\t{\r\n\t\treturn MIPS_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getStorageForMobileVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns simulation screnarios as string\r\n\t */\r\n\tpublic String[] getSimulationScenarios()\r\n\t{\r\n\t\treturn SIMULATION_SCENARIOS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns orchestrator policies as string\r\n\t */\r\n\tpublic String[] getOrchestratorPolicies()\r\n\t{\r\n\t\treturn ORCHESTRATOR_POLICIES;\r\n\t}\r\n\r\n\r\n\tpublic double getNorthernBound() {\r\n\t\treturn NORTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getEasternBound() {\r\n\t\treturn EASTERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getSouthernBound() {\r\n\t\treturn SOUTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getWesternBound() {\r\n\t\treturn WESTERN_BOUND;\r\n\t}\r\n\r\n\t/**\r\n\t * returns mobility characteristic within an array\r\n\t * the result includes mean waiting time (minute) or each place type\r\n\t */ \r\n\tpublic double[] getMobilityLookUpTable()\r\n\t{\r\n\t\treturn mobilityLookUpTable;\r\n\t}\r\n\r\n\t/**\r\n\t * returns application characteristic within two dimensional array\r\n\t * the result includes the following values for each application type\r\n\t * [0] usage percentage (%)\r\n\t * [1] prob. of selecting cloud (%)\r\n\t * [2] poisson mean (sec)\r\n\t * [3] active period (sec)\r\n\t * [4] idle period (sec)\r\n\t * [5] avg data upload (KB)\r\n\t * [6] avg data download (KB)\r\n\t * [7] avg task length (MI)\r\n\t * [8] required # of cores\r\n\t * [9] vm utilization on edge (%)\r\n\t * [10] vm utilization on cloud (%)\r\n\t * [11] vm utilization on mobile (%)\r\n\t * [12] delay sensitivity [0-1]\r\n\t * [13] maximum delay requirement (sec)\r\n\t */ \r\n\tpublic double[][] getTaskLookUpTable()\r\n\t{\r\n\t\treturn taskLookUpTable;\r\n\t}\r\n\r\n\tpublic double[] getTaskProperties(String taskName) {\r\n\t\tdouble[] result = null;\r\n\t\tint index = -1;\r\n\t\tfor (int i=0;i<taskNames.length;i++) {\r\n\t\t\tif (taskNames[i].equals(taskName)) {\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(index >= 0 && index < taskLookUpTable.length)\r\n\t\t\tresult = taskLookUpTable[index];\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic String getTaskName(int taskType)\r\n\t{\r\n\t\treturn taskNames[taskType];\r\n\t}\r\n\r\n\tprivate void isAttributePresent(Element element, String key) {\r\n\t\tString value = element.getAttribute(key);\r\n\t\tif (value.isEmpty() || value == null){\r\n\t\t\tthrow new IllegalArgumentException(\"Attribute '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void isElementPresent(Element element, String key) {\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate Boolean checkElement(Element element, String key) {\r\n\t\tBoolean result = true;\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tresult = false;\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tresult = false;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate void parseApplicationsXML(String filePath)\r\n\t{\r\n\t\tDocument doc = null;\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tdoc = dBuilder.parse(devicesFile);\r\n\t\t\tdoc.getDocumentElement().normalize();\r\n\r\n\t\t\tString mandatoryAttributes[] = {\r\n\t\t\t\t\t\"usage_percentage\", //usage percentage [0-100]\r\n\t\t\t\t\t\"prob_cloud_selection\", //prob. of selecting cloud [0-100]\r\n\t\t\t\t\t\"poisson_interarrival\", //poisson mean (sec)\r\n\t\t\t\t\t\"active_period\", //active period (sec)\r\n\t\t\t\t\t\"idle_period\", //idle period (sec)\r\n\t\t\t\t\t\"data_upload\", //avg data upload (KB)\r\n\t\t\t\t\t\"data_download\", //avg data download (KB)\r\n\t\t\t\t\t\"task_length\", //avg task length (MI)\r\n\t\t\t\t\t\"required_core\", //required # of core\r\n\t\t\t\t\t\"vm_utilization_on_edge\", //vm utilization on edge vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_cloud\", //vm utilization on cloud vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_mobile\", //vm utilization on mobile vm [0-100]\r\n\t\t\t\"delay_sensitivity\"}; //delay_sensitivity [0-1]\r\n\r\n\t\t\tString optionalAttributes[] = {\r\n\t\t\t\"max_delay_requirement\"}; //maximum delay requirement (sec)\r\n\r\n\t\t\tNodeList appList = doc.getElementsByTagName(\"application\");\r\n\t\t\ttaskLookUpTable = new double[appList.getLength()]\r\n\t\t\t\t\t[mandatoryAttributes.length + optionalAttributes.length];\r\n\r\n\t\t\ttaskNames = new String[appList.getLength()];\r\n\t\t\tfor (int i = 0; i < appList.getLength(); i++) {\r\n\t\t\t\tNode appNode = appList.item(i);\r\n\r\n\t\t\t\tElement appElement = (Element) appNode;\r\n\t\t\t\tisAttributePresent(appElement, \"name\");\r\n\t\t\t\tString taskName = appElement.getAttribute(\"name\");\r\n\t\t\t\ttaskNames[i] = taskName;\r\n\r\n\t\t\t\tfor(int m=0; m<mandatoryAttributes.length; m++){\r\n\t\t\t\t\tisElementPresent(appElement, mandatoryAttributes[m]);\r\n\t\t\t\t\ttaskLookUpTable[i][m] = Double.parseDouble(appElement.\r\n\t\t\t\t\t\t\tgetElementsByTagName(mandatoryAttributes[m]).item(0).getTextContent());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor(int o=0; o<optionalAttributes.length; o++){\r\n\t\t\t\t\tdouble value = 0;\r\n\t\t\t\t\tif(checkElement(appElement, optionalAttributes[o]))\r\n\t\t\t\t\t\tvalue = Double.parseDouble(appElement.getElementsByTagName(optionalAttributes[o]).item(0).getTextContent());\r\n\r\n\t\t\t\t\ttaskLookUpTable[i][mandatoryAttributes.length + o] = value;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void parseEdgeDevicesXML(String filePath)\r\n\t{\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tedgeDevicesDoc = dBuilder.parse(devicesFile);\r\n\t\t\tedgeDevicesDoc.getDocumentElement().normalize();\r\n\r\n\t\t\tNodeList datacenterList = edgeDevicesDoc.getElementsByTagName(\"datacenter\");\r\n\t\t\tfor (int i = 0; i < datacenterList.getLength(); i++) {\r\n\t\t\t\tNUM_OF_EDGE_DATACENTERS++;\r\n\t\t\t\tNode datacenterNode = datacenterList.item(i);\r\n\r\n\t\t\t\tElement datacenterElement = (Element) datacenterNode;\r\n\t\t\t\tisAttributePresent(datacenterElement, \"arch\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"os\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"vmm\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerBw\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerSec\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerMem\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerStorage\");\r\n\r\n\t\t\t\tElement location = (Element)datacenterElement.getElementsByTagName(\"location\").item(0);\r\n\t\t\t\tisElementPresent(location, \"attractiveness\");\r\n\t\t\t\tisElementPresent(location, \"wlan_id\");\r\n\t\t\t\tisElementPresent(location, \"x_pos\");\r\n\t\t\t\tisElementPresent(location, \"y_pos\");\r\n\r\n\t\t\t\tString attractiveness = location.getElementsByTagName(\"attractiveness\").item(0).getTextContent();\r\n\t\t\t\tint placeTypeIndex = Integer.parseInt(attractiveness);\r\n\t\t\t\tif(NUM_OF_PLACE_TYPES < placeTypeIndex+1)\r\n\t\t\t\t\tNUM_OF_PLACE_TYPES = placeTypeIndex+1;\r\n\r\n\t\t\t\tNodeList hostList = datacenterElement.getElementsByTagName(\"host\");\r\n\t\t\t\tfor (int j = 0; j < hostList.getLength(); j++) {\r\n\t\t\t\t\tNUM_OF_EDGE_HOSTS++;\r\n\t\t\t\t\tNode hostNode = hostList.item(j);\r\n\r\n\t\t\t\t\tElement hostElement = (Element) hostNode;\r\n\t\t\t\t\tisElementPresent(hostElement, \"core\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"mips\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"ram\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"storage\");\r\n\r\n\t\t\t\t\tNodeList vmList = hostElement.getElementsByTagName(\"VM\");\r\n\t\t\t\t\tfor (int k = 0; k < vmList.getLength(); k++) {\r\n\t\t\t\t\t\tNUM_OF_EDGE_VMS++;\r\n\t\t\t\t\t\tNode vmNode = vmList.item(k);\r\n\r\n\t\t\t\t\t\tElement vmElement = (Element) vmNode;\r\n\t\t\t\t\t\tisAttributePresent(vmElement, \"vmm\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"core\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"mips\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"ram\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"storage\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n}\r", "public class Task extends Cloudlet {\r\n\tprivate Location submittedLocation;\r\n\tprivate double creationTime;\r\n\tprivate int type;\r\n\tprivate int mobileDeviceId;\r\n\tprivate int hostIndex;\r\n\tprivate int vmIndex;\r\n\tprivate int datacenterId;\r\n\r\n\tpublic Task(int _mobileDeviceId, int cloudletId, long cloudletLength, int pesNumber,\r\n\t\t\tlong cloudletFileSize, long cloudletOutputSize,\r\n\t\t\tUtilizationModel utilizationModelCpu,\r\n\t\t\tUtilizationModel utilizationModelRam,\r\n\t\t\tUtilizationModel utilizationModelBw) {\r\n\t\tsuper(cloudletId, cloudletLength, pesNumber, cloudletFileSize,\r\n\t\t\t\tcloudletOutputSize, utilizationModelCpu, utilizationModelRam,\r\n\t\t\t\tutilizationModelBw);\r\n\t\t\r\n\t\tmobileDeviceId = _mobileDeviceId;\r\n\t\tcreationTime = CloudSim.clock();\r\n\t}\r\n\r\n\t\r\n\tpublic void setSubmittedLocation(Location _submittedLocation){\r\n\t\tsubmittedLocation =_submittedLocation;\r\n\t}\r\n\r\n\tpublic void setAssociatedDatacenterId(int _datacenterId){\r\n\t\tdatacenterId=_datacenterId;\r\n\t}\r\n\t\r\n\tpublic void setAssociatedHostId(int _hostIndex){\r\n\t\thostIndex=_hostIndex;\r\n\t}\r\n\r\n\tpublic void setAssociatedVmId(int _vmIndex){\r\n\t\tvmIndex=_vmIndex;\r\n\t}\r\n\t\r\n\tpublic void setTaskType(int _type){\r\n\t\ttype=_type;\r\n\t}\r\n\r\n\tpublic int getMobileDeviceId(){\r\n\t\treturn mobileDeviceId;\r\n\t}\r\n\t\r\n\tpublic Location getSubmittedLocation(){\r\n\t\treturn submittedLocation;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedDatacenterId(){\r\n\t\treturn datacenterId;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedHostId(){\r\n\t\treturn hostIndex;\r\n\t}\r\n\r\n\tpublic int getAssociatedVmId(){\r\n\t\treturn vmIndex;\r\n\t}\r\n\t\r\n\tpublic int getTaskType(){\r\n\t\treturn type;\r\n\t}\r\n\t\r\n\tpublic double getCreationTime() {\r\n\t\treturn creationTime;\r\n\t}\r\n}\r", "public abstract class NetworkModel {\r\n\tprotected int numberOfMobileDevices;\r\n\tprotected String simScenario;\r\n\r\n\tpublic NetworkModel(int _numberOfMobileDevices, String _simScenario){\r\n\t\tnumberOfMobileDevices=_numberOfMobileDevices;\r\n\t\tsimScenario = _simScenario;\r\n\t};\r\n\r\n\t/**\r\n\t * initializes custom network model\r\n\t */\r\n\tpublic abstract void initialize();\r\n\r\n\t/**\r\n\t * calculates the upload delay from source to destination device\r\n\t */\r\n\tpublic abstract double getUploadDelay(int sourceDeviceId, int destDeviceId, Task task);\r\n\r\n\t/**\r\n\t * calculates the download delay from source to destination device\r\n\t */\r\n\tpublic abstract double getDownloadDelay(int sourceDeviceId, int destDeviceId, Task task);\r\n\r\n\t/**\r\n\t * Mobile device manager should inform network manager about the network operation\r\n\t * This information may be important for some network delay models\r\n\t */\r\n\tpublic abstract void uploadStarted(Location accessPointLocation, int destDeviceId);\r\n\tpublic abstract void uploadFinished(Location accessPointLocation, int destDeviceId);\r\n\tpublic abstract void downloadStarted(Location accessPointLocation, int sourceDeviceId);\r\n\tpublic abstract void downloadFinished(Location accessPointLocation, int sourceDeviceId);\r\n}\r", "public class Location {\r\n\tprivate int xPos;\r\n\tprivate int yPos;\r\n\tprivate int servingWlanId;\r\n\tprivate int placeTypeIndex;\r\n\tpublic Location(int _placeTypeIndex, int _servingWlanId, int _xPos, int _yPos){\r\n\t\tservingWlanId = _servingWlanId;\r\n\t\tplaceTypeIndex=_placeTypeIndex;\r\n\t\txPos = _xPos;\r\n\t\tyPos = _yPos;\r\n\t}\r\n\t\r\n\t/*\r\n\t * Default Constructor: Creates an empty Location\r\n\t */\r\n\tpublic Location() {\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object other){\r\n\t\tboolean result = false;\r\n\t if (other == null) return false;\r\n\t if (!(other instanceof Location))return false;\r\n\t if (other == this) return true;\r\n\t \r\n\t Location otherLocation = (Location)other;\r\n\t if(this.xPos == otherLocation.xPos && this.yPos == otherLocation.yPos)\r\n\t \tresult = true;\r\n\r\n\t return result;\r\n\t}\r\n\r\n\tpublic int getServingWlanId(){\r\n\t\treturn servingWlanId;\r\n\t}\r\n\t\r\n\tpublic int getPlaceTypeIndex(){\r\n\t\treturn placeTypeIndex;\r\n\t}\r\n\t\r\n\tpublic int getXPos(){\r\n\t\treturn xPos;\r\n\t}\r\n\t\r\n\tpublic int getYPos(){\r\n\t\treturn yPos;\r\n\t}\r\n}\r", "public class SimLogger {\r\n\tpublic static enum TASK_STATUS {\r\n\t\tCREATED, UPLOADING, PROCESSING, DOWNLOADING, COMLETED,\r\n\t\tREJECTED_DUE_TO_VM_CAPACITY, REJECTED_DUE_TO_BANDWIDTH,\r\n\t\tUNFINISHED_DUE_TO_BANDWIDTH, UNFINISHED_DUE_TO_MOBILITY,\r\n\t\tREJECTED_DUE_TO_WLAN_COVERAGE\r\n\t}\r\n\t\r\n\tpublic static enum NETWORK_ERRORS {\r\n\t\tLAN_ERROR, MAN_ERROR, WAN_ERROR, GSM_ERROR, NONE\r\n\t}\r\n\r\n\tprivate long startTime;\r\n\tprivate long endTime;\r\n\tprivate static boolean fileLogEnabled;\r\n\tprivate static boolean printLogEnabled;\r\n\tprivate String filePrefix;\r\n\tprivate String outputFolder;\r\n\tprivate Map<Integer, LogItem> taskMap;\r\n\tprivate LinkedList<VmLoadLogItem> vmLoadList;\r\n\tprivate LinkedList<ApDelayLogItem> apDelayList;\r\n\r\n\tprivate static SimLogger singleton = new SimLogger();\r\n\t\r\n\tprivate int numOfAppTypes;\r\n\t\r\n\tprivate File successFile = null, failFile = null;\r\n\tprivate FileWriter successFW = null, failFW = null;\r\n\tprivate BufferedWriter successBW = null, failBW = null;\r\n\r\n\t// extract following values for each app type.\r\n\t// last index is average of all app types\r\n\tprivate int[] uncompletedTask = null;\r\n\tprivate int[] uncompletedTaskOnCloud = null;\r\n\tprivate int[] uncompletedTaskOnEdge = null;\r\n\tprivate int[] uncompletedTaskOnMobile = null;\r\n\r\n\tprivate int[] completedTask = null;\r\n\tprivate int[] completedTaskOnCloud = null;\r\n\tprivate int[] completedTaskOnEdge = null;\r\n\tprivate int[] completedTaskOnMobile = null;\r\n\r\n\tprivate int[] failedTask = null;\r\n\tprivate int[] failedTaskOnCloud = null;\r\n\tprivate int[] failedTaskOnEdge = null;\r\n\tprivate int[] failedTaskOnMobile = null;\r\n\r\n\tprivate double[] networkDelay = null;\r\n\tprivate double[] gsmDelay = null;\r\n\tprivate double[] wanDelay = null;\r\n\tprivate double[] manDelay = null;\r\n\tprivate double[] lanDelay = null;\r\n\t\r\n\tprivate double[] gsmUsage = null;\r\n\tprivate double[] wanUsage = null;\r\n\tprivate double[] manUsage = null;\r\n\tprivate double[] lanUsage = null;\r\n\r\n\tprivate double[] serviceTime = null;\r\n\tprivate double[] serviceTimeOnCloud = null;\r\n\tprivate double[] serviceTimeOnEdge = null;\r\n\tprivate double[] serviceTimeOnMobile = null;\r\n\r\n\tprivate double[] processingTime = null;\r\n\tprivate double[] processingTimeOnCloud = null;\r\n\tprivate double[] processingTimeOnEdge = null;\r\n\tprivate double[] processingTimeOnMobile = null;\r\n\r\n\tprivate int[] failedTaskDueToVmCapacity = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnCloud = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnEdge = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnMobile = null;\r\n\t\r\n\tprivate double[] cost = null;\r\n\tprivate double[] QoE = null;\r\n\tprivate int[] failedTaskDuetoBw = null;\r\n\tprivate int[] failedTaskDuetoLanBw = null;\r\n\tprivate int[] failedTaskDuetoManBw = null;\r\n\tprivate int[] failedTaskDuetoWanBw = null;\r\n\tprivate int[] failedTaskDuetoGsmBw = null;\r\n\tprivate int[] failedTaskDuetoMobility = null;\r\n\tprivate int[] refectedTaskDuetoWlanRange = null;\r\n\t\r\n\tprivate double[] orchestratorOverhead = null;\r\n\r\n\t/*\r\n\t * A private Constructor prevents any other class from instantiating.\r\n\t */\r\n\tprivate SimLogger() {\r\n\t\tfileLogEnabled = false;\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\r\n\t/* Static 'instance' method */\r\n\tpublic static SimLogger getInstance() {\r\n\t\treturn singleton;\r\n\t}\r\n\r\n\tpublic static void enableFileLog() {\r\n\t\tfileLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static void enablePrintLog() {\r\n\t\tprintLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static boolean isFileLogEnabled() {\r\n\t\treturn fileLogEnabled;\r\n\t}\r\n\r\n\tpublic static void disableFileLog() {\r\n\t\tfileLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic static void disablePrintLog() {\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic String getOutputFolder() {\r\n\t\treturn outputFolder;\r\n\t}\r\n\r\n\tprivate void appendToFile(BufferedWriter bw, String line) throws IOException {\r\n\t\tbw.write(line);\r\n\t\tbw.newLine();\r\n\t}\r\n\r\n\tpublic static void printLine(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.println(msg);\r\n\t}\r\n\r\n\tpublic static void print(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.print(msg);\r\n\t}\r\n\r\n\tpublic void simStarted(String outFolder, String fileName) {\r\n\t\tstartTime = System.currentTimeMillis();\r\n\t\tfilePrefix = fileName;\r\n\t\toutputFolder = outFolder;\r\n\t\ttaskMap = new HashMap<Integer, LogItem>();\r\n\t\tvmLoadList = new LinkedList<VmLoadLogItem>();\r\n\t\tapDelayList = new LinkedList<ApDelayLogItem>();\r\n\t\t\r\n\t\tnumOfAppTypes = SimSettings.getInstance().getTaskLookUpTable().length;\r\n\t\t\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\ttry {\r\n\t\t\t\tsuccessFile = new File(outputFolder, filePrefix + \"_SUCCESS.log\");\r\n\t\t\t\tsuccessFW = new FileWriter(successFile, true);\r\n\t\t\t\tsuccessBW = new BufferedWriter(successFW);\r\n\r\n\t\t\t\tfailFile = new File(outputFolder, filePrefix + \"_FAIL.log\");\r\n\t\t\t\tfailFW = new FileWriter(failFile, true);\r\n\t\t\t\tfailBW = new BufferedWriter(failFW);\r\n\t\t\t\t\r\n\t\t\t\tappendToFile(successBW, \"#auto generated file!\");\r\n\t\t\t\tappendToFile(failBW, \"#auto generated file!\");\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// extract following values for each app type.\r\n\t\t// last index is average of all app types\r\n\t\tuncompletedTask = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tcompletedTask = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tfailedTask = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tnetworkDelay = new double[numOfAppTypes + 1];\r\n\t\tgsmDelay = new double[numOfAppTypes + 1];\r\n\t\twanDelay = new double[numOfAppTypes + 1];\r\n\t\tmanDelay = new double[numOfAppTypes + 1];\r\n\t\tlanDelay = new double[numOfAppTypes + 1];\r\n\t\t\r\n\t\tgsmUsage = new double[numOfAppTypes + 1];\r\n\t\twanUsage = new double[numOfAppTypes + 1];\r\n\t\tmanUsage = new double[numOfAppTypes + 1];\r\n\t\tlanUsage = new double[numOfAppTypes + 1];\r\n\r\n\t\tserviceTime = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tprocessingTime = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tfailedTaskDueToVmCapacity = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnMobile = new int[numOfAppTypes + 1];\r\n\t\t\r\n\t\tcost = new double[numOfAppTypes + 1];\r\n\t\tQoE = new double[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoLanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoManBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoWanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoGsmBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoMobility = new int[numOfAppTypes + 1];\r\n\t\trefectedTaskDuetoWlanRange = new int[numOfAppTypes + 1];\r\n\r\n\t\torchestratorOverhead = new double[numOfAppTypes + 1];\r\n\t}\r\n\r\n\tpublic void addLog(int deviceId, int taskId, int taskType,\r\n\t\t\tint taskLenght, int taskInputType, int taskOutputSize) {\r\n\t\t// printLine(taskId+\"->\"+taskStartTime);\r\n\t\ttaskMap.put(taskId, new LogItem(deviceId, taskType, taskLenght, taskInputType, taskOutputSize));\r\n\t}\r\n\r\n\tpublic void taskStarted(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskStarted(time);\r\n\t}\r\n\r\n\tpublic void setUploadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setUploadDelay(delay, delayType);\r\n\t}\r\n\r\n\tpublic void setDownloadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setDownloadDelay(delay, delayType);\r\n\t}\r\n\t\r\n\tpublic void taskAssigned(int taskId, int datacenterId, int hostId, int vmId, int vmType) {\r\n\t\ttaskMap.get(taskId).taskAssigned(datacenterId, hostId, vmId, vmType);\r\n\t}\r\n\r\n\tpublic void taskExecuted(int taskId) {\r\n\t\ttaskMap.get(taskId).taskExecuted();\r\n\t}\r\n\r\n\tpublic void taskEnded(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskEnded(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void rejectedDueToVMCapacity(int taskId, double time, int vmType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToVMCapacity(time, vmType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n public void rejectedDueToWlanCoverage(int taskId, double time, int vmType) {\r\n \ttaskMap.get(taskId).taskRejectedDueToWlanCoverage(time, vmType);\r\n\t\trecordLog(taskId);\r\n }\r\n \r\n\tpublic void rejectedDueToBandwidth(int taskId, double time, int vmType, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToBandwidth(time, vmType, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToBandwidth(int taskId, double time, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToBandwidth(time, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToMobility(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToMobility(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void setQoE(int taskId, double QoE){\r\n\t\ttaskMap.get(taskId).setQoE(QoE);\r\n\t}\r\n\t\r\n\tpublic void setOrchestratorOverhead(int taskId, double overhead){\r\n\t\ttaskMap.get(taskId).setOrchestratorOverhead(overhead);\r\n\t}\r\n\r\n\tpublic void addVmUtilizationLog(double time, double loadOnEdge, double loadOnCloud, double loadOnMobile) {\r\n\t\tif(SimSettings.getInstance().getLocationLogInterval() != 0)\r\n\t\t\tvmLoadList.add(new VmLoadLogItem(time, loadOnEdge, loadOnCloud, loadOnMobile));\r\n\t}\r\n\r\n\tpublic void addApDelayLog(double time, double[] apUploadDelays, double[] apDownloadDelays) {\r\n\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0)\r\n\t\t\tapDelayList.add(new ApDelayLogItem(time, apUploadDelays, apDownloadDelays));\r\n\t}\r\n\t\r\n\tpublic void simStopped() throws IOException {\r\n\t\tendTime = System.currentTimeMillis();\r\n\t\tFile vmLoadFile = null, locationFile = null, apUploadDelayFile = null, apDownloadDelayFile = null;\r\n\t\tFileWriter vmLoadFW = null, locationFW = null, apUploadDelayFW = null, apDownloadDelayFW = null;\r\n\t\tBufferedWriter vmLoadBW = null, locationBW = null, apUploadDelayBW = null, apDownloadDelayBW = null;\r\n\r\n\t\t// Save generic results to file for each app type. last index is average\r\n\t\t// of all app types\r\n\t\tFile[] genericFiles = new File[numOfAppTypes + 1];\r\n\t\tFileWriter[] genericFWs = new FileWriter[numOfAppTypes + 1];\r\n\t\tBufferedWriter[] genericBWs = new BufferedWriter[numOfAppTypes + 1];\r\n\r\n\t\t// open all files and prepare them for write\r\n\t\tif (fileLogEnabled) {\r\n\t\t\tvmLoadFile = new File(outputFolder, filePrefix + \"_VM_LOAD.log\");\r\n\t\t\tvmLoadFW = new FileWriter(vmLoadFile, true);\r\n\t\t\tvmLoadBW = new BufferedWriter(vmLoadFW);\r\n\r\n\t\t\tlocationFile = new File(outputFolder, filePrefix + \"_LOCATION.log\");\r\n\t\t\tlocationFW = new FileWriter(locationFile, true);\r\n\t\t\tlocationBW = new BufferedWriter(locationFW);\r\n\r\n\t\t\tapUploadDelayFile = new File(outputFolder, filePrefix + \"_AP_UPLOAD_DELAY.log\");\r\n\t\t\tapUploadDelayFW = new FileWriter(apUploadDelayFile, true);\r\n\t\t\tapUploadDelayBW = new BufferedWriter(apUploadDelayFW);\r\n\r\n\t\t\tapDownloadDelayFile = new File(outputFolder, filePrefix + \"_AP_DOWNLOAD_DELAY.log\");\r\n\t\t\tapDownloadDelayFW = new FileWriter(apDownloadDelayFile, true);\r\n\t\t\tapDownloadDelayBW = new BufferedWriter(apDownloadDelayFW);\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tString fileName = \"ALL_APPS_GENERIC.log\";\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfileName = SimSettings.getInstance().getTaskName(i) + \"_GENERIC.log\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tgenericFiles[i] = new File(outputFolder, filePrefix + \"_\" + fileName);\r\n\t\t\t\tgenericFWs[i] = new FileWriter(genericFiles[i], true);\r\n\t\t\t\tgenericBWs[i] = new BufferedWriter(genericFWs[i]);\r\n\t\t\t\tappendToFile(genericBWs[i], \"#auto generated file!\");\r\n\t\t\t}\r\n\r\n\t\t\tappendToFile(vmLoadBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(locationBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apUploadDelayBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apDownloadDelayBW, \"#auto generated file!\");\r\n\t\t}\r\n\r\n\t\t//the tasks in the map is not completed yet!\r\n\t\tfor (Map.Entry<Integer, LogItem> entry : taskMap.entrySet()) {\r\n\t\t\tLogItem value = entry.getValue();\r\n\r\n\t\t\tuncompletedTask[value.getTaskType()]++;\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tuncompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\t// calculate total values\r\n\t\tuncompletedTask[numOfAppTypes] = IntStream.of(uncompletedTask).sum();\r\n\t\tuncompletedTaskOnCloud[numOfAppTypes] = IntStream.of(uncompletedTaskOnCloud).sum();\r\n\t\tuncompletedTaskOnEdge[numOfAppTypes] = IntStream.of(uncompletedTaskOnEdge).sum();\r\n\t\tuncompletedTaskOnMobile[numOfAppTypes] = IntStream.of(uncompletedTaskOnMobile).sum();\r\n\r\n\t\tcompletedTask[numOfAppTypes] = IntStream.of(completedTask).sum();\r\n\t\tcompletedTaskOnCloud[numOfAppTypes] = IntStream.of(completedTaskOnCloud).sum();\r\n\t\tcompletedTaskOnEdge[numOfAppTypes] = IntStream.of(completedTaskOnEdge).sum();\r\n\t\tcompletedTaskOnMobile[numOfAppTypes] = IntStream.of(completedTaskOnMobile).sum();\r\n\r\n\t\tfailedTask[numOfAppTypes] = IntStream.of(failedTask).sum();\r\n\t\tfailedTaskOnCloud[numOfAppTypes] = IntStream.of(failedTaskOnCloud).sum();\r\n\t\tfailedTaskOnEdge[numOfAppTypes] = IntStream.of(failedTaskOnEdge).sum();\r\n\t\tfailedTaskOnMobile[numOfAppTypes] = IntStream.of(failedTaskOnMobile).sum();\r\n\r\n\t\tnetworkDelay[numOfAppTypes] = DoubleStream.of(networkDelay).sum();\r\n\t\tlanDelay[numOfAppTypes] = DoubleStream.of(lanDelay).sum();\r\n\t\tmanDelay[numOfAppTypes] = DoubleStream.of(manDelay).sum();\r\n\t\twanDelay[numOfAppTypes] = DoubleStream.of(wanDelay).sum();\r\n\t\tgsmDelay[numOfAppTypes] = DoubleStream.of(gsmDelay).sum();\r\n\t\t\r\n\t\tlanUsage[numOfAppTypes] = DoubleStream.of(lanUsage).sum();\r\n\t\tmanUsage[numOfAppTypes] = DoubleStream.of(manUsage).sum();\r\n\t\twanUsage[numOfAppTypes] = DoubleStream.of(wanUsage).sum();\r\n\t\tgsmUsage[numOfAppTypes] = DoubleStream.of(gsmUsage).sum();\r\n\r\n\t\tserviceTime[numOfAppTypes] = DoubleStream.of(serviceTime).sum();\r\n\t\tserviceTimeOnCloud[numOfAppTypes] = DoubleStream.of(serviceTimeOnCloud).sum();\r\n\t\tserviceTimeOnEdge[numOfAppTypes] = DoubleStream.of(serviceTimeOnEdge).sum();\r\n\t\tserviceTimeOnMobile[numOfAppTypes] = DoubleStream.of(serviceTimeOnMobile).sum();\r\n\r\n\t\tprocessingTime[numOfAppTypes] = DoubleStream.of(processingTime).sum();\r\n\t\tprocessingTimeOnCloud[numOfAppTypes] = DoubleStream.of(processingTimeOnCloud).sum();\r\n\t\tprocessingTimeOnEdge[numOfAppTypes] = DoubleStream.of(processingTimeOnEdge).sum();\r\n\t\tprocessingTimeOnMobile[numOfAppTypes] = DoubleStream.of(processingTimeOnMobile).sum();\r\n\r\n\t\tfailedTaskDueToVmCapacity[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacity).sum();\r\n\t\tfailedTaskDueToVmCapacityOnCloud[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnCloud).sum();\r\n\t\tfailedTaskDueToVmCapacityOnEdge[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnEdge).sum();\r\n\t\tfailedTaskDueToVmCapacityOnMobile[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnMobile).sum();\r\n\t\t\r\n\t\tcost[numOfAppTypes] = DoubleStream.of(cost).sum();\r\n\t\tQoE[numOfAppTypes] = DoubleStream.of(QoE).sum();\r\n\t\tfailedTaskDuetoBw[numOfAppTypes] = IntStream.of(failedTaskDuetoBw).sum();\r\n\t\tfailedTaskDuetoGsmBw[numOfAppTypes] = IntStream.of(failedTaskDuetoGsmBw).sum();\r\n\t\tfailedTaskDuetoWanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoWanBw).sum();\r\n\t\tfailedTaskDuetoManBw[numOfAppTypes] = IntStream.of(failedTaskDuetoManBw).sum();\r\n\t\tfailedTaskDuetoLanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoLanBw).sum();\r\n\t\tfailedTaskDuetoMobility[numOfAppTypes] = IntStream.of(failedTaskDuetoMobility).sum();\r\n\t\trefectedTaskDuetoWlanRange[numOfAppTypes] = IntStream.of(refectedTaskDuetoWlanRange).sum();\r\n\r\n\t\torchestratorOverhead[numOfAppTypes] = DoubleStream.of(orchestratorOverhead).sum();\r\n\t\t\r\n\t\t// calculate server load\r\n\t\tdouble totalVmLoadOnEdge = 0;\r\n\t\tdouble totalVmLoadOnCloud = 0;\r\n\t\tdouble totalVmLoadOnMobile = 0;\r\n\t\tfor (VmLoadLogItem entry : vmLoadList) {\r\n\t\t\ttotalVmLoadOnEdge += entry.getEdgeLoad();\r\n\t\t\ttotalVmLoadOnCloud += entry.getCloudLoad();\r\n\t\t\ttotalVmLoadOnMobile += entry.getMobileLoad();\r\n\t\t\tif (fileLogEnabled && SimSettings.getInstance().getVmLoadLogInterval() != 0)\r\n\t\t\t\tappendToFile(vmLoadBW, entry.toString());\r\n\t\t}\r\n\r\n\t\tif (fileLogEnabled) {\r\n\t\t\t// write location info to file for each location\r\n\t\t\t// assuming each location has only one access point\r\n\t\t\tdouble locationLogInterval = SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\tif(locationLogInterval != 0) {\r\n\t\t\t\tfor (int t = 1; t < (SimSettings.getInstance().getSimulationTime() / locationLogInterval); t++) {\r\n\t\t\t\t\tint[] locationInfo = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()];\r\n\t\t\t\t\tDouble time = t * SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (time < SimSettings.CLIENT_ACTIVITY_START_TIME)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (int i = 0; i < SimManager.getInstance().getNumOfMobileDevice(); i++) {\r\n\t\t\t\t\t\tLocation loc = SimManager.getInstance().getMobilityModel().getLocation(i, time);\r\n\t\t\t\t\t\tlocationInfo[loc.getServingWlanId()]++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tlocationBW.write(time.toString());\r\n\t\t\t\t\tfor (int i = 0; i < locationInfo.length; i++)\r\n\t\t\t\t\t\tlocationBW.write(SimSettings.DELIMITER + locationInfo[i]);\r\n\r\n\t\t\t\t\tlocationBW.newLine();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// write delay info to file for each access point\r\n\t\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0) {\r\n\t\t\t\tfor (ApDelayLogItem entry : apDelayList) {\r\n\t\t\t\t\tappendToFile(apUploadDelayBW, entry.getUploadStat());\r\n\t\t\t\t\tappendToFile(apDownloadDelayBW, entry.getDownloadStat());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by\r\n\t\t\t\t// zero problem\r\n\t\t\t\tdouble _serviceTime = (completedTask[i] == 0) ? 0.0 : (serviceTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _networkDelay = (completedTask[i] == 0) ? 0.0 : (networkDelay[i] / ((double) completedTask[i] - (double)completedTaskOnMobile[i]));\r\n\t\t\t\tdouble _processingTime = (completedTask[i] == 0) ? 0.0 : (processingTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _vmLoadOnEdge = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnEdge / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnClould = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnCloud / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnMobile = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnMobile / (double) vmLoadList.size());\r\n\t\t\t\tdouble _cost = (completedTask[i] == 0) ? 0.0 : (cost[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE1 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE2 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) (failedTask[i] + completedTask[i]));\r\n\r\n\t\t\t\tdouble _lanDelay = (lanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (lanDelay[i] / (double) lanUsage[i]);\r\n\t\t\t\tdouble _manDelay = (manUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (manDelay[i] / (double) manUsage[i]);\r\n\t\t\t\tdouble _wanDelay = (wanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (wanDelay[i] / (double) wanUsage[i]);\r\n\t\t\t\tdouble _gsmDelay = (gsmUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (gsmDelay[i] / (double) gsmUsage[i]);\r\n\t\t\t\t\r\n\t\t\t\t// write generic results\r\n\t\t\t\tString genericResult1 = Integer.toString(completedTask[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_processingTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_networkDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_cost) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacity[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoMobility[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE1) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE2) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(refectedTaskDuetoWlanRange[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tdouble _processingTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tString genericResult2 = Integer.toString(completedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnEdge) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnEdge[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tdouble _processingTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tString genericResult3 = Integer.toString(completedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnCloud) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnCloud) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnClould) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnCloud[i]);\r\n\t\t\t\t\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tdouble _processingTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tString genericResult4 = Integer.toString(completedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnMobile) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnMobile[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult5 = Double.toString(_lanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_manDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_wanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_gsmDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoLanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoManBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoWanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoGsmBw[i]);\r\n\t\t\t\t\r\n\t\t\t\t//performance related values\r\n\t\t\t\tdouble _orchestratorOverhead = orchestratorOverhead[i] / (double) (failedTask[i] + completedTask[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult6 = Long.toString((endTime-startTime)/60) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_orchestratorOverhead);\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult1);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult2);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult3);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult4);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult5);\r\n\t\t\t\t\r\n\t\t\t\t//append performance related values only to ALL_ALLPS file\r\n\t\t\t\tif(i == numOfAppTypes) {\r\n\t\t\t\t\tappendToFile(genericBWs[i], genericResult6);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tprintLine(SimSettings.getInstance().getTaskName(i));\r\n\t\t\t\t\tprintLine(\"# of tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ (failedTask[i] + completedTask[i]) + \"(\"\r\n\t\t\t\t\t\t\t+ (failedTaskOnEdge[i] + completedTaskOnEdge[i]) + \"/\" \r\n\t\t\t\t\t\t\t+ (failedTaskOnCloud[i]+ completedTaskOnCloud[i]) + \")\" );\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of failed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ failedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ failedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ failedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of completed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ completedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ completedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ completedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"---------------------------------------\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// close open files\r\n\t\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\t\tsuccessBW.close();\r\n\t\t\t\tfailBW.close();\r\n\t\t\t}\r\n\t\t\tvmLoadBW.close();\r\n\t\t\tlocationBW.close();\r\n\t\t\tapUploadDelayBW.close();\r\n\t\t\tapDownloadDelayBW.close();\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just\r\n\t\t\t\t\t// discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tgenericBWs[i].close();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\t// printout important results\r\n\t\tprintLine(\"# of tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"(\"\r\n\t\t\t\t+ (failedTaskOnEdge[numOfAppTypes] + completedTaskOnEdge[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnCloud[numOfAppTypes]+ completedTaskOnCloud[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnMobile[numOfAppTypes]+ completedTaskOnMobile[numOfAppTypes]) + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of completed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ completedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ completedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of uncompleted tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ uncompletedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ uncompletedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnMobile[numOfAppTypes] + \")\");\r\n\r\n\t\tprintLine(\"# of failed tasks due to vm capacity (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTaskDueToVmCapacity[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks due to Mobility/WLAN Range/Network(WLAN/MAN/WAN/GSM): \"\r\n\t\t\t\t+ failedTaskDuetoMobility[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + refectedTaskDuetoWlanRange[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + failedTaskDuetoBw[numOfAppTypes] \r\n\t\t\t\t+ \"(\" + failedTaskDuetoLanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoManBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoWanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoGsmBw[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"percentage of failed tasks: \"\r\n\t\t\t\t+ String.format(\"%.6f\", ((double) failedTask[numOfAppTypes] * (double) 100)\r\n\t\t\t\t\t\t/ (double) (completedTask[numOfAppTypes] + failedTask[numOfAppTypes]))\r\n\t\t\t\t+ \"%\");\r\n\r\n\t\tprintLine(\"average service time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average processing time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average network delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", networkDelay[numOfAppTypes] / ((double) completedTask[numOfAppTypes] - (double) completedTaskOnMobile[numOfAppTypes]))\r\n\t\t\t\t+ \" seconds. (\" + \"LAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", lanDelay[numOfAppTypes] / (double) lanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"MAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", manDelay[numOfAppTypes] / (double) manUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"WAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", wanDelay[numOfAppTypes] / (double) wanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"GSM delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", gsmDelay[numOfAppTypes] / (double) gsmUsage[numOfAppTypes]) + \")\");\r\n\r\n\t\tprintLine(\"average server utilization Edge/Cloud/Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnEdge / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnCloud / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnMobile / (double) vmLoadList.size()));\r\n\r\n\t\tprintLine(\"average cost: \" + cost[numOfAppTypes] / completedTask[numOfAppTypes] + \"$\");\r\n\t\tprintLine(\"average overhead: \" + orchestratorOverhead[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \" ns\");\r\n\t\tprintLine(\"average QoE (for all): \" + QoE[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"%\");\r\n\t\tprintLine(\"average QoE (for executed): \" + QoE[numOfAppTypes] / completedTask[numOfAppTypes] + \"%\");\r\n\r\n\t\t// clear related collections (map list etc.)\r\n\t\ttaskMap.clear();\r\n\t\tvmLoadList.clear();\r\n\t\tapDelayList.clear();\r\n\t}\r\n\t\r\n\tprivate void recordLog(int taskId){\r\n\t\tLogItem value = taskMap.remove(taskId);\r\n\t\t\r\n\t\tif (value.isInWarmUpPeriod())\r\n\t\t\treturn;\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcompletedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tcompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfailedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcost[value.getTaskType()] += value.getCost();\r\n\t\t\tQoE[value.getTaskType()] += value.getQoE();\r\n\t\t\tserviceTime[value.getTaskType()] += value.getServiceTime();\r\n\t\t\tnetworkDelay[value.getTaskType()] += value.getNetworkDelay();\r\n\t\t\tprocessingTime[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\torchestratorOverhead[value.getTaskType()] += value.getOrchestratorOverhead();\r\n\t\t\t\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY) != 0) {\r\n\t\t\t\tlanUsage[value.getTaskType()]++;\r\n\t\t\t\tlanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY) != 0) {\r\n\t\t\t\tmanUsage[value.getTaskType()]++;\r\n\t\t\t\tmanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY) != 0) {\r\n\t\t\t\twanUsage[value.getTaskType()]++;\r\n\t\t\t\twanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY) != 0) {\r\n\t\t\t\tgsmUsage[value.getTaskType()]++;\r\n\t\t\t\tgsmDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnCloud[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnCloud[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tserviceTimeOnEdge[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnEdge[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_VM_CAPACITY) {\r\n\t\t\tfailedTaskDueToVmCapacity[value.getTaskType()]++;\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskDueToVmCapacityOnEdge[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_BANDWIDTH\r\n\t\t\t\t|| value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_BANDWIDTH) {\r\n\t\t\tfailedTaskDuetoBw[value.getTaskType()]++;\r\n\t\t\tif (value.getNetworkError() == NETWORK_ERRORS.LAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoLanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.MAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoManBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.WAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoWanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.GSM_ERROR)\r\n\t\t\t\tfailedTaskDuetoGsmBw[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_MOBILITY) {\r\n\t\t\tfailedTaskDuetoMobility[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_WLAN_COVERAGE) {\r\n\t\t\trefectedTaskDuetoWlanRange[value.getTaskType()]++;;\r\n }\r\n\t\t\r\n\t\t//if deep file logging is enabled, record every task result\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()){\r\n\t\t\ttry {\r\n\t\t\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED)\r\n\t\t\t\t\tappendToFile(successBW, value.toString(taskId));\r\n\t\t\t\telse\r\n\t\t\t\t\tappendToFile(failBW, value.toString(taskId));\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r" ]
import org.cloudbus.cloudsim.core.CloudSim; import edu.boun.edgecloudsim.core.SimManager; import edu.boun.edgecloudsim.core.SimSettings; import edu.boun.edgecloudsim.edge_client.Task; import edu.boun.edgecloudsim.network.NetworkModel; import edu.boun.edgecloudsim.utils.Location; import edu.boun.edgecloudsim.utils.SimLogger;
/* * Title: EdgeCloudSim - M/M/1 Queue model implementation * * Description: * MM1Queue implements M/M/1 Queue model for WLAN and WAN communication * * Licence: GPL - http://www.gnu.org/copyleft/gpl.html * Copyright (c) 2017, Bogazici University, Istanbul, Turkey */ package edu.boun.edgecloudsim.applications.sample_app4; public class FuzzyExperimentalNetworkModel extends NetworkModel { public static enum NETWORK_TYPE {WLAN, LAN}; public static enum LINK_TYPE {DOWNLOAD, UPLOAD}; public static double MAN_BW = 1300*1024; //Kbps @SuppressWarnings("unused") private int manClients; private int[] wanClients; private int[] wlanClients; private double lastMM1QueeuUpdateTime; private double ManPoissonMeanForDownload; //seconds private double ManPoissonMeanForUpload; //seconds private double avgManTaskInputSize; //bytes private double avgManTaskOutputSize; //bytes //record last n task statistics during MM1_QUEUE_MODEL_UPDATE_INTEVAL seconds to simulate mmpp/m/1 queue model private double totalManTaskInputSize; private double totalManTaskOutputSize; private double numOfManTaskForDownload; private double numOfManTaskForUpload; public static final double[] experimentalWlanDelay = { /*1 Client*/ 88040.279 /*(Kbps)*/, /*2 Clients*/ 45150.982 /*(Kbps)*/, /*3 Clients*/ 30303.641 /*(Kbps)*/, /*4 Clients*/ 27617.211 /*(Kbps)*/, /*5 Clients*/ 24868.616 /*(Kbps)*/, /*6 Clients*/ 22242.296 /*(Kbps)*/, /*7 Clients*/ 20524.064 /*(Kbps)*/, /*8 Clients*/ 18744.889 /*(Kbps)*/, /*9 Clients*/ 17058.827 /*(Kbps)*/, /*10 Clients*/ 15690.455 /*(Kbps)*/, /*11 Clients*/ 14127.744 /*(Kbps)*/, /*12 Clients*/ 13522.408 /*(Kbps)*/, /*13 Clients*/ 13177.631 /*(Kbps)*/, /*14 Clients*/ 12811.330 /*(Kbps)*/, /*15 Clients*/ 12584.387 /*(Kbps)*/, /*15 Clients*/ 12135.161 /*(Kbps)*/, /*16 Clients*/ 11705.638 /*(Kbps)*/, /*17 Clients*/ 11276.116 /*(Kbps)*/, /*18 Clients*/ 10846.594 /*(Kbps)*/, /*19 Clients*/ 10417.071 /*(Kbps)*/, /*20 Clients*/ 9987.549 /*(Kbps)*/, /*21 Clients*/ 9367.587 /*(Kbps)*/, /*22 Clients*/ 8747.625 /*(Kbps)*/, /*23 Clients*/ 8127.663 /*(Kbps)*/, /*24 Clients*/ 7907.701 /*(Kbps)*/, /*25 Clients*/ 7887.739 /*(Kbps)*/, /*26 Clients*/ 7690.831 /*(Kbps)*/, /*27 Clients*/ 7393.922 /*(Kbps)*/, /*28 Clients*/ 7297.014 /*(Kbps)*/, /*29 Clients*/ 7100.106 /*(Kbps)*/, /*30 Clients*/ 6903.197 /*(Kbps)*/, /*31 Clients*/ 6701.986 /*(Kbps)*/, /*32 Clients*/ 6500.776 /*(Kbps)*/, /*33 Clients*/ 6399.565 /*(Kbps)*/, /*34 Clients*/ 6098.354 /*(Kbps)*/, /*35 Clients*/ 5897.143 /*(Kbps)*/, /*36 Clients*/ 5552.127 /*(Kbps)*/, /*37 Clients*/ 5207.111 /*(Kbps)*/, /*38 Clients*/ 4862.096 /*(Kbps)*/, /*39 Clients*/ 4517.080 /*(Kbps)*/, /*40 Clients*/ 4172.064 /*(Kbps)*/, /*41 Clients*/ 4092.922 /*(Kbps)*/, /*42 Clients*/ 4013.781 /*(Kbps)*/, /*43 Clients*/ 3934.639 /*(Kbps)*/, /*44 Clients*/ 3855.498 /*(Kbps)*/, /*45 Clients*/ 3776.356 /*(Kbps)*/, /*46 Clients*/ 3697.215 /*(Kbps)*/, /*47 Clients*/ 3618.073 /*(Kbps)*/, /*48 Clients*/ 3538.932 /*(Kbps)*/, /*49 Clients*/ 3459.790 /*(Kbps)*/, /*50 Clients*/ 3380.649 /*(Kbps)*/, /*51 Clients*/ 3274.611 /*(Kbps)*/, /*52 Clients*/ 3168.573 /*(Kbps)*/, /*53 Clients*/ 3062.536 /*(Kbps)*/, /*54 Clients*/ 2956.498 /*(Kbps)*/, /*55 Clients*/ 2850.461 /*(Kbps)*/, /*56 Clients*/ 2744.423 /*(Kbps)*/, /*57 Clients*/ 2638.386 /*(Kbps)*/, /*58 Clients*/ 2532.348 /*(Kbps)*/, /*59 Clients*/ 2426.310 /*(Kbps)*/, /*60 Clients*/ 2320.273 /*(Kbps)*/, /*61 Clients*/ 2283.828 /*(Kbps)*/, /*62 Clients*/ 2247.383 /*(Kbps)*/, /*63 Clients*/ 2210.939 /*(Kbps)*/, /*64 Clients*/ 2174.494 /*(Kbps)*/, /*65 Clients*/ 2138.049 /*(Kbps)*/, /*66 Clients*/ 2101.604 /*(Kbps)*/, /*67 Clients*/ 2065.160 /*(Kbps)*/, /*68 Clients*/ 2028.715 /*(Kbps)*/, /*69 Clients*/ 1992.270 /*(Kbps)*/, /*70 Clients*/ 1955.825 /*(Kbps)*/, /*71 Clients*/ 1946.788 /*(Kbps)*/, /*72 Clients*/ 1937.751 /*(Kbps)*/, /*73 Clients*/ 1928.714 /*(Kbps)*/, /*74 Clients*/ 1919.677 /*(Kbps)*/, /*75 Clients*/ 1910.640 /*(Kbps)*/, /*76 Clients*/ 1901.603 /*(Kbps)*/, /*77 Clients*/ 1892.566 /*(Kbps)*/, /*78 Clients*/ 1883.529 /*(Kbps)*/, /*79 Clients*/ 1874.492 /*(Kbps)*/, /*80 Clients*/ 1865.455 /*(Kbps)*/, /*81 Clients*/ 1833.185 /*(Kbps)*/, /*82 Clients*/ 1800.915 /*(Kbps)*/, /*83 Clients*/ 1768.645 /*(Kbps)*/, /*84 Clients*/ 1736.375 /*(Kbps)*/, /*85 Clients*/ 1704.106 /*(Kbps)*/, /*86 Clients*/ 1671.836 /*(Kbps)*/, /*87 Clients*/ 1639.566 /*(Kbps)*/, /*88 Clients*/ 1607.296 /*(Kbps)*/, /*89 Clients*/ 1575.026 /*(Kbps)*/, /*90 Clients*/ 1542.756 /*(Kbps)*/, /*91 Clients*/ 1538.544 /*(Kbps)*/, /*92 Clients*/ 1534.331 /*(Kbps)*/, /*93 Clients*/ 1530.119 /*(Kbps)*/, /*94 Clients*/ 1525.906 /*(Kbps)*/, /*95 Clients*/ 1521.694 /*(Kbps)*/, /*96 Clients*/ 1517.481 /*(Kbps)*/, /*97 Clients*/ 1513.269 /*(Kbps)*/, /*98 Clients*/ 1509.056 /*(Kbps)*/, /*99 Clients*/ 1504.844 /*(Kbps)*/, /*100 Clients*/ 1500.631 /*(Kbps)*/ }; public static final double[] experimentalWanDelay = { /*1 Client*/ 20703.973 /*(Kbps)*/, /*2 Clients*/ 12023.957 /*(Kbps)*/, /*3 Clients*/ 9887.785 /*(Kbps)*/, /*4 Clients*/ 8915.775 /*(Kbps)*/, /*5 Clients*/ 8259.277 /*(Kbps)*/, /*6 Clients*/ 7560.574 /*(Kbps)*/, /*7 Clients*/ 7262.140 /*(Kbps)*/, /*8 Clients*/ 7155.361 /*(Kbps)*/, /*9 Clients*/ 7041.153 /*(Kbps)*/, /*10 Clients*/ 6994.595 /*(Kbps)*/, /*11 Clients*/ 6653.232 /*(Kbps)*/, /*12 Clients*/ 6111.868 /*(Kbps)*/, /*13 Clients*/ 5570.505 /*(Kbps)*/, /*14 Clients*/ 5029.142 /*(Kbps)*/, /*15 Clients*/ 4487.779 /*(Kbps)*/, /*16 Clients*/ 3899.729 /*(Kbps)*/, /*17 Clients*/ 3311.680 /*(Kbps)*/, /*18 Clients*/ 2723.631 /*(Kbps)*/, /*19 Clients*/ 2135.582 /*(Kbps)*/, /*20 Clients*/ 1547.533 /*(Kbps)*/, /*21 Clients*/ 1500.252 /*(Kbps)*/, /*22 Clients*/ 1452.972 /*(Kbps)*/, /*23 Clients*/ 1405.692 /*(Kbps)*/, /*24 Clients*/ 1358.411 /*(Kbps)*/, /*25 Clients*/ 1311.131 /*(Kbps)*/ }; public FuzzyExperimentalNetworkModel(int _numberOfMobileDevices, String _simScenario) { super(_numberOfMobileDevices, _simScenario); } @Override public void initialize() {
wanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter
1
WeDevelopTeam/HeroVideo-master
app/src/main/java/com/github/bigexcalibur/herovideo/mvp/live/ui/HomeLiveFragment.java
[ "public class LiveAppIndexAdapter extends RecyclerView.Adapter\n{\n\n private Context context;\n\n private LiveAppIndexInfo mLiveAppIndexInfo;\n\n private int entranceSize;\n\n //直播分类入口\n private static final int TYPE_ENTRANCE = 0;\n\n //直播Item\n private static final int TYPE_LIVE_ITEM = 1;\n\n //直播分类Title\n private static final int TYPE_PARTITION = 2;\n\n //直播页Banner\n private static final int TYPE_BANNER = 3;\n\n private List<BannerEntity> bannerEntitys = new ArrayList<>();\n\n private List<Integer> liveSizes = new ArrayList<>();\n\n private int[] entranceIconRes = new int[]{\n R.drawable.live_home_follow_anchor,\n R.drawable.live_home_live_center,\n R.drawable.live_home_search_room,\n R.drawable.live_home_all_category\n };\n\n private String[] entranceTitles = new String[]{\n \"关注主播\", \"直播中心\",\n \"搜索直播\", \"全部分类\"\n };\n\n public LiveAppIndexAdapter(Context context)\n {\n\n this.context = context;\n }\n\n public void setLiveInfo(LiveAppIndexInfo liveAppIndexInfo)\n {\n\n this.mLiveAppIndexInfo = liveAppIndexInfo;\n entranceSize = 4;\n liveSizes.clear();\n bannerEntitys.clear();\n int tempSize = 0;\n int partitionSize = mLiveAppIndexInfo.getData().getPartitions().size();\n\n List<LiveAppIndexInfo.DataBean.BannerBean> banner = mLiveAppIndexInfo.getData().getBanner();\n Observable.from(banner)\n .forEach(bannerBean -> bannerEntitys.add(new BannerEntity(\n bannerBean.getLink(), bannerBean.getTitle(), bannerBean.getImg())));\n\n for (int i = 0; i < partitionSize; i++)\n {\n liveSizes.add(tempSize);\n tempSize += mLiveAppIndexInfo.getData().getPartitions().get(i).getLives().size();\n }\n }\n\n public int getSpanSize(int pos)\n {\n\n int viewType = getItemViewType(pos);\n switch (viewType)\n {\n case TYPE_ENTRANCE:\n return 3;\n case TYPE_LIVE_ITEM:\n return 6;\n case TYPE_PARTITION:\n return 12;\n case TYPE_BANNER:\n return 12;\n }\n return 0;\n }\n\n @SuppressLint(\"InflateParams\")\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)\n {\n\n View view;\n switch (viewType)\n {\n case TYPE_ENTRANCE:\n view = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.item_live_entrance, null);\n return new LiveEntranceViewHolder(view);\n case TYPE_LIVE_ITEM:\n view = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.item_live_partition, null);\n return new LiveItemViewHolder(view);\n case TYPE_PARTITION:\n view = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.item_live_partition_title, null);\n return new LivePartitionViewHolder(view);\n case TYPE_BANNER:\n view = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.item_live_banner, null);\n return new LiveBannerViewHolder(view);\n }\n return null;\n }\n\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)\n {\n\n position -= 1;\n final LiveAppIndexInfo.DataBean.PartitionsBean.LivesBean livesBean;\n if (holder instanceof LiveEntranceViewHolder)\n {\n\n LiveEntranceViewHolder liveEntranceViewHolder = (LiveEntranceViewHolder) holder;\n liveEntranceViewHolder.title.setText(entranceTitles[position]);\n Glide.with(context)\n .load(entranceIconRes[position])\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .into(((LiveEntranceViewHolder) holder).image);\n } else if (holder instanceof LiveItemViewHolder)\n {\n\n LiveItemViewHolder liveItemViewHolder = (LiveItemViewHolder) holder;\n\n livesBean = mLiveAppIndexInfo.getData().getPartitions().get(getItemPosition(position))\n .getLives().get(position - 1 - entranceSize - getItemPosition(position) * 5);\n\n Glide.with(context)\n .load(livesBean.getCover().getSrc())\n .centerCrop()\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .placeholder(R.drawable.bili_default_image_tv)\n .dontAnimate()\n .into(liveItemViewHolder.itemLiveCover);\n\n Glide.with(context)\n .load(livesBean.getCover().getSrc())\n .centerCrop()\n .dontAnimate()\n .placeholder(R.drawable.ico_user_default)\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .into(((LiveItemViewHolder) holder).itemLiveUserCover);\n\n liveItemViewHolder.itemLiveTitle.setText(livesBean.getTitle());\n liveItemViewHolder.itemLiveUser.setText(livesBean.getOwner().getName());\n liveItemViewHolder.itemLiveCount.setText(String.valueOf(livesBean.getOnline()));\n// liveItemViewHolder.itemLiveLayout.setOnClickListener(v -> LivePlayerActivity.\n// launch((Activity) context, livesBean.getRoom_id(),\n// livesBean.getTitle(), livesBean.getOnline(), livesBean.getOwner().getFace(),\n// livesBean.getOwner().getName(), livesBean.getOwner().getMid()));\n liveItemViewHolder.itemLiveLayout.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n startPlay(livesBean);\n }\n });\n } else if (holder instanceof LivePartitionViewHolder)\n {\n\n LivePartitionViewHolder livePartitionViewHolder = (LivePartitionViewHolder) holder;\n\n LiveAppIndexInfo.DataBean.PartitionsBean.PartitionBean partition = mLiveAppIndexInfo.\n getData().getPartitions().get(getItemPosition(position)).getPartition();\n\n Glide.with(context)\n .load(partition.getSub_icon().getSrc())\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .into(livePartitionViewHolder.itemIcon);\n\n livePartitionViewHolder.itemTitle.setText(partition.getName());\n SpannableStringBuilder stringBuilder = new SpannableStringBuilder(\"当前\" + partition.getCount() + \"个直播\");\n ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(\n context.getResources().getColor(R.color.text_primary_color));\n stringBuilder.setSpan(foregroundColorSpan, 2,\n stringBuilder.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n livePartitionViewHolder.itemCount.setText(stringBuilder);\n } else if (holder instanceof LiveBannerViewHolder)\n {\n LiveBannerViewHolder liveBannerViewHolder = (LiveBannerViewHolder) holder;\n\n liveBannerViewHolder.banner\n .delayTime(5)\n .build(bannerEntitys);\n }\n }\n\n @Override\n public int getItemCount()\n {\n\n if (mLiveAppIndexInfo != null)\n {\n return 1 + entranceIconRes.length\n + mLiveAppIndexInfo.getData().getPartitions().size() * 5;\n } else\n {\n return 0;\n }\n }\n\n @Override\n public int getItemViewType(int position)\n {\n\n if (position == 0)\n {\n return TYPE_BANNER;\n }\n position -= 1;\n if (position < entranceSize)\n {\n return TYPE_ENTRANCE;\n } else if (isPartitionTitle(position))\n {\n return TYPE_PARTITION;\n } else\n {\n return TYPE_LIVE_ITEM;\n }\n }\n\n /**\n * 获取当前Item在第几组中\n */\n private int getItemPosition(int pos)\n {\n\n pos -= entranceSize;\n return pos / 5;\n }\n\n private boolean isPartitionTitle(int pos)\n {\n\n pos -= entranceSize;\n return (pos % 5 == 0);\n }\n\n\n /**\n * 直播界面Banner ViewHolder\n */\n static class LiveBannerViewHolder extends RecyclerView.ViewHolder\n {\n\n @BindView(R.id.item_live_banner)\n public BannerView banner;\n\n LiveBannerViewHolder(View itemView)\n {\n\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n\n /**\n * 直播界面Item分类 ViewHolder\n */\n static class LiveEntranceViewHolder extends RecyclerView.ViewHolder\n {\n\n @BindView(R.id.live_entrance_title)\n public TextView title;\n\n @BindView(R.id.live_entrance_image)\n public ImageView image;\n\n LiveEntranceViewHolder(View itemView)\n {\n\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n\n /**\n * 直播界面Grid Item ViewHolder\n */\n static class LiveItemViewHolder extends RecyclerView.ViewHolder\n {\n\n @BindView(R.id.item_live_cover)\n ImageView itemLiveCover;\n\n @BindView(R.id.item_live_user)\n TextView itemLiveUser;\n\n @BindView(R.id.item_live_title)\n TextView itemLiveTitle;\n\n @BindView(R.id.item_live_user_cover)\n CircleImageView itemLiveUserCover;\n\n @BindView(R.id.item_live_count)\n TextView itemLiveCount;\n\n @BindView(R.id.item_live_layout)\n CardView itemLiveLayout;\n\n LiveItemViewHolder(View itemView)\n {\n\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n\n /**\n * 直播界面分区类型 ViewHolder\n */\n static class LivePartitionViewHolder extends RecyclerView.ViewHolder\n {\n\n @BindView(R.id.item_live_partition_icon)\n ImageView itemIcon;\n\n @BindView(R.id.item_live_partition_title)\n TextView itemTitle;\n\n @BindView(R.id.item_live_partition_count)\n TextView itemCount;\n\n LivePartitionViewHolder(View itemView)\n {\n\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n\n public void startPlay(LiveAppIndexInfo.DataBean.PartitionsBean.LivesBean livesBean){\n String appKey = \"<Bilibili App Key Here>\";\n String secretKey = \"<Bilibili App Secret Key Here>\";\n String cid = \"\" +livesBean.getRoom_id();\n String ts =\"\" + System.currentTimeMillis();\n String apiParams = \"appkey=\"+appKey+\"&\"+\"cid=\"+cid+\"&\"+\"player=1&quality=0&ts=\"+ts;\n\n String sign = Md5.strToMd5Low32(apiParams + secretKey);\n\n LogUtil.test(\"http://live.bilibili.com/api/playurl?\"+apiParams+\"&sign=\" + sign);\n\n RetrofitHelper.getLiveAPI()\n .getLiveUrl(cid,appKey,ts,sign)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .map(responseBody -> parseLiveUrl(responseBody))\n .subscribe(new Observer<String>() {\n @Override\n public void onCompleted() {\n\n }\n\n @Override\n public void onError(Throwable e) {\n ToastUtil.ShortToast(\"error\");\n }\n @Override\n public void onNext(String url) {\n LogUtil.test(url);\n MediaPlayerActivity.configPlayer((Activity)context).setTitle(livesBean.getTitle()).setFullScreenOnly(true).playLive(url);\n }\n });\n }\n\n private String parseLiveUrl(ResponseBody responseBody) {\n String xml = null;\n try {\n xml = responseBody.string();\n } catch (IOException e) {\n e.printStackTrace();\n }\n LogUtil.d(\"xml\", xml);\n Document document = null;\n try {\n document = DocumentHelper.parseText(xml);\n } catch (DocumentException e) {\n e.printStackTrace();\n }\n assert document != null;\n Element rootElement = document.getRootElement();\n Element durlElement = rootElement.element(\"durl\");\n Element urlElement = durlElement.element(\"url\");\n String url = urlElement.getText();\n return url;\n }\n}", "public abstract class RxLazyFragment extends RxFragment implements IRxBaseFragmentView\n{\n\n private View parentView;\n\n private FragmentActivity activity;\n\n // 标志位 标志已经初始化完成。\n protected boolean isPrepared;\n\n //标志位 fragment是否可见\n protected boolean isVisible;\n\n private Unbinder bind;\n private RxBaseFragmentViewPresenter rxBaseFragmentViewPresenter;\n\n public abstract @LayoutRes int getLayoutResId();\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state)\n {\n parentView = inflater.inflate(getLayoutResId(), container, false);\n activity = getSupportActivity();\n return parentView;\n }\n\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState)\n {\n super.onViewCreated(view, savedInstanceState);\n bind = ButterKnife.bind(this, view);\n finishCreateView(savedInstanceState);\n rxBaseFragmentViewPresenter = new RxBaseFragmentViewPresenter(this);\n initThemeChangeObserver();\n }\n\n private void initThemeChangeObserver(){\n rxBaseFragmentViewPresenter.initThemeChangeSubscription();\n rxBaseFragmentViewPresenter.onGlobalThemeChange();\n }\n\n public abstract void finishCreateView(Bundle state);\n\n public void onThemeChange(ThemeChangeEvent themeChangeEvent){\n\n }\n\n @Override\n public void onResume()\n {\n\n super.onResume();\n }\n\n @Override\n public void onDestroyView()\n {\n super.onDestroyView();\n bind.unbind();\n rxBaseFragmentViewPresenter.onDestroyView();\n }\n\n @Override\n public void onAttach(Activity activity)\n {\n\n super.onAttach(activity);\n this.activity = (FragmentActivity) activity;\n }\n\n @Override\n public void onDetach()\n {\n\n super.onDetach();\n this.activity = null;\n }\n\n public FragmentActivity getSupportActivity()\n {\n\n return super.getActivity();\n }\n\n public android.app.ActionBar getSupportActionBar()\n {\n\n return getSupportActivity().getActionBar();\n }\n\n public Context getApplicationContext()\n {\n\n return this.activity == null ? (getActivity() == null ? null :\n getActivity().getApplicationContext()) : this.activity.getApplicationContext();\n }\n\n\n /**\n * Fragment数据的懒加载\n *\n * @param isVisibleToUser\n */\n @Override\n public void setUserVisibleHint(boolean isVisibleToUser)\n {\n\n super.setUserVisibleHint(isVisibleToUser);\n if (getUserVisibleHint())\n {\n isVisible = true;\n onVisible();\n } else\n {\n isVisible = false;\n onInvisible();\n }\n }\n\n protected void onVisible()\n {\n onLazyLoad();\n }\n\n\n @SuppressWarnings(\"unchecked\")\n public <T extends View> T $(int id)\n {\n\n return (T) parentView.findViewById(id);\n }\n\n @Override\n public void onSpecificThemeChange(View view) {\n\n }\n\n @Override\n public void loadData() {\n\n }\n\n @Override\n public void FinishLoadData() {\n\n }\n\n @Override\n public void onNodata() {\n\n }\n\n @Override\n public void onNetDisConnected() {\n\n }\n\n @Override\n public void onGlobalThemeChange() {\n\n }\n\n @Override\n public void onLazyLoad() {\n\n }\n\n @Override\n public void onInvisible() {\n\n }\n\n @Override\n public void finishTask() {\n\n }\n}", "public class RetrofitHelper\n{\n\n private static OkHttpClient mOkHttpClient;\n\n static\n {\n initOkHttpClient();\n }\n\n public static OkHttpClient getOkHttpClient(){\n return mOkHttpClient;\n }\n\n public static BiliAVSearchService getBiliAVSearchAPI()\n {\n return createApi(BiliAVSearchService.class, ApiConstants.RANK_BASE_URL);\n }\n\n public static BiliAVVideoService getBiliAVVideoAPI()\n {\n return createApi(BiliAVVideoService.class,ApiConstants.VIDEO_INTERFACE_URL);\n }\n//\n// public static BiliAVVideoService getBilibiliVideo()\n// {\n// return createApi(BiliAVVideoService.class, ApiConstants.RANK_BASE_URL);\n// }\n\n public static LiveService getLiveAPI()\n {\n\n return createApi(LiveService.class, ApiConstants.LIVE_BASE_URL);\n }\n\n\n public static BiliAppService getBiliAppAPI()\n {\n return createApi(BiliAppService.class, ApiConstants.APP_BASE_URL);\n }\n\n//\n public static BiliApiService getBiliAPI()\n {\n\n return createApi(BiliApiService.class, ApiConstants.API_BASE_URL);\n }\n\n//\n// public static BiliGoService getBiliGoAPI()\n// {\n//\n// return createApi(BiliGoService.class, ApiConstants.BILI_GO_BASE_URL);\n// }\n//\n//\n// public static RankService getRankAPI()\n// {\n//\n// return createApi(RankService.class, ApiConstants.RANK_BASE_URL);\n// }\n//\n//\n// public static UserService getUserAPI()\n// {\n//\n// return createApi(UserService.class, ApiConstants.USER_BASE_URL);\n// }\n//\n//\n// public static VipService getVipAPI()\n// {\n//\n// return createApi(VipService.class, ApiConstants.VIP_BASE_URL);\n// }\n//\n//\n public static BangumiService getBangumiAPI()\n {\n\n return createApi(BangumiService.class, ApiConstants.BANGUMI_BASE_URL);\n }\n//\n//\n// public static SearchService getSearchAPI()\n// {\n//\n// return createApi(SearchService.class, ApiConstants.SEARCH_BASE_URL);\n// }\n//\n// public static AccountService getAccountAPI()\n// {\n//\n// return createApi(AccountService.class, ApiConstants.ACCOUNT_BASE_URL);\n// }\n//\n//\n// public static Im9Service getIm9API()\n// {\n//\n// return createApi(Im9Service.class, ApiConstants.IM9_BASE_URL);\n// }\n//\n//\n /**\n * 根据传入的baseUrl,和api创建retrofit\n *\n * @param clazz\n * @param baseUrl\n * @param <T>\n * @return\n */\n private static <T> T createApi(Class<T> clazz, String baseUrl)\n {\n\n Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(baseUrl)\n .client(mOkHttpClient)\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .addConverterFactory(GsonConverterFactory.create())\n .build();\n\n return retrofit.create(clazz);\n }\n\n\n /**\n * 初始化OKHttpClient,设置缓存,设置超时时间,设置打印日志,设置UA拦截器\n */\n private static void initOkHttpClient()\n {\n\n HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();\n interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n if (mOkHttpClient == null)\n {\n synchronized (RetrofitHelper.class)\n {\n if (mOkHttpClient == null)\n {\n //设置Http缓存\n Cache cache = new Cache(new File(HeroVideoApp.getInstance()\n .getCacheDir(), \"HttpCache\"), 1024 * 1024 * 10);\n\n mOkHttpClient = new OkHttpClient.Builder()\n .cache(cache)\n .addInterceptor(interceptor)\n .addNetworkInterceptor(new CacheInterceptor())\n .addNetworkInterceptor(new StethoInterceptor())\n .retryOnConnectionFailure(true)\n .connectTimeout(30, TimeUnit.SECONDS)\n .writeTimeout(20, TimeUnit.SECONDS)\n .readTimeout(20, TimeUnit.SECONDS)\n // .addInterceptor(new UserAgentInterceptor())\n .build();\n }\n }\n }\n }\n\n\n// /**\n// * 添加UA拦截器,B站请求API需要加上UA才能正常使用\n// */\n// private static class UserAgentInterceptor implements Interceptor\n// {\n//\n// @Override\n// public Response intercept(Chain chain) throws IOException\n// {\n//\n// Request originalRequest = chain.request();\n// Request requestWithUserAgent = originalRequest.newBuilder()\n// .removeHeader(\"User-Agent\")\n// .addHeader(\"User-Agent\", ApiConstants.COMMON_UA_STR)\n// .build();\n// return chain.proceed(requestWithUserAgent);\n// }\n// }\n\n\n /**\n * 为okhttp添加缓存,这里是考虑到服务器不支持缓存时,从而让okhttp支持缓存\n */\n private static class CacheInterceptor implements Interceptor\n {\n\n @Override\n public Response intercept(Chain chain) throws IOException\n {\n\n // 有网络时 设置缓存超时时间1个小时\n int maxAge = 60 * 60;\n // 无网络时,设置超时为1天\n int maxStale = 60 * 60 * 24;\n Request request = chain.request();\n\n if (CommonUtil.isNetworkAvailable(HeroVideoApp.getInstance()))\n {\n //有网络时只从网络获取\n request = request.newBuilder()\n .cacheControl(CacheControl.FORCE_NETWORK)\n .build();\n } else\n {\n //无网络时只从缓存中读取\n request = request.newBuilder()\n .cacheControl(CacheControl.FORCE_CACHE)\n .build();\n }\n Response response = chain.proceed(request);\n if (CommonUtil.isNetworkAvailable(HeroVideoApp.getInstance()))\n {\n response = response.newBuilder()\n .removeHeader(\"Pragma\")\n .header(\"Cache-Control\", \"public, max-age=\" + maxAge)\n .build();\n } else\n {\n response = response.newBuilder()\n .removeHeader(\"Pragma\")\n .header(\"Cache-Control\", \"public, only-if-cached, max-stale=\" + maxStale)\n .build();\n }\n return response;\n }\n }\n}", "public class CustomEmptyView extends FrameLayout\n{\n\n private ImageView mEmptyImg;\n\n private TextView mEmptyText;\n\n public CustomEmptyView(Context context, AttributeSet attrs, int defStyleAttr)\n {\n\n super(context, attrs, defStyleAttr);\n init();\n }\n\n public CustomEmptyView(Context context)\n {\n\n this(context, null);\n }\n\n public CustomEmptyView(Context context, AttributeSet attrs)\n {\n\n this(context, attrs, 0);\n }\n\n\n public void init()\n {\n View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_empty, this);\n mEmptyImg = (ImageView) view.findViewById(R.id.empty_img);\n mEmptyText = (TextView) view.findViewById(R.id.empty_text);\n }\n\n public void setEmptyImage(int imgRes)\n {\n\n mEmptyImg.setImageResource(imgRes);\n }\n\n public void setEmptyText(String text)\n {\n\n mEmptyText.setText(text);\n }\n}", "public class SnackbarUtil\n{\n\n public static void showMessage(View view, String text)\n {\n\n Snackbar.make(view, text, Snackbar.LENGTH_SHORT).show();\n }\n}" ]
import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.github.bigexcalibur.herovideo.LiveAppIndexAdapter; import com.github.bigexcalibur.herovideo.R; import com.github.bigexcalibur.herovideo.mvp.common.ui.RxLazyFragment; import com.github.bigexcalibur.herovideo.network.RetrofitHelper; import com.github.bigexcalibur.herovideo.ui.widget.CustomEmptyView; import com.github.bigexcalibur.herovideo.util.SnackbarUtil; import butterknife.BindView; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.github.bigexcalibur.herovideo.mvp.live.ui; /** * 首页直播界面 */ public class HomeLiveFragment extends RxLazyFragment { @BindView(R.id.recycle) RecyclerView mRecyclerView; @BindView(R.id.swipe_refresh_layout) SwipeRefreshLayout mSwipeRefreshLayout; @BindView(R.id.empty_layout) CustomEmptyView mCustomEmptyView; private LiveAppIndexAdapter mLiveAppIndexAdapter; public static HomeLiveFragment newIntance() { return new HomeLiveFragment(); } @Override public int getLayoutResId() { return R.layout.fragment_home_live; } @Override public void finishCreateView(Bundle state) { isPrepared = true; onLazyLoad(); } @Override public void onLazyLoad() { if (!isPrepared || !isVisible) return; initRefreshLayout(); initRecyclerView(); isPrepared = false; } protected void initRecyclerView() { mLiveAppIndexAdapter = new LiveAppIndexAdapter(getActivity()); mRecyclerView.setAdapter(mLiveAppIndexAdapter); GridLayoutManager layout = new GridLayoutManager(getActivity(), 12); layout.setOrientation(LinearLayoutManager.VERTICAL); layout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return mLiveAppIndexAdapter.getSpanSize(position); } }); mRecyclerView.setLayoutManager(layout); } protected void initRefreshLayout() { mSwipeRefreshLayout.setColorSchemeResources(R.color.theme_color_primary); mSwipeRefreshLayout.setOnRefreshListener(this::loadData); mSwipeRefreshLayout.post(() -> { mSwipeRefreshLayout.setRefreshing(true); loadData(); }); } @Override public void loadData() {
RetrofitHelper.getLiveAPI()
2
jaquadro/ForgeMods
ModularPots/src/com/jaquadro/minecraft/modularpots/client/renderer/LargePotRenderer.java
[ "public class BlockLargePot extends BlockContainer\n{\n public static final String[] subTypes = new String[] { \"default\", \"raw\" };\n\n public enum Direction {\n North (1 << 0),\n East (1 << 1),\n South (1 << 2),\n West (1 << 3),\n NorthWest (1 << 4),\n NorthEast (1 << 5),\n SouthEast (1 << 6),\n SouthWest (1 << 7);\n\n private final int flag;\n\n Direction (int flag) {\n this.flag = flag;\n }\n\n public int getFlag () {\n return this.flag;\n }\n\n public static boolean isSet (int bitflags, Direction direction) {\n return (bitflags & direction.flag) != 0;\n }\n\n public static int set (int bitflags, Direction direction) {\n return bitflags | direction.flag;\n }\n\n public static int clear (int bitflags, Direction direction) {\n return bitflags & ~direction.flag;\n }\n\n public static int setOrClear (int bitflags, Direction direction, boolean set) {\n return set ? set(bitflags, direction) : clear(bitflags, direction);\n }\n }\n\n private boolean colored;\n\n @SideOnly(Side.CLIENT)\n private IIcon iconSide;\n\n @SideOnly(Side.CLIENT)\n private IIcon[] iconArray;\n\n @SideOnly(Side.CLIENT)\n private IIcon[] iconOverlayArray;\n\n // Scratch\n private int scratchDropMetadata;\n\n public BlockLargePot (String blockName, boolean colored) {\n super(Material.clay);\n\n this.colored = colored;\n\n setCreativeTab(ModularPots.tabModularPots);\n setHardness(.5f);\n setResistance(5f);\n setStepSound(Block.soundTypeStone);\n setBlockName(blockName);\n }\n\n @Override\n public void addCollisionBoxesToList (World world, int x, int y, int z, AxisAlignedBB mask, List list, Entity colliding) {\n float dim = .0625f;\n\n TileEntityLargePot te = getTileEntity(world, x, y, z);\n if (te == null || te.getSubstrate() == null || !isSubstrateSolid(te.getSubstrate()))\n setBlockBounds(0, 0, 0, 1, dim, 1);\n else\n setBlockBounds(0, 0, 0, 1, 1 - dim, 1);\n super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding);\n\n if (!isCompatibleNeighbor(world, x, y, z, -1, 0)) {\n setBlockBounds(0, 0, 0, dim, 1, 1);\n super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding);\n }\n if (!isCompatibleNeighbor(world, x, y, z, 0, -1)) {\n setBlockBounds(0, 0, 0, 1, 1, dim);\n super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding);\n }\n if (!isCompatibleNeighbor(world, x, y, z, 1, 0)) {\n setBlockBounds(1 - dim, 0, 0, 1, 1, 1);\n super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding);\n }\n if (!isCompatibleNeighbor(world, x, y, z, 0, 1)) {\n setBlockBounds(0, 0, 1 - dim, 1, 1, 1);\n super.addCollisionBoxesToList(world, x, y, z, mask, list, colliding);\n }\n\n setBlockBoundsForItemRender();\n }\n\n @Override\n public void setBlockBoundsForItemRender () {\n setBlockBounds(0, 0, 0, 1, 1, 1);\n }\n\n @Override\n public boolean isOpaqueCube () {\n return false;\n }\n\n @Override\n public boolean renderAsNormalBlock () {\n return false;\n }\n\n @Override\n public int getRenderType () {\n return ClientProxy.largePotRenderID;\n }\n\n @Override\n public boolean canRenderInPass (int pass) {\n ClientProxy.renderPass = pass;\n return true;\n }\n\n @Override\n public int getRenderBlockPass () {\n return 1;\n }\n\n @Override\n public boolean isSideSolid (IBlockAccess world, int x, int y, int z, ForgeDirection side) {\n return side != ForgeDirection.UP;\n }\n\n @Override\n public boolean shouldSideBeRendered (IBlockAccess blockAccess, int x, int y, int z, int side) {\n int nx = x;\n int nz = z;\n\n switch (side) {\n case 0:\n y++;\n break;\n case 1:\n y--;\n break;\n case 2:\n z++;\n break;\n case 3:\n z--;\n break;\n case 4:\n x++;\n break;\n case 5:\n x--;\n break;\n }\n\n if (side >= 2 && side < 6)\n return !isCompatibleNeighbor(blockAccess, x, y, z, nx - x, nz - z);\n\n return side != 1;\n }\n\n @Override\n public boolean canSustainPlant (IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plantable) {\n TileEntityLargePot te = getTileEntity(world, x, y, z);\n if (te == null || te.getSubstrate() == null)\n return false;\n\n EnumPlantType plantType = plantable.getPlantType(world, x, y + 1, z);\n Block plant = plantable.getPlant(world, x, y + 1, z);\n Block substrate = Block.getBlockFromItem(te.getSubstrate());\n\n ItemStack plantItem = new ItemStack(plant, 1, plantable.getPlantMetadata(world, x, y, z));\n if (PlantRegistry.instance().isBlacklisted(plantItem))\n return false;\n\n if (plant == Blocks.cactus)\n return substrate == Blocks.sand;\n\n return plantType == EnumPlantType.Crop && substrate == Blocks.farmland;\n }\n\n @Override\n public boolean isFertile (World world, int x, int y, int z) {\n return true;\n }\n\n @Override\n public void onNeighborBlockChange (World world, int x, int y, int z, Block block) {\n if (world.isRemote)\n return;\n\n if (y >= world.getHeight() - 1)\n return;\n\n Block overBlock = world.getBlock(x, y + 1, z);\n if (overBlock.isAir(world, x, y, z)) {\n TileEntityLargePot tileEntity = getTileEntity(world, x, y, z);\n if (tileEntity != null) {\n tileEntity.setItem(null, 0);\n tileEntity.markDirty();\n }\n }\n }\n\n public boolean isCompatibleNeighbor (IBlockAccess world, int x, int y, int z, int dx, int dz) {\n Block block = world.getBlock(x + dx, y, z + dz);\n if (block != this)\n return false;\n\n int meta = world.getBlockMetadata(x, y, z);\n int metaComp = world.getBlockMetadata(x + dx, y, z + dz);\n if (meta != metaComp)\n return false;\n\n if (!colored && meta == 1)\n return false;\n\n BlockLargePot pot = (BlockLargePot) block;\n TileEntityLargePot teThis = getTileEntity(world, x, y, z);\n TileEntityLargePot teThat = getTileEntity(world, x + dx, y, z + dz);\n if (teThis == null || teThat == null)\n return false;\n\n if (teThis.getSubstrate() != teThat.getSubstrate() || teThis.getSubstrateData() != teThat.getSubstrateData())\n return false;\n\n return true;\n }\n\n @Override\n public void onBlockHarvested (World world, int x, int y, int z, int p_149681_5_, EntityPlayer player) {\n super.onBlockHarvested(world, x, y, z, p_149681_5_, player);\n\n if (player.capabilities.isCreativeMode) {\n TileEntityLargePot te = getTileEntity(world, x, y, z);\n if (te != null) {\n te.setSubstrate(null, 0);\n te.setItem(null, 0);\n te.markDirty();\n }\n }\n }\n\n @Override\n public void breakBlock (World world, int x, int y, int z, Block block, int data) {\n TileEntityLargePot te = getTileEntity(world, x, y, z);\n\n if (te != null && te.getSubstrate() != null) {\n Block substrate = Block.getBlockFromItem(te.getSubstrate());\n if (substrate != Blocks.water) {\n if (substrate == Blocks.farmland)\n substrate = Blocks.dirt;\n\n ItemStack item = new ItemStack(substrate, 1, te.getSubstrateOriginalData());\n dropBlockAsItem(world, x, y, z, item);\n }\n }\n\n if (te != null && te.getFlowerPotItem() != null) {\n ItemStack item = new ItemStack(te.getFlowerPotItem(), 1, te.getFlowerPotData());\n dropBlockAsItem(world, x, y, z, item);\n }\n\n if (te != null)\n scratchDropMetadata = te.getCarving() << 8;\n\n super.breakBlock(world, x, y, z, block, data);\n }\n\n @Override\n public ArrayList<ItemStack> getDrops (World world, int x, int y, int z, int metadata, int fortune) {\n ArrayList<ItemStack> items = new ArrayList<ItemStack>();\n\n int count = quantityDropped(metadata, fortune, world.rand);\n for (int i = 0; i < count; i++) {\n Item item = getItemDropped(metadata, world.rand, fortune);\n if (item != null)\n items.add(new ItemStack(item, 1, metadata | scratchDropMetadata));\n }\n\n return items;\n }\n\n @Override\n public boolean onBlockActivated (World world, int x, int y, int z, EntityPlayer player, int side, float vx, float vy, float vz) {\n if (side != 1)\n return false;\n\n ItemStack itemStack = player.inventory.getCurrentItem();\n if (itemStack == null)\n return false;\n\n TileEntityLargePot tileEntity = getTileEntity(world, x, y, z);\n if (tileEntity == null) {\n tileEntity = new TileEntityLargePot();\n world.setTileEntity(x, y, z, tileEntity);\n }\n\n IPlantable plantable = null;\n Item item = itemStack.getItem();\n if (item instanceof IPlantable)\n plantable = (IPlantable) item;\n else if (item instanceof ItemBlock) {\n Block itemBlock = Block.getBlockFromItem(item);\n if (itemBlock instanceof IPlantable)\n plantable = (IPlantable) itemBlock;\n }\n\n if (tileEntity.getSubstrate() == null && isValidSubstrate(item))\n applySubstrate(world, x, y, z, tileEntity, player);\n else if (tileEntity.getSubstrate() != null && canApplyItemToSubstrate(tileEntity, itemStack))\n applyItemToSubstrate(world, x, y, z, tileEntity, player);\n else if (plantable != null && canSustainPlantActivated(world, x, y, z, plantable)) {\n if (!enoughAirAbove(world, x, y, z, plantable))\n return false;\n applyPlantable(world, x, y, z, tileEntity, player, plantable);\n }\n else\n return false;\n\n return true;\n }\n\n protected void applySubstrate (World world, int x, int y, int z, TileEntityLargePot tile, EntityPlayer player) {\n ItemStack substrate = player.inventory.getCurrentItem();\n\n if (!colored && world.getBlockMetadata(x, y, z) == 1) {\n world.setBlockToAir(x, y, z);\n world.playSoundAtEntity(player, \"dig.sand\", 1.0f, 1.0f);\n for (int i = 0; i < 4; i++)\n dropBlockAsItem(world, x, y, z, new ItemStack(Items.clay_ball));\n return;\n }\n\n if (substrate.getItem() == Items.water_bucket) {\n tile.setSubstrate(Item.getItemFromBlock(Blocks.water), 0);\n tile.markDirty();\n if (!player.capabilities.isCreativeMode)\n player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.bucket));\n }\n else {\n tile.setSubstrate(substrate.getItem(), substrate.getItemDamage());\n if (Block.getBlockFromItem(substrate.getItem()) == Blocks.farmland)\n tile.setSubstrate(substrate.getItem(), 1, substrate.getItemDamage());\n\n tile.markDirty();\n if (!player.capabilities.isCreativeMode && --substrate.stackSize <= 0)\n player.inventory.setInventorySlotContents(player.inventory.currentItem, null);\n }\n world.markBlockForUpdate(x, y, z);\n }\n\n protected boolean canApplyItemToSubstrate (TileEntityLargePot tile, ItemStack itemStack) {\n return itemStack.getItem() == Items.water_bucket\n || itemStack.getItem() == ModItems.usedSoilTestKit\n || itemStack.getItem() == Items.bucket\n || itemStack.getItem() instanceof ItemHoe\n || itemStack.getItem() instanceof ItemTool;\n }\n\n protected void applyItemToSubstrate (World world, int x, int y, int z, TileEntityLargePot tile, EntityPlayer player) {\n ItemStack item = player.inventory.getCurrentItem();\n if (item.getItem() == Items.bucket) {\n if (Block.getBlockFromItem(tile.getSubstrate()) == Blocks.water) {\n player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.water_bucket));\n tile.setSubstrate(null, 0);\n tile.markDirty();\n world.markBlockForUpdate(x, y, z);\n }\n return;\n }\n\n if (item.getItem() instanceof ItemTool && item.getItem().getToolClasses(item).contains(\"shovel\")) {\n if (Block.getBlockFromItem(tile.getSubstrate()) != Blocks.water) {\n ItemStack drop = new ItemStack(tile.getSubstrate(), 1, tile.getSubstrateOriginalData());\n dropBlockAsItem(world, x, y, z, drop);\n\n if (tile.getFlowerPotItem() != null) {\n drop = new ItemStack(tile.getFlowerPotItem(), 1, tile.getFlowerPotData());\n dropBlockAsItem(world, x, y, z, drop);\n }\n\n tile.setSubstrate(null, 0);\n tile.setItem(null, 0);\n tile.markDirty();\n world.markBlockForUpdate(x, y, z);\n\n world.playSoundEffect(x + .5f, y + .5f, z + .5f, Blocks.dirt.stepSound.getStepResourcePath(),\n (Blocks.dirt.stepSound.getVolume() + 1) / 2f, Blocks.dirt.stepSound.getPitch() * .8f);\n\n if (world.getBlock(x, y + 1, z) == ModBlocks.largePotPlantProxy)\n world.setBlockToAir(x, y + 1, z);\n }\n return;\n }\n\n if (item.getItem() == Items.water_bucket)\n applyWaterToSubstrate(world, x, y, z, tile, player);\n else if (item.getItem() instanceof ItemHoe)\n applyHoeToSubstrate(world, x, y, z, tile, player);\n else if (item.getItem() == ModItems.usedSoilTestKit)\n applyTestKit(world, x, y, z, item);\n }\n\n protected void applyWaterToSubstrate (World world, int x, int y, int z, TileEntityLargePot tile, EntityPlayer player) {\n if (Block.getBlockFromItem(tile.getSubstrate()) == Blocks.dirt) {\n tile.setSubstrate(Item.getItemFromBlock(Blocks.farmland), 1, tile.getSubstrateData());\n tile.markDirty();\n\n world.markBlockForUpdate(x, y, z);\n }\n }\n\n protected void applyHoeToSubstrate (World world, int x, int y, int z, TileEntityLargePot tile, EntityPlayer player) {\n Block substrate = Block.getBlockFromItem(tile.getSubstrate());\n if (substrate == Blocks.dirt || substrate == Blocks.grass) {\n tile.setSubstrate(Item.getItemFromBlock(Blocks.farmland), 1, tile.getSubstrateData());\n tile.markDirty();\n\n world.markBlockForUpdate(x, y, z);\n world.playSoundEffect(x + .5f, y + .5f, z + .5f, Blocks.farmland.stepSound.getStepResourcePath(),\n (Blocks.farmland.stepSound.getVolume() + 1) / 2f, Blocks.farmland.stepSound.getPitch() * .8f);\n }\n }\n\n public boolean applyTestKit (World world, int x, int y, int z, ItemStack testKit) {\n if (testKit.getItem() != ModItems.usedSoilTestKit)\n return false;\n\n TileEntityLargePot tileEntity = getTileEntity(world, x, y, z);\n if (tileEntity == null)\n return false;\n\n Block substrate = Block.getBlockFromItem(tileEntity.getSubstrate());\n if (substrate != Blocks.dirt && substrate != Blocks.grass && substrate != Blocks.farmland)\n return false;\n\n tileEntity.setBiomeData(testKit.getItemDamage());\n world.markBlockForUpdate(x, y, z);\n\n for (int i = 0; i < 5; i++) {\n double d0 = world.rand.nextGaussian() * 0.02D;\n double d1 = world.rand.nextGaussian() * 0.02D;\n double d2 = world.rand.nextGaussian() * 0.02D;\n world.spawnParticle(\"happyVillager\", x + world.rand.nextFloat(), y + .5f + world.rand.nextFloat(), z + world.rand.nextFloat(), d0, d1, d2);\n }\n\n return true;\n }\n\n protected void applyPlantable (World world, int x, int y, int z, TileEntityLargePot tile, EntityPlayer player, IPlantable plantable) {\n ItemStack itemStack = player.inventory.getCurrentItem();\n\n // TODO: Non-compliant IPlantable, use config\n Block itemBlock = plantable.getPlant(world, x, y, z);\n int itemMeta = itemStack.getItemDamage();\n if (itemBlock == null && plantable instanceof Block) {\n itemBlock = (Block) plantable;\n }\n else {\n int plantMeta = plantable.getPlantMetadata(world, x, y, z);\n if (plantMeta != world.getBlockMetadata(x, y, z))\n itemMeta = plantMeta;\n }\n\n world.setBlock(x, y + 1, z, ModBlocks.largePotPlantProxy, itemMeta, 3);\n if (itemBlock instanceof BlockDoublePlant || itemBlock.getRenderType() == 40)\n world.setBlock(x, y + 2, z, ModBlocks.largePotPlantProxy, itemMeta | 8, 3);\n\n tile.setItem(itemStack.getItem(), itemMeta);\n tile.markDirty();\n\n if (!player.capabilities.isCreativeMode && --itemStack.stackSize <= 0)\n player.inventory.setInventorySlotContents(player.inventory.currentItem, null);\n }\n\n private boolean enoughAirAbove (IBlockAccess world, int x, int y, int z, IPlantable plant) {\n Block plantBlock = plant.getPlant(world, x, y + 1, z);\n int height = (plantBlock instanceof BlockDoublePlant) ? 2 : 1;\n\n boolean enough = true;\n for (int i = 0; i < height; i++)\n enough &= world.isAirBlock(x, y + 1 + i, z);\n\n return enough;\n }\n\n protected boolean isValidSubstrate (Item item) {\n if (item == Items.water_bucket)\n return true;\n\n Block block = Block.getBlockFromItem(item);\n if (block == null)\n return false;\n\n return block == Blocks.dirt\n || block == Blocks.sand\n || block == Blocks.gravel\n || block == Blocks.soul_sand\n || block == Blocks.grass\n || block == Blocks.water\n || block == Blocks.farmland;\n }\n\n private boolean isSubstrateSolid (Item item) {\n Block block = Block.getBlockFromItem(item);\n return block != Blocks.water;\n }\n\n protected boolean canSustainPlantActivated (IBlockAccess world, int x, int y, int z, IPlantable plantable) {\n TileEntityLargePot te = getTileEntity(world, x, y, z);\n if (te == null || te.getSubstrate() == null)\n return false;\n\n Block substrate = Block.getBlockFromItem(te.getSubstrate());\n if (substrate == null)\n return false;\n\n EnumPlantType plantType = plantable.getPlantType(world, x, y + 1, z);\n Block plant = plantable.getPlant(world, x, y + 1, z);\n\n if (plant == null && plantable instanceof Block)\n plant = (Block) plantable;\n\n if (plant != null) {\n ItemStack plantItem = new ItemStack(plant, 1, plantable.getPlantMetadata(world, x, y, z));\n if (PlantRegistry.instance().isBlacklisted(plantItem))\n return false;\n }\n\n // TODO: Non-compliant IPlantable, use config\n if (plantType == null)\n plantType = EnumPlantType.Plains;\n\n if (plant == Blocks.cactus)\n return false;\n\n switch (plantType) {\n case Desert:\n return substrate == Blocks.sand;\n case Nether:\n return substrate == Blocks.soul_sand;\n //case Crop:\n // return substrate == Blocks.dirt || substrate == Blocks.farmland;\n case Cave:\n return true;\n case Plains:\n return substrate == Blocks.grass || substrate == Blocks.dirt;\n case Beach:\n return substrate == Blocks.grass || substrate == Blocks.dirt || substrate == Blocks.sand;\n case Water:\n return substrate == Blocks.water;\n default:\n return false;\n }\n }\n\n public TileEntityLargePot getTileEntity (IBlockAccess world, int x, int y, int z) {\n TileEntity tileEntity = world.getTileEntity(x, y, z);\n return (tileEntity != null && tileEntity instanceof TileEntityLargePot) ? (TileEntityLargePot) tileEntity : null;\n }\n\n @Override\n public TileEntity createNewTileEntity (World world, int data) {\n return new TileEntityLargePot();\n }\n\n @SideOnly(Side.CLIENT)\n @Override\n public IIcon getIcon (int side, int data) {\n if (colored)\n return iconArray[data & 15];\n\n switch (data) {\n case 1:\n return Blocks.clay.getIcon(side, 0);\n default:\n return iconSide;\n }\n }\n\n @SideOnly(Side.CLIENT)\n public IIcon getBottomIcon (int data) {\n if (!colored && data == 1)\n return Blocks.clay.getIcon(0, 0);\n else\n return iconSide;\n }\n\n @SideOnly(Side.CLIENT)\n public IIcon getOverlayIcon (int data) {\n if (iconOverlayArray[data] != null)\n return iconOverlayArray[data];\n\n return null;\n }\n\n @Override\n public void getSubBlocks (Item item, CreativeTabs creativeTabs, List blockList) {\n if (colored) {\n for (int i = 0; i < 16; i++)\n blockList.add(new ItemStack(item, 1, i));\n }\n else {\n blockList.add(new ItemStack(item, 1, 0));\n blockList.add(new ItemStack(item, 1, 1));\n }\n }\n\n @SideOnly(Side.CLIENT)\n @Override\n public void registerBlockIcons (IIconRegister iconRegister) {\n iconSide = iconRegister.registerIcon(ModularPots.MOD_ID + \":large_pot\");\n\n if (colored) {\n iconArray = new IIcon[16];\n for (int i = 0; i < 16; i++) {\n String colorName = ItemDye.field_150921_b[getBlockFromDye(i)];\n iconArray[i] = iconRegister.registerIcon(ModularPots.MOD_ID + \":large_pot_\" + colorName);\n }\n }\n\n iconOverlayArray = new IIcon[256];\n for (int i = 1; i < iconOverlayArray.length; i++) {\n PatternConfig pattern = ModularPots.config.getPattern(i);\n if (pattern != null && pattern.getOverlay() != null)\n iconOverlayArray[i] = iconRegister.registerIcon(ModularPots.MOD_ID + \":\" + pattern.getOverlay());\n }\n }\n\n public static int getBlockFromDye (int index) {\n return index & 15;\n }\n}", "public class ClientProxy extends CommonProxy\n{\n public static int renderPass = 0;\n public static int largePotRenderID;\n public static int transformPlantRenderID;\n public static int thinLogRenderID;\n public static int flowerLeafRenderID;\n public static int thinLogFenceRenderID;\n\n @Override\n public void registerRenderers ()\n {\n largePotRenderID = RenderingRegistry.getNextAvailableRenderId();\n transformPlantRenderID = RenderingRegistry.getNextAvailableRenderId();\n thinLogRenderID = RenderingRegistry.getNextAvailableRenderId();\n flowerLeafRenderID = RenderingRegistry.getNextAvailableRenderId();\n thinLogFenceRenderID = RenderingRegistry.getNextAvailableRenderId();\n\n RenderingRegistry.registerBlockHandler(largePotRenderID, new LargePotRenderer());\n RenderingRegistry.registerBlockHandler(transformPlantRenderID, new TransformPlantRenderer());\n RenderingRegistry.registerBlockHandler(thinLogRenderID, new ThinLogRenderer());\n RenderingRegistry.registerBlockHandler(flowerLeafRenderID, new FlowerLeafRenderer());\n RenderingRegistry.registerBlockHandler(thinLogFenceRenderID, new ThinLogFenceRenderer());\n }\n}", "public class TileEntityLargePot extends TileEntity\n{\n private static final int DEFAULT_BIOME_DATA = 65407;\n\n private Item flowerPotItem;\n private int flowerPotData;\n private Item substrate;\n private int substrateData;\n private int substrateOrigData;\n private int carving;\n\n private boolean hasBiomeOverride;\n private int biomeData = DEFAULT_BIOME_DATA;\n\n public TileEntityLargePot () { }\n\n public TileEntityLargePot (Item item, int itemData) {\n this.flowerPotItem = item;\n this.flowerPotData = itemData;\n }\n\n public Item getFlowerPotItem () {\n return flowerPotItem;\n }\n\n public int getFlowerPotData () {\n return flowerPotData;\n }\n\n public Item getSubstrate () {\n return substrate;\n }\n\n public int getSubstrateData () {\n return substrateData;\n }\n\n public int getSubstrateOriginalData () {\n return substrateOrigData;\n }\n\n public int getCarving () {\n return carving;\n }\n\n public boolean hasBiomeDataOverride () {\n return hasBiomeOverride;\n }\n\n public int getBiomeData () {\n return biomeData;\n }\n\n public float getBiomeTemperature () {\n return (biomeData & 255) / 255f;\n }\n\n public float getBiomeHumidity () {\n return ((biomeData >> 8) & 255) / 255f;\n }\n\n @Override\n public void writeToNBT (NBTTagCompound tag) {\n super.writeToNBT(tag);\n\n if (flowerPotItem != null)\n tag.setString(\"Item\", Item.itemRegistry.getNameForObject(flowerPotItem));\n if (flowerPotData != 0)\n tag.setShort(\"ItemD\", (short) flowerPotData);\n if (substrate != null)\n tag.setString(\"Subs\", Item.itemRegistry.getNameForObject(substrate));\n if (substrateData != 0)\n tag.setShort(\"SubsD\", (short) substrateData);\n if (substrateOrigData != 0)\n tag.setShort(\"SubsO\", (short) substrateOrigData);\n if (hasBiomeOverride || biomeData != DEFAULT_BIOME_DATA)\n tag.setInteger(\"Biom\", biomeData);\n if (carving != 0)\n tag.setShort(\"Carv\", (short) carving);\n }\n\n @Override\n public void readFromNBT (NBTTagCompound tag) {\n super.readFromNBT(tag);\n\n flowerPotItem = null;\n flowerPotData = 0;\n substrate = null;\n substrateData = 0;\n\n if (tag.hasKey(\"Item\")) {\n String itemString = tag.getString(\"Item\");\n if (itemString == null || itemString.equals(\"\"))\n flowerPotItem = null;\n else\n flowerPotItem = (Item)Item.itemRegistry.getObject(itemString);\n\n flowerPotData = tag.hasKey(\"ItemD\") ? tag.getShort(\"ItemD\") : 0;\n }\n\n if (tag.hasKey(\"Subs\")) {\n String substrateString = tag.getString(\"Subs\");\n if (substrateString == null || substrateString.equals(\"\"))\n substrate = null;\n else\n substrate = (Item)Item.itemRegistry.getObject(substrateString);\n\n substrateData = tag.hasKey(\"SubsD\") ? tag.getShort(\"SubsD\") : 0;\n substrateOrigData = tag.hasKey(\"SubsO\") ? tag.getShort(\"SubsO\") : 0;\n }\n\n hasBiomeOverride = tag.hasKey(\"Biom\");\n biomeData = tag.hasKey(\"Biom\") ? tag.getInteger(\"Biom\") : DEFAULT_BIOME_DATA;\n\n carving = tag.hasKey(\"Carv\") ? tag.getShort(\"Carv\") : 0;\n }\n\n @Override\n public Packet getDescriptionPacket () {\n NBTTagCompound tag = new NBTTagCompound();\n writeToNBT(tag);\n\n return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 5, tag);\n }\n\n @Override\n public void onDataPacket (NetworkManager net, S35PacketUpdateTileEntity pkt) {\n readFromNBT(pkt.func_148857_g());\n getWorldObj().func_147479_m(xCoord, yCoord, zCoord); // markBlockForRenderUpdate\n\n int y = yCoord;\n while (getWorldObj().getBlock(xCoord, ++y, zCoord) instanceof BlockLargePotPlantProxy)\n getWorldObj().func_147479_m(xCoord, y, zCoord);\n }\n\n public void setItem (Item item, int itemData) {\n this.flowerPotItem = item;\n this.flowerPotData = itemData;\n }\n\n public void setSubstrate (Item item, int itemData) {\n this.substrate = item;\n this.substrateData = itemData;\n }\n \n public void setSubstrate (Item item, int itemData, int origData) {\n this.substrate = item;\n this.substrateData = itemData;\n this.substrateOrigData = origData;\n }\n\n public void setBiomeData (int data) {\n this.biomeData = data;\n this.hasBiomeOverride = true;\n }\n\n public void setCarving (int id) {\n carving = id;\n }\n}", "public enum Direction {\n North (1 << 0),\n East (1 << 1),\n South (1 << 2),\n West (1 << 3),\n NorthWest (1 << 4),\n NorthEast (1 << 5),\n SouthEast (1 << 6),\n SouthWest (1 << 7);\n\n private final int flag;\n\n Direction (int flag) {\n this.flag = flag;\n }\n\n public int getFlag () {\n return this.flag;\n }\n\n public static boolean isSet (int bitflags, Direction direction) {\n return (bitflags & direction.flag) != 0;\n }\n\n public static int set (int bitflags, Direction direction) {\n return bitflags | direction.flag;\n }\n\n public static int clear (int bitflags, Direction direction) {\n return bitflags & ~direction.flag;\n }\n\n public static int setOrClear (int bitflags, Direction direction, boolean set) {\n return set ? set(bitflags, direction) : clear(bitflags, direction);\n }\n}", "public enum Direction {\n North (1 << 0),\n East (1 << 1),\n South (1 << 2),\n West (1 << 3),\n NorthWest (1 << 4),\n NorthEast (1 << 5),\n SouthEast (1 << 6),\n SouthWest (1 << 7);\n\n private final int flag;\n\n Direction (int flag) {\n this.flag = flag;\n }\n\n public int getFlag () {\n return this.flag;\n }\n\n public static boolean isSet (int bitflags, Direction direction) {\n return (bitflags & direction.flag) != 0;\n }\n\n public static int set (int bitflags, Direction direction) {\n return bitflags | direction.flag;\n }\n\n public static int clear (int bitflags, Direction direction) {\n return bitflags & ~direction.flag;\n }\n\n public static int setOrClear (int bitflags, Direction direction, boolean set) {\n return set ? set(bitflags, direction) : clear(bitflags, direction);\n }\n}" ]
import com.jaquadro.minecraft.modularpots.block.BlockLargePot; import com.jaquadro.minecraft.modularpots.client.ClientProxy; import com.jaquadro.minecraft.modularpots.tileentity.TileEntityLargePot; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import net.minecraft.block.Block; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import static com.jaquadro.minecraft.modularpots.block.BlockLargePot.Direction; import static com.jaquadro.minecraft.modularpots.block.BlockLargePot.Direction.*;
package com.jaquadro.minecraft.modularpots.client.renderer; public class LargePotRenderer implements ISimpleBlockRenderingHandler { private float[] baseColor = new float[3]; private float[] activeRimColor = new float[3]; private float[] activeInWallColor = new float[3]; private float[] activeBottomColor = new float[3]; private float[] activeSubstrateColor = new float[3]; @Override public void renderInventoryBlock (Block block, int metadata, int modelId, RenderBlocks renderer) { if (!(block instanceof BlockLargePot)) return; renderInventoryBlock((BlockLargePot) block, metadata, modelId, renderer); } private void renderInventoryBlock (BlockLargePot block, int metadata, int modelId, RenderBlocks renderer) { Tessellator tessellator = Tessellator.instance; int damage = metadata; metadata &= 15; block.setBlockBoundsForItemRender(); renderer.setRenderBoundsFromBlock(block); GL11.glRotatef(90, 0, 1, 0); GL11.glTranslatef(-.5f, -.5f, -.5f); // Bottom tessellator.startDrawingQuads(); tessellator.setNormal(0, -1, 0); renderer.renderFaceYNeg(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 0, metadata)); tessellator.draw(); // Sides tessellator.startDrawingQuads(); tessellator.setNormal(0, 0, -1); renderer.renderFaceZNeg(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 2, metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(0, 0, 1); renderer.renderFaceZPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 3, metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(-1, 0, 0); renderer.renderFaceXNeg(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 4, metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(1, 0, 0); renderer.renderFaceXPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 5, metadata)); tessellator.draw(); boolean blendEnabled = GL11.glIsEnabled(GL11.GL_BLEND); if (!blendEnabled) GL11.glEnable(GL11.GL_BLEND); // Overlay if ((damage & 0xFF00) != 0) { IIcon icon = block.getOverlayIcon((damage >> 8) & 255); tessellator.startDrawingQuads(); tessellator.setNormal(0, 0, -1); renderer.renderFaceZNeg(block, 0, 0, 0, icon); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(0, 0, 1); renderer.renderFaceZPos(block, 0, 0, 0, icon); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(-1, 0, 0); renderer.renderFaceXNeg(block, 0, 0, 0, icon); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(1, 0, 0); renderer.renderFaceXPos(block, 0, 0, 0, icon); tessellator.draw(); } if (!blendEnabled) GL11.glDisable(GL11.GL_BLEND); // Top Lip tessellator.startDrawingQuads(); tessellator.setNormal(0, 1, 0); float dim = .0625f; renderer.setRenderBounds(0, 0, 0, 1, 1, dim); renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata)); renderer.setRenderBounds(0, 0, 1 - dim, 1, 1, 1); renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata)); renderer.setRenderBounds(0, 0, 0, dim, 1, 1); renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata)); renderer.setRenderBounds(1 - dim, 0, 0, 1, 1, 1); renderer.renderFaceYPos(block, 0, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata)); tessellator.draw(); block.setBlockBoundsForItemRender(); renderer.setRenderBoundsFromBlock(block); // Interior Sides tessellator.startDrawingQuads(); tessellator.setNormal(0, 0, -1); renderer.renderFaceZNeg(block, 0, 0, 1 - dim, renderer.getBlockIconFromSideAndMetadata(block, 2, metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(0, 0, 1); renderer.renderFaceZPos(block, 0, 0, dim - 1, renderer.getBlockIconFromSideAndMetadata(block, 3, metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(-1, 0, 0); renderer.renderFaceXNeg(block, 1 - dim, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 4, metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(1, 0, 0); renderer.renderFaceXPos(block, dim - 1, 0, 0, renderer.getBlockIconFromSideAndMetadata(block, 5, metadata)); tessellator.draw(); // Interior Bottom tessellator.startDrawingQuads(); tessellator.setNormal(0, 1, 0); renderer.renderFaceYPos(block, 0, dim - 1, 0, renderer.getBlockIconFromSideAndMetadata(block, 1, metadata)); tessellator.draw(); GL11.glTranslatef(.5f, .5f, .5f); } @Override public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { if (!(block instanceof BlockLargePot)) return false; try { if (ClientProxy.renderPass == 0) return renderWorldBlockPass0(world, x, y, z, (BlockLargePot) block, modelId, renderer); else if (ClientProxy.renderPass == 1) return renderWorldBlockPass1(world, x, y, z, (BlockLargePot) block, modelId, renderer); } catch (Exception e) { } return false; } private void renderEmptyPlane (Block block, int x, int y, int z, RenderBlocks renderer) { renderer.setRenderBounds(0, 0, 0, 0, 0, 0); renderer.renderFaceYNeg(block, x, y, z, Blocks.hardened_clay.getIcon(0, 0)); } private boolean renderWorldBlockPass1 (IBlockAccess world, int x, int y, int z, BlockLargePot block, int modelId, RenderBlocks renderer) {
TileEntityLargePot tileEntity = block.getTileEntity(world, x, y, z);
2
daquexian/chaoli-forum-for-android-2
app/src/main/java/com/daquexian/chaoli/forum/utils/SignUpUtils.java
[ "public class ChaoliApplication extends Application {\n private static Context appContext;\n @Override\n public void onCreate() {\n super.onCreate();\n // train classifier on app start\n CodeProcessor.init(this);\n ChaoliApplication.appContext = getApplicationContext();\n if (NightModeHelper.isDay()){\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n }else {\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n }\n Stetho.initializeWithDefaults(this);\n }\n\n public static Context getAppContext() {\n return appContext;\n }\n\n /**\n * get the app-wide shared preference.\n * @return app-wide shared preference\n */\n public static SharedPreferences getSp() {\n return appContext.getSharedPreferences(Constants.APP_NAME, MODE_PRIVATE);\n }\n}", "@SuppressWarnings({\"unused\", \"WeakerAccess\"})\r\npublic class Constants\r\n{\r\n\tpublic static final String APP_NAME = \"chaoli\";\t\t// for shared preference\r\n\tpublic static final String APP_DIR_NAME = \"ChaoLi\";\t// for directory where save attachments\r\n\tpublic static final int paddingLeft = 16;\r\n\tpublic static final int paddingTop = 16;\r\n\tpublic static final int paddingRight = 16;\r\n\tpublic static final int paddingBottom = 16;\r\n\tpublic static final int getNotificationInterval = 15;\r\n\r\n\tpublic static final int MAX_IMAGE_WIDTH = (int) (Resources.getSystem().getDisplayMetrics().widthPixels * 0.8);\r\n\r\n\tpublic static final String BASE_BASE_URL = \"https://chaoli.club/\";\r\n\tpublic static final String BASE_URL = BASE_BASE_URL + \"index.php/\";\r\n\tpublic static final String GET_TOKEN_URL = BASE_URL + \"user/login.json\";\r\n\t// index.php/member/name.json/我是大缺弦\r\n\tpublic static final String GET_USER_ID_URL = BASE_URL + \"member/name.json/\";\r\n\tpublic static final String LOGIN_URL = BASE_URL + \"user/login\";\r\n\tpublic static final String HOMEPAGE_URL = BASE_URL;\r\n\tpublic static final String LOGOUT_PRE_URL = BASE_URL + \"user/logout?token=\";\r\n\tpublic static final String GET_CAPTCHA_URL = BASE_URL + \"mscaptcha\";\r\n\tpublic static final String SIGN_UP_URL = BASE_URL + \"user/join?invite=\";\r\n\tpublic static final String GET_ALL_NOTIFICATIONS_URL = BASE_URL + \"settings/notifications.json\";\r\n\t// activity.json/32/2\r\n\tpublic static final String GET_ACTIVITIES_URL = BASE_URL + \"member/activity.json/\";\r\n\t// statistics.ajax/32\r\n\tpublic static final String GET_STATISTICS_URL = BASE_URL + \"member/statistics.ajax/\";\r\n\t// index.json/channelName?searchDetail\r\n\t// index.json/all?search=%23%E4%B8%8A%E9%99%90%EF%BC%9A0%20~%20100\r\n\t// index.json/chem?search=%23%E7%B2%BE%E5%93%81\r\n\t//public static final String conversationListURL = BASE_URL + \"/conversations/index.json/\";\r\n\tpublic static final String conversationListURL = BASE_URL + \"conversations/index.json/\";\r\n\tpublic static final String ATTACHMENT_IMAGE_URL = \"https://dn-chaoli-upload.qbox.me/\";\r\n\t// index.json/1430/p2\r\n\tpublic static final String postListURL = BASE_URL + \"conversation/index.json/\";\r\n\tpublic static final String loginURL = BASE_URL + \"user/login\";\r\n\tpublic static final String replyURL = BASE_URL + \"?p=conversation/reply.ajax/\";\r\n\tpublic static final String editURL = BASE_URL + \"?p=conversation/editPost.ajax/\";\r\n\tpublic static final String cancelEditURL = BASE_URL + \"?p=attachment/removeSession/\";\r\n\tpublic static final String notifyNewMsgURL = BASE_URL + \"settings/notificationCheck/\";\r\n\tpublic static final String avatarURL = \"https://dn-chaoli-upload.qbox.me/\";\r\n\t// .ajax/<conversationId>/<floor>&userId=<myId>&token=<token>\r\n\tpublic static final String preQuoteURL = BASE_URL + \"?p=conversation/quotePost.json/\";\r\n\t// .json/<postId>&userId=<myId>&token=<token>\r\n\tpublic static final String quoteURL = BASE_URL + \"?p=conversation/reply.ajax/\";\r\n\tpublic static final String deleteURL = BASE_URL + \"?p=conversation/deletePost.ajax/\";\r\n\tpublic static final String restoreURL = BASE_URL + \"conversation/restorePost/\";\r\n\r\n\tpublic static final String GET_QUESTION_URL = \"https://chaoli.club/reg-exam/get-q.php?tags=\";\r\n\tpublic static final String CONFIRM_ANSWER_URL = \"https://chaoli.club/reg-exam/confirm.php\";\r\n\r\n\tpublic static final String GET_PROFILE_URL = BASE_URL + \"settings/general.json\";\r\n\tpublic static final String CHECK_NOTIFICATION_URL = BASE_URL + \"?p=settings/notificationCheck.ajax\";\r\n\tpublic static final String UPDATE_URL = BASE_URL + \"?p=conversations/update.ajax/all/\";\r\n\tpublic static final String MODIFY_SETTINGS_URL = BASE_URL + \"settings/general\";\r\n\r\n\tpublic static final String GO_TO_POST_URL = BASE_URL + \"conversation/post/\";\r\n\r\n\t/* 给主题设置版块 */\r\n\tpublic static final String SET_CHANNEL_URL = BASE_URL + \"?p=conversation/save.json/\";\r\n\t/* 发表主题 */\r\n\tpublic static final String POST_CONVERSATION_URL = BASE_URL + \"?p=conversation/start.ajax\";\r\n\t/* 添加可见用户 */\r\n\tpublic static final String ADD_MEMBER_URL = BASE_URL + \"?p=conversation/addMember.ajax/\";\r\n\t/* 取消可见用户 */\r\n\tpublic static final String REMOVE_MEMBER_URL = BASE_URL + \"?p=conversation/removeMember.ajax/\";\r\n\t/* 获取可见用户列表 */\r\n\tpublic static final String GET_MEMBERS_ALLOWED_URL = BASE_URL + \"\";\r\n\t/* 隐藏主题 */\r\n\tpublic static final String IGNORE_CONVERSATION_URL = BASE_URL + \"?p=conversation/ignore.ajax/\";\r\n\t/* 关注主题 */\r\n\tpublic static final String STAR_CONVERSATION_URL = BASE_URL + \"?p=conversation/star.json/\";\r\n\r\n\tpublic static final String SETTINGS_SP = \"settings\";\r\n\tpublic static final String INVITING_CODE_SP = \"icsp\";\r\n\tpublic static final String NIGHT_MODE = \"nightMode\";\r\n\tpublic static final String CLICK_TWICE_TO_EXIT = \"ctte\";\r\n\r\n\tpublic static final String GLOBAL = \"global\";\r\n\tpublic static final String FIRST_ENTER_DEMO_MODE = \"fedm\";\r\n\r\n\tpublic static final String conversationSP = \"conversationList\";\r\n\tpublic static final String conversationSPKey = \"listJSON\";\r\n\r\n\tpublic static final String postSP = \"postList\";\r\n\tpublic static final String postSPKey = \"listJSON\";\r\n\r\n\tpublic static final String loginSP = \"loginReturn\";\r\n\tpublic static final String loginSPKey = \"listJSON\";\r\n\tpublic static final String loginBool = \"logged\";\r\n\r\n\tpublic static final String[] IMAGE_FILE_EXTENSION = {\".jpg\", \".png\", \".gif\", \".jpeg\"};\r\n\r\n\tpublic static final String NONE = \"none\";\r\n\r\n\tpublic static final float MIN_EXPRESSION_ALPHA = 0.4f;\r\n\r\n\tpublic static final int POST_PER_PAGE = 20;\r\n\r\n\tpublic static final String[] iconStrs = new String[]{ \" /:) \" , \" /:D \" , \" /^b^ \" , \" /o.o \" , \" /xx \" , \" /# \" , \" /)) \" , \" /-- \" , \" /TT \" , \" /== \" ,\r\n\t\t\t\" /.** \" , \" /:( \" , \" /vv \" , \" /$$ \" , \" /?? \" , \" /:/ \" , \" /xo \" , \" /o0 \" , \" />< \" , \" /love \" ,\r\n\t\t\t\" /... \" , \" /XD \" , \" /ii \" , \" /^^ \" , \" /<< \" , \" />. \" , \" /-_- \" , \" /0o0 \" , \" /zz \" , \" /O!O \" ,\r\n\t\t\t\" /## \" , \" /:O \" , \" /< \" , \" /heart \" , \" /break \" , \" /rose \" , \" /gift \" , \" /bow \" , \" /moon \" , \" /sun \" ,\r\n\t\t\t\" /coin \" , \" /bulb \" , \" /tea \" , \" /cake \" , \" /music \" , \" /rock \" , \" /v \" , \" /good \" , \" /bad \" , \" /ok \" ,\r\n\t\t\t\" /asnowwolf-smile \" , \" /asnowwolf-laugh \" , \" /asnowwolf-upset \" , \" /asnowwolf-tear \" ,\r\n\t\t\t\" /asnowwolf-worry \" , \" /asnowwolf-shock \" , \" /asnowwolf-amuse \" };\r\n\tpublic static final String[] icons = new String[]{\"1\", \"2\", \"3\", \"4\",\r\n\t\t\t\"5\", \"6\", \"7\", \"8\", \"9\",\r\n\t\t\t\"10\", \"11\", \"12\", \"13\", \"14\",\r\n\t\t\t\"15\", \"16\", \"17\", \"18\", \"19\",\r\n\t\t\t\"20\", \"21\", \"22\", \"23\", \"24\",\r\n\t\t\t\"25\", \"26\", \"27\", \"28\", \"29\",\r\n\t\t\t\"30\", \"31\", \"32\", \"33\", \"34\",\r\n\t\t\t\"35\", \"36\", \"37\", \"38\", \"39\",\r\n\t\t\t\"40\", \"41\", \"42\", \"43\", \"44\",\r\n\t\t\t\"45\", \"46\", \"47\", \"48\", \"49\",\r\n\t\t\t\"50\", \"asonwwolf_smile\", \"asonwwolf_laugh\", \"asonwwolf_upset\", \"asonwwolf_tear\",\r\n\t\t\t\"asonwwolf_worry\", \"asonwwolf_shock\", \"asonwwolf_amuse\"};\r\n}\r", "public class BusinessQuestion {\n private static final String TAG = \"BusinessQuestion\";\n public String id;\n public String question;\n public Boolean choice;\n public Boolean multiAnswer;\n public ObservableList<String> options;\n\n public ObservableList<Boolean> isChecked = new ObservableArrayList<>();\n public ObservableField<String> answer = new ObservableField<>();\n\n public BusinessQuestion(Question item) {\n for (int i = 0; i < 4; i++) isChecked.add(false);\n id = item._id.$id;\n question = item.question;\n choice = Boolean.valueOf(item.choice);\n multiAnswer = Boolean.valueOf(item.multi_answer);\n options = new ObservableArrayList<>();\n options.addAll(item.options);\n while (options.size() < 4) {\n options.add(ChaoliApplication.getAppContext().getString(R.string.useless_option));\n }\n }\n\n public static ArrayList<BusinessQuestion> fromList(List<Question> questionList) {\n ArrayList<BusinessQuestion> businessQuestionList = new ArrayList<>();\n for (Question item : questionList) {\n businessQuestionList.add(new BusinessQuestion(item));\n }\n return businessQuestionList;\n }\n}", "public class Question {\n public class id{\n public String $id;\n }\n public id _id;\n\n public String getQuestion() {\n return question;\n }\n\n public Boolean isMultiAnswer(){\n return Boolean.valueOf(multi_answer);\n }\n\n public List<String> getOptions() {\n return options;\n }\n\n public String getChoice() {\n return choice;\n }\n\n public String question, choice, multi_answer;\n\n public List<String> options = new ArrayList<>();\n public List<String> answers = new ArrayList<>();\n\n public Question() {}\n public Question(BusinessQuestion businessQuestion) {\n _id = new id();\n _id.$id = businessQuestion.id;\n choice = String.valueOf(businessQuestion.choice);\n multi_answer = String.valueOf(businessQuestion.multiAnswer);\n if (choice.equals(\"false\")) answers.add(businessQuestion.answer.get());\n else {\n for (int i = 0; i < businessQuestion.isChecked.size(); i++) {\n if (businessQuestion.isChecked.get(i)) answers.add(String.valueOf(i));\n }\n }\n }\n\n public static ArrayList<Question> fromList(List<BusinessQuestion> list) {\n ArrayList<Question> questionList = new ArrayList<>();\n for (BusinessQuestion businessQuestion : list) {\n questionList.add(new Question(businessQuestion));\n }\n return questionList;\n }\n}", "public class MyOkHttp {\n private final static String TAG = \"MyOkHttp\";\n private static OkHttpClient okHttpClient;\n private static CookiesManager mCookiesManager;\n private static Context mContext = ChaoliApplication.getAppContext();\n\n public static void cancel(Object tag) {\n for (Call call : okHttpClient.dispatcher().queuedCalls()) {\n if (tag.equals(call.request().tag())) call.cancel();\n }\n for (Call call : okHttpClient.dispatcher().runningCalls()) {\n if (tag.equals(call.request().tag())) call.cancel();\n }\n }\n\n private static class MyInterceptor implements Interceptor {\n @Override\n public Response intercept(Chain chain) throws IOException {\n Response response = chain.proceed(chain.request());\n Log.w(\"Retrofit@Response\", response.body().string());\n return response;\n }\n }\n\n public synchronized static OkHttpClient getClient(){\n if (okHttpClient == null) {\n OkHttpClient.Builder builder = new OkHttpClient.Builder();\n /**\n * 解决5.0以下系统默认不支持TLS协议导致网络访问失败的问题。\n */\n try {\n // Create a trust manager that does not validate certificate chains\n final X509TrustManager trustAllCert =\n new X509TrustManager() {\n @Override\n public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {\n }\n\n @Override\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return new java.security.cert.X509Certificate[]{};\n }\n };\n // Install the all-trusting trust manager\n final SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(trustAllCert);\n builder.sslSocketFactory(sslSocketFactory, trustAllCert);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n mCookiesManager = new CookiesManager();\n okHttpClient = builder\n .cookieJar(mCookiesManager)\n .connectTimeout(15, TimeUnit.SECONDS)\n .readTimeout(30, TimeUnit.SECONDS)\n .addNetworkInterceptor(new StethoInterceptor())\n //.addInterceptor(new MyInterceptor())\n //.connectTimeout(5, TimeUnit.SECONDS)\n //.readTimeout(5, TimeUnit.SECONDS)\n .build();\n }\n return okHttpClient;\n }\n\n public synchronized static void clearCookie(){\n if (mCookiesManager != null) {\n mCookiesManager.clear();\n }\n }\n\n public static class MyOkHttpClient {\n private MultipartBody.Builder builder;\n //private FormBody.Builder formBuilder;\n private RequestBody requestBody;\n private Request.Builder requestBuilder;\n private Request request;\n\n public MyOkHttpClient get(String url){\n requestBuilder = new Request.Builder().get();\n requestBuilder = requestBuilder.url(url);\n return this;\n }\n public MyOkHttpClient post(String url){\n requestBody = builder.build();\n requestBuilder = new Request.Builder().post(requestBody);\n requestBuilder = requestBuilder.url(url);\n return this;\n }\n public MyOkHttpClient add(String key, String value) {\n if (builder == null) builder = new MultipartBody.Builder().setType(MultipartBody.FORM);\n builder.addFormDataPart(key, value);\n //if (formBuilder == null) formBuilder = new FormBody.Builder();\n //formBuilder.add(key, value);\n return this;\n }\n\n public MyOkHttpClient add(String key, String type, File file) {\n if (builder == null) builder = new MultipartBody.Builder().setType(MultipartBody.FORM);\n if (file != null) builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(type), file));\n return this;\n }\n /*public MyOkHttpClient url(String url) {\n requestBuilder = requestBuilder.url(url);\n return this;\n }*/\n\n public void enqueue(final Callback callback) {\n request = requestBuilder.build();\n Call call = getClient().newCall(request);\n call.enqueue(new okhttp3.Callback() {\n @Override\n public void onFailure(final Call call, final IOException e) {\n new Handler(ChaoliApplication.getAppContext().getMainLooper()).post(new Runnable() {\n @Override\n public void run() {\n callback.onFailure(call, e);\n }\n });\n }\n\n @Override\n public void onResponse(final Call call, final Response response) throws IOException {\n final String responseStr = response.body().string();\n new Handler(ChaoliApplication.getAppContext().getMainLooper()).post(new Runnable() {\n @Override\n public void run() {\n try {\n callback.onResponse(call, response, responseStr);\n } catch (IOException e) {\n onFailure(call, e);\n }\n }\n });\n response.body().close();\n }\n });\n }\n @Deprecated\n public void enqueue(final Context context, final Callback callback) {\n enqueue(callback);\n }\n\n public void enqueue(final Callback1 callback) {\n request = requestBuilder.build();\n Call call = getClient().newCall(request);\n call.enqueue(new okhttp3.Callback() {\n @Override\n public void onFailure(final Call call, final IOException e) {\n callback.onFailure(call, e);\n }\n\n @Override\n public void onResponse(final Call call, final Response response) throws IOException {\n callback.onResponse(call, response);\n }\n });\n }\n\n @Deprecated\n public void enqueue(final Context context, final Callback1 callback) {\n enqueue(callback);\n }\n }\n public static abstract class Callback {\n public abstract void onFailure(Call call, IOException e);\n public abstract void onResponse(Call call, Response response, String responseStr) throws IOException;\n }\n\n public static abstract class Callback1 {\n public abstract void onFailure(Call call, IOException e);\n public abstract void onResponse(Call call, Response response) throws IOException;\n }\n\n /**\n * https://segmentfault.com/a/1190000004345545\n */\n private static class CookiesManager implements CookieJar {\n private final PersistentCookieStore cookieStore = new PersistentCookieStore(mContext);\n\n @Override\n public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {\n if (cookies != null && cookies.size() > 0) {\n for (Cookie item : cookies) {\n cookieStore.add(url, item);\n }\n }\n }\n\n @Override\n public List<Cookie> loadForRequest(HttpUrl url) {\n return cookieStore.get(url);\n }\n\n public void clear(){\n cookieStore.removeAll();\n }\n }\n}", "public class MyRetrofit {\n private final static String TAG = \"MyRetrofit\";\n\n private static Retrofit retrofit;\n private static ChaoliService service;\n\n public synchronized static ChaoliService getService(){\n if (service == null) {\n Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerTypeAdapter()).create();\n retrofit = new Retrofit.Builder()\n .baseUrl(Constants.BASE_BASE_URL)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .client(MyOkHttp.getClient())\n .build();\n service = retrofit.create(ChaoliService.class);\n }\n return service;\n }\n\n private static class IntegerTypeAdapter extends TypeAdapter<Integer> {\n @Override\n public void write(JsonWriter writer, Integer value) throws IOException {\n if (value == null) {\n writer.nullValue();\n return;\n }\n writer.value(value);\n }\n\n @Override\n public Integer read(JsonReader reader) throws IOException {\n if(reader.peek() == JsonToken.NULL){\n reader.nextNull();\n return null;\n }\n String stringValue = reader.nextString();\n try{\n int value = Integer.valueOf(stringValue);\n return value;\n }catch(NumberFormatException e){\n return null;\n }\n }\n }\n}" ]
import android.util.Log; import com.daquexian.chaoli.forum.ChaoliApplication; import com.daquexian.chaoli.forum.meta.Constants; import com.daquexian.chaoli.forum.model.BusinessQuestion; import com.daquexian.chaoli.forum.model.Question; import com.daquexian.chaoli.forum.network.MyOkHttp; import com.daquexian.chaoli.forum.network.MyRetrofit; import com.google.gson.Gson; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.daquexian.chaoli.forum.utils; /** * Created by jianhao on 16-3-27. */ public class SignUpUtils { private static final String TAG = "SignUpUtils"; public static final Map<String, String> subjectTags = new HashMap<String, String>(){{ put("数学", "math"); put("生物", "bio"); put("化学", "chem"); put("物理", "phys"); put("综合", ""); }}; public static int ANSWERS_WRONG = -1; public static void getQuestionObjList(final GetQuestionObserver observer, String subject){ MyRetrofit.getService() .getQuestion(subject) .enqueue(new Callback<ArrayList<Question>>() { @Override public void onResponse(Call<ArrayList<Question>> call, Response<ArrayList<Question>> response) {
observer.onGetQuestionObjList(BusinessQuestion.fromList(response.body()));
2
DeFuture/AmazeFileManager-master
src/main/java/com/amaze/filemanager/adapters/Recycleradapter.java
[ "public class Main extends android.support.v4.app.Fragment {\n public File[] file;\n public ArrayList<Layoutelements> list;\n public ArrayList<SmbFile> smbFiles;\n public Recycleradapter adapter;\n public Futils utils;\n public boolean selection;\n public boolean results = false,smbMode=false;\n public ActionMode mActionMode;\n public SharedPreferences Sp;\n public Drawable folder,apk,darkimage,darkvideo;\n Resources res;\n public LinearLayout buttons;\n public int sortby, dsort, asc;\n\n public String home, current = Environment.getExternalStorageDirectory().getPath();\n Shortcuts sh;\n HashMap<String, Bundle> scrolls = new HashMap<String, Bundle>();\n Main ma = this;\n public HistoryManager history,hidden;\n IconUtils icons;\n public boolean rootMode,showHidden,circularImages,showPermissions,showSize,showLastModified;\n View footerView;\n public LinearLayout pathbar;\n public CountDownTimer timer;\n private View rootView;\n public android.support.v7.widget.RecyclerView listView;\n public boolean gobackitem,islist,showThumbs,coloriseIcons,showDividers;\n public IconHolder ic;\n public MainActivity mainActivity;\n public boolean showButtonOnStart = false;\n public String skin, fabSkin,iconskin;\n public int skinselection;\n public int theme;\n public int theme1;\n public float[] color;\n public ColorMatrixColorFilter colorMatrixColorFilter;\n public Animation animation,animation1;\n public String year,goback;\n ArrayList<String> hiddenfiles;\n String Intentpath,itemsstring;\n int no;\n TabHandler tabHandler;\n boolean savepaths;\n LinearLayoutManager mLayoutManager;\n GridLayoutManager mLayoutManagerGrid;\n public SwipeRefreshLayout mSwipeRefreshLayout;\n boolean addheader=false;\n StickyRecyclerHeadersDecoration headersDecor;\n DividerItemDecoration dividerItemDecoration;\n public int paddingTop;\n int mToolbarHeight,hidemode;\n View mToolbarContainer;\n public int skin_color,icon_skin_color;\n boolean SmbAnonym=false;\n String smbUser,smbPass;\n public String smbPath;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n mainActivity=(MainActivity)getActivity();\n no=getArguments().getInt(\"no\", 1);\n home=getArguments().getString(\"home\");\n current=getArguments().getString(\"lastpath\");\n tabHandler=new TabHandler(getActivity(),null,null,1);\n Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());\n savepaths=Sp.getBoolean(\"savepaths\", true);\n skin = Sp.getString(\"skin_color\", \"#3f51b5\");\n fabSkin = Sp.getString(\"fab_skin_color\", \"#e91e63\");\n iconskin=Sp.getString(\"icon_skin_color\", skin);\n skin_color=Color.parseColor(skin);\n icon_skin_color=Color.parseColor(iconskin);\n sh = new Shortcuts(getActivity());\n islist = Sp.getBoolean(\"view\", true);\n Calendar calendar = Calendar.getInstance();\n year=(\"\"+calendar.get(Calendar.YEAR)).substring(2, 4);\n theme=Integer.parseInt(Sp.getString(\"theme\", \"0\"));\n theme1 = theme==2 ? PreferenceUtils.hourOfDay() : theme;\n hidemode=Sp.getInt(\"hidemode\", 0);\n showPermissions=Sp.getBoolean(\"showPermissions\", false);\n showSize=Sp.getBoolean(\"showFileSize\",false);\n showDividers=Sp.getBoolean(\"showDividers\",true);\n gobackitem=Sp.getBoolean(\"goBack_checkbox\", false);\n circularImages=Sp.getBoolean(\"circularimages\",true);\n showLastModified=Sp.getBoolean(\"showLastModified\",true);\n icons = new IconUtils(Sp, getActivity());\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n rootView = inflater.inflate(R.layout.main_frag, container, false);\n listView = (android.support.v7.widget.RecyclerView) rootView.findViewById(R.id.listView);\n if(getArguments()!=null)\n Intentpath=getArguments().getString(\"path\");\n animation = AnimationUtils.loadAnimation(getActivity(), R.anim.load_list_anim);\n animation1 = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_newtab);\n mToolbarContainer=getActivity().findViewById(R.id.lin);\n buttons = (LinearLayout) getActivity().findViewById(R.id.buttons);\n pathbar = (LinearLayout) getActivity().findViewById(R.id.pathbar);\n showThumbs=Sp.getBoolean(\"showThumbs\", true);\n ic=new IconHolder(getActivity(),showThumbs,!islist);\n res = getResources();\n goback=res.getString(R.string.goback);\n itemsstring=res.getString(R.string.items);\n apk=res.getDrawable(R.drawable.ic_doc_apk_grid);\n if(theme1==1) {\n\n mainActivity.getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.holo_dark_background)));\n } else {\n\n if(islist) mainActivity.getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.background_light)));\n\n } listView.setHasFixedSize(true);\n mLayoutManager=new LinearLayoutManager(getActivity());\n int columns=Integer.parseInt(Sp.getString(\"columns\",\"3\"));\n mLayoutManagerGrid=new GridLayoutManager(getActivity(),columns);\n if (islist) {\n listView.setLayoutManager(mLayoutManager);\n } else {\n listView.setLayoutManager(mLayoutManagerGrid);\n }\n mToolbarContainer.setBackgroundColor(skin_color);\n // listView.setPadding(listView.getPaddingLeft(), paddingTop, listView.getPaddingRight(), listView.getPaddingBottom());\n return rootView;\n }public int dpToPx(int dp) {\n DisplayMetrics displayMetrics = getResources().getDisplayMetrics();\n int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));\n return px;\n }\n public static int getToolbarHeight(Context context) {\n final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(\n new int[]{android.R.attr.actionBarSize});\n int toolbarHeight = (int) styledAttributes.getDimension(0, 0);\n styledAttributes.recycle();\n\n return toolbarHeight;\n }\n @Override\n public void onActivityCreated(Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n setHasOptionsMenu(false);\n mainActivity = (MainActivity) getActivity();\n utils = new Futils();\n String x=getSelectionColor();\n skinselection=Color.parseColor(x);\n color=calculatevalues(x);\n ColorMatrix colorMatrix = new ColorMatrix(calculatefilter(color));\n colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);\n history = new HistoryManager(getActivity(), \"Table1\");\n hidden = new HistoryManager(getActivity(), \"Table2\");\n hiddenfiles=hidden.readTable();\n rootMode = Sp.getBoolean(\"rootmode\", false);\n showHidden=Sp.getBoolean(\"showHidden\",false);\n coloriseIcons=Sp.getBoolean(\"coloriseIcons\",false);\n if(islist){\n folder = res.getDrawable(R.drawable.ic_grid_folder_new);}\n else{folder = res.getDrawable(R.drawable.ic_grid_folder1);}\n folder = res.getDrawable(R.drawable.ic_grid_folder_new);\n getSortModes();\n darkimage=res.getDrawable(R.drawable.ic_doc_image_dark);\n darkvideo=res.getDrawable(R.drawable.ic_doc_video_dark);\n this.setRetainInstance(false);\n File f;\n if(savepaths)\n f=new File(current);\n else f=new File(home);\n mainActivity.initiatebbar();\n\n // use a linear layout manager\n footerView=getActivity().getLayoutInflater().inflate(R.layout.divider, null);\n mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);\n\n mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n @Override\n public void onRefresh() {\n loadlist(new File(current),false);\n }\n });\n mToolbarHeight=getToolbarHeight(getActivity());\n paddingTop = (mToolbarHeight) + dpToPx(72);\n if(hidemode==2)mToolbarHeight=paddingTop;\n mToolbarContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n @Override\n public void onGlobalLayout() {\n if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {\n mToolbarContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);\n }\n else {\n mToolbarContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);\n }\n paddingTop=mToolbarContainer.getHeight();\n\n if(hidemode!=2)mToolbarHeight=mainActivity.toolbar.getHeight();\n }\n\n });\n mSwipeRefreshLayout.setColorSchemeColors(Color.parseColor(fabSkin));\n mSwipeRefreshLayout.setProgressViewOffset(true, paddingTop, paddingTop + dpToPx(72));\n\n if (savedInstanceState == null){\n if(Intentpath!=null) {\n File file1=new File(Intentpath);\n if(file1.isDirectory()) {\n\n loadlist(file1,false);\n }\n else {\n utils.openFile(file1, mainActivity);\n loadlist(f,false);\n }\n } else {\n\n loadlist(f, false);\n }\n } else {\n Bundle b = new Bundle();\n String cur = savedInstanceState.getString(\"current\");\n if (cur != null) {\n b.putInt(\"index\", savedInstanceState.getInt(\"index\"));\n b.putInt(\"top\", savedInstanceState.getInt(\"top\"));\n scrolls.put(cur, b);\n retreiveSmbFromSavedInstance(savedInstanceState);\n list = savedInstanceState.getParcelableArrayList(\"list\");\n if (savedInstanceState.getBoolean(\"results\")) {\n try {\n createViews(list, true, new File(current));\n ((TextView) ma.pathbar.findViewById(R.id.pathname)).setText(ma.utils.getString(ma.getActivity(), R.string.searchresults));\n results = true;\n } catch (Exception e) {\n }\n }else{\n createViews(list, true, new File(cur));\n }\n if (savedInstanceState.getBoolean(\"selection\")) {\n\n for (int i : savedInstanceState.getIntegerArrayList(\"position\")) {\n adapter.toggleChecked(i);\n }\n }\n }\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n\n int index;\n View vi;\n if(listView!=null){\n if (islist) {\n\n index = (mLayoutManager).findFirstVisibleItemPosition();\n vi = listView.getChildAt(0);\n } else {\n index = (mLayoutManagerGrid).findFirstVisibleItemPosition();\n vi = listView.getChildAt(0);\n }\n int top = (vi == null) ? 0 : vi.getTop();\n outState.putInt(\"index\", index);\n outState.putInt(\"top\", top);\n outState.putParcelableArrayList(\"list\", list);\n outState.putString(\"current\", current);\n outState.putBoolean(\"selection\", selection);\n if (selection) {\n outState.putIntegerArrayList(\"position\", adapter.getCheckedItemPositions());\n }\n if(results){\n outState.putBoolean(\"results\", results);\n }\n if(smbMode)\n addSmbToSavedInstance(outState,smbUser,smbPass,smbFiles,SmbAnonym);\n }}\n\n public void home() {\n ma.loadlist(new File(ma.home), false);\n }\n\n\n\n public void onListItemClicked(int position, View v) {\n if (results) {\n String path = list.get(position).getDesc();\n if(selection)adapter.toggleChecked(position);\n else{\n\n final File f = new File(path);\n if (list.get(position).isDirectory()) {\n\n loadlist(f, false);\n results = false;\n } else {\n if (mainActivity.mReturnIntent) {\n returnIntentResults(f);\n } else\n utils.openFile(f, (MainActivity) getActivity());\n }}\n }else if(smbMode){\n if(selection)adapter.toggleChecked(position);\n else{Toast.makeText(getActivity(),\"Go\",Toast.LENGTH_LONG).show();\n loadSmblist(smbFiles.get(position), false);}\n } else if (selection == true) {\n if(!list.get(position).getSize().equals(goback)){\n adapter.toggleChecked(position);\n }else{selection = false;\n if(mActionMode!=null)\n mActionMode.finish();\n mActionMode = null;}\n\n } else {\n if(!list.get(position).getSize().equals(goback)){\n\n String path;\n Layoutelements l=list.get(position);\n\n if(!l.hasSymlink()){\n\n path= l.getDesc();\n }\n else {\n\n path=l.getSymlink();\n }\n\n final File f = new File(path);\n\n if (l.isDirectory()) {\n\n computeScroll();\n loadlist(f, false);\n } else {\n if (mainActivity.mReturnIntent) {\n returnIntentResults(f);\n } else {\n\n utils.openFile(f, (MainActivity) getActivity());\n }\n }\n\n } else {\n\n goBackItemClick();\n\n }\n }\n }\n\n private void returnIntentResults (File file) {\n mainActivity.mReturnIntent = false;\n\n Intent intent = new Intent();\n if (mainActivity.mRingtonePickerIntent) {\n\n Log.d(\"pickup\", \"ringtone\");\n Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());\n\n intent.putExtra(android.media.RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri);\n getActivity().setResult(getActivity().RESULT_OK, intent);\n getActivity().finish();\n } else {\n\n Log.d(\"pickup\", \"file\");\n intent.setData(Uri.fromFile(file));\n getActivity().setResult(getActivity().RESULT_OK, intent);\n getActivity().finish();\n }\n }\n\n public void loadlist(final File f, boolean back) {\n if(mActionMode!=null){mActionMode.finish();}\n new LoadList(back, ma).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, f);\n\n try {\n animation = AnimationUtils.loadAnimation(getActivity(), R.anim.load_list_anim);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n listView.setAnimation(animation);\n }\n public void loadSmblist(final SmbFile f, boolean back) {\n if(mActionMode!=null){mActionMode.finish();}\n new LoadSmbList(back, ma).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, f);\n\n try {\n animation = AnimationUtils.loadAnimation(getActivity(), R.anim.load_list_anim);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n listView.setAnimation(animation);\n }\n\n @SuppressWarnings(\"unchecked\")\n public void loadsearchlist(ArrayList<String[]> f) {\n\n new LoadSearchList(ma).execute(f);\n\n }\n\n\n public void createViews(ArrayList<Layoutelements> bitmap, boolean back, File f) {\n try {\n if (bitmap != null) {\n if(gobackitem)\n if (!f.getPath().equals(\"/\")) {\n if (bitmap.size() == 0 || !bitmap.get(0).getSize().equals(goback))\n bitmap.add(0, utils.newElement(res.getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha), \"..\", \"\", \"\", goback,false, true,\"\"));\n }\n adapter = new Recycleradapter(ma,\n bitmap, ma.getActivity());\n mSwipeRefreshLayout.setRefreshing(false);\n try { listView.setAdapter(adapter);\n if(!addheader && islist){\n listView.removeItemDecoration(dividerItemDecoration);\n listView.removeItemDecoration(headersDecor);\n addheader=true;}\n if(addheader && islist){\n dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST,showDividers);\n listView.addItemDecoration(dividerItemDecoration);\n\n headersDecor = new StickyRecyclerHeadersDecoration(adapter);\n listView.addItemDecoration(headersDecor);addheader=false;}\n results = false;\n current = f.getPath();\n if (back) {\n if (scrolls.containsKey(current)) {\n Bundle b = scrolls.get(current);\n if(islist)\n mLayoutManager.scrollToPositionWithOffset(b.getInt(\"index\"),b.getInt(\"top\"));\n else mLayoutManagerGrid.scrollToPositionWithOffset(b.getInt(\"index\"),b.getInt(\"top\"));\n }\n }\n //floatingActionButton.show();\n mainActivity.updatepaths();\n listView.setOnScrollListener(new HidingScrollListener(mToolbarHeight,hidemode) {\n\n @Override\n public void onMoved(int distance) {\n mToolbarContainer.setTranslationY(-distance);\n }\n\n @Override\n public void onShow() {\n mToolbarContainer.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();\n }\n\n @Override\n public void onHide() {\n mToolbarContainer.findViewById(R.id.lin).animate().translationY(-mToolbarHeight).setInterpolator(new AccelerateInterpolator(2)).start();\n }\n\n });\n if (buttons.getVisibility() == View.VISIBLE) mainActivity.bbar(this);\n\n mainActivity.updateDrawer(current);\n mainActivity.updatepager();\n\n } catch (Exception e) {\n }\n } else {//Toast.makeText(getActivity(),res.getString(R.string.error),Toast.LENGTH_LONG).show();\n loadlist(new File(current), true);\n }\n } catch (Exception e) {\n }\n\n }\n\n\n public ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {\n private void hideOption(int id, Menu menu) {\n MenuItem item = menu.findItem(id);\n item.setVisible(false);\n }\n\n private void showOption(int id, Menu menu) {\n MenuItem item = menu.findItem(id);\n item.setVisible(true);\n }\n public void initMenu(Menu menu) {\n /*menu.findItem(R.id.cpy).setIcon(icons.getCopyDrawable());\n menu.findItem(R.id.cut).setIcon(icons.getCutDrawable());\n menu.findItem(R.id.delete).setIcon(icons.getDeleteDrawable());\n menu.findItem(R.id.all).setIcon(icons.getAllDrawable());*/\n }\n View v;\n // called when the action mode is created; startActionMode() was called\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\n // Inflate a menu resource providing context menu items\n MenuInflater inflater = mode.getMenuInflater();\n v=getActivity().getLayoutInflater().inflate(R.layout.actionmode,null);\n try {\n v.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n }\n });\n v.setMinimumWidth(getActivity().findViewById(R.id.tab_spinner).getWidth());\n } catch (Exception e) {\n e.printStackTrace();\n }\n mode.setCustomView(v);\n mainActivity.setPagingEnabled(false);\n // assumes that you have \"contexual.xml\" menu resources\n inflater.inflate(R.menu.contextual, menu);\n initMenu(menu);\n hideOption(R.id.addshortcut,menu);\n hideOption(R.id.sethome, menu);\n hideOption(R.id.rename, menu);\n hideOption(R.id.share, menu);\n hideOption(R.id.about, menu);\n hideOption(R.id.openwith, menu);\n hideOption(R.id.ex, menu);\n if(mainActivity.mReturnIntent)\n showOption(R.id.openmulti,menu);\n //hideOption(R.id.setringtone,menu);\n mode.setTitle(utils.getString(getActivity(), R.string.select));\n /*if(Build.VERSION.SDK_INT<19)\n getActivity().findViewById(R.id.action_bar).setVisibility(View.GONE);*/\n // rootView.findViewById(R.id.buttonbarframe).setBackgroundColor(res.getColor(R.color.toolbar_cab));\n ObjectAnimator anim = ObjectAnimator.ofInt(getActivity().findViewById(R.id.buttonbarframe), \"backgroundColor\", skin_color, res.getColor(R.color.holo_dark_action_mode));\n anim.setDuration(0);\n anim.setEvaluator(new ArgbEvaluator());\n anim.start();\n if (Build.VERSION.SDK_INT >= 21) {\n\n Window window = getActivity().getWindow();\n if(mainActivity.colourednavigation)\n window.setNavigationBarColor(res.getColor(android.R.color.black));\n }\n return true;\n }\n\n // the following method is called each time\n // the action mode is shown. Always called after\n // onCreateActionMode, but\n // may be called multiple times if the mode is invalidated.\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\n ArrayList<Integer> positions = adapter.getCheckedItemPositions();\n TextView textView1 = (TextView) v.findViewById(R.id.item_count);\n textView1.setText(positions.size() + \"\");\n textView1.setOnClickListener(null);\n hideOption(R.id.openmulti,menu);\n if(mainActivity.mReturnIntent)\n if(Build.VERSION.SDK_INT>=16)\n showOption(R.id.openmulti, menu);\n //tv.setText(positions.size());\n if(!results)\n {hideOption(R.id.openparent,menu);\n if (positions.size() == 1) {\n showOption(R.id.addshortcut,menu);\n showOption(R.id.permissions, menu);\n\n showOption(R.id.openwith, menu);\n showOption(R.id.about, menu);\n showOption(R.id.share,menu);\n showOption(R.id.rename, menu);\n\n File x = new File(list.get(adapter.getCheckedItemPositions().get(0))\n\n .getDesc());\n\n if (x.isDirectory()) {\n hideOption(R.id.openwith,menu);\n showOption(R.id.sethome, menu);\n hideOption(R.id.share,menu);\n hideOption(R.id.openmulti, menu);\n } else if (x.getName().toLowerCase().endsWith(\".zip\") || x.getName().toLowerCase().endsWith(\".jar\") || x.getName().toLowerCase().endsWith(\".apk\") || x.getName().toLowerCase().endsWith(\".rar\")|| x.getName().toLowerCase().endsWith(\".tar\")|| x.getName().toLowerCase().endsWith(\".tar.gz\")) {\n\n showOption(R.id.ex, menu);\n\n if(mainActivity.mReturnIntent)\n if(Build.VERSION.SDK_INT>=16)\n showOption(R.id.openmulti,menu);\n }\n } else {\n try {\n if(mainActivity.mReturnIntent)\n if(Build.VERSION.SDK_INT>=16)showOption(R.id.openmulti,menu);\n for (int c : adapter.getCheckedItemPositions()) {\n File x = new File(list.get(c).getDesc());\n if (x.isDirectory()) {\n hideOption(R.id.share, menu);\n hideOption(R.id.openmulti,menu);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n hideOption(R.id.ex, menu);\n\n hideOption(R.id.sethome, menu);\n\n hideOption(R.id.openwith, menu);\n\n //hideOption(R.id.setringtone, menu);\n\n hideOption(R.id.permissions, menu);\n\n hideOption(R.id.about, menu);\n\n }}else {\n if (positions.size() == 1) {\n showOption(R.id.addshortcut,menu);\n showOption(R.id.permissions, menu);\n showOption(R.id.openparent,menu);\n showOption(R.id.openwith, menu);\n showOption(R.id.about, menu);\n showOption(R.id.share,menu);\n showOption(R.id.rename, menu);\n\n File x = new File(list.get(adapter.getCheckedItemPositions().get(0))\n\n .getDesc());\n\n if (x.isDirectory()) {\n hideOption(R.id.openwith,menu);\n showOption(R.id.sethome, menu);\n hideOption(R.id.share,menu);\n hideOption(R.id.openmulti,menu);\n } else if (x.getName().toLowerCase().endsWith(\".zip\") || x.getName().toLowerCase().endsWith(\".jar\") || x.getName().toLowerCase().endsWith(\".apk\") || x.getName().toLowerCase().endsWith(\".rar\")|| x.getName().toLowerCase().endsWith(\".tar\")|| x.getName().toLowerCase().endsWith(\".tar.gz\")) {\n\n showOption(R.id.ex, menu);\n\n if(mainActivity.mReturnIntent)\n if(Build.VERSION.SDK_INT>=16)\n showOption(R.id.openmulti,menu);\n }\n } else {\n hideOption(R.id.openparent,menu);\n\n if(mainActivity.mReturnIntent)\n if(Build.VERSION.SDK_INT>=16)\n showOption(R.id.openmulti,menu);\n try {\n for (int c : adapter.getCheckedItemPositions()) {\n File x = new File(list.get(c).getDesc());\n if (x.isDirectory()) {\n hideOption(R.id.share, menu);\n hideOption(R.id.openmulti,menu);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n hideOption(R.id.ex, menu);\n\n hideOption(R.id.sethome, menu);\n\n hideOption(R.id.openwith, menu);\n\n //hideOption(R.id.setringtone, menu);\n\n hideOption(R.id.permissions, menu);\n\n hideOption(R.id.about, menu);\n\n }\n }\n\n return false; // Return false if nothing is done\n }\n\n // called when the user selects a contextual menu item\n public boolean onActionItemClicked(ActionMode mode, MenuItem item) {\n computeScroll();\n ArrayList<Integer> plist = adapter.getCheckedItemPositions();\n switch (item.getItemId()) {\n case R.id.openmulti:\n if(Build.VERSION.SDK_INT>=16){\n Intent intentresult=new Intent();\n ArrayList<Uri> resulturis=new ArrayList<Uri>();\n for(int k:plist){\n try {\n resulturis.add(Uri.fromFile(new File(list.get(k).getDesc())));\n } catch (Exception e) {\n\n }\n }\n final ClipData clipData = new ClipData(\n null, new String[]{\"*/*\"}, new ClipData.Item(resulturis.get(0)));\n for (int i = 1; i < resulturis.size(); i++) {\n clipData.addItem(new ClipData.Item(resulturis.get(i)));\n }\n intentresult.setClipData(clipData);\n mode.finish();\n getActivity().setResult(getActivity().RESULT_OK, intentresult);\n getActivity().finish();}\n return true;\n case R.id.sethome:\n int pos = plist.get(0);\n home = list.get(pos).getDesc();\n Toast.makeText(getActivity(),\n utils.getString(getActivity(), R.string.newhomedirectory) + \" \" + list.get(pos).getTitle(),\n Toast.LENGTH_LONG).show();\n mainActivity.updatepaths();\n mode.finish();\n return true;\n case R.id.about:\n String x;\n x=list.get((plist.get(0))).getDesc();\n utils.showProps(new File(x), ma,rootMode);\n mode.finish();\n return true;\n /*case R.id.setringtone:\n File fx;\n if(results)\n fx=new File(slist.get((plist.get(0))).getDesc());\n else\n fx=new File(list.get((plist.get(0))).getDesc());\n\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DATA, fx.getAbsolutePath());\n values.put(MediaStore.MediaColumns.TITLE, \"Amaze\");\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"audio/mp3\");\n //values.put(MediaStore.MediaColumns.SIZE, fx.);\n values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);\n values.put(MediaStore.Audio.Media.IS_RINGTONE, true);\n values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);\n values.put(MediaStore.Audio.Media.IS_ALARM, false);\n values.put(MediaStore.Audio.Media.IS_MUSIC, false);\n\n Uri uri = MediaStore.Audio.Media.getContentUriForPath(fx.getAbsolutePath());\n Uri newUri = getActivity().getContentResolver().insert(uri, values);\n try {\n RingtoneManager.setActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_RINGTONE, newUri);\n //Settings.System.putString(getActivity().getContentResolver(), Settings.System.RINGTONE, newUri.toString());\n Toast.makeText(getActivity(), \"Successful\" + fx.getAbsolutePath(), Toast.LENGTH_LONG).show();\n } catch (Throwable t) {\n\n Log.d(\"ringtone\", \"failed\");\n }\n return true;*/\n case R.id.delete:\n utils.deleteFiles(list,ma, plist);\n\n\n return true;\n case R.id.share:\n ArrayList<File> arrayList=new ArrayList<File>();\n for(int i:plist){\n arrayList.add(new File(list.get(i).getDesc()));\n }\n utils.shareFiles(arrayList,getActivity());\n return true;\n case R.id.openparent:\n loadlist(new File(list.get(plist.get(0)).getDesc()).getParentFile(),false);\n return true;\n case R.id.all:\n if (adapter.areAllChecked(current)) {\n adapter.toggleChecked(false,current);\n } else {\n adapter.toggleChecked(true,current);\n }\n mode.invalidate();\n\n return true;\n case R.id.rename:\n\n final ActionMode m = mode;\n final File f;\n f= new File(list.get(\n (plist.get(0))).getDesc());\n View dialog = getActivity().getLayoutInflater().inflate(\n R.layout.dialog, null);\n MaterialDialog.Builder a = new MaterialDialog.Builder(getActivity());\n final EditText edit = (EditText) dialog\n .findViewById(R.id.newname);\n edit.setText(f.getName());\n a.customView(dialog, true);\n if(theme1==1)\n a.theme(Theme.DARK);\n a.title(utils.getString(getActivity(), R.string.rename));\n\n a.callback(new MaterialDialog.ButtonCallback() {\n @Override\n public void onPositive(MaterialDialog materialDialog) {\n\n boolean b = utils.rename(f, edit.getText()\n .toString(),rootMode);\n m.finish();\n updateList();\n if (b) {\n Toast.makeText(getActivity(),\n utils.getString(getActivity(), R.string.renamed),\n Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(getActivity(),\n utils.getString(getActivity(), R.string.renameerror),\n Toast.LENGTH_LONG).show();\n\n }\n }\n\n @Override\n public void onNegative(MaterialDialog materialDialog) {\n\n materialDialog.cancel();\n }\n });\n a.positiveText(R.string.save);\n a.negativeText(R.string.cancel);\n a.positiveColor(Color.parseColor(fabSkin));\n a.negativeColor(Color.parseColor(fabSkin));\n a.build().show();\n mode.finish();\n return true;\n case R.id.hide:\n for (int i1 = 0; i1 < plist.size(); i1++) {\n hide(list.get(plist.get(i1)).getDesc());\n }\n updateList();mode.finish();\n return true;\n case R.id.book:\n for (int i1 = 0; i1 < plist.size(); i1++) {\n try {\n sh.addS(new File(list.get(plist.get(i1)).getDesc()));\n } catch (Exception e) {\n }\n }\n mainActivity.updateDrawer();\n Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.bookmarksadded), Toast.LENGTH_LONG).show();\n mode.finish();\n return true;\n case R.id.ex:\n Intent intent = new Intent(getActivity(), ExtractService.class);\n intent.putExtra(\"zip\", list.get((plist.get(0))).getDesc());\n getActivity().startService(intent);\n mode.finish();\n return true;\n case R.id.cpy:\n mainActivity.MOVE_PATH=null;\n ArrayList<String> copies = new ArrayList<String>();\n for (int i2 = 0; i2 < plist.size(); i2++) {\n copies.add(list.get(plist.get(i2)).getDesc());\n }\n mainActivity.COPY_PATH = copies;\n mainActivity.supportInvalidateOptionsMenu();\n mode.finish();\n return true;\n case R.id.cut:\n mainActivity.COPY_PATH=null;\n ArrayList<String> copie = new ArrayList<String>();\n for (int i3 = 0; i3 < plist.size(); i3++) {\n copie.add(list.get(plist.get(i3)).getDesc());\n }\n mainActivity.MOVE_PATH = copie;\n mainActivity.supportInvalidateOptionsMenu();\n mode.finish();\n return true;\n case R.id.compress:\n ArrayList<String> copies1 = new ArrayList<String>();\n for (int i4 = 0; i4 < plist.size(); i4++) {\n copies1.add(list.get(plist.get(i4)).getDesc());}\n utils.showNameDialog((MainActivity) getActivity(), copies1, current);\n mode.finish();\n return true;\n case R.id.openwith:\n utils.openunknown(new File(list.get((plist.get(0))).getDesc()), getActivity(), true);\n return true;\n case R.id.permissions:\n utils.setPermissionsDialog(list.get(plist.get(0)),ma);\n mode.finish();\n return true;\n case R.id.addshortcut:\n addShortcut(list.get(plist.get(0)));\n mode.finish();return true;\n default:\n return false;\n }\n }\n\n // called when the user exits the action mode\n public void onDestroyActionMode(ActionMode mode) {\n mActionMode = null;\n selection = false;\n if(!results)adapter.toggleChecked(false, current);\n else adapter.toggleChecked(false);\n mainActivity.setPagingEnabled(true);\n ObjectAnimator anim = ObjectAnimator.ofInt(getActivity().findViewById(R.id.buttonbarframe), \"backgroundColor\", res.getColor(R.color.holo_dark_action_mode), skin_color);\n anim.setDuration(0);\n anim.setEvaluator(new ArgbEvaluator());\n anim.start();\n if (Build.VERSION.SDK_INT >= 21) {\n\n Window window = getActivity().getWindow();\n if(mainActivity.colourednavigation)window.setNavigationBarColor(mainActivity.skinStatusBar);\n }\n }\n };\n\n public void computeScroll() {\n View vi = listView.getChildAt(0);\n int top = (vi == null) ? 0 : vi.getTop();\n int index;if(islist)\n index= mLayoutManager.findFirstVisibleItemPosition();\n else index=mLayoutManagerGrid.findFirstVisibleItemPosition();\n Bundle b = new Bundle();\n b.putInt(\"index\", index);\n b.putInt(\"top\", top);\n scrolls.put(current, b);\n }\n\n public void goBack() {\n File f = new File(current);\n if (!results) {\n if(selection){\n System.out.println(\"adapter checked false\");\n adapter.toggleChecked(false);}\n else{\n if(current.equals(\"/\") || current.equals(home))\n mainActivity.exit();\n else if (utils.canGoBack(f) ) {\n loadlist(f.getParentFile(), true);\n }else mainActivity.exit();}\n } else {\n loadlist(f, true);\n }\n }\n public void goBackItemClick() {\n File f = new File(current);\n if (!results) {\n if(selection){\n adapter.toggleChecked(false);}\n else{\n if(current.equals(\"/\"))\n mainActivity.exit();\n else if (utils.canGoBack(f) ) {\n loadlist(f.getParentFile(), true);\n }else mainActivity.exit();}\n } else {\n loadlist(f, true);\n }\n }\n private BroadcastReceiver receiver2 = new BroadcastReceiver() {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n updateList();\n }\n };\n public void updateList(){\n computeScroll();\n ic.cleanup();\n loadlist(new File(current), true);}\n\n public void getSortModes() {\n int t = Integer.parseInt(Sp.getString(\"sortby\", \"0\"));\n if (t <= 3) {\n sortby = t;\n asc = 1;\n } else if (t > 3) {\n asc = -1;\n sortby = t - 4;\n }\n dsort = Integer.parseInt(Sp.getString(\"dirontop\", \"0\"));\n\n }\n\n @Override\n public void onResume() {\n super.onResume();\n (getActivity()).registerReceiver(receiver2, new IntentFilter(\"loadlist\"));\n }\n\n @Override\n public void onPause() {\n super.onPause();\n (getActivity()).unregisterReceiver(receiver2);\n }\n @Override\n public void onStop() {\n super.onStop();\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n tabHandler.close();\n if(history!=null)\n history.end();\n if(hidden!=null)\n hidden.end();\n }\n @Override\n public void onStart() {\n super.onStart();\n history = new HistoryManager(getActivity(), \"Table1\");\n }\n\n public ArrayList<Layoutelements> addToSmb(SmbFile[] mFile) throws SmbException {\n Log.e(\"Connected\",mFile.length+\"\");\n ArrayList<Layoutelements> a = new ArrayList<Layoutelements>();\n smbFiles=new ArrayList<SmbFile>();\n for (int i = 0; i < mFile.length; i++) {\n smbFiles.add(mFile[i]);\n if (mFile[i].isDirectory()) {\n a.add(new Layoutelements(folder,mFile[i].getName(), mFile[i].getPath(),\"\",\"\",\"\",false,\"\",true));\n } else {\n try {\n a.add(new Layoutelements(Icons.loadMimeIcon(getActivity(), mFile[i].getPath(),!islist),mFile[i].getName(), mFile[i].getPath(),\"\",\"\",utils.readableFileSize(mFile[i].length()), false, \"\",false));\n } catch (Exception e) {\n e.printStackTrace();\n }}\n }\n Log.e(\"Connected\",a.size()+\"Size\");\n return a;\n }\n public ArrayList<Layoutelements> addTo(ArrayList<String[]> mFile) {\n ArrayList<Layoutelements> a = new ArrayList<Layoutelements>();\n for (int i = 0; i < mFile.size(); i++) {\n String[] ele=mFile.get(i);\n File f=new File(ele[0]);\n String size=\"\";\n if(!hiddenfiles.contains(ele[0])){\n if (isDirectory(ele)) {\n if(!ele[5].trim().equals(\"\") && !ele[5].toLowerCase().trim().equals(\"null\"))size=ele[5]+\" \"+itemsstring;\n else size=\"\";\n a.add(utils.newElement(folder, f.getPath(),mFile.get(i)[2],mFile.get(i)[1],size,true,false,ele[4]));\n\n } else {\n\n try {\n if(!ele[5].trim().equals(\"\") && !ele[5].toLowerCase().trim().equals(\"null\"))size=utils.readableFileSize(Long.parseLong(ele[5]));\n else size=\"\";\n } catch (NumberFormatException e) {\n //e.printStackTrace();\n }\n try {\n a.add(utils.newElement(Icons.loadMimeIcon(getActivity(), f.getPath(),!islist), f.getPath(),mFile.get(i)[2],mFile.get(i)[1],size,false,false,ele[4]));\n } catch (Exception e) {\n e.printStackTrace();\n }}\n }\n }\n return a;\n }\n\n public boolean isDirectory(String[] path){\n if(rootMode)\n if(path[1].length()!=0)return new File(path[0]).isDirectory();\n else return path[3].equals(\"-1\");\n else\n return new File(path[0]).isDirectory();\n }\n\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n\n\n }\n\n void addSmbToSavedInstance(Bundle savedInstance, String user, String pass, ArrayList<SmbFile> list, boolean anonym) {\n savedInstance.putBoolean(\"SmbMode\", smbMode);\n savedInstance.putString(\"SmbPath\",smbPath);\n if (!anonym) {\n savedInstance.putString(\"SmbUser\", user);\n savedInstance.putString(\"SmbPass\", pass);\n savedInstance.putBoolean(\"SmbAnonym\", false);\n } else savedInstance.putBoolean(\"SmbAnonym\", true);\n ArrayList<String> stringArrayList = new ArrayList<>();\n for (SmbFile smbFile : list) {\n stringArrayList.add(smbFile.getPath());\n }\n savedInstance.putStringArrayList(\"SmbFileList\", stringArrayList);\n }\n\n void retreiveSmbFromSavedInstance(Bundle savedInstance) {\n smbMode = savedInstance.getBoolean(\"SmbMode\");\n if (!smbMode) return;\n smbPath=savedInstance.getString(\"SmbPath\");\n SmbAnonym = savedInstance.getBoolean(\"SmbAnonym\");\n ArrayList<String> stringArrayList = savedInstance.getStringArrayList(\"SmbFileList\");\n smbFiles=new ArrayList<SmbFile>();\n try {\n if(SmbAnonym) {\n for(String a:stringArrayList)\n smbFiles.add( new SmbFile(a,NtlmPasswordAuthentication.ANONYMOUS));\n }else{\n NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(\n null,smbUser= savedInstance.getString(\"SmbUser\"),smbPass=savedInstance.getString(\"SmbPass\"));\n for(String a:stringArrayList)\n smbFiles.add( new SmbFile(a,auth1));\n }\n } catch (MalformedURLException e) {\n e.printStackTrace();\n }\n }\n public SmbFile connectingWithSmbServer(String[] auth,boolean anonym) {\n try {\n String yourPeerIP=auth[0];\n String path = \"smb://\" + yourPeerIP;\n smbPath=path;\n SmbFile smbFile;\n if(anonym){\n SmbAnonym=true;\n smbFile = new SmbFile(path,NtlmPasswordAuthentication.ANONYMOUS);\n }\n else {\n SmbAnonym=false;\n smbUser=auth[1];\n smbPass=auth[2];\n NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(\n null, auth[1], auth[2]);\n smbFile = new SmbFile(path, auth1);\n }return smbFile;\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(\"Connected\", e.getMessage());\n return null;\n }\n }\n public void updatehiddenfiles(){\n hiddenfiles=hidden.readTable();\n }\n public void initPoppyViewListeners(View poppy){\n/*\n ImageView imageView = ((ImageView)poppy.findViewById(R.id.overflow));\n showPopup(imageView);\n final ImageView homebutton=(ImageView)poppy.findViewById(R.id.home);\n homebutton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n home();if(mActionMode!=null){mActionMode.finish();}\n }\n });\n ImageView imageView1 = ((ImageView)poppy.findViewById(R.id.search));\n imageView1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n search();\n if (mActionMode != null) {\n mActionMode.finish();\n }\n }\n });*/\n }\n\n public void hide(String path){\n hidden.addPath(path);\n hiddenfiles=hidden.readTable();\n if(new File(path).isDirectory()){\n File f1 = new File(path + \"/\" + \".nomedia\");\n if (!f1.exists()) {\n try {\n boolean b = f1.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n } }\n utils.scanFile(path,getActivity());}\n\n }\n\n public void restartPC(final Activity activity) {\n if (activity == null)\n return;\n final int enter_anim = android.R.anim.fade_in;\n final int exit_anim = android.R.anim.fade_out;\n activity.overridePendingTransition(enter_anim, exit_anim);\n activity.finish();\n activity.overridePendingTransition(enter_anim, exit_anim);\n Intent i=new Intent(getActivity(),MainActivity.class);\n i.putExtra(\"restart\",true);\n i.setAction(Intent.ACTION_MAIN);\n activity.startActivity(i);\n }\n\n public String getSelectionColor(){\n\n String[] colors = new String[]{\n \"#F44336\",\"#74e84e40\",\n \"#e91e63\",\"#74ec407a\",\n \"#9c27b0\",\"#74ab47bc\",\n \"#673ab7\",\"#747e57c2\",\n \"#3f51b5\",\"#745c6bc0\",\n \"#2196F3\",\"#74738ffe\",\n \"#03A9F4\",\"#7429b6f6\",\n \"#00BCD4\",\"#7426c6da\",\n \"#009688\",\"#7426a69a\",\n \"#4CAF50\",\"#742baf2b\",\n \"#8bc34a\",\"#749ccc65\",\n \"#FFC107\",\"#74ffca28\",\n \"#FF9800\",\"#74ffa726\",\n \"#FF5722\",\"#74ff7043\",\n \"#795548\",\"#748d6e63\",\n \"#212121\",\"#79bdbdbd\",\n \"#607d8b\",\"#7478909c\",\n \"#004d40\",\"#740E5D50\"\n };\n return colors[ Arrays.asList(colors).indexOf(skin)+1];\n }\n\n public float[] calculatefilter(float[] values){\n float[] src= {\n\n values[0], 0, 0, 0, 0,\n 0, values[1], 0, 0, 0,\n 0, 0, values[2],0, 0,\n 0, 0, 0, 1, 0\n };\n return src;\n }\n public float[] calculatevalues(String color){\n int c=Color.parseColor(color);\n float r=(float)Color.red(c)/255;\n float g=(float)Color.green(c)/255;\n float b=(float)Color.blue(c)/255;\n return new float[]{r,g,b};\n }private void addShortcut(Layoutelements path) {\n //Adding shortcut for MainActivity\n //on Home screen\n Intent shortcutIntent = new Intent(getActivity().getApplicationContext(),\n MainActivity.class);\n shortcutIntent.putExtra(\"path\", path.getDesc());\n shortcutIntent.setAction(Intent.ACTION_MAIN);\n\n Intent addIntent = new Intent();\n addIntent\n .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);\n addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, new File(path.getDesc()).getName());\n\n addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,\n Intent.ShortcutIconResource.fromContext(getActivity(),\n R.drawable.ic_launcher));\n\n addIntent\n .setAction(\"com.android.launcher.action.INSTALL_SHORTCUT\");\n getActivity().sendBroadcast(addIntent);\n }\n}", "public class Icons {\n private static HashMap<String, Integer> sMimeIcons = new HashMap<String, Integer>();\nprivate static void add(String mimeType, int resId) {\n if (sMimeIcons.put(mimeType, resId) != null) {\n throw new RuntimeException(mimeType + \" already registered!\");\n }\n }\nstatic {\n int icon;\n\n // Package\n icon = R.drawable.ic_doc_apk;\n add(\"application/vnd.android.package-archive\", icon);\n\n // Audio\n icon = R.drawable.ic_doc_audio_am;\n add(\"application/ogg\", icon);\n add(\"application/x-flac\", icon);\n\n // Certificate\n icon = R.drawable.ic_doc_certificate;\n add(\"application/pgp-keys\", icon);\n add(\"application/pgp-signature\", icon);\n add(\"application/x-pkcs12\", icon);\n add(\"application/x-pkcs7-certreqresp\", icon);\n add(\"application/x-pkcs7-crl\", icon);\n add(\"application/x-x509-ca-cert\", icon);\n add(\"application/x-x509-user-cert\", icon);\n add(\"application/x-pkcs7-certificates\", icon);\n add(\"application/x-pkcs7-mime\", icon);\n add(\"application/x-pkcs7-signature\", icon);\n\n // Source code\n icon = R.drawable.ic_doc_codes;\n add(\"application/rdf+xml\", icon);\n add(\"application/rss+xml\", icon);\n add(\"application/x-object\", icon);\n add(\"application/xhtml+xml\", icon);\n add(\"text/css\", icon);\n add(\"text/html\", icon);\n add(\"text/xml\", icon);\n add(\"text/x-c++hdr\", icon);\n add(\"text/x-c++src\", icon);\n add(\"text/x-chdr\", icon);\n add(\"text/x-csrc\", icon);\n add(\"text/x-dsrc\", icon);\n add(\"text/x-csh\", icon);\n add(\"text/x-haskell\", icon);\n add(\"text/x-java\", icon);\n add(\"text/x-literate-haskell\", icon);\n add(\"text/x-pascal\", icon);\n add(\"text/x-tcl\", icon);\n add(\"text/x-tex\", icon);\n add(\"application/x-latex\", icon);\n add(\"application/x-texinfo\", icon);\n add(\"application/atom+xml\", icon);\n add(\"application/ecmascript\", icon);\n add(\"application/json\", icon);\n add(\"application/javascript\", icon);\n add(\"application/xml\", icon);\n add(\"text/javascript\", icon);\n add(\"application/x-javascript\", icon);\n\n // Compressed\n icon = R.drawable.ic_doc_compressed;\n add(\"application/mac-binhex40\", icon);\n add(\"application/rar\", icon);\n add(\"application/zip\", icon);\n add(\"application/java-archive\",icon);\n add(\"application/x-apple-diskimage\", icon);\n add(\"application/x-debian-package\", icon);\n add(\"application/x-gtar\", icon);\n add(\"application/x-iso9660-image\", icon);\n add(\"application/x-lha\", icon);\n add(\"application/x-lzh\", icon);\n add(\"application/x-lzx\", icon);\n add(\"application/x-stuffit\", icon);\n add(\"application/x-tar\", icon);\n add(\"application/x-webarchive\", icon);\n add(\"application/x-webarchive-xml\", icon);\n add(\"application/gzip\", icon);\n add(\"application/x-7z-compressed\", icon);\n add(\"application/x-deb\", icon);\n add(\"application/x-rar-compressed\", icon);\n\n // Contact\n icon = R.drawable.ic_doc_contact_am;\n add(\"text/x-vcard\", icon);\n add(\"text/vcard\", icon);\n\n // Event\n icon = R.drawable.ic_doc_event_am;\n add(\"text/calendar\", icon);\n add(\"text/x-vcalendar\", icon);\n\n // Font\n icon = R.drawable.ic_doc_font;\n add(\"application/x-font\", icon);\n add(\"application/font-woff\", icon);\n add(\"application/x-font-woff\", icon);\n add(\"application/x-font-ttf\", icon);\n\n // Image\n icon = R.drawable.ic_doc_image;\n add(\"application/vnd.oasis.opendocument.graphics\", icon);\n add(\"application/vnd.oasis.opendocument.graphics-template\", icon);\n add(\"application/vnd.oasis.opendocument.image\", icon);\n add(\"application/vnd.stardivision.draw\", icon);\n add(\"application/vnd.sun.xml.draw\", icon);\n add(\"application/vnd.sun.xml.draw.template\", icon);\n add(\"image/jpeg\", icon);\n add(\"image/png\", icon);\n // PDF\n icon = R.drawable.ic_doc_pdf;\n add(\"application/pdf\", icon);\n\n // Presentation\n icon = R.drawable.ic_doc_presentation;\n add(\"application/vnd.ms-powerpoint\", icon);\n add(\"application/vnd.openxmlformats-officedocument.presentationml.presentation\", icon);\n add(\"application/vnd.openxmlformats-officedocument.presentationml.template\", icon);\n add(\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\", icon);\n add(\"application/vnd.stardivision.impress\", icon);\n add(\"application/vnd.sun.xml.impress\", icon);\n add(\"application/vnd.sun.xml.impress.template\", icon);\n add(\"application/x-kpresenter\", icon);\n add(\"application/vnd.oasis.opendocument.presentation\", icon);\n\n // Spreadsheet\n icon = R.drawable.ic_doc_spreadsheet_am;\n add(\"application/vnd.oasis.opendocument.spreadsheet\", icon);\n add(\"application/vnd.oasis.opendocument.spreadsheet-template\", icon);\n add(\"application/vnd.ms-excel\", icon);\n add(\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\", icon);\n add(\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\", icon);\n add(\"application/vnd.stardivision.calc\", icon);\n add(\"application/vnd.sun.xml.calc\", icon);\n add(\"application/vnd.sun.xml.calc.template\", icon);\n add(\"application/x-kspread\", icon);\n\n // Doc\n icon = R.drawable.ic_doc_doc_am;\n add(\"application/msword\", icon);\n add(\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\", icon);\n add(\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\", icon);\n add(\"application/vnd.oasis.opendocument.text\", icon);\n add(\"application/vnd.oasis.opendocument.text-master\", icon);\n add(\"application/vnd.oasis.opendocument.text-template\", icon);\n add(\"application/vnd.oasis.opendocument.text-web\", icon);\n add(\"application/vnd.stardivision.writer\", icon);\n add(\"application/vnd.stardivision.writer-global\", icon);\n add(\"application/vnd.sun.xml.writer\", icon);\n add(\"application/vnd.sun.xml.writer.global\", icon);\n add(\"application/vnd.sun.xml.writer.template\", icon);\n add(\"application/x-abiword\", icon);\n add(\"application/x-kword\", icon);\n\n // Text\n icon = R.drawable.ic_doc_text_am;\n add(\"text/plain\", icon);\n\n // Video\n icon = R.drawable.ic_doc_video_am;\n add(\"application/x-quicktimeplayer\", icon);\n add(\"application/x-shockwave-flash\", icon);\n }\n\n public static boolean isText(String name) {\n String mimeType=MimeTypes.getMimeType(new File(name));\n\n Integer res = sMimeIcons.get(mimeType);\n if (res != null && res == R.drawable.ic_doc_text_am) return true;\n if(mimeType!=null && mimeType.contains(\"/\")){\n final String typeOnly = mimeType.split(\"/\")[0];\n if (\"text\".equals(typeOnly)) {\n return true;}}\n return false;\n }\n public static boolean isVideo(String name){\n String mimeType=MimeTypes.getMimeType(new File(name));\n Integer res = sMimeIcons.get(mimeType);\n if (res != null && res == R.drawable.ic_doc_video_am) return true;\n if(mimeType!=null && mimeType.contains(\"/\")){\n final String typeOnly = mimeType.split(\"/\")[0];\n if (\"video\".equals(typeOnly)) {\n return true;}}\n return false;\n }\n public static boolean isAudio(String name){\n String mimeType=MimeTypes.getMimeType(new File(name));\n Integer res = sMimeIcons.get(mimeType);\n if (res != null && res == R.drawable.ic_doc_audio_am) return true;\n if(mimeType!=null && mimeType.contains(\"/\")){\n final String typeOnly = mimeType.split(\"/\")[0];\n if (\"audio\".equals(typeOnly)) {\n return true;}}\n return false;\n }\n public static boolean isCode(String name) {\n Integer res = sMimeIcons.get(MimeTypes.getMimeType(new File(name)));\n if (res != null && res == R.drawable.ic_doc_codes) return true;\n return false;\n }\n public static boolean isArchive(String name) {\n Integer res = sMimeIcons.get(MimeTypes.getMimeType(new File(name)));\n if (res != null && res == R.drawable.ic_doc_compressed) return true;\n return false;\n }\n\n public static boolean isApk(String name) {\n Integer res = sMimeIcons.get(MimeTypes.getMimeType(new File(name)));\n if (res != null && res == R.drawable.ic_doc_apk) return true;\n return false;\n }\n public static boolean isPdf(String name) {\n Integer res = sMimeIcons.get(MimeTypes.getMimeType(new File(name)));\n if (res != null && res == R.drawable.ic_doc_pdf) return true;\n return false;\n }\n\n public static boolean isPicture(String name) {\n Integer res = sMimeIcons.get(MimeTypes.getMimeType(new File(name)));\n if (res != null && res == R.drawable.ic_doc_image) return true;\n return false;\n }\npublic static boolean isgeneric(String name){\n String mimeType = MimeTypes.getMimeType(new File(name));\n if (mimeType == null) {\n return true;\n }\n Integer resId = sMimeIcons.get(mimeType);\nif(resId==null){return true;}\n\n\n return false;}\n public static Drawable loadMimeIcon(Context context, String path,boolean grid) {\n final Resources res = context.getResources();\n String mimeType = MimeTypes.getMimeType(new File(path));\n if (mimeType == null) {\n /* if(grid)\n return res.getDrawable(R.drawable.ic_doc_generic_am_grid);\n*/\n return res.getDrawable(R.drawable.ic_doc_generic_am);\n }\n\n\n // Look for exact match first\n Integer resId = sMimeIcons.get(mimeType);\n\n if (resId != null) {switch (resId){\n case R.drawable.ic_doc_apk: if(grid)resId=R.drawable.ic_doc_apk_grid;\n break;/*\n case R.drawable.ic_doc_audio_am: if(grid)resId=R.drawable.ic_doc_audio_am_grid;\n break;\n case R.drawable.ic_doc_certificate: if(grid)resId=R.drawable.ic_doc_certificate_grid;\n break;\n case R.drawable.ic_doc_codes: if(grid)resId=R.drawable.ic_doc_codes_grid;\n break;\n case R.drawable.ic_doc_font: if(grid)resId=R.drawable.ic_doc_font_grid;\n break;\n case R.drawable.ic_doc_generic_am: if(grid)resId=R.drawable.ic_doc_generic_am_grid;\n break;\n */case R.drawable.ic_doc_image: if(grid)resId=R.drawable.ic_doc_image_grid;\n break;}\n /*case R.drawable.ic_doc_pdf: if(grid)resId=R.drawable.ic_doc_pdf_grid;\n break;\n case R.drawable.ic_doc_video_am: if(grid)resId=R.drawable.ic_doc_video_am_grid;\n break;\n case R.drawable.ic_doc_text_am: if(grid)resId=R.drawable.ic_doc_text_am_grid;\n break;\n }*/\n return res.getDrawable(resId);\n }\n\n\n // Otherwise look for partial match\n final String typeOnly = mimeType.split(\"/\")[0];\n if (\"audio\".equals(typeOnly)) {\n /* if(grid)return res.getDrawable(R.drawable.ic_doc_audio_am_grid);else*/ return res.getDrawable(R.drawable.ic_doc_audio_am);\n } else if (\"image\".equals(typeOnly)) {\n if(grid)return res.getDrawable(R.drawable.ic_doc_image_grid);else return res.getDrawable(R.drawable.ic_doc_image);\n } else if (\"text\".equals(typeOnly)) {\n /*if(grid)return res.getDrawable(R.drawable.ic_doc_text_am_grid);else*/ return res.getDrawable(R.drawable.ic_doc_text_am);\n } else if (\"video\".equals(typeOnly)) {\n /*if(grid)return res.getDrawable(R.drawable.ic_doc_video_am_grid);else*/ return res.getDrawable(R.drawable.ic_doc_video_am);\n }\n /*if(grid)return res.getDrawable(R.drawable.ic_doc_generic_am_grid);else*/ return res.getDrawable(R.drawable.ic_doc_generic_am);}\n}", "public class Layoutelements implements Parcelable {\n public Layoutelements(Parcel im) {\n try {\n Bitmap bitmap = (Bitmap) im.readParcelable(getClass().getClassLoader());\n // Convert Bitmap to Drawable:\n imageId = new BitmapDrawable(bitmap);\n\n title = im.readString();\n desc = im.readString();\n permissions = im.readString();\n symlink = im.readString();\n int j = im.readInt();\n date = im.readLong();\n int i = im.readInt();\n if (i == 0) {\n header = false;\n } else {\n header = true;\n } if (j == 0) {\n isDirectory = false;\n } else {\n isDirectory= true;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n date1 = im.readString();\n }\n\n\n public int describeContents() {\n // TODO: Implement this method\n return 0;\n }\n\n public void writeToParcel(Parcel p1, int p2) {\n p1.writeString(title);\n p1.writeString(desc);\n p1.writeString(permissions);\n p1.writeString(symlink);\n p1.writeInt(isDirectory?1:0);\n p1.writeLong(date);\n p1.writeInt(header ? 1 : 0);\n p1.writeParcelable(((BitmapDrawable) imageId).getBitmap(), p2);\n p1.writeString(date1);\n // TODO: Implement this method\n }\n\n private Drawable imageId;\n private String title;\n private String desc;\n private String permissions;\n private String symlink;\n private String size;\n private boolean isDirectory;\n private long date = 0;\n private String date1 = \"\";\n private boolean header;\n\n public Layoutelements(Drawable imageId, String title, String desc, String permissions, String symlink, String size, boolean header, String date,boolean isDirectory) {\n this.imageId = imageId;\n this.title = title;\n this.desc = desc;\n this.permissions = permissions.trim();\n this.symlink = symlink.trim();\n this.size = size;\n this.header = header;\n this.isDirectory = isDirectory;\n if (!date.trim().equals(\"\")) {\n this.date = Long.parseLong(date);\n this.date1 = new Futils().getdate(this.date, \"MMM dd, yyyy\", \"15\");\n }\n }\n\n\n public static final Parcelable.Creator<Layoutelements> CREATOR =\n new Parcelable.Creator<Layoutelements>() {\n public Layoutelements createFromParcel(Parcel in) {\n return new Layoutelements(in);\n }\n\n public Layoutelements[] newArray(int size) {\n return new Layoutelements[size];\n }\n };\n\n public Drawable getImageId() {\n return imageId;\n }\n\n\n public String getDesc() {\n return desc.toString();\n }\n\n\n public String getTitle() {\n return title.toString();\n }\n\n public boolean isDirectory() {\n return isDirectory;}\n\n public String getSize() {\n return size;\n }\n\n public String getDate() {\n return date1;\n }\n\n public long getDate1() {\n return date;\n }\n\n public String getPermissions() {\n return permissions;\n }\n\n public String getSymlink() {\n return symlink;\n }\n\n public boolean hasSymlink() {\n if (getSymlink() != null && getSymlink().length() != 0) {\n return true;\n } else return false;\n }\n\n @Override\n public String toString() {\n return title + \"\\n\" + desc;\n }\n}", "public final class MimeTypes {\n\n public static final String ALL_MIME_TYPES = \"*/*\";\n\n\n private static final HashMap<String, String> MIME_TYPES = new HashMap<String, String>();\n\n private MimeTypes() {\n\n }\n\n static {\n\n\n\t\t/*\n * ================= MIME TYPES ====================\n\t\t */\n MIME_TYPES.put(\"asm\", \"text/x-asm\");\n MIME_TYPES.put(\"def\", \"text/plain\");\n MIME_TYPES.put(\"in\", \"text/plain\");\n MIME_TYPES.put(\"rc\", \"text/plain\");\n MIME_TYPES.put(\"list\", \"text/plain\");\n MIME_TYPES.put(\"log\", \"text/plain\");\n MIME_TYPES.put(\"pl\", \"text/plain\");\n MIME_TYPES.put(\"prop\", \"text/plain\");\n MIME_TYPES.put(\"properties\", \"text/plain\");\n MIME_TYPES.put(\"rc\", \"text/plain\");\n\n MIME_TYPES.put(\"epub\", \"application/epub+zip\");\n MIME_TYPES.put(\"ibooks\", \"application/x-ibooks+zip\");\n\n MIME_TYPES.put(\"ifb\", \"text/calendar\");\n MIME_TYPES.put(\"eml\", \"message/rfc822\");\n MIME_TYPES.put(\"msg\", \"application/vnd.ms-outlook\");\n\n MIME_TYPES.put(\"ace\", \"application/x-ace-compressed\");\n MIME_TYPES.put(\"bz\", \"application/x-bzip\");\n MIME_TYPES.put(\"bz2\", \"application/x-bzip2\");\n MIME_TYPES.put(\"cab\", \"application/vnd.ms-cab-compressed\");\n MIME_TYPES.put(\"gz\", \"application/x-gzip\");\n MIME_TYPES.put(\"lrf\", \"application/octet-stream\");\n MIME_TYPES.put(\"jar\", \"application/java-archive\");\n MIME_TYPES.put(\"xz\", \"application/x-xz\");\n MIME_TYPES.put(\"Z\", \"application/x-compress\");\n\n MIME_TYPES.put(\"bat\", \"application/x-msdownload\");\n MIME_TYPES.put(\"ksh\", \"text/plain\");\n MIME_TYPES.put(\"sh\", \"application/x-sh\");\n\n MIME_TYPES.put(\"db\", \"application/octet-stream\");\n MIME_TYPES.put(\"db3\", \"application/octet-stream\");\n\n MIME_TYPES.put(\"otf\", \"application/x-font-otf\");\n MIME_TYPES.put(\"ttf\", \"application/x-font-ttf\");\n MIME_TYPES.put(\"psf\", \"application/x-font-linux-psf\");\n\n MIME_TYPES.put(\"cgm\", \"image/cgm\");\n MIME_TYPES.put(\"btif\", \"image/prs.btif\");\n MIME_TYPES.put(\"dwg\", \"image/vnd.dwg\");\n MIME_TYPES.put(\"dxf\", \"image/vnd.dxf\");\n MIME_TYPES.put(\"fbs\", \"image/vnd.fastbidsheet\");\n MIME_TYPES.put(\"fpx\", \"image/vnd.fpx\");\n MIME_TYPES.put(\"fst\", \"image/vnd.fst\");\n MIME_TYPES.put(\"mdi\", \"image/vnd.ms-mdi\");\n MIME_TYPES.put(\"npx\", \"image/vnd.net-fpx\");\n MIME_TYPES.put(\"xif\", \"image/vnd.xiff\");\n MIME_TYPES.put(\"pct\", \"image/x-pict\");\n MIME_TYPES.put(\"pic\", \"image/x-pict\");\n\n MIME_TYPES.put(\"adp\", \"audio/adpcm\");\n MIME_TYPES.put(\"au\", \"audio/basic\");\n MIME_TYPES.put(\"snd\", \"audio/basic\");\n MIME_TYPES.put(\"m2a\", \"audio/mpeg\");\n MIME_TYPES.put(\"m3a\", \"audio/mpeg\");\n MIME_TYPES.put(\"oga\", \"audio/ogg\");\n MIME_TYPES.put(\"spx\", \"audio/ogg\");\n MIME_TYPES.put(\"aac\", \"audio/x-aac\");\n MIME_TYPES.put(\"mka\", \"audio/x-matroska\");\n\n MIME_TYPES.put(\"jpgv\", \"video/jpeg\");\n MIME_TYPES.put(\"jpgm\", \"video/jpm\");\n MIME_TYPES.put(\"jpm\", \"video/jpm\");\n MIME_TYPES.put(\"mj2\", \"video/mj2\");\n MIME_TYPES.put(\"mjp2\", \"video/mj2\");\n MIME_TYPES.put(\"mpa\", \"video/mpeg\");\n MIME_TYPES.put(\"ogv\", \"video/ogg\");\n MIME_TYPES.put(\"flv\", \"video/x-flv\");\n MIME_TYPES.put(\"mkv\", \"video/x-matroska\");\n\n }\n\n\n public static String getMimeType(File file) {\n if (file.isDirectory()) {\n return null;\n }\n\n String type = \"*/*\";\n final String extension = getExtension(file.getName());\n\n if (extension != null && !extension.isEmpty()) {\n final String extensionLowerCase = extension.toLowerCase(Locale\n .getDefault());\n final MimeTypeMap mime = MimeTypeMap.getSingleton();\n type = mime.getMimeTypeFromExtension(extensionLowerCase);\n if (type == null) {\n type = MIME_TYPES.get(extensionLowerCase);\n }\n }\n if(type==null)type=\"*/*\";\n return type;\n }\n\n public static boolean mimeTypeMatch(String mime, String input) {\n return Pattern.matches(mime.replace(\"*\", \".*\"), input);\n }\n\n\n public static String getExtension(String a) {\n if(a.contains(\".\"))\n return a.substring(a.lastIndexOf(\".\") + 1).toLowerCase();\n else return \"\";\n }\n\n}", "public class RoundedImageView extends ImageView {\n\n public RoundedImageView(Context ctx, AttributeSet attrs) {\n super(ctx, attrs);\n }\n\n @Override\n protected void onDraw(Canvas canvas) {\n\n Drawable drawable = getDrawable();\n\n if (drawable == null) {\n return;\n }\n\n if (getWidth() == 0 || getHeight() == 0) {\n return;\n }\n Bitmap b = ((BitmapDrawable) drawable).getBitmap();\n Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);\n\n int w = getWidth(), h = getHeight();\n\n Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);\n canvas.drawBitmap(roundBitmap, 0, 0, null);\n\n }\n\n public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {\n Bitmap finalBitmap;\n if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)\n finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,\n false);\n else\n finalBitmap = bitmap;\n Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),\n finalBitmap.getHeight(), Config.ARGB_8888);\n Canvas canvas = new Canvas(output);\n\n final Paint paint = new Paint();\n final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),\n finalBitmap.getHeight());\n\n paint.setAntiAlias(true);\n paint.setFilterBitmap(true);\n paint.setDither(true);\n canvas.drawARGB(0, 0, 0, 0);\n paint.setColor(Color.parseColor(\"#BAB399\"));\n canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f,\n finalBitmap.getHeight() / 2 + 0.7f,\n finalBitmap.getWidth() / 2 + 0.1f, paint);\n paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));\n canvas.drawBitmap(finalBitmap, rect, rect, paint);\n\n return output;\n }\n\n}" ]
import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.ColorMatrixColorFilter; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.support.v7.widget.RecyclerView; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import com.amaze.filemanager.R; import com.amaze.filemanager.fragments.Main; import com.amaze.filemanager.utils.Icons; import com.amaze.filemanager.utils.Layoutelements; import com.amaze.filemanager.utils.MimeTypes; import com.amaze.filemanager.utils.RoundedImageView; import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter; import java.io.File; import java.util.ArrayList;
package com.amaze.filemanager.adapters; /** * Created by Arpit on 11-04-2015. */ public class Recycleradapter extends RecyclerArrayAdapter<String, RecyclerView.ViewHolder> implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> { Main main; ArrayList<Layoutelements> items; Context context; private SparseBooleanArray myChecked = new SparseBooleanArray(); ColorMatrixColorFilter colorMatrixColorFilter; LayoutInflater mInflater; int filetype=-1; int item_count; public Recycleradapter(Main m,ArrayList<Layoutelements> items,Context context){ this.main=m; this.items=items; this.context=context; for (int i = 0; i < items.size(); i++) { myChecked.put(i, false); } colorMatrixColorFilter=main.colorMatrixColorFilter; mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); item_count=items.size()+(main.islist?2:3); } public void toggleChecked(int position) { if (myChecked.get(position)) { myChecked.put(position, false); } else { myChecked.put(position, true); } notifyDataSetChanged(); if (main.selection == false || main.mActionMode == null) { main.selection = true; /*main.mActionMode = main.getActivity().startActionMode( main.mActionModeCallback);*/ main.mActionMode = main.mainActivity.toolbar.startActionMode(main.mActionModeCallback); } main.mActionMode.invalidate(); if (getCheckedItemPositions().size() == 0) { main.selection = false; main.mActionMode.finish(); main.mActionMode = null; } } public void toggleChecked(boolean b,String path) { int a; if(path.equals("/") || !main.gobackitem)a=0;else a=1; for (int i = a; i < items.size(); i++) { myChecked.put(i, b); } notifyDataSetChanged(); if(main.mActionMode!=null) main.mActionMode.invalidate(); if (getCheckedItemPositions().size() == 0) { main.selection = false; if(main.mActionMode!=null) main.mActionMode.finish(); main.mActionMode = null; } } public void toggleChecked(boolean b) { int a=0; for (int i = a; i < items.size(); i++) { myChecked.put(i, b); } notifyDataSetChanged(); if(main.mActionMode!=null)main.mActionMode.invalidate(); if (getCheckedItemPositions().size() == 0) { main.selection = false; if(main.mActionMode!=null) main.mActionMode.finish(); main.mActionMode = null; } } public ArrayList<Integer> getCheckedItemPositions() { ArrayList<Integer> checkedItemPositions = new ArrayList<Integer>(); for (int i = 0; i < myChecked.size(); i++) { if (myChecked.get(i)) { (checkedItemPositions).add(i); } } return checkedItemPositions; } public boolean areAllChecked(String path) { boolean b = true; int a; if(path.equals("/") || !main.gobackitem)a=0;else a=1; for (int i = a; i < myChecked.size(); i++) { if (!myChecked.get(i)) { b = false; } } return b; } public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case
public RoundedImageView viewmageV;
4
sathipal/lwm2m_over_mqtt
src/com/ibm/lwm2m/client/LwM2MClient.java
[ "public class LwM2MServerObject extends MQTTResource {\n\t\n\tpublic static final String RESOURCE_NAME = \"1\";\n\tObserveSpec observeSpec = new ObserveSpec();\n\tprivate static final AtomicInteger instanceCounter = new AtomicInteger(0); \n\t\n\tpublic LwM2MServerObject(String name, boolean bInstance) {\n\t\tsuper(name);\n\t\t\n\t\tif(true == bInstance) {\n\t\t\tserverId = new IntegerResource(\"0\", false, 10);\n\t\t\tlifttime = new IntegerResource(\"1\", true, 86400); \n\t\t\tminPeriod = new IntegerResource(\"2\", true, 1);\n\t\t\tmaxPeriod = new IntegerResource(\"3\", true, 10);\n\t\t\tdisable = new ExecResource(\"4\"); \n\t\t\tdisableTimeout = new IntegerResource(\"5\", true, 10);\n\t\t\tbstoreNotification = new BooleanResource(\"6\", true, false);\n\t\t\tbinding = new StringResource(\"7\", true, \"MQTT\");\n\t\t\tbRegistrationUpdateTrigger = new ExecResource(\"8\");\n\t\t}\n\t}\n\t\n\tprivate IntegerResource serverId;\n\tprivate IntegerResource lifttime; \n\tprivate IntegerResource minPeriod;\n\tprivate IntegerResource maxPeriod;\n\tprivate ExecResource disable; \n\tprivate IntegerResource disableTimeout;\n\tprivate BooleanResource bstoreNotification;\n\tprivate StringResource binding;\n\tprivate ExecResource bRegistrationUpdateTrigger;\n\t\n\tpublic static LwM2MServerObject createObject() {\n\t\tLwM2MServerObject to = new LwM2MServerObject(RESOURCE_NAME, false);\n\t\tLwM2MClient.getRootResource().add(to);\n\t\treturn to;\n\t}\n\t\n\tpublic static LwM2MServerObject createObjectInstance() {\n\t\tLwM2MServerObject to = new LwM2MServerObject(\n\t\t\t\tInteger.toString(instanceCounter.getAndIncrement()), true);\n\t\tResource resource = LwM2MClient.getRootResource().getChild(RESOURCE_NAME);\n\t\tresource.add(to);\n\t\tto.add(to.serverId);\n\t\tto.add(to.lifttime);\n\t\tto.add(to.minPeriod);\n\t\tto.add(to.maxPeriod);\n\t\tto.add(to.disable);\n\t\tto.add(to.disableTimeout);\n\t\tto.add(to.bstoreNotification);\n\t\tto.add(to.binding);\n\t\tto.add(to.bRegistrationUpdateTrigger);\n\t\treturn to;\n\t}\n\n\tpublic ObserveSpec getObserveSpec() {\n\t\t\n\t\tif(this.observeSpec == null) {\n\t\t\tobserveSpec = new ObserveSpec(Integer.valueOf(minPeriod.getValue()),\n\t\t\t\t\tInteger.valueOf(maxPeriod.getValue()));\n\t\t} else {\n\t\t\tobserveSpec.setMaxPeriod(Integer.valueOf(maxPeriod.getValue()));\n\t\t\tobserveSpec.setMinPeriod(Integer.valueOf(minPeriod.getValue()));\n\t\t}\n\t\t\n\t\treturn observeSpec;\n\t\t\n\t}\n\t\n}", "public class TemperatureSensorObject extends MQTTResource {\n\t\n\tpublic static final String RESOURCE_NAME = \"3303\";\n\t\n\tprivate boolean bInstance = false;\n\tprivate static final AtomicInteger instanceCounter = new AtomicInteger(0);\n\t\n\tprivate FloatResource minMeasuredValue; \n\tprivate FloatResource maxMeasuredValue;\n\tprivate FloatResource minRangeValue;\n\tprivate FloatResource maxRangeValue;\n\tprivate FloatResource sensorValue;\n\n\tprivate ObserveSpec observeSpec;\n\t\n\tpublic TemperatureSensorObject(String name, boolean bInstance) {\n\t\tsuper(name);\n\t\tthis.bInstance = bInstance;\n\t\t\n\t\t/* only object-instance will hold the resources */\n\t\tif(bInstance == true) {\n\t\t\tminMeasuredValue = new FloatResource(\"5601\", false, 0f); \n\t\t\tmaxMeasuredValue = new FloatResource(\"5602\", false, 0f);\n\t\t\tminRangeValue = new FloatResource(\"5603\", false, 0f);\n\t\t\tmaxRangeValue = new FloatResource(\"5604\", false, 0f);\n\t\t\tsensorValue = new FloatResource(\"5700\", false, 0f);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void handlePOST(MQTTExchange exchange) {\n\t\tRequest request = exchange.getRequest();\n\t\tTemperatureSensorObject.createObjectInstance(Integer.valueOf(request.getObjectInstanceId()));\n\t\tif(!bInstance)\n\t\t\texchange.respond(ResponseCode.CREATED, \"\");\n\t\telse \n\t\t\texchange.respond(ResponseCode.CHANGED, \"\");\n\t\tLwM2MClient.getClient().updateRegisteration();\n\t}\n\n\t@Override\n\tpublic void handlePUT(MQTTExchange exchange) {\n\t\t/*\n \t * Content will have following 2 parameters delimited by space,\n \t * 1st parameter to carry whether its a normal write request\n \t * or the write attribute request\n \t * \n \t * 0 - write attribute request\n \t * 1 - write request \n \t * \n \t * 2nd parameter - value or the list of attributes\n \t * \n \t */\n \tString[] parameters = exchange.getRequest().getPayloadText().split(\" \", 2);\n \t// check whether its a write attribute request\n \tif(PUT.value(parameters[0]) == PUT.ATTRIBUTES) {\n\t\t\tthis.observeSpec = ObserveSpecParser.parse(Request.getParameters(parameters[1]));\n\t\t\texchange.respond(ResponseCode.CHANGED);\n\t\t} else {\n\t\t\texchange.respond(ResponseCode.METHOD_NOT_ALLOWED, \"\");\t\n\t\t}\n\t}\n\n\tpublic static TemperatureSensorObject createObject() {\n\t\tTemperatureSensorObject to = new TemperatureSensorObject(RESOURCE_NAME, false);\n\t\tLwM2MClient.getRootResource().add(to);\n\t\treturn to;\n\t}\n\t\n\tpublic static synchronized TemperatureSensorObject createObjectInstance() {\n\t\tTemperatureSensorObject to = new TemperatureSensorObject(\n\t\t\t\tInteger.toString(instanceCounter.getAndIncrement()), true);\n\t\t\n\t\tResource resource = LwM2MClient.getRootResource().getChild(RESOURCE_NAME);\n\t\tresource.add(to);\n\t\tto.add(to.minMeasuredValue);\n\t\tto.add(to.maxMeasuredValue);\n\t\tto.add(to.minRangeValue);\n\t\tto.add(to.maxRangeValue);\n\t\tto.add(to.sensorValue);\n\t\treturn to;\n\t}\n\t\n\tpublic static synchronized TemperatureSensorObject createObjectInstance(int id) {\n\t\tTemperatureSensorObject to = new TemperatureSensorObject(\n\t\t\t\tInteger.toString(id), true);\n\t\tinstanceCounter.set(id + 1);\n\t\tResource resource = LwM2MClient.getRootResource().getChild(RESOURCE_NAME);\n\t\tresource.add(to);\n\t\tto.add(to.minMeasuredValue);\n\t\tto.add(to.maxMeasuredValue);\n\t\tto.add(to.minRangeValue);\n\t\tto.add(to.maxRangeValue);\n\t\tto.add(to.sensorValue);\n\t\treturn to;\n\t}\n\t\n\t@Override\n\tpublic void handleDELETE(MQTTExchange exchange) {\n\t\t// If its the instance delete request, delete it\n\t\tif(bInstance) {\n\t\t\tResource resource = this.getParent();\n\t\t\tresource.remove(this);\n\t\t\texchange.respond(ResponseCode.DELETED, \"\");\n\t\t} else {\n\t\t\texchange.respond(ResponseCode.METHOD_NOT_ALLOWED, \"\");\n\t\t}\n\t\tLwM2MClient.getClient().updateRegisteration();\t\t\n\t}\n\n\n}", "public abstract class AbstractRequestObserver {\n protected Request mqttRequest;\n\n public AbstractRequestObserver(final Request mqttRequest) {\n this.mqttRequest = mqttRequest;\n }\n\n public abstract void onResponse(final Response mqttResponse);\n public abstract void onError(final Response mqttResponse);\n\n\tpublic void onCancel() {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n}", "public class MQTTWrapper {\n\tprivate static final Logger LOG = LoggerFactory.getLogger(MQTTWrapper.class);\n\t\n\tprivate static int QOS = 2;\n\t\n\t// \"tcp://localhost:1800\";\n private final InetSocketAddress brokerAddress;\n private final String endpointID;\n \n /* root resource */\n private final Resource root;\n \n\tprivate IMqttClient mqttClient = null;\n\tprivate MqttCallback callback;\n\n\tpublic MQTTWrapper(InetSocketAddress brokerAddress, String endpointID) {\n\t\tthis.brokerAddress = brokerAddress;\n\t\tthis.endpointID = endpointID;\n\t\tthis.root = new RootResource();\n\t}\n\n\tpublic void start() {\n\t\tMemoryPersistence persistence = new MemoryPersistence();\n\t\ttry {\n\t\t\tString serverURI = \"tcp://\"+brokerAddress.getHostString()+\":\"+brokerAddress.getPort();\n\t\t\tmqttClient = new MqttClient(serverURI, endpointID, persistence);\n MqttConnectOptions connOpts = new MqttConnectOptions();\n connOpts.setCleanSession(true);\n LOG.info(\"Connecting endpoint \"+ endpointID + \" to broker: \"+serverURI);\n mqttClient.connect(connOpts);\n LOG.info(\"Connected\");\n\t\t} catch(MqttException me) {\n LOG.error(\"reason \"+me.getReasonCode());\n LOG.error(\"msg \"+me.getMessage());\n LOG.error(\"loc \"+me.getLocalizedMessage());\n LOG.error(\"cause \"+me.getCause());\n LOG.error(\"excep \"+me);\n me.printStackTrace();\n }\n\t}\n\t\n\tpublic void stop() {\n\t\ttry {\n LOG.info(\"Disconnecting \" + endpointID + \" from broker\");\n mqttClient.disconnect();\n\t\t} catch(MqttException me) {\n\t\t\tLOG.error(\"reason \"+me.getReasonCode());\n\t\t\tLOG.error(\"msg \"+me.getMessage());\n\t\t\tLOG.error(\"loc \"+me.getLocalizedMessage());\n\t\t\tLOG.error(\"cause \"+me.getCause());\n\t\t\tLOG.error(\"excep \"+me);\n me.printStackTrace();\n }\n\t}\n\t\n\tpublic void setCallBack(MqttCallback callback) {\n\t\tmqttClient.setCallback(callback);\n\t\tthis.callback = callback;\n\t}\n\t\n\tpublic void subscribe(String topic, int qos) {\n\t\ttry {\n\t\t\tLOG.info(\"Subscribe to :: \"+ topic);\n\t\t\tmqttClient.subscribe(topic, qos);\n\t\t} catch (MqttException me) {\n\t\t\tLOG.error(\"reason \"+me.getReasonCode());\n\t\t\tLOG.error(\"msg \"+me.getMessage());\n\t\t\tLOG.error(\"loc \"+me.getLocalizedMessage());\n\t\t\tLOG.error(\"cause \"+me.getCause());\n\t\t\tLOG.error(\"excep \"+me);\n me.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic void subscribe(String[] topics, int[] qos) {\n\t\ttry {\n\t\t\tfor(int i = 0; i < topics.length; i++) {\n\t\t\t\tLOG.info(\"Subscribe to :: \"+topics[i]);\n\t\t\t}\n\t\t\tmqttClient.subscribe(topics, qos);\n\t\t} catch (MqttException me) {\n\t\t\tLOG.error(\"reason \"+me.getReasonCode());\n\t\t\tLOG.error(\"msg \"+me.getMessage());\n\t\t\tLOG.error(\"loc \"+me.getLocalizedMessage());\n\t\t\tLOG.error(\"cause \"+me.getCause());\n\t\t\tLOG.error(\"excep \"+me);\n me.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic void publish(String topic, String content) {\n\t\ttry {\n\t\t\tMqttMessage message = new MqttMessage(content.getBytes());\n message.setQos(QOS);\n LOG.info(\"publish :: {\"+topic+\" [\"+message+\" ]}\");\n\t\t\tmqttClient.publish(topic, message);\n\t\t} catch (MqttException me) {\n\t\t\tLOG.error(\"reason \"+me.getReasonCode());\n\t\t\tLOG.error(\"msg \"+me.getMessage());\n\t\t\tLOG.error(\"loc \"+me.getLocalizedMessage());\n\t\t\tLOG.error(\"cause \"+me.getCause());\n\t\t\tLOG.error(\"excep \"+me);\n me.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic MQTTWrapper add(Resource... resources) {\n\t\tfor (Resource r:resources) {\n\t\t\tLOG.info(\"adding resource \"+ r.getName() +\" under root\");\n\t\t\troot.add(r);\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic Resource getRoot() {\n\t\t// TODO Auto-generated method stub\n\t\treturn root;\n\t}\n\t\n\tpublic MqttCallback getMqttCallback() {\n\t\treturn this.callback;\n\t}\n\t\n\tprivate class RootResource extends MQTTResource {\n\t\t\n\t\tpublic RootResource() {\n\t\t\tsuper(\"\");\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void handleGET(MQTTExchange exchange) {\n\t\t\texchange.respond(ResponseCode.CONTENT, \"Hi, Am root resource\");\n\t\t}\n\t\t\n\t}\n\n\tpublic void destroy() {\n\t\ttry {\n LOG.info(\"Disconnecting \" + endpointID + \" from broker\");\n mqttClient.disconnect();\n mqttClient.close();\n\t\t} catch(MqttException me) {\n\t\t\tLOG.error(\"reason \"+me.getReasonCode());\n\t\t\tLOG.error(\"msg \"+me.getMessage());\n\t\t\tLOG.error(\"loc \"+me.getLocalizedMessage());\n\t\t\tLOG.error(\"cause \"+me.getCause());\n\t\t\tLOG.error(\"excep \"+me);\n me.printStackTrace();\n }\n\t\t\n\t}\n}", "public class MqttV3MessageReceiver implements MqttCallback {\n\n\tprivate MQTTWrapper mqttClient;\n\tprivate static final Logger LOG = LoggerFactory.getLogger(MqttV3MessageReceiver.class);\n\tprivate static ConcurrentHashMap<Long, AbstractRequestObserver> requestObservers = new ConcurrentHashMap();\n\tprivate static ScheduledThreadPoolExecutor executor = \n\t\t\tnew ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1);\n\t\n\tpublic MqttV3MessageReceiver(MQTTWrapper mqttClient) {\n\t\tthis.mqttClient = mqttClient;\n\t}\n\t\n\t@Override\n\tpublic void messageArrived(final String topic, final MqttMessage message)\n\t\t\tthrows Exception {\n\t\t\n\t\texecutor.execute(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\thandleMessage(topic, message);\n\t\t\t\t} catch (Throwable t) {\n\t\t\t\t\tt.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\t\n\t\n\n\tprotected void handleMessage(String topic, MqttMessage message) {\n\t\tLOG.info(\"MSG { \"+topic + \" [\"+message.toString()+\"]}\");\n\t\t\n\t\tif(topic.startsWith(Request.RESPONSE_TOPIC_STARTER)) {\n\t\t\tString[] paths = topic.split(\"/\");\n\t\t\tLong messageID = Long.valueOf(paths[paths.length - 1]);\n\t\t\t// the last one must contain the message-id\n\t\t\tAbstractRequestObserver requestObserver = \n\t\t\t\t\trequestObservers.get(messageID);\n\t\t\tif(requestObserver != null) {\n\t\t\t\tResponse response = new Response(message);\n\t\t\t\tif(ResponseCode.isSuccess(ResponseCode.valueOf(response.getCode()))) {\n\t\t\t\t\trequestObserver.onResponse(response);\n\t\t\t\t} else {\n\t\t\t\t\trequestObserver.onError(response);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tRequest request = new Request(topic, message);\n\t\tMQTTExchange exchange = new MQTTExchange(request, null);\n\t\texchange.setMqttClient(this.mqttClient);\n\t\t\n\t\tResource resource = getResource(request);\n\t\tif(resource == null) {\n\t\t\t// Check if its a POST operation, in which case\n\t\t\t// we need to return the parent resource to create\n\t\t\t// the new instance\n\t\t\tif(request.getOperation() == Operation.POST) {\n\t\t\t\tresource = getParentResource(request);\n\t\t\t}\n\t\t\tif(resource == null) {\n\t\t\t\texchange.respond(ResponseCode.NOT_FOUND);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\texchange.setResource(resource);\n\t\t\n\t\tswitch(request.getOperation()) {\n\t\t\tcase POST:\n\t\t\t\tresource.handlePOST(exchange);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase PUT:\n\t\t\t\tresource.handlePUT(exchange);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase DELETE:\n\t\t\t\tresource.handleDELETE(exchange);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase GET:\n\t\t\t\tresource.handleGET(exchange);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase RESET:\n\t\t\t\tresource.handleRESET(exchange);\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t}\n\n\tprivate Resource getResource(Request request) {\n\t\tResource resource = this.mqttClient.getRoot();\n\t\tLOG.debug(\" root-resource:: \"+resource);\n\t\t\n\t\t\n\t\tString id = request.getObjectId();\n\t\tLOG.debug(\" getObjectId:: \"+id);\n\t\tif(id == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tresource = resource.getChild(id);\n\t\t}\n\t\t\n\t\t\n\t\tid = request.getObjectInstanceId(); \n\t\tLOG.debug(\" getObjectInstanceId:: \"+id);\n\t\tif(id != null && resource != null) {\n\t\t\tresource = resource.getChild(id);\n\t\t}\n\t\t\n\t\tid = request.getResourceId(); \n\t\tif(id != null && resource != null) {\n\t\t\tresource = resource.getChild(id);\n\t\t}\n\t\t\n\t\treturn resource;\n\t}\n\t\n\tprivate Resource getParentResource(Request request) {\n\t\tResource resource = this.mqttClient.getRoot();\n\t\tLOG.debug(\" root-resource:: \"+resource);\n\t\t\n\t\tString id = request.getObjectId();\n\t\tLOG.debug(\" getObjectId:: \"+id);\n\t\tif(id == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\tresource = resource.getChild(id);\n\t\t}\n\t\t\n\t\treturn resource;\n\t}\n\n\tpublic void addRequest(Long messageID,\n\t\t\tAbstractRequestObserver requestObserver) {\n\t\trequestObservers.put(messageID, requestObserver);\n\t}\n\t\n\tpublic void removeRequest(Long messageID) {\n\t\trequestObservers.remove(messageID);\n\t}\n\t\n\tpublic AbstractRequestObserver getRequest(Long messageID) {\n\t\treturn requestObservers.get(messageID);\n\t}\n\n\t\n\tpublic void connectionLost(Throwable cause) {\n\t\tLOG.info(\"Connection lost \"+cause.getMessage());\n\t\tcause.printStackTrace();\n\t\t\n\t}\n\n\tpublic void deliveryComplete(IMqttDeliveryToken token) {\n\t\t//System.out.println(\"DeliveryComplte :: \"+token.toString());\n\t\t\n\t}\n\t\n\tpublic MQTTWrapper getMqttClinet() {\n\t\t// TODO Auto-generated method stub\n\t\treturn mqttClient;\n\t}\n\n\tpublic void cancel(long messageID) {\n\t\tAbstractRequestObserver obs = this.requestObservers.get(messageID);\n\t\tobs.onCancel();\n\t}\n\n}", "public class Request {\n\n\tprivate static final Logger LOG = LoggerFactory.getLogger(Request.class);\n\t\n\tpublic static final String REQUEST_TOPIC_STARTER = \"LWM/S\";\n\tpublic static final String RESPONSE_TOPIC_STARTER = \"LWM/R\";\n\t\n\tprivate String organizationID;\n\tprivate String endpointID;\n\tprivate String applicationID;\n\tprivate Operation operation;\n\tprivate String resource = \"\";\n\tprivate MqttPayload payload;\n\t\n\tprivate LwM2MNode node;\n\n\tprivate MQTTWrapper mqttClient;\n\n\tprivate class LwM2MNode {\n\t\tprivate String objectId;\n\t\tprivate String objectIdInstance;\n\t\tprivate String resourceId;\n\t}\n\t\n\tprivate class MqttPayload {\n\t\tprivate long messageID;\n\t\tprivate String requestorEndpointID;\n\t\tprivate String requestorAppID;\n\t\tprivate int option;\n\t\t\n\t\tprivate StringBuilder content = new StringBuilder();\n\t}\n\t\n\t\n\tpublic Request(String topic, MqttMessage message) {\n\t\tparseTopic(topic);\n\t\tparseContent(message);\n\t}\n\t\n\tpublic Request(Operation operation) {\n\t\tthis.operation = operation;\n\t\tpayload = new MqttPayload();\n\t}\n\n\tpublic String getResourcePath() {\n\t\treturn resource;\n\t}\n\t\n\tprivate void parseContent(MqttMessage message) {\n\t\ttry {\n\t\t\tString content = new String(message.getPayload(), \"UTF-8\");\n\t\t\tString[] parms = content.split(\" \", 4);\n\t\t\t\n\t\t\tthis.payload = new MqttPayload(); \n\t\t\tpayload.messageID = Long.parseLong(parms[0]);\n\t\t\tpayload.requestorEndpointID = parms[1];\n\t\t\tpayload.requestorAppID = parms[2];\n\t\t\tif(parms.length >=4)\n\t\t\t\tpayload.content = payload.content.append(parms[3]);\n\t\t\t\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t\t\n\t}\n\t\n\tprivate void parseTopic(String topic) {\n\t\t\n\t\t// LWM/S/ORG_ID/Device_ID/App_ID/MethodName/PATH?queryString\n\t\t\n\t\tString[] levels = topic.split(\"/\");\n\t\t\n\t\t// get org id now\n\t\t\n\t\tthis.organizationID = levels[2];\n\t\tthis.endpointID = levels[3];\n\t\tthis.applicationID = levels[4];\n\t\tthis.operation = Operation.valueOf(levels[5]);\n\t\t\n\t\tint length = levels[0].length() + levels[1].length() +\n\t\t\t\t\t levels[2].length() + levels[3].length() +\n\t\t\t\t\t levels[4].length() + levels[5].length() + 6;\n\t\t\n\t\t\n\t\tresource = topic.substring(length);\n\n\t\t// extract the objectid, object-instanceid and resource-id\n String[] resources = resource.split(\"/\");\n \n if(resources == null || resources.length == 0) {\n \treturn;\n }\n \n node = new LwM2MNode();\n node.objectId = resources[0];\n \n // extract the objectid instance\n if(resources.length > 1) {\n \tnode.objectIdInstance = resources[1];\n }\n \n if(resources.length > 2) {\n node.resourceId = resources[2];\n }\n\t}\n\n\tpublic List<String> getURIPaths() {\n\t\tArrayList list = new ArrayList();\n\t\tString paths[] = this.resource.split(\"/\");\n\t\tfor(int i = 0; i < paths.length; i++) {\n\t\t\tlist.add(paths[i]);\n\t\t}\n\t\treturn list;\n\t}\n\n\t\n\tpublic Operation getOperation() {\n\t\treturn this.operation;\n\t}\n\n\tpublic String getEndpointId() {\n\t\treturn endpointID;\n\t}\n\t\n\tpublic void setEndPointId(String endPointId) {\n\t\tthis.endpointID = endPointId;\n\t}\n\t\n\tpublic String toString() {\n\t\treturn this.getTopic() +\" [\" + this.getMessageAsString() + \"]\";\n\t}\n\n\tpublic String getObjectId() {\n\t\tif(null != node) {\n\t\t\treturn node.objectId;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic String getObjectInstanceId() {\n\t\tif(null != node) {\n\t\t\treturn node.objectIdInstance;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic String getResourceId() {\n\t\tif(null != node) {\n\t\t\treturn node.resourceId;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean isObserve() {\n\t\tif(( getOperation() == Operation.GET) &&\n\t\t\t\tGET.value(getPayloadText()) == GET.OBSERVE) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isRead() {\n\t\tif(( getOperation() == Operation.GET) &&\n\t\t\t\tGET.value(getPayloadText()) == GET.READ) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean isDiscover() {\n\t\tif(( getOperation() == Operation.GET) &&\n\t\t\t\tGET.value(getPayloadText()) == GET.DISCOVER) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic String getPayloadText() {\n\t\treturn this.payload.content.toString();\n\t}\n\t\n\tpublic byte[] getPayloadContent() {\n\t\tif(this.payload.content == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn this.payload.content.toString().getBytes(); \n\t}\n\n\tpublic static Request newPost() {\n\t\tRequest req = new Request(Operation.POST);\n\t\treq.payload = req.new MqttPayload();\n\t\treq.payload.messageID = MessageID.get();\n\t\treturn req;\n\t}\n\n\tpublic void addURIPath(String resource) {\n\t\tthis.resource = this.resource +\"/\"+resource;\n\t}\n\n\tpublic static Request newPut() {\n\t\tRequest req = new Request(Operation.PUT);\n\t\treq.payload = req.new MqttPayload();\n\t\treq.payload.messageID = MessageID.get();\n\t\treturn req;\n\t}\n\n\tpublic static Request newDelete() {\n\t\tRequest req = new Request(Operation.DELETE);\n\t\treq.payload = req.new MqttPayload();\n\t\treq.payload.messageID = MessageID.get();\n\t\treturn req;\n\t}\n\t\n\tpublic static Request newGet() {\n\t\tRequest req = new Request(Operation.GET);\n\t\treq.payload = req.new MqttPayload();\n\t\treq.payload.messageID = MessageID.get();\n\t\treturn req;\n\t}\n\n\tpublic void setPayloadContent(String content) {\n\t\tthis.payload.content.append(content);\n\t}\n\t\n\tpublic long getMessageID() {\n\t\treturn this.payload.messageID;\n\t}\n\n\tpublic String getMessageAsString() {\n\t\treturn this.payload.messageID +\" \"+\n\t\t\t\tthis.payload.requestorEndpointID +\" \"+\n\t\t\t\tthis.payload.requestorAppID +\" \"+\n\t\t\t\tthis.payload.content;\n\t}\n\t\n\tpublic String getTopic() {\n\t\tStringBuilder sb = new StringBuilder(50);\n\t\t\n\t\tsb.append(REQUEST_TOPIC_STARTER);\n\t\tsb.append(\"/\");\n\t\tsb.append(this.organizationID);\n\t\tsb.append(\"/\");\n\t\tsb.append(this.endpointID);\n\t\tsb.append(\"/\");\n\t\tsb.append(this.applicationID);\n\t\tsb.append(\"/\");\n\t\tsb.append(this.operation);\n\t\tif(this.resource.charAt(0) != '/') {\n\t\t\tsb.append(\"/\");\t\n\t\t}\n\t\tsb.append(this.resource);\n\t\treturn sb.toString();\n\t}\n\n\tpublic void setOrganizationID(String organizationID) {\n\t\tthis.organizationID = organizationID; \n\t\t\n\t}\n\n\tpublic void setApplicationID(String applicationID) {\n\t\tthis.applicationID = applicationID;\n\t}\n\t\n\tpublic void setRequestorApplicationID(String applicationID) {\n\t\tthis.payload.requestorAppID = applicationID;\n\t}\n\t\n\tpublic void setRequestorEndpointID(String endpointID) {\n\t\tthis.payload.requestorEndpointID = endpointID;\n\t}\n\t\n\tpublic String getRequestorApplicationID() {\n\t\treturn this.payload.requestorAppID;\n\t}\n\t\n\tpublic String getRequestorEndpointID() {\n\t\treturn this.payload.requestorEndpointID;\n\t}\n\t\n\tpublic String getOrganizationID() {\n\t\treturn this.organizationID;\n\t}\n\n\tpublic void setPayloadContent(byte[] content) {\n\t\ttry {\n\t\t\tif(content != null && content.length > 0)\n\t\t\t\tthis.payload.content.append(new String(content, \"UTF-8\"));\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t}\n\t\n\tpublic void addPayloadContent(byte[] content) {\n\t\ttry {\n\t\t\tif(content != null && content.length > 0) {\n\t\t\t\tthis.payload.content.append(\" \");\n\t\t\t\tthis.payload.content.append(new String(content, \"UTF-8\"));\n\t\t\t}\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/*\n\t * Cancel the observation\n\t */\n\tpublic void cancel() {\n\t\tthis.operation = Operation.RESET;\n\t\tmqttClient.publish(this.getTopic(), this.getMessageAsString());\n\t\t((MqttV3MessageReceiver)mqttClient.getMqttCallback()).cancel(this.getMessageID());\n\t}\n\n\tpublic void setMqttClient(MQTTWrapper mqttClient) {\n\t\tthis.mqttClient = mqttClient;\n\t\t\n\t}\n\n\tpublic static List<String> getParameters(String content) {\n \tString[] parms = content.split(\"&\");\n\t\tList<String> queryParms = new ArrayList();\n\t\tfor(int i = 0; i < parms.length ; i++) {\n\t\t\tqueryParms.add(parms[i]);\n\t\t}\n\t\treturn queryParms;\n\t}\n\n}", "public interface Resource {\n\t\n\tpublic String getName();\n\n\tpublic void handlePOST(MQTTExchange exchange);\n\tpublic void handlePUT(MQTTExchange exchange);\n\tpublic void handleGET(MQTTExchange exchange);\n\tpublic void handleDELETE(MQTTExchange exchange);\n\t\n\tpublic void handleRESET(MQTTExchange exchange);\n\n\tvoid add(Resource child);\n\tpublic Resource getParent();\n\tpublic boolean remove(Resource child);\n\tpublic void setParent(Resource resource);\n\n\tResource getChild(String name);\n\n\tCollection<Resource> getChildren();\n\n}", "public class Response {\n\n\tprivate float responseCode;\n\tprivate String payload = \"\";\n\t\n\tpublic Response(ResponseCode responseCode) {\n\t\tthis.responseCode = responseCode.value;\n\t}\n\n\tpublic Response(MqttMessage message) {\n\t\tString msg = null;\n\t\ttry {\n\t\t\tmsg = new String(message.getPayload(), \"UTF-8\");\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\tString[] data = msg.split(\" \", 2);\n\t\tthis.payload = data[1];\n\t\tthis.responseCode = Float.valueOf(data[0]);\n\t}\n\n\tpublic void setPayload(String payload) {\n\t\tthis.payload = payload;\n\t}\n\n\tpublic void setPayload(byte[] payload) {\n\t\ttry {\n\t\t\tthis.payload = new String(payload, \"UTF-8\");\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t\n\t}\n\t\n\tpublic String getMessage() {\n\t\treturn responseCode + \" \" + payload;\n\t}\n\n\tpublic float getCode() {\n\t\treturn responseCode;\n\t}\n\t\n\tpublic byte[] getPayload() {\n\t\treturn this.payload.getBytes();\n\t}\n\t\n\tpublic String getPayloadText() {\n\t\treturn this.payload;\n\t}\n\n}" ]
import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Iterator; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibm.lwm2m.objects.LwM2MServerObject; import com.ibm.lwm2m.objects.TemperatureSensorObject; import com.ibm.mqttv3.binding.AbstractRequestObserver; import com.ibm.mqttv3.binding.MQTTWrapper; import com.ibm.mqttv3.binding.MqttV3MessageReceiver; import com.ibm.mqttv3.binding.Request; import com.ibm.mqttv3.binding.Resource; import com.ibm.mqttv3.binding.Response;
System.out.println(" >> IPSO temperature Object - <3303/0> "); System.out.println(" >> 3303/0/5700 - SensorValue "); System.out.println(" >> 3303/0/5601 - Minimum Measured Value "); System.out.println(" >> 3303/0/5602 - Maximum Measured Value "); System.out.println(" >> 3303/0/5603 - Min Range Value "); System.out.println(" >> 3303/0/5604 - Max Range Value "); } void userAction() { list(); Scanner in = new Scanner(System.in); while (true) { System.out.println("Enter the command "); String input = in.nextLine(); String[] parameters = input.split(" "); try { switch (parameters[0]) { case "register": if (registerLocationID == null) { this.register(); } else { System.out.println("This client is already registered in the server"); } break; case "deregister": if (registerLocationID != null) { this.deregister(); } else { System.out.println("This client is either not registered " + "or already de-registered from the server"); } in.close(); System.exit(0); break; case "update-register": this.updateRegisteration(); break; case "get": if (parameters.length == 2) { LocalResource resource = ((LocalResource) getResource(parameters[1])); if (resource != null) { System.out.println(resource.getValue()); } else { System.out.println("Resource - " + parameters[1] + " not found!"); } } else { System.out .println("Please specify the command as get <resource-id>"); } break; case "update": if (parameters.length == 3) { LocalResource resource = (LocalResource) getResource(parameters[1]); if (resource != null) { resource.setValue(parameters[2]); } else { System.out.println("Resource - " + parameters[1] + " not found!"); } } else { System.out .println("Please specify the command as update <resource-id> <value>"); } break; default: list(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private String getServerId() { Resource resource = mqttClient.getRoot(); // Get the server object resource = resource.getChild("1"); // Get the server object instance resource = resource.getChild("0"); // get the server id resource resource = resource.getChild("0"); return ((LocalResource) resource).getValue(); } private void setServerId(String id) { Resource resource = mqttClient.getRoot(); // Get the server object resource = resource.getChild("1"); // Get the server object instance resource = resource.getChild("0"); // get the server id resource resource = resource.getChild("0"); ((LocalResource) resource).setValue(id); } public synchronized static LwM2MClient getClient() { if(client == null) { client = new LwM2MClient(); } return client; } public static Resource getRootResource() { return client.mqttClient.getRoot(); } private abstract class SyncRequestObserver<T> extends
AbstractRequestObserver {
2
HackGSU/mobile-android
app/src/main/java/com/hackgsu/fall2016/android/HackGSUApplication.java
[ "public class FullscreenWebViewActivity extends AppCompatActivity {\n\tpublic static final String EXTRA_URL = \"extra_url\";\n\tprivate ContentLoadingProgressBar progressBar;\n\tprivate WebView webView;\n\n\t@Override\n\tprotected void onCreate (Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\n\t\tsetContentView(R.layout.activity_fullscreen_web_view);\n\t\twebView = (WebView) findViewById(R.id.web_view);\n\t\tprogressBar = (ContentLoadingProgressBar) findViewById(R.id.progress_bar);\n\n\t\twebView.getSettings().setJavaScriptEnabled(true);\n\t\twebView.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic void onPageFinished (WebView view, String url) {\n\t\t\t\tsuper.onPageFinished(view, url);\n\n\t\t\t\tprogressBar.hide();\n\t\t\t}\n\t\t});\n\t\tprogressBar.show();\n\n\t\tActionBar actionBar = getSupportActionBar();\n\t\tif (actionBar != null) {\n\t\t\tactionBar.hide();\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onStart () {\n\t\tsuper.onStart();\n\n\t\tString url = getIntent().getStringExtra(EXTRA_URL);\n\t\tif (HackGSUApplication.isNullOrEmpty(url)) {\n\t\t\tHackGSUApplication.toast(this, \"I had trouble loading that url..\");\n\t\t\tfinish();\n\t\t}\n\t\telse { webView.loadUrl(url); }\n\t}\n\n\t@Override\n\tprotected void onPause () {\n\t\tsuper.onPause();\n\n\t\tfinish();\n\t}\n}", "public class AnnouncementController {\n\tpublic static final String ANNOUNCEMENTS_BOOKMARKED_KEY = \"announcements_bookmarked\";\n\tpublic static final String ANNOUNCEMENTS_LIKED_KEY = \"announcements_liked\";\n\tpublic static final String ANNOUNCEMENTS_NOTIFIED_KEY = \"announcements_notified\";\n\tpublic static final String ANNOUNCEMENTS_TABLE = \"announcements\";\n\tpublic static final String ANNOUNCEMENTS_TABLE_DEV = \"announcements_dev\";\n\n\tpublic static String getAnnouncementsTableString (Context context) {\n\t\treturn HackGSUApplication.isInDevMode(context) ? ANNOUNCEMENTS_TABLE_DEV : ANNOUNCEMENTS_TABLE;\n\t}\n\n\tpublic static void sendOrUpdateAnnouncement (Context context, Announcement announcement, final CallbackWithType<Void> callback) {\n\t\tFirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();\n\t\tif (currentUser != null) {\n\t\t\tDatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();\n\t\t\tDatabaseReference announcementRef = dbRef.child(getAnnouncementsTableString(context)).getRef();\n\t\t\tDatabaseReference announcementRefWithId;\n\t\t\tif (announcement.getFirebaseKey() == null || announcement.getFirebaseKey().equals(\"\")) {\n\t\t\t\tannouncementRefWithId = announcementRef.push();\n\t\t\t}\n\t\t\telse { announcementRefWithId = announcementRef.child(announcement.getFirebaseKey()); }\n\t\t\tannouncementRefWithId.setValue(announcement, new DatabaseReference.CompletionListener() {\n\t\t\t\t@SuppressLint (\"CommitPrefEdits\")\n\t\t\t\t@Override\n\t\t\t\tpublic void onComplete (DatabaseError databaseError, DatabaseReference databaseReference) {\n\t\t\t\t\tif (callback != null) {\n\t\t\t\t\t\tif (databaseError == null) { callback.onComplete(null); }\n\t\t\t\t\t\telse { callback.onError(); }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic static void setIsBookmarkedByMeBasedOnPrefs (Context context, ArrayList<Announcement> announcements) {\n\t\tif (context != null && announcements != null) {\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_BOOKMARKED_KEY, new HashSet<String>());\n\n\t\t\tfor (Announcement announcement : announcements) {\n\t\t\t\tannouncement.setBookmarkedByMe(bookmarkedAnnouncementIds.contains(announcement.getFirebaseKey()));\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void setIsLikedByMeBasedOnPrefs (Context context, ArrayList<Announcement> announcements) {\n\t\tif (context != null && announcements != null) {\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_LIKED_KEY, new HashSet<String>());\n\n\t\t\tfor (Announcement announcement : announcements) {\n\t\t\t\tannouncement.setLikedByMe(bookmarkedAnnouncementIds.contains(announcement.getFirebaseKey()));\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressLint (\"CommitPrefEdits\")\n\tpublic static boolean shouldNotify (Context context, Announcement announcement) {\n\t\tboolean notificationsEnabled = HackGSUApplication.areNotificationsEnabled(context);\n\t\tboolean returnValue;\n\t\tif (context != null && announcement != null && !HackGSUApplication.isNullOrEmpty(announcement.getFirebaseKey())) {\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> notifiedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_NOTIFIED_KEY, new HashSet<String>());\n\t\t\treturnValue = !notifiedAnnouncementIds.contains(announcement.getFirebaseKey());\n\t\t\tif (returnValue) {\n\t\t\t\tnotifiedAnnouncementIds.add(announcement.getFirebaseKey());\n\t\t\t\tprefs.edit().remove(ANNOUNCEMENTS_NOTIFIED_KEY).commit();\n\t\t\t\tprefs.edit().putStringSet(ANNOUNCEMENTS_NOTIFIED_KEY, notifiedAnnouncementIds).commit();\n\t\t\t}\n\t\t}\n\t\telse { return notificationsEnabled; }\n\t\treturn notificationsEnabled && returnValue;\n\t}\n\n\t@SuppressLint (\"CommitPrefEdits\")\n\tpublic static void toggleBookmark (Context context, Announcement announcement) {\n\t\tif (context != null && announcement != null && announcement.getFirebaseKey() != null) {\n\t\t\tannouncement.setBookmarkedByMe(!announcement.isBookmarkedByMe());\n\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_BOOKMARKED_KEY, new HashSet<String>());\n\n\t\t\tif (announcement.isBookmarkedByMe()) { bookmarkedAnnouncementIds.add(announcement.getFirebaseKey()); }\n\t\t\telse { bookmarkedAnnouncementIds.remove(announcement.getFirebaseKey()); }\n\n\t\t\tprefs.edit().remove(ANNOUNCEMENTS_BOOKMARKED_KEY).commit();\n\t\t\tprefs.edit().putStringSet(ANNOUNCEMENTS_BOOKMARKED_KEY, bookmarkedAnnouncementIds).apply();\n\t\t}\n\t}\n\n\t@SuppressLint (\"CommitPrefEdits\")\n\tpublic static void toggleLiked (Context context, Announcement announcement) {\n\t\tif (context != null && announcement != null && announcement.getFirebaseKey() != null) {\n\t\t\tannouncement.toggleLikedByMe();\n\n\t\t\tSharedPreferences prefs = HackGSUApplication.getPrefs(context);\n\t\t\tSet<String> bookmarkedAnnouncementIds = prefs.getStringSet(ANNOUNCEMENTS_LIKED_KEY, new HashSet<String>());\n\n\t\t\tif (announcement.isLikedByMe()) { bookmarkedAnnouncementIds.add(announcement.getFirebaseKey()); }\n\t\t\telse { bookmarkedAnnouncementIds.remove(announcement.getFirebaseKey()); }\n\n\t\t\tsendOrUpdateAnnouncement(context, announcement, null);\n\n\t\t\tprefs.edit().remove(ANNOUNCEMENTS_LIKED_KEY).commit();\n\t\t\tprefs.edit().putStringSet(ANNOUNCEMENTS_LIKED_KEY, bookmarkedAnnouncementIds).apply();\n\t\t}\n\t}\n}", "public class AnnouncementsUpdatedEvent extends BaseEvent<ArrayList<Announcement>> {\n\tpublic AnnouncementsUpdatedEvent (ArrayList<Announcement> announcements) {\n\t\tsuper(announcements);\n\t}\n}", "public class ScheduleUpdatedEvent extends BaseEvent<ArrayList<ScheduleEvent>> {\n\tpublic ScheduleUpdatedEvent (ArrayList<ScheduleEvent> scheduleEvents) {\n\t\tsuper(scheduleEvents);\n\t}\n}", "public class Announcement implements Serializable, Comparable<Announcement> {\n\tprivate String bodyText;\n\tprivate boolean bookmarkedByMe;\n\tprivate String firebaseKey;\n\tprivate boolean likedByMe;\n\tprivate int likes;\n\tprivate long timestamp;\n\tprivate String title;\n\tprivate Topic topic;\n\n\tpublic Announcement (String title, String bodyText, Topic topic) {\n\t\tthis.title = title;\n\t\tthis.bodyText = bodyText;\n\t\tthis.topic = topic;\n\n\t\tsetTimestamp(System.currentTimeMillis());\n\t}\n\n\tpublic Announcement () { }\n\n\tpublic enum Topic {\n\t\tGENERAL(R.drawable.ic_announcements), TECH(R.drawable.ic_devices), FOOD(R.drawable.ic_food);\n\t\tprivate\n\t\t@DrawableRes int icon;\n\n\t\tTopic (int icon) {\n\t\t\tthis.icon = icon;\n\t\t}\n\n\t\tpublic\n\t\t@DrawableRes\n\t\tint getIcon () {\n\t\t\treturn icon;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int compareTo (Announcement other) {\n\t\treturn other == null || other.getTimestampDateTime().isBefore(getTimestampDateTime()) ? -1 : 1;\n\t}\n\n\t@Exclude\n\tpublic void setFirebaseKey (String firebaseKey) {\n\t\tthis.firebaseKey = firebaseKey;\n\t}\n\n\t@Exclude\n\tpublic String getFirebaseKey () {\n\t\treturn firebaseKey;\n\t}\n\n\tpublic String getTitle () {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle (String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic int getLikes () {\n\t\treturn likes;\n\t}\n\n\tpublic void setLikes (int likes) {\n\t\tthis.likes = likes;\n\t}\n\n\tpublic String getBodyText () {\n\t\treturn bodyText;\n\t}\n\n\tpublic void setBodyText (String bodyText) {\n\t\tthis.bodyText = bodyText;\n\t}\n\n\tpublic long getTimestamp () {\n\t\treturn timestamp;\n\t}\n\n\t@Exclude\n\tpublic LocalDateTime getTimestampDateTime () {\n\t\treturn new LocalDateTime(getTimestamp());\n\t}\n\n\tpublic void setTimestamp (long timestamp) {\n\t\tthis.timestamp = timestamp;\n\t}\n\n\tpublic String getTopic () {\n\t\treturn topic == null ? null : topic.name();\n\t}\n\n\tpublic void setTopic (String topic) {\n\t\ttry {\n\t\t\tthis.topic = Topic.valueOf(topic);\n\t\t} catch (IllegalArgumentException ignored) {\n\t\t\tthis.topic = Topic.GENERAL;\n\t\t}\n\t}\n\n\t@Exclude\n\tpublic void setTopicEnum (Topic topic) {\n\t\tthis.topic = topic;\n\t}\n\n\t@Exclude\n\tpublic Topic getTopicEnum () {\n\t\treturn topic;\n\t}\n\n\t@Exclude\n\tpublic String getShareText (Context context) {\n\t\t// TODO: 10/6/16 : Maybe make this share message more better..? Also add Play Store link\n\t\tDateTimeFormatter dateTimeFormatter = HackGSUApplication.getTimeFormatter24OrNot(context);\n\t\tString time = getTimestampDateTime().toString(dateTimeFormatter);\n\t\treturn String.format(\"Look at this announcement at HackGSU\\n\\ntitle: %s\\nWhen: %s - %s\\nMessage: %s\",\n\t\t\t\t\t\t\t getTitle(),\n\t\t\t\t\t\t\t HackGSUApplication.toHumanReadableRelative(getTimestampDateTime()),\n\t\t\t\t\t\t\t time,\n\t\t\t\t\t\t\t getBodyText());\n\t}\n\n\t@Exclude\n\tpublic void toggleLikedByMe () {\n\t\tif (isLikedByMe()) { unlike(); }\n\t\telse { like(); }\n\t}\n\n\t@Exclude\n\tpublic boolean isLikedByMe () {\n\t\treturn likedByMe;\n\t}\n\n\t@Exclude\n\tpublic boolean isBookmarkedByMe () {\n\t\treturn bookmarkedByMe;\n\t}\n\n\t@Exclude\n\tpublic void setBookmarkedByMe (boolean bookmarkedByMe) {\n\t\tthis.bookmarkedByMe = bookmarkedByMe;\n\t}\n\n\t@Exclude\n\tpublic void setLikedByMe (boolean likedByMe) {\n\t\tthis.likedByMe = likedByMe;\n\t}\n\n\t@Exclude\n\tprivate void like () {\n\t\tif (!isLikedByMe()) { likes++; }\n\t\tsetLikedByMe(true);\n\t}\n\n\t@Exclude\n\tprivate void unlike () {\n\t\tif (isLikedByMe()) { likes--; }\n\t\tsetLikedByMe(false);\n\t}\n}", "public class ScheduleEvent implements Comparable<ScheduleEvent> {\n\tprivate String description;\n\tprivate long timestamp;\n\tprivate String title;\n\tprivate String url;\n\n\tpublic ScheduleEvent () {\n\t}\n\n\tpublic ScheduleEvent (String title, String description, long timestamp) {\n\t\tthis.title = title;\n\t\tthis.description = description;\n\t\tthis.timestamp = timestamp;\n\t}\n\n\t@Override\n\tpublic int compareTo (ScheduleEvent other) {\n\t\treturn other == null || other.getTimestamp().isBefore(getTimestamp()) ? 1 : -1;\n\t}\n\n\tpublic String getDescription () {\n\t\treturn description;\n\t}\n\n\tpublic LocalDateTime getTimestamp () {\n\t\treturn new LocalDateTime(timestamp);\n\t}\n\n\tpublic String getTitle () {\n\t\treturn title;\n\t}\n\n\tpublic String getUrl () {\n\t\treturn url;\n\t}\n\n\tpublic String getShareText (Context context) {\n\t\t// TODO: 10/6/16 : Maybe make this share message more better..? Also add Play Store link\n\t\tDateTimeFormatter dateTimeFormatter = HackGSUApplication.getTimeFormatter24OrNot(context);\n\t\tString time = getTimestamp().toString(dateTimeFormatter);\n\t\treturn String.format(\"Look at this event at HackGSU\\n\\nTitle: %s\\nWhen: %s - %s\",\n\t\t\t\t\t\t\t getTitle(),\n\t\t\t\t\t\t\t HackGSUApplication.toHumanReadableRelative(getTimestamp()),\n\t\t\t\t\t\t\t time);\n\t}\n}", "public class FirebaseService extends Service {\n\tpublic FirebaseService () {\n\t}\n\n\t@Override\n\tpublic IBinder onBind (Intent intent) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic int onStartCommand (Intent intent, int flags, int startId) {\n\t\tfinal SharedPreferences firebasePrefs = getApplicationContext().getSharedPreferences(\"firebasePrefs\", MODE_PRIVATE);\n\t\tFirebaseAuth firebaseAuth = FirebaseAuth.getInstance();\n\n\t\tFirebaseAuth.AuthStateListener firebaseAuthListener = new FirebaseAuth.AuthStateListener() {\n\t\t\t@Override\n\t\t\tpublic void onAuthStateChanged (@NonNull FirebaseAuth firebaseAuth) {\n\t\t\t\tFirebaseUser user = firebaseAuth.getCurrentUser();\n\t\t\t\tif (user != null) {\n\t\t\t\t\tLog.d(TAG, \"onAuthStateChanged:signed_in:\" + user.getUid());\n\n\t\t\t\t\tHackGSUApplication.refreshSchedule();\n\n\t\t\t\t\tDatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();\n\t\t\t\t\tdbRef.child(AnnouncementController.getAnnouncementsTableString(getApplicationContext()))\n\t\t\t\t\t\t .getRef()\n\t\t\t\t\t\t .addListenerForSingleValueEvent(new ValueEventListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onDataChange (DataSnapshot snapshot) {\n\t\t\t\t\t\t\tHackGSUApplication.parseDataSnapshotForAnnouncements(getApplicationContext(), snapshot);\n\t\t\t\t\t\t\tfor (Announcement announcement : DataStore.getAnnouncements()) {\n\t\t\t\t\t\t\t\tAnnouncementController.shouldNotify(getApplicationContext(), announcement);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tDatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();\n\t\t\t\t\t\t\tdbRef.child(\"opening_ceremonies_room\").getRef().addValueEventListener(new ValueEventListener() {\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void onDataChange (DataSnapshot dataSnapshot) {\n\t\t\t\t\t\t\t\t\tString openingCeremoniesRoomNumber = dataSnapshot.getValue(String.class);\n\t\t\t\t\t\t\t\t\tBusUtils.post(new OpeningCeremoniesRoomNumberUpdateEvent(openingCeremoniesRoomNumber));\n\t\t\t\t\t\t\t\t\tDataStore.setOpeningCeremoniesRoomNumber(openingCeremoniesRoomNumber);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void onCancelled (DatabaseError databaseError) { }\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tDatabaseReference announcementsRef = dbRef.child(AnnouncementController.getAnnouncementsTableString(getApplicationContext()))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .getRef();\n\t\t\t\t\t\t\tannouncementsRef.addValueEventListener(new ValueEventListener() {\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void onDataChange (DataSnapshot dataSnapshot) {\n\t\t\t\t\t\t\t\t\tHackGSUApplication.parseDataSnapshotForAnnouncements(getApplicationContext(), dataSnapshot);\n\n\t\t\t\t\t\t\t\t\tfor (Announcement announcement : DataStore.getAnnouncements()) {\n\t\t\t\t\t\t\t\t\t\tif (AnnouncementController.shouldNotify(getApplicationContext(), announcement)) {\n\t\t\t\t\t\t\t\t\t\t\tNotificationController.sendAnnouncementNotification(getApplicationContext(), announcement);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t@Override\n\t\t\t\t\t\t\t\tpublic void onCancelled (DatabaseError databaseError) { }\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onCancelled (DatabaseError databaseError) { }\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLog.d(TAG, \"onAuthStateChanged:signed_out\");\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfirebaseAuth.addAuthStateListener(firebaseAuthListener);\n\n\t\tif (!firebasePrefs.getBoolean(\"hasAuthed\", false)) {\n\t\t\tfirebaseAuth.signInAnonymously().addOnCompleteListener(new OnCompleteListener<AuthResult>() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onComplete (@NonNull Task<AuthResult> task) {\n\t\t\t\t\tLog.d(TAG, \"signInAnonymously:onComplete:\" + task.isSuccessful());\n\n\t\t\t\t\tif (!task.isSuccessful()) {\n\t\t\t\t\t\tLog.w(TAG, \"signInAnonymously\", task.getException());\n\t\t\t\t\t\tToast.makeText(getApplicationContext(), \"Authentication failed.\", Toast.LENGTH_SHORT).show();\n\t\t\t\t\t}\n\t\t\t\t\telse { firebasePrefs.edit().putBoolean(\"hasAuthed\", true).apply(); }\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\treturn START_STICKY;\n\t}\n}", "public final class BusUtils {\n\tprivate static final EventBus BUS = EventBus.getDefault();\n\tprivate static final String TAG = BusUtils.class.getSimpleName();\n\n\tprivate BusUtils () { }\n\n\tpublic static EventBus get () { return BUS; }\n\n\tpublic static void post (final BaseEvent event) { post(event, false); }\n\n\tpublic static void post (final BaseEvent event, final boolean sticky) {\n\t\tLog.i(TAG, \"post: \" + event);\n\t\tget().removeStickyEvent(event.getClass());\n\t\tHackGSUApplication.runOnUI(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run () {\n\t\t\t\tif (sticky) { get().postSticky(event); }\n\t\t\t\telse { get().post(event); }\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static void register (Object object) {\n\t\ttry { get().register(object); } catch (Exception ignored) { }\n\t}\n}" ]
import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.util.DisplayMetrics; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.*; import com.hackgsu.fall2016.android.activities.FullscreenWebViewActivity; import com.hackgsu.fall2016.android.controllers.AnnouncementController; import com.hackgsu.fall2016.android.events.AnnouncementsUpdatedEvent; import com.hackgsu.fall2016.android.events.ScheduleUpdatedEvent; import com.hackgsu.fall2016.android.model.Announcement; import com.hackgsu.fall2016.android.model.ScheduleEvent; import com.hackgsu.fall2016.android.services.FirebaseService; import com.hackgsu.fall2016.android.utils.BusUtils; import net.danlew.android.joda.JodaTimeAndroid; import org.joda.time.LocalDateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import java.util.ArrayList; import java.util.Collections;
package com.hackgsu.fall2016.android; /** * Created by Joshua King on 9/27/16. */ public class HackGSUApplication extends Application { public static final String IS_IN_DEV_MODE = "is_in_dev_mode"; public static final String NOTIFICATIONS_ENABLED = "notifications_enabled"; private FirebaseAuth firebaseAuth; private FirebaseAuth.AuthStateListener firebaseAuthListener; public static boolean areNotificationsEnabled (Context context) { return getPrefs(context).getBoolean(NOTIFICATIONS_ENABLED, true); } @NonNull private static Announcement convertDataSnapshotToAnnouncement (DataSnapshot child) { Announcement announcement = child.getValue(Announcement.class); announcement.setFirebaseKey(child.getKey()); return announcement; } public static float convertDpToPx (float dp, Context context) { return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT); } public static void delayRunnableOnUI (final long millsToDelay, final Runnable runnableToRun) { new Thread(new Runnable() { public void run () { try { Thread.sleep(millsToDelay); } catch (InterruptedException ignored) {} (new Handler(Looper.getMainLooper())).post(runnableToRun); } }).start(); } public static LocalDateTime getDateTimeOfHackathon (int dayIndex, int hour, int minute) { return getDateTimeOfHackathon().plusDays(dayIndex).withHourOfDay(hour).withMinuteOfHour(minute); } @NonNull public static LocalDateTime getDateTimeOfHackathon () { return new LocalDateTime().withDate(2017, 3, 31).withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(30).withHourOfDay(19); } public static SharedPreferences getPrefs (Context context) { return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); } public static DateTimeFormatter getTimeFormatter24OrNot (Context context) { return getTimeFormatter24OrNot(context, new DateTimeFormatterBuilder()); } public static DateTimeFormatter getTimeFormatter24OrNot (Context context, DateTimeFormatterBuilder dateTimeFormatterBuilder) { if (DateFormat.is24HourFormat(context)) { dateTimeFormatterBuilder.appendHourOfDay(2).appendLiteral(":").appendMinuteOfHour(2); } else { dateTimeFormatterBuilder.appendHourOfHalfday(1).appendLiteral(":").appendMinuteOfHour(2).appendLiteral(" ").appendPattern("a"); } return dateTimeFormatterBuilder.toFormatter(); } @NonNull public static Runnable getUrlRunnable (final Context context, final String url, final boolean openInApp) { return new Runnable() { @Override public void run () { openWebUrl(context, url, openInApp); } }; } public static void hideKeyboard (View parentViewToGetFocus, Context context) { View view = parentViewToGetFocus.findFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } public static boolean isInDevMode (Context context) { return getPrefs(context).getBoolean(IS_IN_DEV_MODE, false); } public static boolean isNullOrEmpty (String s) { return s == null || s.equals(""); } public static boolean isOneFalse (boolean... b) { for (boolean bool : b) { if (!bool) { return true; } } return false; } public static void openWebUrl (Context context, String url, boolean withinApp) { if (withinApp) { Intent codeOfConductViewIntent = new Intent(context, FullscreenWebViewActivity.class); codeOfConductViewIntent.putExtra(FullscreenWebViewActivity.EXTRA_URL, url); codeOfConductViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(codeOfConductViewIntent); } else { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(intent); } } public static void parseDataSnapshotForAnnouncements (Context context, DataSnapshot snapshot) { ArrayList<Announcement> announcements = new ArrayList<>(); for (DataSnapshot child : snapshot.getChildren()) { Announcement announcement = convertDataSnapshotToAnnouncement(child); announcements.add(announcement); } Collections.sort(announcements); DataStore.setAnnouncements(context, announcements); BusUtils.post(new AnnouncementsUpdatedEvent(announcements)); } public static void refreshAnnouncements (final Context context) { DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); dbRef.child(AnnouncementController.getAnnouncementsTableString(context)).getRef().addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange (DataSnapshot snapshot) { parseDataSnapshotForAnnouncements(context, snapshot); } @Override public void onCancelled (DatabaseError databaseError) { } }); } public static void refreshSchedule () { DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
final ArrayList<ScheduleEvent> scheduleEvents = new ArrayList<>();
5
timpalpant/java-genomics-toolkit
src/edu/unc/genomics/wigmath/ValueDistribution.java
[ "public abstract class CommandLineTool {\n\n /**\n * The default bite-size to use for applications that process files in chunks\n * TODO Read from a configuration file\n */\n public static final int DEFAULT_CHUNK_SIZE = 10_000_000;\n\n /**\n * Do the main computation of this tool\n * \n * @throws IOException\n */\n public abstract void run() throws IOException;\n\n /**\n * Parse command-line arguments and run the tool Exit on parameter exceptions\n * \n * @param args\n */\n public void instanceMain(String[] args) throws CommandLineToolException {\n // Initialize the command-line options parser\n JCommander jc = new JCommander(this);\n\n // Add factories for parsing Paths, Assemblies, IntervalFiles, and WigFiles\n jc.addConverterFactory(new PathFactory());\n jc.addConverterFactory(new AssemblyFactory());\n\n // Set the program name to be the class name\n String[] nameParts = getClass().getName().split(\"\\\\.\");\n String shortName = StringUtils.join(Arrays.copyOfRange(nameParts, nameParts.length - 2, nameParts.length), '.');\n jc.setProgramName(shortName);\n\n try {\n jc.parse(args);\n } catch (ParameterException e) {\n System.err.println(e.getMessage());\n jc.usage();\n System.exit(-1);\n }\n\n ValidationStringency stringency = SAMFileReader.getDefaultValidationStringency();\n try {\n SAMFileReader.setDefaultValidationStringency(SAMFileReader.ValidationStringency.LENIENT);\n run();\n } catch (IOException e) {\n throw new CommandLineToolException(\"IO error while running\", e);\n } finally {\n SAMFileReader.setDefaultValidationStringency(stringency);\n }\n }\n}", "public class CommandLineToolException extends RuntimeException {\n\n /**\n\t * \n\t */\n private static final long serialVersionUID = 4740440799806133636L;\n\n /**\n\t * \n\t */\n public CommandLineToolException() {\n // TODO Auto-generated constructor stub\n }\n\n /**\n * @param message\n */\n public CommandLineToolException(String message) {\n super(message);\n // TODO Auto-generated constructor stub\n }\n\n /**\n * @param cause\n */\n public CommandLineToolException(Throwable cause) {\n super(cause);\n // TODO Auto-generated constructor stub\n }\n\n /**\n * @param message\n * @param cause\n */\n public CommandLineToolException(String message, Throwable cause) {\n super(message, cause);\n // TODO Auto-generated constructor stub\n }\n\n /**\n * @param message\n * @param cause\n * @param enableSuppression\n * @param writableStackTrace\n */\n public CommandLineToolException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n // TODO Auto-generated constructor stub\n }\n\n}", "public class ReadablePathValidator implements IParameterValidator {\n\n /*\n * (non-Javadoc)\n * \n * @see com.beust.jcommander.IParameterValidator#validate(java.lang.String,\n * java.lang.String)\n */\n @Override\n public void validate(String name, String value) throws ParameterException {\n PathConverter converter = new PathConverter();\n Path p = converter.convert(value);\n if (!Files.isReadable(p)) {\n throw new ParameterException(\"Parameter \" + name + \" should be a readable file\");\n }\n }\n\n}", "public class Autocorrelation extends CommandLineTool {\n\n private static final Logger log = Logger.getLogger(Autocorrelation.class);\n\n @Parameter(names = { \"-i\", \"--input\" }, description = \"Input file\", required = true, validateWith = ReadablePathValidator.class)\n public Path inputFile;\n @Parameter(names = { \"-l\", \"--loci\" }, description = \"Genomic loci (Bed format)\", required = true, validateWith = ReadablePathValidator.class)\n public Path lociFile;\n @Parameter(names = { \"-o\", \"--output\" }, description = \"Output file\", required = true)\n public Path outputFile;\n @Parameter(names = { \"-m\", \"--max\" }, description = \"Autocorrelation limit (bp)\")\n public int limit = 200;\n\n @Override\n public void run() throws IOException {\n try (WigFileReader wig = WigFileReader.autodetect(inputFile);\n IntervalFileReader<? extends Interval> loci = IntervalFileReader.autodetect(lociFile);\n BufferedWriter writer = Files.newBufferedWriter(outputFile, Charset.defaultCharset())) {\n log.debug(\"Computing autocorrelation for each window\");\n int skipped = 0;\n for (Interval interval : loci) {\n float[] data;\n try {\n data = wig.query(interval).getValues();\n } catch (IOException | WigFileException e) {\n log.debug(\"Skipping interval: \" + interval.toString());\n skipped++;\n continue;\n }\n\n // Compute the autocorrelation\n float[] auto = FFTUtils.autocovariance(data, limit);\n\n // Write to output\n writer.write(interval.toBed());\n for (int i = 0; i < auto.length; i++) {\n writer.write(\"\\t\" + auto[i]);\n }\n writer.newLine();\n }\n\n log.info(\"Skipped \" + skipped + \" intervals\");\n }\n }\n\n public static void main(String[] args) {\n new Autocorrelation().instanceMain(args);\n }\n}", "public class FloatHistogram {\n\n int[] bins = null;\n int nBins;\n double xLow, xHigh;\n double delBin;\n\n int overFlows = 0, underFlows = 0;\n\n public FloatHistogram(int nBins, double xLow, double xHigh) {\n\n this.nBins = nBins;\n this.xLow = xLow;\n this.xHigh = xHigh;\n\n bins = new int[nBins];\n delBin = (xHigh - xLow) / (float) nBins;\n\n reset();\n }\n\n public void addValue(double data) {\n if (data < xLow) {\n underFlows++;\n } else if (data >= xHigh) {\n overFlows++;\n } else {\n int bin = (int) ((data - xLow) / delBin);\n if (bin >= 0 && bin < nBins) {\n bins[bin]++;\n }\n }\n }\n\n public int[] getHistogram() {\n return bins;\n }\n\n public double getBinSize() {\n return delBin;\n }\n\n public void reset() {\n Arrays.fill(bins, 0);\n underFlows = 0;\n overFlows = 0;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"<\" + xLow + \"\\t\" + underFlows + \"\\n\");\n for (int i = 0; i < bins.length; i++) {\n sb.append(xLow + i * delBin + \"\\t\" + bins[i] + \"\\n\");\n }\n sb.append(\">\" + xHigh + \"\\t\" + overFlows);\n return sb.toString();\n }\n\n}" ]
import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import org.apache.log4j.Logger; import com.beust.jcommander.Parameter; import edu.unc.genomics.CommandLineTool; import edu.unc.genomics.CommandLineToolException; import edu.unc.genomics.Interval; import edu.unc.genomics.ReadablePathValidator; import edu.unc.genomics.io.WigFileReader; import edu.unc.genomics.io.WigFileException; import edu.unc.genomics.ngs.Autocorrelation; import edu.unc.utils.FloatHistogram;
package edu.unc.genomics.wigmath; /** * Make a histogram of the values in a Wig file * * @author timpalpant * */ public class ValueDistribution extends CommandLineTool { private static final Logger log = Logger.getLogger(Autocorrelation.class); @Parameter(names = { "-i", "--input" }, description = "Input file", required = true, validateWith = ReadablePathValidator.class) public Path inputFile; @Parameter(names = { "-l", "--min" }, description = "Minimum bin value") public Float min; @Parameter(names = { "-h", "--max" }, description = "Maximum bin value") public Float max; @Parameter(names = { "-n", "--bins" }, description = "Number of bins") public int numBins = 40; @Parameter(names = { "-o", "--output" }, description = "Output file") public Path outputFile; FloatHistogram hist; double mean, stdev, skewness, kurtosis; long N; public void run() throws IOException { try (WigFileReader reader = WigFileReader.autodetect(inputFile)) { log.debug("Generating histogram of Wig values"); if (min == null) { min = (float) reader.min(); } if (max == null) { max = (float) reader.max(); } hist = new FloatHistogram(numBins, min, max); N = reader.numBases(); mean = reader.mean(); stdev = reader.stdev(); // Also compute the skewness and kurtosis while going through the values double sumOfCubeOfDeviances = 0; double sumOfFourthOfDeviances = 0; for (String chr : reader.chromosomes()) { int start = reader.getChrStart(chr); int stop = reader.getChrStop(chr); log.debug("Processing chromosome " + chr + " region " + start + "-" + stop); // Process the chromosome in chunks int bp = start; while (bp < stop) { int chunkStart = bp; int chunkStop = Math.min(bp + DEFAULT_CHUNK_SIZE - 1, stop); Interval chunk = new Interval(chr, chunkStart, chunkStop); log.debug("Processing chunk " + chunk); try { float[] data = reader.query(chunk).getValues(); for (int i = 0; i < data.length; i++) { if (!Float.isNaN(data[i]) && !Float.isInfinite(data[i])) { hist.addValue(data[i]); double deviance = data[i] - mean; double cubeOfDeviance = Math.pow(deviance, 3); sumOfCubeOfDeviances += cubeOfDeviance; sumOfFourthOfDeviances += deviance * cubeOfDeviance; } } } catch (WigFileException e) { log.error("Error getting data from Wig file for chunk " + chunk);
throw new CommandLineToolException("Error getting data from Wig file for chunk " + chunk);
1
wakaleo/maven-schemaspy-plugin
src/main/java/net/sourceforge/schemaspy/view/DotFormatter.java
[ "public class Config\r\n{\r\n private static Config instance;\r\n private final List<String> options;\r\n private Map<String, String> dbSpecificOptions;\r\n private Map<String, String> originalDbSpecificOptions;\r\n private boolean helpRequired;\r\n private boolean dbHelpRequired;\r\n private File outputDir;\r\n private File graphvizDir;\r\n private String dbType;\r\n private String schema;\r\n private List<String> schemas;\r\n private String user;\r\n private Boolean singleSignOn;\r\n private Boolean noSchema;\r\n private String password;\r\n private Boolean promptForPassword;\r\n private String db;\r\n private String host;\r\n private Integer port;\r\n private String server;\r\n private String meta;\r\n private Pattern tableInclusions;\r\n private Pattern tableExclusions;\r\n private Pattern columnExclusions;\r\n private Pattern indirectColumnExclusions;\r\n private String userConnectionPropertiesFile;\r\n private Properties userConnectionProperties;\r\n private Integer maxDbThreads;\r\n private Integer maxDetailedTables;\r\n private String driverPath;\r\n private String css;\r\n private String charset;\r\n private String font;\r\n private Integer fontSize;\r\n private String description;\r\n private String dbPropertiesLoadedFrom;\r\n private Level logLevel;\r\n private SqlFormatter sqlFormatter;\r\n private String sqlFormatterClass;\r\n private Boolean generateHtml;\r\n private Boolean includeImpliedConstraints;\r\n private Boolean logoEnabled;\r\n private Boolean rankDirBugEnabled;\r\n private Boolean encodeCommentsEnabled;\r\n private Boolean numRowsEnabled;\r\n private Boolean viewsEnabled;\r\n private Boolean meterEnabled;\r\n private Boolean railsEnabled;\r\n private Boolean evaluteAll;\r\n private Boolean highQuality;\r\n private Boolean lowQuality;\r\n private Boolean adsEnabled;\r\n private String schemaSpec; // used in conjunction with evaluateAll\r\n private boolean populating = false;\r\n public static final String DOT_CHARSET = \"UTF-8\";\r\n private static final String ESCAPED_EQUALS = \"\\\\=\";\r\n\r\n /**\r\n * Default constructor. Intended for when you want to inject properties\r\n * independently (i.e. not from a command line interface).\r\n */\r\n public Config()\r\n {\r\n if (instance == null)\r\n setInstance(this);\r\n options = new ArrayList<String>();\r\n }\r\n\r\n /**\r\n * Construct a configuration from an array of options (e.g. from a command\r\n * line interface).\r\n *\r\n * @param options\r\n */\r\n public Config(String[] argv)\r\n {\r\n setInstance(this);\r\n options = fixupArgs(Arrays.asList(argv));\r\n\r\n helpRequired = options.remove(\"-?\") ||\r\n options.remove(\"/?\") ||\r\n options.remove(\"?\") ||\r\n options.remove(\"-h\") ||\r\n options.remove(\"-help\") ||\r\n options.remove(\"--help\");\r\n dbHelpRequired = options.remove(\"-dbHelp\") || options.remove(\"-dbhelp\");\r\n }\r\n\r\n public static Config getInstance() {\r\n if (instance == null)\r\n instance = new Config();\r\n\r\n return instance;\r\n }\r\n\r\n /**\r\n * Sets the global instance.\r\n *\r\n * Useful for things like selecting a specific configuration in a UI.\r\n *\r\n * @param config\r\n */\r\n public static void setInstance(Config config) {\r\n instance = config;\r\n }\r\n\r\n public void setHtmlGenerationEnabled(boolean generateHtml) {\r\n this.generateHtml = generateHtml;\r\n }\r\n\r\n public boolean isHtmlGenerationEnabled() {\r\n if (generateHtml == null)\r\n generateHtml = !options.remove(\"-nohtml\");\r\n\r\n return generateHtml;\r\n }\r\n\r\n public void setImpliedConstraintsEnabled(boolean includeImpliedConstraints) {\r\n this.includeImpliedConstraints = includeImpliedConstraints;\r\n }\r\n\r\n public boolean isImpliedConstraintsEnabled() {\r\n if (includeImpliedConstraints == null)\r\n includeImpliedConstraints = !options.remove(\"-noimplied\");\r\n\r\n return includeImpliedConstraints;\r\n }\r\n\r\n public void setOutputDir(String outputDirName) {\r\n if (outputDirName.endsWith(\"\\\"\"))\r\n outputDirName = outputDirName.substring(0, outputDirName.length() - 1);\r\n\r\n setOutputDir(new File(outputDirName));\r\n }\r\n\r\n public void setOutputDir(File outputDir) {\r\n this.outputDir = outputDir;\r\n }\r\n\r\n public File getOutputDir() {\r\n if (outputDir == null) {\r\n setOutputDir(pullRequiredParam(\"-o\"));\r\n }\r\n\r\n return outputDir;\r\n }\r\n\r\n /**\r\n * Set the path to Graphviz so we can find dot to generate ER diagrams\r\n *\r\n * @param graphvizDir\r\n */\r\n public void setGraphvizDir(String graphvizDir) {\r\n if (graphvizDir.endsWith(\"\\\"\"))\r\n graphvizDir = graphvizDir.substring(0, graphvizDir.length() - 1);\r\n\r\n setGraphvizDir(new File(graphvizDir));\r\n }\r\n\r\n /**\r\n * Set the path to Graphviz so we can find dot to generate ER diagrams\r\n *\r\n * @param graphvizDir\r\n */\r\n public void setGraphvizDir(File graphvizDir) {\r\n this.graphvizDir = graphvizDir;\r\n }\r\n\r\n /**\r\n * Return the path to Graphviz (used to find the dot executable to run to\r\n * generate ER diagrams).<p/>\r\n *\r\n * Returns {@link #getDefaultGraphvizPath()} if a specific Graphviz path\r\n * was not specified.\r\n *\r\n * @return\r\n */\r\n public File getGraphvizDir() {\r\n if (graphvizDir == null) {\r\n String gv = pullParam(\"-gv\");\r\n if (gv != null) {\r\n setGraphvizDir(gv);\r\n } else {\r\n // expect to find Graphviz's bin directory on the PATH\r\n }\r\n }\r\n\r\n return graphvizDir;\r\n }\r\n\r\n /**\r\n * Meta files are XML-based files that provide additional metadata\r\n * about the schema being evaluated.<p>\r\n * <code>meta</code> is either the name of an individual XML file or\r\n * the directory that contains meta files.<p>\r\n * If a directory is specified then it is expected to contain files\r\n * matching the pattern <code>[schema].meta.xml</code>.\r\n * For databases that don't have schema substitute database for schema.\r\n * @param meta\r\n */\r\n public void setMeta(String meta) {\r\n this.meta = meta;\r\n }\r\n\r\n public String getMeta() {\r\n if (meta == null)\r\n meta = pullParam(\"-meta\");\r\n return meta;\r\n }\r\n\r\n public void setDbType(String dbType) {\r\n this.dbType = dbType;\r\n }\r\n\r\n public String getDbType() {\r\n if (dbType == null) {\r\n dbType = pullParam(\"-t\");\r\n if (dbType == null)\r\n dbType = \"ora\";\r\n }\r\n\r\n return dbType;\r\n }\r\n\r\n public void setDb(String db) {\r\n this.db = db;\r\n }\r\n\r\n public String getDb() {\r\n if (db == null)\r\n db = pullParam(\"-db\");\r\n return db;\r\n }\r\n\r\n public void setSchema(String schema) {\r\n this.schema = schema;\r\n }\r\n\r\n public String getSchema() {\r\n if (schema == null)\r\n schema = pullParam(\"-s\");\r\n return schema;\r\n }\r\n\r\n /**\r\n * Some databases types (e.g. older versions of Informix) don't really\r\n * have the concept of a schema but still return true from\r\n * {@link DatabaseMetaData#supportsSchemasInTableDefinitions()}.\r\n * This option lets you ignore that and treat all the tables\r\n * as if they were in one flat namespace.\r\n */\r\n public boolean isSchemaDisabled() {\r\n if (noSchema == null)\r\n noSchema = options.remove(\"-noschema\");\r\n\r\n return noSchema;\r\n }\r\n\r\n public void setHost(String host) {\r\n this.host = host;\r\n }\r\n\r\n public String getHost() {\r\n if (host == null)\r\n host = pullParam(\"-host\");\r\n return host;\r\n }\r\n\r\n public void setPort(Integer port) {\r\n this.port = port;\r\n }\r\n\r\n public Integer getPort() {\r\n if (port == null)\r\n try {\r\n port = Integer.valueOf(pullParam(\"-port\"));\r\n } catch (Exception notSpecified) {}\r\n return port;\r\n }\r\n\r\n public void setServer(String server) {\r\n this.server = server;\r\n }\r\n\r\n public String getServer() {\r\n if (server == null) {\r\n server = pullParam(\"-server\");\r\n }\r\n\r\n return server;\r\n }\r\n\r\n public void setUser(String user) {\r\n this.user = user;\r\n }\r\n\r\n /**\r\n * User used to connect to the database.\r\n * Required unless single sign-on is enabled\r\n * (see {@link #setSingleSignOn(boolean)}).\r\n * @return\r\n */\r\n public String getUser() {\r\n if (user == null) {\r\n if (!isSingleSignOn())\r\n user = pullRequiredParam(\"-u\");\r\n else\r\n user = pullParam(\"-u\");\r\n }\r\n return user;\r\n }\r\n\r\n /**\r\n * By default a \"user\" (as specified with -u) is required.\r\n * This option allows disabling of that requirement for\r\n * single sign-on environments.\r\n *\r\n * @param enabled defaults to <code>false</code>\r\n */\r\n public void setSingleSignOn(boolean enabled) {\r\n singleSignOn = enabled;\r\n }\r\n\r\n /**\r\n * @see #setSingleSignOn(boolean)\r\n */\r\n public boolean isSingleSignOn() {\r\n if (singleSignOn == null)\r\n singleSignOn = options.remove(\"-sso\");\r\n\r\n return singleSignOn;\r\n }\r\n\r\n /**\r\n * Set the password used to connect to the database.\r\n * @param password\r\n */\r\n public void setPassword(String password) {\r\n this.password = password;\r\n }\r\n\r\n /**\r\n * @see #setPassword(String)\r\n * @return\r\n */\r\n public String getPassword() {\r\n if (password == null)\r\n password = pullParam(\"-p\");\r\n return password;\r\n }\r\n\r\n /**\r\n * Set to <code>true</code> to prompt for the password\r\n * @param promptForPassword\r\n */\r\n public void setPromptForPasswordEnabled(boolean promptForPassword) {\r\n this.promptForPassword = promptForPassword;\r\n }\r\n\r\n /**\r\n * @see #setPromptForPasswordEnabled(boolean)\r\n * @return\r\n */\r\n public boolean isPromptForPasswordEnabled() {\r\n if (promptForPassword == null) {\r\n promptForPassword = options.remove(\"-pfp\");\r\n }\r\n\r\n return promptForPassword;\r\n }\r\n\r\n public void setMaxDetailedTabled(int maxDetailedTables) {\r\n this.maxDetailedTables = new Integer(maxDetailedTables);\r\n }\r\n\r\n public int getMaxDetailedTables() {\r\n if (maxDetailedTables == null) {\r\n int max = 300; // default\r\n try {\r\n max = Integer.parseInt(pullParam(\"-maxdet\"));\r\n } catch (Exception notSpecified) {}\r\n\r\n maxDetailedTables = new Integer(max);\r\n }\r\n\r\n return maxDetailedTables.intValue();\r\n }\r\n\r\n public String getConnectionPropertiesFile() {\r\n return userConnectionPropertiesFile;\r\n }\r\n\r\n /**\r\n * Properties from this file (in key=value pair format) are passed to the\r\n * database connection.<br>\r\n * user (from -u) and password (from -p) will be passed in the\r\n * connection properties if specified.\r\n * @param propertiesFilename\r\n * @throws FileNotFoundException\r\n * @throws IOException\r\n */\r\n public void setConnectionPropertiesFile(String propertiesFilename) throws FileNotFoundException, IOException {\r\n if (userConnectionProperties == null)\r\n userConnectionProperties = new Properties();\r\n userConnectionProperties.load(new FileInputStream(propertiesFilename));\r\n userConnectionPropertiesFile = propertiesFilename;\r\n }\r\n\r\n /**\r\n * Returns a {@link Properties} populated either from the properties file specified\r\n * by {@link #setConnectionPropertiesFile(String)}, the properties specified by\r\n * {@link #setConnectionProperties(String)} or not populated.\r\n * @return\r\n * @throws FileNotFoundException\r\n * @throws IOException\r\n */\r\n public Properties getConnectionProperties() throws FileNotFoundException, IOException {\r\n if (userConnectionProperties == null) {\r\n String props = pullParam(\"-connprops\");\r\n if (props != null) {\r\n if (props.indexOf(ESCAPED_EQUALS) != -1) {\r\n setConnectionProperties(props);\r\n } else {\r\n setConnectionPropertiesFile(props);\r\n }\r\n } else {\r\n userConnectionProperties = new Properties();\r\n }\r\n }\r\n\r\n return userConnectionProperties;\r\n }\r\n\r\n /**\r\n * Specifies connection properties to use in the format:\r\n * <code>key1\\=value1;key2\\=value2</code><br>\r\n * user (from -u) and password (from -p) will be passed in the\r\n * connection properties if specified.<p>\r\n * This is an alternative form of passing connection properties than by file\r\n * (see {@link #setConnectionPropertiesFile(String)})\r\n *\r\n * @param properties\r\n */\r\n public void setConnectionProperties(String properties) {\r\n userConnectionProperties = new Properties();\r\n\r\n StringTokenizer tokenizer = new StringTokenizer(properties, \";\");\r\n while (tokenizer.hasMoreElements()) {\r\n String pair = tokenizer.nextToken();\r\n int index = pair.indexOf(ESCAPED_EQUALS);\r\n if (index != -1) {\r\n String key = pair.substring(0, index);\r\n String value = pair.substring(index + ESCAPED_EQUALS.length());\r\n userConnectionProperties.put(key, value);\r\n }\r\n }\r\n }\r\n\r\n public void setDriverPath(String driverPath) {\r\n this.driverPath = driverPath;\r\n }\r\n\r\n public String getDriverPath() {\r\n if (driverPath == null)\r\n driverPath = pullParam(\"-dp\");\r\n\r\n // was previously -cp:\r\n if (driverPath == null)\r\n driverPath = pullParam(\"-cp\");\r\n\r\n return driverPath;\r\n }\r\n\r\n /**\r\n * The filename of the cascading style sheet to use.\r\n * Note that this file is parsed and used to determine characteristics\r\n * of the generated diagrams, so it must contain specific settings that\r\n * are documented within schemaSpy.css.<p>\r\n *\r\n * Defaults to <code>\"schemaSpy.css\"</code>.\r\n *\r\n * @param css\r\n */\r\n public void setCss(String css) {\r\n this.css = css;\r\n }\r\n\r\n public String getCss() {\r\n if (css == null) {\r\n css = pullParam(\"-css\");\r\n if (css == null)\r\n css = \"schemaSpy.css\";\r\n }\r\n return css;\r\n }\r\n\r\n /**\r\n * The font to use within diagrams. Modify the .css to specify HTML fonts.\r\n *\r\n * @param font\r\n */\r\n public void setFont(String font) {\r\n this.font = font;\r\n }\r\n\r\n /**\r\n * @see #setFont(String)\r\n */\r\n public String getFont() {\r\n if (font == null) {\r\n font = pullParam(\"-font\");\r\n if (font == null)\r\n font = \"Helvetica\";\r\n }\r\n return font;\r\n }\r\n\r\n /**\r\n * The font size to use within diagrams. This is the size of the font used for\r\n * 'large' (e.g. not 'compact') diagrams.<p>\r\n *\r\n * Modify the .css to specify HTML font sizes.<p>\r\n *\r\n * Defaults to 11.\r\n *\r\n * @param fontSize\r\n */\r\n public void setFontSize(int fontSize) {\r\n this.fontSize = new Integer(fontSize);\r\n }\r\n\r\n /**\r\n * @see #setFontSize(int)\r\n * @return\r\n */\r\n public int getFontSize() {\r\n if (fontSize == null) {\r\n int size = 11; // default\r\n try {\r\n size = Integer.parseInt(pullParam(\"-fontsize\"));\r\n } catch (Exception notSpecified) {}\r\n\r\n fontSize = new Integer(size);\r\n }\r\n\r\n return fontSize.intValue();\r\n }\r\n\r\n /**\r\n * The character set to use within HTML pages (defaults to <code>\"ISO-8859-1\"</code>).\r\n *\r\n * @param charset\r\n */\r\n public void setCharset(String charset) {\r\n this.charset = charset;\r\n }\r\n\r\n /**\r\n * @see #setCharset(String)\r\n */\r\n public String getCharset() {\r\n if (charset == null) {\r\n charset = pullParam(\"-charset\");\r\n if (charset == null)\r\n charset = \"ISO-8859-1\";\r\n }\r\n return charset;\r\n }\r\n\r\n /**\r\n * Description of schema that gets display on main pages.\r\n *\r\n * @param description\r\n */\r\n public void setDescription(String description) {\r\n this.description = description;\r\n }\r\n\r\n /**\r\n * @see #setDescription(String)\r\n */\r\n public String getDescription() {\r\n if (description == null)\r\n description = pullParam(\"-desc\");\r\n return description;\r\n }\r\n\r\n /**\r\n * Maximum number of threads to use when querying database metadata information.\r\n *\r\n * @param maxDbThreads\r\n */\r\n public void setMaxDbThreads(int maxDbThreads) {\r\n this.maxDbThreads = new Integer(maxDbThreads);\r\n }\r\n\r\n /**\r\n * @see #setMaxDbThreads(int)\r\n * @throws InvalidConfigurationException if unable to load properties\r\n */\r\n public int getMaxDbThreads() throws InvalidConfigurationException {\r\n if (maxDbThreads == null) {\r\n Properties properties;\r\n try {\r\n properties = getDbProperties(getDbType());\r\n } catch (IOException exc) {\r\n throw new InvalidConfigurationException(\"Failed to load properties for \" + getDbType() + \": \" + exc)\r\n .setParamName(\"-type\");\r\n }\r\n\r\n int max = Integer.MAX_VALUE;\r\n String threads = properties.getProperty(\"dbThreads\");\r\n if (threads == null)\r\n threads = properties.getProperty(\"dbthreads\");\r\n if (threads != null)\r\n max = Integer.parseInt(threads);\r\n threads = pullParam(\"-dbThreads\");\r\n if (threads == null)\r\n threads = pullParam(\"-dbthreads\");\r\n if (threads != null)\r\n max = Integer.parseInt(threads);\r\n if (max < 0)\r\n max = Integer.MAX_VALUE;\r\n else if (max == 0)\r\n max = 1;\r\n\r\n maxDbThreads = new Integer(max);\r\n }\r\n\r\n return maxDbThreads.intValue();\r\n }\r\n\r\n public boolean isLogoEnabled() {\r\n if (logoEnabled == null)\r\n logoEnabled = !options.remove(\"-nologo\");\r\n\r\n return logoEnabled;\r\n }\r\n\r\n /**\r\n * Don't use this unless absolutely necessary as it screws up the layout\r\n *\r\n * @param enabled\r\n */\r\n public void setRankDirBugEnabled(boolean enabled) {\r\n rankDirBugEnabled = enabled;\r\n }\r\n\r\n /**\r\n * @see #setRankDirBugEnabled(boolean)\r\n */\r\n public boolean isRankDirBugEnabled() {\r\n if (rankDirBugEnabled == null)\r\n rankDirBugEnabled = options.remove(\"-rankdirbug\");\r\n\r\n return rankDirBugEnabled;\r\n }\r\n\r\n /**\r\n * Look for Ruby on Rails-based naming conventions in\r\n * relationships between logical foreign keys and primary keys.<p>\r\n *\r\n * Basically all tables have a primary key named <code>ID</code>.\r\n * All tables are named plural names.\r\n * The columns that logically reference that <code>ID</code> are the singular\r\n * form of the table name suffixed with <code>_ID</code>.<p>\r\n *\r\n * @param enabled\r\n */\r\n public void setRailsEnabled(boolean enabled) {\r\n railsEnabled = enabled;\r\n }\r\n\r\n /**\r\n * @see #setRailsEnabled(boolean)\r\n *\r\n * @return\r\n */\r\n public boolean isRailsEnabled() {\r\n if (railsEnabled == null)\r\n railsEnabled = options.remove(\"-rails\");\r\n\r\n return railsEnabled;\r\n }\r\n\r\n /**\r\n * Allow Html In Comments - encode them unless otherwise specified\r\n */\r\n public void setEncodeCommentsEnabled(boolean enabled) {\r\n encodeCommentsEnabled = enabled;\r\n }\r\n\r\n /**\r\n * @see #setEncodeCommentsEnabled(boolean)\r\n */\r\n public boolean isEncodeCommentsEnabled() {\r\n if (encodeCommentsEnabled == null)\r\n encodeCommentsEnabled = !options.remove(\"-ahic\");\r\n\r\n return encodeCommentsEnabled;\r\n }\r\n\r\n /**\r\n * If enabled we'll attempt to query/render the number of rows that\r\n * each table contains.<p/>\r\n *\r\n * Defaults to <code>true</code> (enabled).\r\n *\r\n * @param enabled\r\n */\r\n public void setNumRowsEnabled(boolean enabled) {\r\n numRowsEnabled = enabled;\r\n }\r\n\r\n /**\r\n * @see #setNumRowsEnabled(boolean)\r\n * @return\r\n */\r\n public boolean isNumRowsEnabled() {\r\n if (numRowsEnabled == null)\r\n numRowsEnabled = !options.remove(\"-norows\");\r\n\r\n return numRowsEnabled;\r\n }\r\n\r\n /**\r\n * If enabled we'll include views in the analysis.<p/>\r\n *\r\n * Defaults to <code>true</code> (enabled).\r\n *\r\n * @param enabled\r\n */\r\n public void setViewsEnabled(boolean enabled) {\r\n viewsEnabled = enabled;\r\n }\r\n\r\n /**\r\n * @see #setViewsEnabled(boolean)\r\n * @return\r\n */\r\n public boolean isViewsEnabled() {\r\n if (viewsEnabled == null)\r\n viewsEnabled = !options.remove(\"-noviews\");\r\n\r\n return viewsEnabled;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if metering should be embedded in\r\n * the generated pages.<p/>\r\n * Defaults to <code>false</code> (disabled).\r\n * @return\r\n */\r\n public boolean isMeterEnabled() {\r\n if (meterEnabled == null)\r\n meterEnabled = options.remove(\"-meter\");\r\n\r\n return meterEnabled;\r\n }\r\n\r\n /**\r\n * Set the columns to exclude from all relationship diagrams.\r\n *\r\n * @param columnExclusions regular expression of the columns to\r\n * exclude\r\n */\r\n public void setColumnExclusions(String columnExclusions) {\r\n this.columnExclusions = Pattern.compile(columnExclusions);\r\n }\r\n\r\n /**\r\n * See {@link #setColumnExclusions(String)}\r\n * @return\r\n */\r\n public Pattern getColumnExclusions() {\r\n if (columnExclusions == null) {\r\n String strExclusions = pullParam(\"-X\");\r\n if (strExclusions == null)\r\n strExclusions = \"[^.]\"; // match nothing\r\n\r\n columnExclusions = Pattern.compile(strExclusions);\r\n }\r\n\r\n return columnExclusions;\r\n }\r\n\r\n /**\r\n * Set the columns to exclude from relationship diagrams where the specified\r\n * columns aren't directly referenced by the focal table.\r\n *\r\n * @param columnExclusions regular expression of the columns to\r\n * exclude\r\n */\r\n public void setIndirectColumnExclusions(String fullColumnExclusions) {\r\n indirectColumnExclusions = Pattern.compile(fullColumnExclusions);\r\n }\r\n\r\n /**\r\n * @see #setIndirectColumnExclusions(String)\r\n *\r\n * @return\r\n */\r\n public Pattern getIndirectColumnExclusions() {\r\n if (indirectColumnExclusions == null) {\r\n String strExclusions = pullParam(\"-x\");\r\n if (strExclusions == null)\r\n strExclusions = \"[^.]\"; // match nothing\r\n\r\n indirectColumnExclusions = Pattern.compile(strExclusions);\r\n }\r\n\r\n return indirectColumnExclusions;\r\n }\r\n\r\n /**\r\n * Set the tables to include as a regular expression\r\n * @param tableInclusions\r\n */\r\n public void setTableInclusions(String tableInclusions) {\r\n this.tableInclusions = Pattern.compile(tableInclusions);\r\n }\r\n\r\n /**\r\n * Get the regex {@link Pattern} for which tables to include in the analysis.\r\n *\r\n * @return\r\n */\r\n public Pattern getTableInclusions() {\r\n if (tableInclusions == null) {\r\n String strInclusions = pullParam(\"-i\");\r\n if (strInclusions == null)\r\n strInclusions = \".*\"; // match anything\r\n\r\n try {\r\n tableInclusions = Pattern.compile(strInclusions);\r\n } catch (PatternSyntaxException badPattern) {\r\n throw new InvalidConfigurationException(badPattern).setParamName(\"-i\");\r\n }\r\n }\r\n\r\n return tableInclusions;\r\n }\r\n\r\n /**\r\n * Set the tables to exclude as a regular expression\r\n * @param tableInclusions\r\n */\r\n public void setTableExclusions(String tableExclusions) {\r\n this.tableExclusions = Pattern.compile(tableExclusions);\r\n }\r\n\r\n /**\r\n * Get the regex {@link Pattern} for which tables to exclude from the analysis.\r\n *\r\n * @return\r\n */\r\n public Pattern getTableExclusions() {\r\n if (tableExclusions == null) {\r\n String strExclusions = pullParam(\"-I\");\r\n if (strExclusions == null)\r\n strExclusions = \"\"; // match nothing\r\n\r\n try {\r\n tableExclusions = Pattern.compile(strExclusions);\r\n } catch (PatternSyntaxException badPattern) {\r\n throw new InvalidConfigurationException(badPattern).setParamName(\"-I\");\r\n }\r\n }\r\n\r\n return tableExclusions;\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n public List<String> getSchemas() {\r\n if (schemas == null) {\r\n String tmp = pullParam(\"-schemas\");\r\n if (tmp == null)\r\n tmp = pullParam(\"-schemata\");\r\n if (tmp != null) {\r\n schemas = new ArrayList<String>();\r\n\r\n for (String name : tmp.split(\"[ ,\\\"]\"))\r\n schemas.add(name);\r\n\r\n if (schemas.isEmpty())\r\n schemas = null;\r\n }\r\n }\r\n\r\n return schemas;\r\n }\r\n\r\n /**\r\n * Set the name of the {@link SqlFormatter SQL formatter} class to use to\r\n * format SQL into HTML.<p/>\r\n * The implementation of the class must be made available to the class\r\n * loader, typically by specifying the path to its jar with <em>-dp</em>\r\n * ({@link #setDriverPath(String)}).\r\n */\r\n public void setSqlFormatter(String formatterClassName) {\r\n sqlFormatterClass = formatterClassName;\r\n sqlFormatter = null;\r\n }\r\n\r\n /**\r\n * Set the {@link SqlFormatter SQL formatter} to use to format\r\n * SQL into HTML.\r\n */\r\n public void setSqlFormatter(SqlFormatter sqlFormatter) {\r\n this.sqlFormatter = sqlFormatter;\r\n if (sqlFormatter != null)\r\n sqlFormatterClass = sqlFormatter.getClass().getName();\r\n }\r\n\r\n /**\r\n * Returns an implementation of {@link SqlFormatter SQL formatter} to use to format\r\n * SQL into HTML. The default implementation is {@link DefaultSqlFormatter}.\r\n *\r\n * @return\r\n * @throws InvalidConfigurationException if unable to instantiate an instance\r\n */\r\n @SuppressWarnings(\"unchecked\")\r\n public SqlFormatter getSqlFormatter() throws InvalidConfigurationException {\r\n if (sqlFormatter == null) {\r\n if (sqlFormatterClass == null) {\r\n sqlFormatterClass = pullParam(\"-sqlFormatter\");\r\n\r\n if (sqlFormatterClass == null)\r\n sqlFormatterClass = DefaultSqlFormatter.class.getName();\r\n }\r\n\r\n try {\r\n Class<SqlFormatter> clazz = (Class<SqlFormatter>)Class.forName(sqlFormatterClass);\r\n sqlFormatter = clazz.newInstance();\r\n } catch (Exception exc) {\r\n throw new InvalidConfigurationException(\"Failed to initialize instance of SQL formatter: \", exc)\r\n .setParamName(\"-sqlFormatter\");\r\n }\r\n }\r\n\r\n return sqlFormatter;\r\n }\r\n\r\n public void setEvaluateAllEnabled(boolean enabled) {\r\n evaluteAll = enabled;\r\n }\r\n\r\n public boolean isEvaluateAllEnabled() {\r\n if (evaluteAll == null)\r\n evaluteAll = options.remove(\"-all\");\r\n return evaluteAll;\r\n }\r\n\r\n /**\r\n * Returns true if we're evaluating a bunch of schemas in one go and\r\n * at this point we're evaluating a specific schema.\r\n *\r\n * @return boolean\r\n */\r\n public boolean isOneOfMultipleSchemas() {\r\n // set by MultipleSchemaAnalyzer\r\n return Boolean.getBoolean(\"oneofmultipleschemas\");\r\n }\r\n\r\n /**\r\n * When -all (evaluateAll) is specified then this is the regular\r\n * expression that determines which schemas to evaluate.\r\n *\r\n * @param schemaSpec\r\n */\r\n public void setSchemaSpec(String schemaSpec) {\r\n this.schemaSpec = schemaSpec;\r\n }\r\n\r\n public String getSchemaSpec() {\r\n if (schemaSpec == null)\r\n schemaSpec = pullParam(\"-schemaSpec\");\r\n\r\n return schemaSpec;\r\n }\r\n\r\n /**\r\n * Set the renderer to use for the -Tpng[:renderer[:formatter]] dot option as specified\r\n * at <a href='http://www.graphviz.org/doc/info/command.html'>\r\n * http://www.graphviz.org/doc/info/command.html</a>.<p>\r\n * Note that the leading \":\" is required while :formatter is optional.<p>\r\n * The default renderer is typically GD.<p>\r\n * Note that using {@link #setHighQuality(boolean)} is the preferred approach\r\n * over using this method.\r\n */\r\n public void setRenderer(String renderer) {\r\n Dot.getInstance().setRenderer(renderer);\r\n }\r\n\r\n /**\r\n * @see #setRenderer(String)\r\n * @return\r\n */\r\n public String getRenderer() {\r\n String renderer = pullParam(\"-renderer\");\r\n if (renderer != null)\r\n setRenderer(renderer);\r\n\r\n return Dot.getInstance().getRenderer();\r\n }\r\n\r\n /**\r\n * If <code>false</code> then generate output of \"lower quality\"\r\n * than the default.\r\n * Note that the default is intended to be \"higher quality\",\r\n * but various installations of Graphviz may have have different abilities.\r\n * That is, some might not have the \"lower quality\" libraries and others might\r\n * not have the \"higher quality\" libraries.<p>\r\n * Higher quality output takes longer to generate and results in significantly\r\n * larger image files (which take longer to download / display), but it generally\r\n * looks better.\r\n */\r\n public void setHighQuality(boolean highQuality) {\r\n this.highQuality = highQuality;\r\n lowQuality = !highQuality;\r\n Dot.getInstance().setHighQuality(highQuality);\r\n }\r\n\r\n /**\r\n * @see #setHighQuality(boolean)\r\n */\r\n public boolean isHighQuality() {\r\n if (highQuality == null) {\r\n highQuality = options.remove(\"-hq\");\r\n if (highQuality) {\r\n // use whatever is the default unless explicitly specified otherwise\r\n Dot.getInstance().setHighQuality(highQuality);\r\n }\r\n }\r\n\r\n highQuality = Dot.getInstance().isHighQuality();\r\n return highQuality;\r\n }\r\n\r\n /**\r\n * @see #setHighQuality(boolean)\r\n */\r\n public boolean isLowQuality() {\r\n if (lowQuality == null) {\r\n lowQuality = options.remove(\"-lq\");\r\n if (lowQuality) {\r\n // use whatever is the default unless explicitly specified otherwise\r\n Dot.getInstance().setHighQuality(!lowQuality);\r\n }\r\n }\r\n\r\n lowQuality = !Dot.getInstance().isHighQuality();\r\n return lowQuality;\r\n }\r\n\r\n /**\r\n * <code>true</code> if we should display advertisements.\r\n * Defaults to <code>true</code>.<p>\r\n * <b>Please do not disable ads unless absolutely necessary</b>.\r\n *\r\n * @return\r\n */\r\n public void setAdsEnabled(boolean enabled) {\r\n adsEnabled = enabled;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if we should display advertisements.<p>\r\n * <b>Please do not disable ads unless absolutely necessary</b>.\r\n *\r\n * @return\r\n */\r\n public boolean isAdsEnabled() {\r\n if (adsEnabled == null) {\r\n adsEnabled = !options.remove(\"-noads\");\r\n }\r\n\r\n return adsEnabled ;\r\n }\r\n\r\n /**\r\n * Set the level of logging to perform.<p/>\r\n * The levels in descending order are:\r\n * <ul>\r\n * <li><code>severe</code> (highest - least detail)\r\n * <li><code>warning</code> (default)\r\n * <li><code>info</code>\r\n * <li><code>config</code>\r\n * <li><code>fine</code>\r\n * <li><code>finer</code>\r\n * <li><code>finest</code> (lowest - most detail)\r\n * </ul>\r\n *\r\n * @param logLevel\r\n */\r\n public void setLogLevel(String logLevel) {\r\n if (logLevel == null) {\r\n this.logLevel = Level.WARNING;\r\n return;\r\n }\r\n\r\n Map<String, Level> levels = new LinkedHashMap<String, Level>();\r\n levels.put(\"severe\", Level.SEVERE);\r\n levels.put(\"warning\", Level.WARNING);\r\n levels.put(\"info\", Level.INFO);\r\n levels.put(\"config\", Level.CONFIG);\r\n levels.put(\"fine\", Level.FINE);\r\n levels.put(\"finer\", Level.FINER);\r\n levels.put(\"finest\", Level.FINEST);\r\n\r\n this.logLevel = levels.get(logLevel.toLowerCase());\r\n if (this.logLevel == null) {\r\n throw new InvalidConfigurationException(\"Invalid logLevel: '\" + logLevel +\r\n \"'. Must be one of: \" + levels.keySet());\r\n }\r\n }\r\n\r\n /**\r\n * Returns the level of logging to perform.\r\n * See {@link #setLogLevel(String)}.\r\n *\r\n * @return\r\n */\r\n public Level getLogLevel() {\r\n if (logLevel == null) {\r\n setLogLevel(pullParam(\"-loglevel\"));\r\n }\r\n\r\n return logLevel;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the options indicate that the user wants\r\n * to see some help information.\r\n *\r\n * @return\r\n */\r\n public boolean isHelpRequired() {\r\n return helpRequired;\r\n }\r\n\r\n public boolean isDbHelpRequired() {\r\n return dbHelpRequired;\r\n }\r\n\r\n public static String getLoadedFromJar() {\r\n String classpath = System.getProperty(\"java.class.path\");\r\n //return new StringTokenizer(classpath, File.pathSeparator).nextToken();\r\n String originalPath = new StringTokenizer(classpath, File.pathSeparator).nextToken();\r\n String loadedFrom = null; \r\n\r\n /*\r\n *Get the JAR file path from the URL. \r\n *We canot simply use location.getPath() because the returned value is invalid in Windows\r\n * \r\n *First we try to get a File from the URL, returning the canonical path.\r\n *If we cannot create a File from the URL we fall back to the original return value\r\n * \r\n */\r\n URL location = Config.class.getProtectionDomain().getCodeSource().getLocation();\r\n File urlFile = null; \r\n try\r\n {\r\n try\r\n {\r\n urlFile= new File(location.toURI()); \r\n }\r\n catch (URISyntaxException use)\r\n {\r\n urlFile= new File(location.getPath()); \r\n }\r\n loadedFrom=urlFile.getCanonicalPath();\r\n }\r\n catch (IOException ioe)\r\n {\r\n\t//Fallback to the original path returned \r\n loadedFrom=originalPath;\r\n }\r\n return loadedFrom ;\r\n }\r\n\r\n /**\r\n * @param type\r\n * @return\r\n * @throws IOException\r\n * @throws InvalidConfigurationException if db properties are incorrectly formed\r\n */\r\n public Properties getDbProperties(String type) throws IOException, InvalidConfigurationException {\r\n ResourceBundle bundle = null;\r\n\r\n try {\r\n File propertiesFile = new File(type);\r\n bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile));\r\n dbPropertiesLoadedFrom = propertiesFile.getAbsolutePath();\r\n } catch (FileNotFoundException notFoundOnFilesystemWithoutExtension) {\r\n try {\r\n File propertiesFile = new File(type + \".properties\");\r\n bundle = new PropertyResourceBundle(new FileInputStream(propertiesFile));\r\n dbPropertiesLoadedFrom = propertiesFile.getAbsolutePath();\r\n } catch (FileNotFoundException notFoundOnFilesystemWithExtensionTackedOn) {\r\n try {\r\n bundle = ResourceBundle.getBundle(type);\r\n dbPropertiesLoadedFrom = \"[\" + getLoadedFromJar() + \"]\" + File.separator + type + \".properties\";\r\n } catch (Exception notInJarWithoutPath) {\r\n try {\r\n String path = TableOrderer.class.getPackage().getName() + \".dbTypes.\" + type;\r\n path = path.replace('.', '/');\r\n bundle = ResourceBundle.getBundle(path);\r\n dbPropertiesLoadedFrom = \"[\" + getLoadedFromJar() + \"]/\" + path + \".properties\";\r\n } catch (Exception notInJar) {\r\n notInJar.printStackTrace();\r\n notFoundOnFilesystemWithExtensionTackedOn.printStackTrace();\r\n throw notFoundOnFilesystemWithoutExtension;\r\n }\r\n }\r\n }\r\n }\r\n\r\n Properties props = asProperties(bundle);\r\n bundle = null;\r\n String saveLoadedFrom = dbPropertiesLoadedFrom; // keep original thru recursion\r\n\r\n // bring in key/values pointed to by the include directive\r\n // example: include.1=mysql::selectRowCountSql\r\n for (int i = 1; true; ++i) {\r\n String include = (String)props.remove(\"include.\" + i);\r\n if (include == null)\r\n break;\r\n\r\n int separator = include.indexOf(\"::\");\r\n if (separator == -1)\r\n throw new InvalidConfigurationException(\"include directive in \" + dbPropertiesLoadedFrom + \" must have '::' between dbType and key\");\r\n\r\n String refdType = include.substring(0, separator).trim();\r\n String refdKey = include.substring(separator + 2).trim();\r\n\r\n // recursively resolve the ref'd properties file and the ref'd key\r\n Properties refdProps = getDbProperties(refdType);\r\n props.put(refdKey, refdProps.getProperty(refdKey));\r\n }\r\n\r\n // bring in base properties files pointed to by the extends directive\r\n String baseDbType = (String)props.remove(\"extends\");\r\n if (baseDbType != null) {\r\n baseDbType = baseDbType.trim();\r\n Properties baseProps = getDbProperties(baseDbType);\r\n\r\n // overlay our properties on top of the base's\r\n baseProps.putAll(props);\r\n props = baseProps;\r\n }\r\n\r\n // done with this level of recursion...restore original\r\n dbPropertiesLoadedFrom = saveLoadedFrom;\r\n\r\n return props;\r\n }\r\n\r\n protected String getDbPropertiesLoadedFrom() throws IOException {\r\n if (dbPropertiesLoadedFrom == null)\r\n getDbProperties(getDbType());\r\n return dbPropertiesLoadedFrom;\r\n }\r\n\r\n public List<String> getRemainingParameters()\r\n {\r\n try {\r\n populate();\r\n } catch (IllegalArgumentException exc) {\r\n throw new InvalidConfigurationException(exc);\r\n } catch (IllegalAccessException exc) {\r\n throw new InvalidConfigurationException(exc);\r\n } catch (InvocationTargetException exc) {\r\n if (exc.getCause() instanceof InvalidConfigurationException)\r\n throw (InvalidConfigurationException)exc.getCause();\r\n throw new InvalidConfigurationException(exc.getCause());\r\n } catch (IntrospectionException exc) {\r\n throw new InvalidConfigurationException(exc);\r\n }\r\n\r\n return options;\r\n }\r\n\r\n /**\r\n * Options that are specific to a type of database. E.g. things like <code>host</code>,\r\n * <code>port</code> or <code>db</code>, but <b>don't</b> have a setter in this class.\r\n *\r\n * @param dbSpecificOptions\r\n */\r\n public void setDbSpecificOptions(Map<String, String> dbSpecificOptions) {\r\n this.dbSpecificOptions = dbSpecificOptions;\r\n originalDbSpecificOptions = new HashMap<String, String>(dbSpecificOptions);\r\n }\r\n\r\n public Map<String, String> getDbSpecificOptions() {\r\n if (dbSpecificOptions == null)\r\n dbSpecificOptions = new HashMap<String, String>();\r\n return dbSpecificOptions;\r\n }\r\n\r\n /**\r\n * Returns a {@link Properties} populated with the contents of <code>bundle</code>\r\n *\r\n * @param bundle ResourceBundle\r\n * @return Properties\r\n */\r\n public static Properties asProperties(ResourceBundle bundle) {\r\n Properties props = new Properties();\r\n Enumeration<String> iter = bundle.getKeys();\r\n while (iter.hasMoreElements()) {\r\n String key = iter.nextElement();\r\n props.put(key, bundle.getObject(key));\r\n }\r\n\r\n return props;\r\n }\r\n\r\n /**\r\n * 'Pull' the specified parameter from the collection of options. Returns\r\n * null if the parameter isn't in the list and removes it if it is.\r\n *\r\n * @param paramId\r\n * @return\r\n */\r\n private String pullParam(String paramId) {\r\n return pullParam(paramId, false, false);\r\n }\r\n\r\n private String pullRequiredParam(String paramId) {\r\n return pullParam(paramId, true, false);\r\n }\r\n\r\n /**\r\n * @param paramId\r\n * @param required\r\n * @param dbTypeSpecific\r\n * @return\r\n * @throws MissingRequiredParameterException\r\n */\r\n private String pullParam(String paramId, boolean required, boolean dbTypeSpecific)\r\n throws MissingRequiredParameterException {\r\n int paramIndex = options.indexOf(paramId);\r\n if (paramIndex < 0) {\r\n if (required)\r\n throw new MissingRequiredParameterException(paramId, dbTypeSpecific);\r\n return null;\r\n }\r\n options.remove(paramIndex);\r\n String param = options.get(paramIndex).toString();\r\n options.remove(paramIndex);\r\n return param;\r\n }\r\n\r\n /**\r\n * Thrown to indicate that a required parameter is missing\r\n */\r\n public static class MissingRequiredParameterException extends RuntimeException {\r\n private static final long serialVersionUID = 1L;\r\n private final boolean dbTypeSpecific;\r\n\r\n public MissingRequiredParameterException(String paramId, boolean dbTypeSpecific) {\r\n this(paramId, null, dbTypeSpecific);\r\n }\r\n\r\n public MissingRequiredParameterException(String paramId, String description, boolean dbTypeSpecific) {\r\n super(\"Required parameter '\" + paramId + \"' \" +\r\n (description == null ? \"\" : \"(\" + description + \") \") +\r\n \"was not specified.\" +\r\n (dbTypeSpecific ? \" It is required for this database type.\" : \"\"));\r\n this.dbTypeSpecific = dbTypeSpecific;\r\n }\r\n\r\n public boolean isDbTypeSpecific() {\r\n return dbTypeSpecific;\r\n }\r\n }\r\n\r\n /**\r\n * Allow an equal sign in args...like \"-o=foo.bar\". Useful for things like\r\n * Ant and Maven.\r\n *\r\n * @param args\r\n * List\r\n * @return List\r\n */\r\n protected List<String> fixupArgs(List<String> args) {\r\n List<String> expandedArgs = new ArrayList<String>();\r\n\r\n for (String arg : args) {\r\n int indexOfEquals = arg.indexOf('=');\r\n if (indexOfEquals != -1 && indexOfEquals -1 != arg.indexOf(ESCAPED_EQUALS)) {\r\n expandedArgs.add(arg.substring(0, indexOfEquals));\r\n expandedArgs.add(arg.substring(indexOfEquals + 1));\r\n } else {\r\n expandedArgs.add(arg);\r\n }\r\n }\r\n\r\n // some OSes/JVMs do filename expansion with runtime.exec() and some don't,\r\n // so MultipleSchemaAnalyzer has to surround params with double quotes...\r\n // strip them here for the OSes/JVMs that don't do anything with the params\r\n List<String> unquotedArgs = new ArrayList<String>();\r\n\r\n for (String arg : expandedArgs) {\r\n if (arg.startsWith(\"\\\"\") && arg.endsWith(\"\\\"\")) // \".*\" becomes .*\r\n arg = arg.substring(1, arg.length() - 1);\r\n unquotedArgs.add(arg);\r\n }\r\n\r\n return unquotedArgs;\r\n }\r\n\r\n /**\r\n * Call all the getters to populate all the lazy initialized stuff.\r\n *\r\n * @throws InvocationTargetException\r\n * @throws IllegalAccessException\r\n * @throws IllegalArgumentException\r\n * @throws IntrospectionException\r\n */\r\n private void populate() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException {\r\n if (!populating) { // prevent recursion\r\n populating = true;\r\n\r\n BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);\r\n PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();\r\n for (int i = 0; i < props.length; ++i) {\r\n Method readMethod = props[i].getReadMethod();\r\n if (readMethod != null)\r\n readMethod.invoke(this, (Object[])null);\r\n }\r\n\r\n populating = false;\r\n }\r\n }\r\n\r\n public static Set<String> getBuiltInDatabaseTypes(String loadedFromJar) {\r\n Set<String> databaseTypes = new TreeSet<String>();\r\n JarInputStream jar = null;\r\n\r\n try {\r\n jar = new JarInputStream(new FileInputStream(loadedFromJar));\r\n JarEntry entry;\r\n\r\n while ((entry = jar.getNextJarEntry()) != null) {\r\n String entryName = entry.getName();\r\n int dotPropsIndex = entryName.indexOf(\".properties\");\r\n if (dotPropsIndex != -1)\r\n databaseTypes.add(entryName.substring(0, dotPropsIndex));\r\n }\r\n } catch (IOException exc) {\r\n } finally {\r\n if (jar != null) {\r\n try {\r\n jar.close();\r\n } catch (IOException ignore) {}\r\n }\r\n }\r\n\r\n return databaseTypes;\r\n }\r\n\r\n protected void dumpUsage(String errorMessage, boolean detailedDb) {\r\n if (errorMessage != null) {\r\n System.out.flush();\r\n System.err.println(\"*** \" + errorMessage + \" ***\");\r\n } else {\r\n System.out.println(\"SchemaSpy generates an HTML representation of a database schema's relationships.\");\r\n }\r\n\r\n System.err.flush();\r\n System.out.println();\r\n\r\n if (!detailedDb) {\r\n System.out.println(\"Usage:\");\r\n System.out.println(\" java -jar \" + getLoadedFromJar() + \" [options]\");\r\n System.out.println(\" -t databaseType type of database - defaults to ora\");\r\n System.out.println(\" use -dbhelp for a list of built-in types\");\r\n System.out.println(\" -u user connect to the database with this user id\");\r\n System.out.println(\" -s schema defaults to the specified user\");\r\n System.out.println(\" -p password defaults to no password\");\r\n System.out.println(\" -o outputDirectory directory to place the generated output in\");\r\n System.out.println(\" -dp pathToDrivers optional - looks for JDBC drivers here before looking\");\r\n System.out.println(\" in driverPath in [databaseType].properties.\");\r\n System.out.println(\"Go to http://schemaspy.sourceforge.net for a complete list/description\");\r\n System.out.println(\" of additional parameters.\");\r\n System.out.println();\r\n }\r\n\r\n if (detailedDb) {\r\n System.out.println(\"Built-in database types and their required connection parameters:\");\r\n for (String type : getBuiltInDatabaseTypes(getLoadedFromJar())) {\r\n new DbSpecificConfig(type).dumpUsage();\r\n }\r\n System.out.println();\r\n }\r\n\r\n if (detailedDb) {\r\n System.out.println(\"You can use your own database types by specifying the filespec of a .properties file with -t.\");\r\n System.out.println(\"Grab one out of \" + getLoadedFromJar() + \" and modify it to suit your needs.\");\r\n System.out.println();\r\n }\r\n\r\n System.out.println(\"Sample usage using the default database type (implied -t ora):\");\r\n System.out.println(\" java -jar schemaSpy.jar -db mydb -s myschema -u devuser -p password -o output\");\r\n System.out.println();\r\n System.out.flush();\r\n }\r\n\r\n /**\r\n * Get the value of the specified parameter.\r\n * Used for properties that are common to most db's, but aren't required.\r\n *\r\n * @param paramName\r\n * @return\r\n */\r\n public String getParam(String paramName) {\r\n try {\r\n BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);\r\n PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();\r\n for (int i = 0; i < props.length; ++i) {\r\n PropertyDescriptor prop = props[i];\r\n if (prop.getName().equalsIgnoreCase(paramName)) {\r\n Object result = prop.getReadMethod().invoke(this, (Object[])null);\r\n return result == null ? null : result.toString();\r\n }\r\n }\r\n } catch (Exception failed) {\r\n failed.printStackTrace();\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Return all of the configuration options as a List of Strings, with\r\n * each parameter and its value as a separate element.\r\n *\r\n * @return\r\n * @throws IOException\r\n */\r\n public List<String> asList() throws IOException {\r\n List<String> params = new ArrayList<String>();\r\n\r\n if (originalDbSpecificOptions != null) {\r\n for (String key : originalDbSpecificOptions.keySet()) {\r\n String value = originalDbSpecificOptions.get(key);\r\n if (!key.startsWith(\"-\"))\r\n key = \"-\" + key;\r\n params.add(key);\r\n params.add(value);\r\n }\r\n }\r\n if (isEncodeCommentsEnabled())\r\n params.add(\"-ahic\");\r\n if (isEvaluateAllEnabled())\r\n params.add(\"-all\");\r\n if (!isHtmlGenerationEnabled())\r\n params.add(\"-nohtml\");\r\n if (!isImpliedConstraintsEnabled())\r\n params.add(\"-noimplied\");\r\n if (!isLogoEnabled())\r\n params.add(\"-nologo\");\r\n if (isMeterEnabled())\r\n params.add(\"-meter\");\r\n if (!isNumRowsEnabled())\r\n params.add(\"-norows\");\r\n if (!isViewsEnabled())\r\n params.add(\"-noviews\");\r\n if (isRankDirBugEnabled())\r\n params.add(\"-rankdirbug\");\r\n if (isRailsEnabled())\r\n params.add(\"-rails\");\r\n if (isSingleSignOn())\r\n params.add(\"-sso\");\r\n if (!isAdsEnabled())\r\n params.add(\"-noads\");\r\n if (isSchemaDisabled())\r\n params.add(\"-noschema\");\r\n\r\n String value = getDriverPath();\r\n if (value != null) {\r\n params.add(\"-dp\");\r\n params.add(value);\r\n }\r\n params.add(\"-css\");\r\n params.add(getCss());\r\n params.add(\"-charset\");\r\n params.add(getCharset());\r\n params.add(\"-font\");\r\n params.add(getFont());\r\n params.add(\"-fontsize\");\r\n params.add(String.valueOf(getFontSize()));\r\n params.add(\"-t\");\r\n params.add(getDbType());\r\n params.add(\"-renderer\"); // instead of -hq and/or -lq\r\n params.add(getRenderer());\r\n value = getDescription();\r\n if (value != null) {\r\n params.add(\"-desc\");\r\n params.add(value);\r\n }\r\n value = getPassword();\r\n if (value != null) {\r\n params.add(\"-p\");\r\n params.add(value);\r\n }\r\n if (isPromptForPasswordEnabled())\r\n params.add(\"-pfp\");\r\n value = getSchema();\r\n if (value != null) {\r\n params.add(\"-s\");\r\n params.add(value);\r\n }\r\n value = getUser();\r\n if (value != null) {\r\n params.add(\"-u\");\r\n params.add(value);\r\n }\r\n value = getConnectionPropertiesFile();\r\n if (value != null) {\r\n params.add(\"-connprops\");\r\n params.add(value);\r\n } else {\r\n Properties props = getConnectionProperties();\r\n if (!props.isEmpty() ) {\r\n params.add(\"-connprops\");\r\n StringBuilder buf = new StringBuilder();\r\n for (Entry<Object, Object> entry : props.entrySet()) {\r\n buf.append(entry.getKey());\r\n buf.append(ESCAPED_EQUALS);\r\n buf.append(entry.getValue());\r\n buf.append(';');\r\n }\r\n params.add(buf.toString());\r\n }\r\n }\r\n value = getDb();\r\n if (value != null) {\r\n params.add(\"-db\");\r\n params.add(value);\r\n }\r\n value = getHost();\r\n if (value != null) {\r\n params.add(\"-host\");\r\n params.add(value);\r\n }\r\n if (getPort() != null) {\r\n params.add(\"-port\");\r\n params.add(getPort().toString());\r\n }\r\n value = getServer();\r\n if (value != null) {\r\n params.add(\"-server\");\r\n params.add(value);\r\n }\r\n value = getMeta();\r\n if (value != null) {\r\n params.add(\"-meta\");\r\n params.add(value);\r\n }\r\n if (getGraphvizDir() != null) {\r\n params.add(\"-gv\");\r\n params.add(getGraphvizDir().toString());\r\n }\r\n params.add(\"-loglevel\");\r\n params.add(getLogLevel().toString().toLowerCase());\r\n params.add(\"-sqlFormatter\");\r\n params.add(getSqlFormatter().getClass().getName());\r\n params.add(\"-i\");\r\n params.add(getTableInclusions().pattern());\r\n params.add(\"-I\");\r\n params.add(getTableExclusions().pattern());\r\n params.add(\"-x\");\r\n params.add(getColumnExclusions().pattern());\r\n params.add(\"-X\");\r\n params.add(getIndirectColumnExclusions().pattern());\r\n params.add(\"-dbthreads\");\r\n params.add(String.valueOf(getMaxDbThreads()));\r\n params.add(\"-maxdet\");\r\n params.add(String.valueOf(getMaxDetailedTables()));\r\n params.add(\"-o\");\r\n params.add(getOutputDir().toString());\r\n\r\n return params;\r\n }\r\n}\r", "public class Database {\r\n private final String databaseName;\r\n private final String schema;\r\n private String description;\r\n private final Map<String, Table> tables = new CaseInsensitiveMap<Table>();\r\n private final Map<String, View> views = new CaseInsensitiveMap<View>();\r\n private final Map<String, Table> remoteTables = new CaseInsensitiveMap<Table>(); // key: schema.tableName value: RemoteTable\r\n private final DatabaseMetaData meta;\r\n private final Connection connection;\r\n private final String connectTime = new SimpleDateFormat(\"EEE MMM dd HH:mm z yyyy\").format(new Date());\r\n private Set<String> sqlKeywords;\r\n private Pattern invalidIdentifierPattern;\r\n private final Logger logger = Logger.getLogger(getClass().getName());\r\n private final boolean fineEnabled = logger.isLoggable(Level.FINE);\r\n\r\n public Database(Config config, Connection connection, DatabaseMetaData meta, String name, String schema, Properties properties, SchemaMeta schemaMeta) throws SQLException, MissingResourceException {\r\n this.connection = connection;\r\n this.meta = meta;\r\n databaseName = name;\r\n this.schema = schema;\r\n description = config.getDescription();\r\n\r\n initTables(meta, properties, config);\r\n if (config.isViewsEnabled())\r\n initViews(meta, properties, config);\r\n\r\n initCheckConstraints(properties);\r\n initTableIds(properties);\r\n initIndexIds(properties);\r\n initTableComments(properties);\r\n initTableColumnComments(properties);\r\n initViewComments(properties);\r\n initViewColumnComments(properties);\r\n\r\n connectTables();\r\n updateFromXmlMetadata(schemaMeta);\r\n }\r\n\r\n public String getName() {\r\n return databaseName;\r\n }\r\n\r\n public String getSchema() {\r\n return schema;\r\n }\r\n\r\n /**\r\n * Details of the database type that's running under the covers.\r\n *\r\n * @return null if a description wasn't specified.\r\n */\r\n public String getDescription() {\r\n return description;\r\n }\r\n\r\n public Collection<Table> getTables() {\r\n return tables.values();\r\n }\r\n\r\n /**\r\n * Return a {@link Map} of all {@link Table}s keyed by their name.\r\n *\r\n * @return\r\n */\r\n public Map<String, Table> getTablesByName() {\r\n \treturn tables;\r\n }\r\n\r\n public Collection<View> getViews() {\r\n return views.values();\r\n }\r\n\r\n public Collection<Table> getRemoteTables() {\r\n return remoteTables.values();\r\n }\r\n\r\n public Connection getConnection() {\r\n return connection;\r\n }\r\n\r\n public DatabaseMetaData getMetaData() {\r\n return meta;\r\n }\r\n\r\n public String getConnectTime() {\r\n return connectTime;\r\n }\r\n\r\n public String getDatabaseProduct() {\r\n try {\r\n return meta.getDatabaseProductName() + \" - \" + meta.getDatabaseProductVersion();\r\n } catch (SQLException exc) {\r\n return \"\";\r\n }\r\n }\r\n\r\n /**\r\n * \"macro\" to validate that a table is somewhat valid\r\n */\r\n class NameValidator {\r\n private final String clazz;\r\n private final Pattern include;\r\n private final Pattern exclude;\r\n private final Set<String> validTypes;\r\n\r\n /**\r\n * @param clazz table or view\r\n * @param include\r\n * @param exclude\r\n * @param verbose\r\n * @param validTypes\r\n */\r\n NameValidator(String clazz, Pattern include, Pattern exclude, String[] validTypes) {\r\n this.clazz = clazz;\r\n this.include = include;\r\n this.exclude = exclude;\r\n this.validTypes = new HashSet<String>();\r\n for (String type : validTypes)\r\n {\r\n this.validTypes.add(type.toUpperCase());\r\n }\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the table/view name is deemed \"valid\"\r\n *\r\n * @param name name of the table or view\r\n * @param type type as returned by metadata.getTables():TABLE_TYPE\r\n * @return\r\n */\r\n boolean isValid(String name, String type) {\r\n // some databases (MySQL) return more than we wanted\r\n if (!validTypes.contains(type.toUpperCase()))\r\n return false;\r\n\r\n // Oracle 10g introduced problematic flashback tables\r\n // with bizarre illegal names\r\n // Naming Convention \"BIN$\"${globalUID}${version}\r\n // http://docs.oracle.com/cd/B19306_01/backup.102/b14192/flashptr004.htm#i1016977\r\n if (name.indexOf(\"BIN$\") == 0) {\r\n if (fineEnabled) {\r\n logger.fine(\"Excluding \" + clazz + \" \" + name +\r\n \": \\\"BIN$\\\" prefix implies a (deleted) table in the Oracle Recycle Bin \");\r\n }\r\n return false;\r\n }\r\n\r\n if (exclude.matcher(name).matches()) {\r\n if (fineEnabled) {\r\n logger.fine(\"Excluding \" + clazz + \" \" + name +\r\n \": matches exclusion pattern \\\"\" + exclude + '\"');\r\n }\r\n return false;\r\n }\r\n\r\n boolean valid = include.matcher(name).matches();\r\n if (fineEnabled) {\r\n if (valid) {\r\n logger.fine(\"Including \" + clazz + \" \" + name +\r\n \": matches inclusion pattern \\\"\" + include + '\"');\r\n } else {\r\n logger.fine(\"Excluding \" + clazz + \" \" + name +\r\n \": doesn't match inclusion pattern \\\"\" + include + '\"');\r\n }\r\n }\r\n return valid;\r\n }\r\n }\r\n\r\n /**\r\n * Create/initialize any tables in the schema.\r\n\r\n * @param metadata\r\n * @param properties\r\n * @param config\r\n * @throws SQLException\r\n */\r\n private void initTables(final DatabaseMetaData metadata, final Properties properties,\r\n final Config config) throws SQLException {\r\n final Pattern include = config.getTableInclusions();\r\n final Pattern exclude = config.getTableExclusions();\r\n final int maxThreads = config.getMaxDbThreads();\r\n\r\n String[] types = getTypes(\"tableTypes\", \"TABLE\", properties);\r\n NameValidator validator = new NameValidator(\"table\", include, exclude, types);\r\n List<BasicTableMeta> entries = getBasicTableMeta(metadata, true, properties, types);\r\n\r\n TableCreator creator;\r\n if (maxThreads == 1) {\r\n creator = new TableCreator();\r\n } else {\r\n // creating tables takes a LONG time (based on JProbe analysis),\r\n // so attempt to speed it up by doing several in parallel.\r\n // note that it's actually DatabaseMetaData.getIndexInfo() that's expensive\r\n\r\n creator = new ThreadedTableCreator(maxThreads);\r\n\r\n // \"prime the pump\" so if there's a database problem we'll probably see it now\r\n // and not in a secondary thread\r\n while (!entries.isEmpty()) {\r\n BasicTableMeta entry = entries.remove(0);\r\n\r\n if (validator.isValid(entry.name, entry.type)) {\r\n new TableCreator().create(entry, properties);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // kick off the secondary threads to do the creation in parallel\r\n for (BasicTableMeta entry : entries) {\r\n if (validator.isValid(entry.name, entry.type)) {\r\n creator.create(entry, properties);\r\n }\r\n }\r\n\r\n // wait for everyone to finish\r\n creator.join();\r\n }\r\n\r\n /**\r\n * Create/initialize any views in the schema.\r\n *\r\n * @param metadata\r\n * @param properties\r\n * @param config\r\n * @throws SQLException\r\n */\r\n private void initViews(DatabaseMetaData metadata, Properties properties,\r\n Config config) throws SQLException {\r\n Pattern includeTables = config.getTableInclusions();\r\n Pattern excludeTables = config.getTableExclusions();\r\n Pattern excludeColumns = config.getColumnExclusions();\r\n Pattern excludeIndirectColumns = config.getIndirectColumnExclusions();\r\n\r\n String[] types = getTypes(\"viewTypes\", \"VIEW\", properties);\r\n NameValidator validator = new NameValidator(\"view\", includeTables, excludeTables, types);\r\n\r\n for (BasicTableMeta entry : getBasicTableMeta(metadata, false, properties, types)) {\r\n if (validator.isValid(entry.name, entry.type)) {\r\n View view = new View(this, entry.schema, entry.name, entry.remarks,\r\n entry.viewSql, properties,\r\n excludeIndirectColumns, excludeColumns);\r\n views.put(view.getName(), view);\r\n if (logger.isLoggable(Level.FINE)) {\r\n logger.fine(\"Found details of view \" + view.getName());\r\n } else {\r\n System.out.print('.');\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Collection of fundamental table/view metadata\r\n */\r\n private class BasicTableMeta\r\n {\r\n @SuppressWarnings(\"hiding\")\r\n final String schema;\r\n final String name;\r\n final String type;\r\n final String remarks;\r\n final String viewSql;\r\n final long numRows; // -1 if not determined\r\n\r\n /**\r\n * @param schema\r\n * @param name\r\n * @param type typically \"TABLE\" or \"VIEW\"\r\n * @param remarks\r\n * @param text optional textual SQL used to create the view\r\n * @param numRows number of rows, or -1 if not determined\r\n */\r\n BasicTableMeta(String schema, String name, String type, String remarks, String text, long numRows)\r\n {\r\n this.schema = schema;\r\n this.name = name;\r\n this.type = type;\r\n this.remarks = remarks;\r\n viewSql = text;\r\n this.numRows = numRows;\r\n }\r\n }\r\n\r\n /**\r\n * Return a list of basic details of the tables in the schema.\r\n *\r\n * @param metadata\r\n * @param forTables true if we're getting table data, false if getting view data\r\n * @param properties\r\n * @return\r\n * @throws SQLException\r\n */\r\n private List<BasicTableMeta> getBasicTableMeta(DatabaseMetaData metadata,\r\n boolean forTables,\r\n Properties properties,\r\n String... types) throws SQLException {\r\n String queryName = forTables ? \"selectTablesSql\" : \"selectViewsSql\";\r\n String sql = properties.getProperty(queryName);\r\n List<BasicTableMeta> basics = new ArrayList<BasicTableMeta>();\r\n ResultSet rs = null;\r\n\r\n if (sql != null) {\r\n String clazz = forTables ? \"table\" : \"view\";\r\n PreparedStatement stmt = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String name = rs.getString(clazz + \"_name\");\r\n String sch = getOptionalString(rs, clazz + \"_schema\");\r\n if (sch == null)\r\n sch = schema;\r\n String remarks = getOptionalString(rs, clazz + \"_comment\");\r\n String text = forTables ? null : getOptionalString(rs, \"view_definition\");\r\n String rows = forTables ? getOptionalString(rs, \"table_rows\") : null;\r\n long numRows = rows == null ? -1 : Long.parseLong(rows);\r\n\r\n basics.add(new BasicTableMeta(sch, name, clazz, remarks, text, numRows));\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n System.out.flush();\r\n System.err.println();\r\n System.err.println(\"Failed to retrieve \" + clazz + \" names with custom SQL: \" + sqlException);\r\n System.err.println(sql);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n\r\n if (basics.isEmpty()) {\r\n rs = metadata.getTables(null, schema, \"%\", types);\r\n\r\n try {\r\n while (rs.next()) {\r\n String name = rs.getString(\"TABLE_NAME\");\r\n String type = rs.getString(\"TABLE_TYPE\");\r\n String schem = rs.getString(\"TABLE_SCHEM\");\r\n String remarks = getOptionalString(rs, \"REMARKS\");\r\n\r\n basics.add(new BasicTableMeta(schem, name, type, remarks, null, -1));\r\n }\r\n } catch (SQLException exc) {\r\n if (forTables)\r\n throw exc;\r\n\r\n System.out.flush();\r\n System.err.println();\r\n System.err.println(\"Ignoring view \" + rs.getString(\"TABLE_NAME\") + \" due to exception:\");\r\n exc.printStackTrace();\r\n System.err.println(\"Continuing analysis.\");\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n }\r\n }\r\n\r\n return basics;\r\n }\r\n\r\n /**\r\n * Return a database-specific array of types from the .properties file\r\n * with the specified property name.\r\n *\r\n * @param propName\r\n * @param defaultValue\r\n * @param props\r\n * @return\r\n */\r\n private String[] getTypes(String propName, String defaultValue, Properties props) {\r\n String value = props.getProperty(propName, defaultValue);\r\n List<String> types = new ArrayList<String>();\r\n for (String type : value.split(\",\")) {\r\n type = type.trim();\r\n if (type.length() > 0)\r\n types.add(type);\r\n }\r\n\r\n return types.toArray(new String[types.size()]);\r\n }\r\n\r\n /**\r\n * Some databases don't play nice with their metadata.\r\n * E.g. Oracle doesn't have a REMARKS column at all.\r\n * This method ignores those types of failures, replacing them with null.\r\n */\r\n public String getOptionalString(ResultSet rs, String columnName)\r\n {\r\n try {\r\n return rs.getString(columnName);\r\n } catch (SQLException ignore) {\r\n return null;\r\n }\r\n }\r\n\r\n private void initCheckConstraints(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectCheckConstraintsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String tableName = rs.getString(\"table_name\");\r\n Table table = tables.get(tableName);\r\n if (table != null)\r\n table.addCheckConstraint(rs.getString(\"constraint_name\"), rs.getString(\"text\"));\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n System.err.println();\r\n System.err.println(\"Failed to retrieve check constraints: \" + sqlException);\r\n System.err.println(sql);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n private void initTableIds(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectTableIdsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String tableName = rs.getString(\"table_name\");\r\n Table table = tables.get(tableName);\r\n if (table != null)\r\n table.setId(rs.getObject(\"table_id\"));\r\n }\r\n } catch (SQLException sqlException) {\r\n System.err.println();\r\n System.err.println(sql);\r\n throw sqlException;\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n private void initIndexIds(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectIndexIdsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String tableName = rs.getString(\"table_name\");\r\n Table table = tables.get(tableName);\r\n if (table != null) {\r\n TableIndex index = table.getIndex(rs.getString(\"index_name\"));\r\n if (index != null)\r\n index.setId(rs.getObject(\"index_id\"));\r\n }\r\n }\r\n } catch (SQLException sqlException) {\r\n System.err.println();\r\n System.err.println(sql);\r\n throw sqlException;\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Initializes table comments.\r\n * If the SQL also returns view comments then they're plugged into the\r\n * appropriate views.\r\n *\r\n * @param properties\r\n * @throws SQLException\r\n */\r\n private void initTableComments(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectTableCommentsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String tableName = rs.getString(\"table_name\");\r\n Table table = tables.get(tableName);\r\n if (table == null)\r\n table = views.get(tableName);\r\n\r\n if (table != null)\r\n table.setComments(rs.getString(\"comments\"));\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n System.err.println();\r\n System.err.println(\"Failed to retrieve table/view comments: \" + sqlException);\r\n System.err.println(sql);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Initializes view comments.\r\n *\r\n * @param properties\r\n * @throws SQLException\r\n */\r\n private void initViewComments(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectViewCommentsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String viewName = rs.getString(\"view_name\");\r\n if (viewName == null)\r\n viewName = rs.getString(\"table_name\");\r\n Table view = views.get(viewName);\r\n\r\n if (view != null)\r\n view.setComments(rs.getString(\"comments\"));\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n System.err.println();\r\n System.err.println(\"Failed to retrieve table/view comments: \" + sqlException);\r\n System.err.println(sql);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Initializes table column comments.\r\n * If the SQL also returns view column comments then they're plugged into the\r\n * appropriate views.\r\n *\r\n * @param properties\r\n * @throws SQLException\r\n */\r\n private void initTableColumnComments(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectColumnCommentsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String tableName = rs.getString(\"table_name\");\r\n Table table = tables.get(tableName);\r\n if (table == null)\r\n table = views.get(tableName);\r\n\r\n if (table != null) {\r\n TableColumn column = table.getColumn(rs.getString(\"column_name\"));\r\n if (column != null)\r\n column.setComments(rs.getString(\"comments\"));\r\n }\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n System.err.println();\r\n System.err.println(\"Failed to retrieve column comments: \" + sqlException);\r\n System.err.println(sql);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Initializes view column comments.\r\n *\r\n * @param properties\r\n * @throws SQLException\r\n */\r\n private void initViewColumnComments(Properties properties) throws SQLException {\r\n String sql = properties.getProperty(\"selectViewColumnCommentsSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = prepareStatement(sql, null);\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n String viewName = rs.getString(\"view_name\");\r\n if (viewName == null)\r\n viewName = rs.getString(\"table_name\");\r\n Table view = views.get(viewName);\r\n\r\n if (view != null) {\r\n TableColumn column = view.getColumn(rs.getString(\"column_name\"));\r\n if (column != null)\r\n column.setComments(rs.getString(\"comments\"));\r\n }\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n System.err.println();\r\n System.err.println(\"Failed to retrieve view column comments: \" + sqlException);\r\n System.err.println(sql);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Create a <code>PreparedStatement</code> from the specified SQL.\r\n * The SQL can contain these named parameters (but <b>not</b> question marks).\r\n * <ol>\r\n * <li>:schema - replaced with the name of the schema\r\n * <li>:owner - alias for :schema\r\n * <li>:table - replaced with the name of the table\r\n * </ol>\r\n * @param sql String - SQL without question marks\r\n * @param tableName String - <code>null</code> if the statement doesn't deal with <code>Table</code>-level details.\r\n * @throws SQLException\r\n * @return PreparedStatement\r\n */\r\n public PreparedStatement prepareStatement(String sql, String tableName) throws SQLException {\r\n StringBuilder sqlBuf = new StringBuilder(sql);\r\n List<String> sqlParams = getSqlParams(sqlBuf, tableName); // modifies sqlBuf\r\n PreparedStatement stmt = getConnection().prepareStatement(sqlBuf.toString());\r\n\r\n try {\r\n for (int i = 0; i < sqlParams.size(); ++i) {\r\n stmt.setString(i + 1, sqlParams.get(i).toString());\r\n }\r\n } catch (SQLException exc) {\r\n stmt.close();\r\n throw exc;\r\n }\r\n\r\n return stmt;\r\n }\r\n\r\n public Table addRemoteTable(String remoteSchema, String remoteTableName, String baseSchema, Properties properties, Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {\r\n String fullName = remoteSchema + \".\" + remoteTableName;\r\n Table remoteTable = remoteTables.get(fullName);\r\n if (remoteTable == null) {\r\n if (properties != null)\r\n remoteTable = new RemoteTable(this, remoteSchema, remoteTableName, baseSchema, properties, excludeIndirectColumns, excludeColumns);\r\n else\r\n remoteTable = new ExplicitRemoteTable(this, remoteSchema, remoteTableName, baseSchema);\r\n\r\n logger.fine(\"Adding remote table \" + fullName);\r\n remoteTable.connectForeignKeys(tables, excludeIndirectColumns, excludeColumns);\r\n remoteTables.put(fullName, remoteTable);\r\n }\r\n\r\n return remoteTable;\r\n }\r\n\r\n /**\r\n * Return an uppercased <code>Set</code> of all SQL keywords used by a database\r\n *\r\n * @return\r\n * @throws SQLException\r\n */\r\n public Set<String> getSqlKeywords() throws SQLException {\r\n if (sqlKeywords == null) {\r\n // from http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt:\r\n String[] sql92Keywords =\r\n (\"ADA\" +\r\n \"| C | CATALOG_NAME | CHARACTER_SET_CATALOG | CHARACTER_SET_NAME\" +\r\n \"| CHARACTER_SET_SCHEMA | CLASS_ORIGIN | COBOL | COLLATION_CATALOG\" +\r\n \"| COLLATION_NAME | COLLATION_SCHEMA | COLUMN_NAME | COMMAND_FUNCTION | COMMITTED\" +\r\n \"| CONDITION_NUMBER | CONNECTION_NAME | CONSTRAINT_CATALOG | CONSTRAINT_NAME\" +\r\n \"| CONSTRAINT_SCHEMA | CURSOR_NAME\" +\r\n \"| DATA | DATETIME_INTERVAL_CODE | DATETIME_INTERVAL_PRECISION | DYNAMIC_FUNCTION\" +\r\n \"| FORTRAN\" +\r\n \"| LENGTH\" +\r\n \"| MESSAGE_LENGTH | MESSAGE_OCTET_LENGTH | MESSAGE_TEXT | MORE | MUMPS\" +\r\n \"| NAME | NULLABLE | NUMBER\" +\r\n \"| PASCAL | PLI\" +\r\n \"| REPEATABLE | RETURNED_LENGTH | RETURNED_OCTET_LENGTH | RETURNED_SQLSTATE\" +\r\n \"| ROW_COUNT\" +\r\n \"| SCALE | SCHEMA_NAME | SERIALIZABLE | SERVER_NAME | SUBCLASS_ORIGIN\" +\r\n \"| TABLE_NAME | TYPE\" +\r\n \"| UNCOMMITTED | UNNAMED\" +\r\n \"| ABSOLUTE | ACTION | ADD | ALL | ALLOCATE | ALTER | AND\" +\r\n \"| ANY | ARE | AS | ASC\" +\r\n \"| ASSERTION | AT | AUTHORIZATION | AVG\" +\r\n \"| BEGIN | BETWEEN | BIT | BIT_LENGTH | BOTH | BY\" +\r\n \"| CASCADE | CASCADED | CASE | CAST | CATALOG | CHAR | CHARACTER | CHAR_LENGTH\" +\r\n \"| CHARACTER_LENGTH | CHECK | CLOSE | COALESCE | COLLATE | COLLATION\" +\r\n \"| COLUMN | COMMIT | CONNECT | CONNECTION | CONSTRAINT\" +\r\n \"| CONSTRAINTS | CONTINUE\" +\r\n \"| CONVERT | CORRESPONDING | COUNT | CREATE | CROSS | CURRENT\" +\r\n \"| CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | CURSOR\" +\r\n \"| DATE | DAY | DEALLOCATE | DEC | DECIMAL | DECLARE | DEFAULT | DEFERRABLE\" +\r\n \"| DEFERRED | DELETE | DESC | DESCRIBE | DESCRIPTOR | DIAGNOSTICS\" +\r\n \"| DISCONNECT | DISTINCT | DOMAIN | DOUBLE | DROP\" +\r\n \"| ELSE | END | END-EXEC | ESCAPE | EXCEPT | EXCEPTION\" +\r\n \"| EXEC | EXECUTE | EXISTS\" +\r\n \"| EXTERNAL | EXTRACT\" +\r\n \"| FALSE | FETCH | FIRST | FLOAT | FOR | FOREIGN | FOUND | FROM | FULL\" +\r\n \"| GET | GLOBAL | GO | GOTO | GRANT | GROUP\" +\r\n \"| HAVING | HOUR\" +\r\n \"| IDENTITY | IMMEDIATE | IN | INDICATOR | INITIALLY | INNER | INPUT\" +\r\n \"| INSENSITIVE | INSERT | INT | INTEGER | INTERSECT | INTERVAL | INTO | IS\" +\r\n \"| ISOLATION\" +\r\n \"| JOIN\" +\r\n \"| KEY\" +\r\n \"| LANGUAGE | LAST | LEADING | LEFT | LEVEL | LIKE | LOCAL | LOWER\" +\r\n \"| MATCH | MAX | MIN | MINUTE | MODULE | MONTH\" +\r\n \"| NAMES | NATIONAL | NATURAL | NCHAR | NEXT | NO | NOT | NULL\" +\r\n \"| NULLIF | NUMERIC\" +\r\n \"| OCTET_LENGTH | OF | ON | ONLY | OPEN | OPTION | OR\" +\r\n \"| ORDER | OUTER\" +\r\n \"| OUTPUT | OVERLAPS\" +\r\n \"| PAD | PARTIAL | POSITION | PRECISION | PREPARE | PRESERVE | PRIMARY\" +\r\n \"| PRIOR | PRIVILEGES | PROCEDURE | PUBLIC\" +\r\n \"| READ | REAL | REFERENCES | RELATIVE | RESTRICT | REVOKE | RIGHT\" +\r\n \"| ROLLBACK | ROWS\" +\r\n \"| SCHEMA | SCROLL | SECOND | SECTION | SELECT | SESSION | SESSION_USER | SET\" +\r\n \"| SIZE | SMALLINT | SOME | SPACE | SQL | SQLCODE | SQLERROR | SQLSTATE\" +\r\n \"| SUBSTRING | SUM | SYSTEM_USER\" +\r\n \"| TABLE | TEMPORARY | THEN | TIME | TIMESTAMP | TIMEZONE_HOUR | TIMEZONE_MINUTE\" +\r\n \"| TO | TRAILING | TRANSACTION | TRANSLATE | TRANSLATION | TRIM | TRUE\" +\r\n \"| UNION | UNIQUE | UNKNOWN | UPDATE | UPPER | USAGE | USER | USING\" +\r\n \"| VALUE | VALUES | VARCHAR | VARYING | VIEW\" +\r\n \"| WHEN | WHENEVER | WHERE | WITH | WORK | WRITE\" +\r\n \"| YEAR\" +\r\n \"| ZONE\").split(\"|,\\\\s*\");\r\n\r\n String[] nonSql92Keywords = getMetaData().getSQLKeywords().toUpperCase().split(\",\\\\s*\");\r\n\r\n sqlKeywords = new HashSet<String>();\r\n sqlKeywords.addAll(Arrays.asList(sql92Keywords));\r\n sqlKeywords.addAll(Arrays.asList(nonSql92Keywords));\r\n }\r\n\r\n return sqlKeywords;\r\n }\r\n\r\n /**\r\n * Return <code>id</code> quoted if required, otherwise return <code>id</code>\r\n *\r\n * @param id\r\n * @return\r\n * @throws SQLException\r\n */\r\n public String getQuotedIdentifier(String id) throws SQLException {\r\n // look for any character that isn't valid (then matcher.find() returns true)\r\n Matcher matcher = getInvalidIdentifierPattern().matcher(id);\r\n\r\n boolean quotesRequired = matcher.find() || getSqlKeywords().contains(id.toUpperCase());\r\n\r\n if (quotesRequired) {\r\n // name contains something that must be quoted\r\n String quote = getMetaData().getIdentifierQuoteString().trim();\r\n return quote + id + quote;\r\n }\r\n\r\n // no quoting necessary\r\n return id;\r\n }\r\n\r\n /**\r\n * Return a <code>Pattern</code> whose matcher will return <code>true</code>\r\n * when run against an identifier that contains a character that is not\r\n * acceptable by the database without being quoted.\r\n */\r\n private Pattern getInvalidIdentifierPattern() throws SQLException {\r\n if (invalidIdentifierPattern == null) {\r\n String validChars = \"a-zA-Z0-9_\";\r\n String reservedRegexChars = \"-&^\";\r\n String extraValidChars = getMetaData().getExtraNameCharacters();\r\n for (int i = 0; i < extraValidChars.length(); ++i) {\r\n char ch = extraValidChars.charAt(i);\r\n if (reservedRegexChars.indexOf(ch) >= 0)\r\n validChars += \"\\\\\";\r\n validChars += ch;\r\n }\r\n\r\n invalidIdentifierPattern = Pattern.compile(\"[^\" + validChars + \"]\");\r\n }\r\n\r\n return invalidIdentifierPattern;\r\n }\r\n\r\n /**\r\n * Replaces named parameters in <code>sql</code> with question marks and\r\n * returns appropriate matching values in the returned <code>List</code> of <code>String</code>s.\r\n *\r\n * @param sql StringBuffer input SQL with named parameters, output named params are replaced with ?'s.\r\n * @param tableName String\r\n * @return List of Strings\r\n *\r\n * @see #prepareStatement(String, String)\r\n */\r\n private List<String> getSqlParams(StringBuilder sql, String tableName) {\r\n Map<String, String> namedParams = new HashMap<String, String>();\r\n @SuppressWarnings(\"hiding\")\r\n String schema = getSchema();\r\n if (schema == null)\r\n schema = getName(); // some 'schema-less' db's treat the db name like a schema (unusual case)\r\n namedParams.put(\":schema\", schema);\r\n namedParams.put(\":owner\", schema); // alias for :schema\r\n if (tableName != null) {\r\n namedParams.put(\":table\", tableName);\r\n namedParams.put(\":view\", tableName); // alias for :table\r\n }\r\n\r\n List<String> sqlParams = new ArrayList<String>();\r\n int nextColon = sql.indexOf(\":\");\r\n while (nextColon != -1) {\r\n String paramName = new StringTokenizer(sql.substring(nextColon), \" ,\\\"')\").nextToken();\r\n String paramValue = namedParams.get(paramName);\r\n if (paramValue == null)\r\n throw new InvalidConfigurationException(\"Unexpected named parameter '\" + paramName + \"' found in SQL '\" + sql + \"'\");\r\n sqlParams.add(paramValue);\r\n sql.replace(nextColon, nextColon + paramName.length(), \"?\"); // replace with a ?\r\n nextColon = sql.indexOf(\":\", nextColon);\r\n }\r\n\r\n return sqlParams;\r\n }\r\n\r\n /**\r\n * Take the supplied XML-based metadata and update our model of the schema with it\r\n *\r\n * @param schemaMeta\r\n * @throws SQLException\r\n */\r\n private void updateFromXmlMetadata(SchemaMeta schemaMeta) throws SQLException {\r\n if (schemaMeta != null) {\r\n final Pattern excludeNone = Pattern.compile(\"[^.]\");\r\n final Properties noProps = new Properties();\r\n\r\n description = schemaMeta.getComments();\r\n\r\n // done in three passes:\r\n // 1: create any new tables\r\n // 2: add/mod columns\r\n // 3: connect\r\n\r\n // add the newly defined tables and columns first\r\n for (TableMeta tableMeta : schemaMeta.getTables()) {\r\n Table table;\r\n\r\n if (tableMeta.getRemoteSchema() != null) {\r\n table = remoteTables.get(tableMeta.getRemoteSchema() + '.' + tableMeta.getName());\r\n if (table == null) {\r\n table = addRemoteTable(tableMeta.getRemoteSchema(), tableMeta.getName(), getSchema(), null, excludeNone, excludeNone);\r\n }\r\n } else {\r\n table = tables.get(tableMeta.getName());\r\n\r\n if (table == null)\r\n table = views.get(tableMeta.getName());\r\n\r\n if (table == null) {\r\n table = new Table(Database.this, getSchema(), tableMeta.getName(), null, noProps, excludeNone, excludeNone);\r\n tables.put(table.getName(), table);\r\n }\r\n }\r\n\r\n table.update(tableMeta);\r\n }\r\n\r\n // then tie the tables together\r\n for (TableMeta tableMeta : schemaMeta.getTables()) {\r\n Table table;\r\n\r\n if (tableMeta.getRemoteSchema() != null) {\r\n table = remoteTables.get(tableMeta.getRemoteSchema() + '.' + tableMeta.getName());\r\n } else {\r\n table = tables.get(tableMeta.getName());\r\n if (table == null)\r\n table = views.get(tableMeta.getName());\r\n }\r\n\r\n table.connect(tableMeta, tables, remoteTables);\r\n }\r\n }\r\n }\r\n\r\n private void connectTables() throws SQLException {\r\n Pattern excludeColumns = Config.getInstance().getColumnExclusions();\r\n Pattern excludeIndirectColumns = Config.getInstance().getIndirectColumnExclusions();\r\n\r\n for (Table table : tables.values()) {\r\n table.connectForeignKeys(tables, excludeIndirectColumns, excludeColumns);\r\n }\r\n }\r\n\r\n /**\r\n * Single-threaded implementation of a class that creates tables\r\n */\r\n private class TableCreator {\r\n private final Pattern excludeColumns = Config.getInstance().getColumnExclusions();\r\n private final Pattern excludeIndirectColumns = Config.getInstance().getIndirectColumnExclusions();\r\n\r\n /**\r\n * Create a table and put it into <code>tables</code>\r\n */\r\n void create(BasicTableMeta tableMeta, Properties properties) throws SQLException {\r\n createImpl(tableMeta, properties);\r\n }\r\n\r\n protected void createImpl(BasicTableMeta tableMeta, Properties properties) throws SQLException {\r\n Table table = new Table(Database.this, tableMeta.schema, tableMeta.name, tableMeta.remarks, properties, excludeIndirectColumns, excludeColumns);\r\n if (tableMeta.numRows != -1) {\r\n table.setNumRows(tableMeta.numRows);\r\n }\r\n\r\n synchronized (tables) {\r\n tables.put(table.getName(), table);\r\n }\r\n\r\n if (logger.isLoggable(Level.FINE)) {\r\n logger.fine(\"Found details of table \" + table.getName());\r\n } else {\r\n System.out.print('.');\r\n }\r\n }\r\n\r\n /**\r\n * Wait for all of the tables to be created.\r\n * By default this does nothing since this implementation isn't threaded.\r\n */\r\n void join() {\r\n }\r\n }\r\n\r\n /**\r\n * Multi-threaded implementation of a class that creates tables\r\n */\r\n private class ThreadedTableCreator extends TableCreator {\r\n private final Set<Thread> threads = new HashSet<Thread>();\r\n private final int maxThreads;\r\n\r\n ThreadedTableCreator(int maxThreads) {\r\n this.maxThreads = maxThreads;\r\n }\r\n\r\n @Override\r\n void create(final BasicTableMeta tableMeta, final Properties properties) throws SQLException {\r\n Thread runner = new Thread() {\r\n @Override\r\n public void run() {\r\n try {\r\n createImpl(tableMeta, properties);\r\n } catch (SQLException exc) {\r\n exc.printStackTrace(); // nobody above us in call stack...dump it here\r\n } finally {\r\n synchronized (threads) {\r\n threads.remove(this);\r\n threads.notify();\r\n }\r\n }\r\n }\r\n };\r\n\r\n synchronized (threads) {\r\n // wait for enough 'room'\r\n while (threads.size() >= maxThreads) {\r\n try {\r\n threads.wait();\r\n } catch (InterruptedException interrupted) {\r\n }\r\n }\r\n\r\n threads.add(runner);\r\n }\r\n\r\n runner.start();\r\n }\r\n\r\n /**\r\n * Wait for all of the started threads to complete\r\n */\r\n @Override\r\n public void join() {\r\n while (true) {\r\n Thread thread;\r\n\r\n synchronized (threads) {\r\n Iterator<Thread> iter = threads.iterator();\r\n if (!iter.hasNext())\r\n break;\r\n\r\n thread = iter.next();\r\n }\r\n\r\n try {\r\n thread.join();\r\n } catch (InterruptedException exc) {\r\n }\r\n }\r\n }\r\n }\r\n}\r", "public class Table implements Comparable<Table> {\r\n private final String schema;\r\n private final String name;\r\n protected final CaseInsensitiveMap<TableColumn> columns = new CaseInsensitiveMap<TableColumn>();\r\n private final List<TableColumn> primaryKeys = new ArrayList<TableColumn>();\r\n private final CaseInsensitiveMap<ForeignKeyConstraint> foreignKeys = new CaseInsensitiveMap<ForeignKeyConstraint>();\r\n private final CaseInsensitiveMap<TableIndex> indexes = new CaseInsensitiveMap<TableIndex>();\r\n private Object id;\r\n private final Map<String, String> checkConstraints = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);\r\n private Long numRows;\r\n protected final Database db;\r\n protected final Properties properties;\r\n private String comments;\r\n private int maxChildren;\r\n private int maxParents;\r\n private final static Logger logger = Logger.getLogger(Table.class.getName());\r\n\r\n /**\r\n * Construct a table that knows everything about the database table's metadata\r\n *\r\n * @param db\r\n * @param schema\r\n * @param name\r\n * @param comments\r\n * @param properties\r\n * @param excludeIndirectColumns\r\n * @param excludeColumns\r\n * @throws SQLException\r\n */\r\n public Table(Database db, String schema, String name, String comments, Properties properties, Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {\r\n this.schema = schema;\r\n this.name = name;\r\n this.db = db;\r\n this.properties = properties;\r\n logger.fine(\"Creating \" + getClass().getSimpleName().toLowerCase() + \" \" +\r\n schema == null ? name : (schema + '.' + name));\r\n setComments(comments);\r\n initColumns(excludeIndirectColumns, excludeColumns);\r\n initIndexes();\r\n initPrimaryKeys(db.getMetaData());\r\n }\r\n\r\n /**\r\n * \"Connect\" all of this table's foreign keys to their referenced primary keys\r\n * (and, in some cases, do the reverse as well).\r\n *\r\n * @param tables\r\n * @param excludeIndirectColumns\r\n * @param excludeColumns\r\n * @throws SQLException\r\n */\r\n public void connectForeignKeys(Map<String, Table> tables, Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {\r\n ResultSet rs = null;\r\n\r\n try {\r\n rs = db.getMetaData().getImportedKeys(null, getSchema(), getName());\r\n\r\n while (rs.next()) {\r\n addForeignKey(rs.getString(\"FK_NAME\"), rs.getString(\"FKCOLUMN_NAME\"),\r\n rs.getString(\"PKTABLE_SCHEM\"), rs.getString(\"PKTABLE_NAME\"),\r\n rs.getString(\"PKCOLUMN_NAME\"),\r\n rs.getInt(\"UPDATE_RULE\"), rs.getInt(\"DELETE_RULE\"),\r\n tables, excludeIndirectColumns, excludeColumns);\r\n }\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n }\r\n\r\n // also try to find all of the 'remote' tables in other schemas that\r\n // point to our primary keys (not necessary in the normal case\r\n // as we infer this from the opposite direction)\r\n if (getSchema() != null) {\r\n try {\r\n rs = db.getMetaData().getExportedKeys(null, getSchema(), getName());\r\n\r\n while (rs.next()) {\r\n String otherSchema = rs.getString(\"FKTABLE_SCHEM\");\r\n if (!getSchema().equals(otherSchema))\r\n db.addRemoteTable(otherSchema, rs.getString(\"FKTABLE_NAME\"), getSchema(), properties, excludeIndirectColumns, excludeColumns);\r\n }\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Get the foreign keys associated with this table\r\n *\r\n * @return\r\n */\r\n public Collection<ForeignKeyConstraint> getForeignKeys() {\r\n return Collections.unmodifiableCollection(foreignKeys.values());\r\n }\r\n\r\n /**\r\n * Add a check constraint to the table\r\n * (no real details, just name and textual representation)\r\n *\r\n * @param constraintName\r\n * @param text\r\n */\r\n public void addCheckConstraint(String constraintName, String text) {\r\n checkConstraints.put(constraintName, text);\r\n }\r\n\r\n /**\r\n * @param rs ResultSet from {@link DatabaseMetaData#getImportedKeys(String, String, String)}\r\n * rs.getString(\"FK_NAME\");\r\n * rs.getString(\"FKCOLUMN_NAME\");\r\n * rs.getString(\"PKTABLE_SCHEM\");\r\n * rs.getString(\"PKTABLE_NAME\");\r\n * rs.getString(\"PKCOLUMN_NAME\");\r\n * @param tables Map\r\n * @param db\r\n * @throws SQLException\r\n */\r\n protected void addForeignKey(String fkName, String fkColName,\r\n String pkTableSchema, String pkTableName, String pkColName,\r\n int updateRule, int deleteRule,\r\n Map<String, Table> tables,\r\n Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {\r\n if (fkName == null)\r\n return;\r\n\r\n ForeignKeyConstraint foreignKey = foreignKeys.get(fkName);\r\n\r\n if (foreignKey == null) {\r\n foreignKey = new ForeignKeyConstraint(this, fkName, updateRule, deleteRule);\r\n\r\n foreignKeys.put(fkName, foreignKey);\r\n }\r\n\r\n TableColumn childColumn = getColumn(fkColName);\r\n if (childColumn != null) {\r\n foreignKey.addChildColumn(childColumn);\r\n\r\n Table parentTable = tables.get(pkTableName);\r\n String parentSchema = pkTableSchema;\r\n String baseSchema = Config.getInstance().getSchema();\r\n\r\n // if named table doesn't exist in this schema\r\n // or exists here but really referencing same named table in another schema\r\n if (parentTable == null ||\r\n (baseSchema != null && parentSchema != null &&\r\n !baseSchema.equals(parentSchema))) {\r\n parentTable = db.addRemoteTable(parentSchema, pkTableName, baseSchema,\r\n properties, excludeIndirectColumns, excludeColumns);\r\n }\r\n\r\n if (parentTable != null) {\r\n TableColumn parentColumn = parentTable.getColumn(pkColName);\r\n if (parentColumn != null) {\r\n foreignKey.addParentColumn(parentColumn);\r\n\r\n childColumn.addParent(parentColumn, foreignKey);\r\n parentColumn.addChild(childColumn, foreignKey);\r\n } else {\r\n logger.warning(\"Couldn't add FK '\" + foreignKey.getName() + \"' to table '\" + this +\r\n \"' - Column '\" + pkColName + \"' doesn't exist in table '\" + parentTable + \"'\");\r\n }\r\n } else {\r\n logger.warning(\"Couldn't add FK '\" + foreignKey.getName() + \"' to table '\" + this +\r\n \"' - Unknown Referenced Table '\" + pkTableName + \"'\");\r\n }\r\n } else {\r\n logger.warning(\"Couldn't add FK '\" + foreignKey.getName() + \"' to table '\" + this +\r\n \"' - Column '\" + fkColName + \"' doesn't exist\");\r\n }\r\n }\r\n\r\n /**\r\n * @param meta\r\n * @throws SQLException\r\n */\r\n private void initPrimaryKeys(DatabaseMetaData meta) throws SQLException {\r\n if (properties == null)\r\n return;\r\n\r\n ResultSet rs = null;\r\n\r\n try {\r\n rs = meta.getPrimaryKeys(null, getSchema(), getName());\r\n\r\n while (rs.next())\r\n setPrimaryColumn(rs);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n }\r\n }\r\n\r\n /**\r\n * @param rs\r\n * @throws SQLException\r\n */\r\n private void setPrimaryColumn(ResultSet rs) throws SQLException {\r\n String pkName = rs.getString(\"PK_NAME\");\r\n if (pkName == null)\r\n return;\r\n\r\n TableIndex index = getIndex(pkName);\r\n if (index != null) {\r\n index.setIsPrimaryKey(true);\r\n }\r\n\r\n String columnName = rs.getString(\"COLUMN_NAME\");\r\n\r\n setPrimaryColumn(getColumn(columnName));\r\n }\r\n\r\n /**\r\n * @param primaryColumn\r\n */\r\n void setPrimaryColumn(TableColumn primaryColumn) {\r\n primaryKeys.add(primaryColumn);\r\n }\r\n\r\n /**\r\n * @param excludeIndirectColumns\r\n * @param excludeColumns\r\n * @throws SQLException\r\n */\r\n private void initColumns(Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {\r\n ResultSet rs = null;\r\n\r\n synchronized (Table.class) {\r\n try {\r\n rs = db.getMetaData().getColumns(null, getSchema(), getName(), \"%\");\r\n\r\n while (rs.next())\r\n addColumn(rs, excludeIndirectColumns, excludeColumns);\r\n } catch (SQLException exc) {\r\n class ColumnInitializationFailure extends SQLException {\r\n private static final long serialVersionUID = 1L;\r\n\r\n public ColumnInitializationFailure(SQLException failure) {\r\n super(\"Failed to collect column details for \" + (isView() ? \"view\" : \"table\") + \" '\" + getName() + \"' in schema '\" + getSchema() + \"'\");\r\n initCause(failure);\r\n }\r\n }\r\n\r\n throw new ColumnInitializationFailure(exc);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n }\r\n }\r\n\r\n if (!isView() && !isRemote())\r\n initColumnAutoUpdate(false);\r\n }\r\n\r\n /**\r\n * @param forceQuotes\r\n * @throws SQLException\r\n */\r\n private void initColumnAutoUpdate(boolean forceQuotes) throws SQLException {\r\n ResultSet rs = null;\r\n PreparedStatement stmt = null;\r\n\r\n // we've got to get a result set with all the columns in it\r\n // so we can ask if the columns are auto updated\r\n // Ugh!!! Should have been in DatabaseMetaData instead!!!\r\n StringBuilder sql = new StringBuilder(\"select * from \");\r\n if (getSchema() != null) {\r\n sql.append(getSchema());\r\n sql.append('.');\r\n }\r\n\r\n if (forceQuotes) {\r\n String quote = db.getMetaData().getIdentifierQuoteString().trim();\r\n sql.append(quote + getName() + quote);\r\n } else\r\n sql.append(db.getQuotedIdentifier(getName()));\r\n\r\n sql.append(\" where 0 = 1\");\r\n\r\n try {\r\n stmt = db.getMetaData().getConnection().prepareStatement(sql.toString());\r\n rs = stmt.executeQuery();\r\n\r\n ResultSetMetaData rsMeta = rs.getMetaData();\r\n for (int i = rsMeta.getColumnCount(); i > 0; --i) {\r\n TableColumn column = getColumn(rsMeta.getColumnName(i));\r\n column.setIsAutoUpdated(rsMeta.isAutoIncrement(i));\r\n }\r\n } catch (SQLException exc) {\r\n if (forceQuotes) {\r\n // don't completely choke just because we couldn't do this....\r\n logger.warning(\"Failed to determine auto increment status: \" + exc);\r\n logger.warning(\"SQL: \" + sql.toString());\r\n } else {\r\n initColumnAutoUpdate(true);\r\n }\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n\r\n /**\r\n * @param rs - from {@link DatabaseMetaData#getColumns(String, String, String, String)}\r\n * @param excludeIndirectColumns\r\n * @param excludeColumns\r\n * @throws SQLException\r\n */\r\n protected void addColumn(ResultSet rs, Pattern excludeIndirectColumns, Pattern excludeColumns) throws SQLException {\r\n String columnName = rs.getString(\"COLUMN_NAME\");\r\n\r\n if (columnName == null)\r\n return;\r\n\r\n if (getColumn(columnName) == null) {\r\n TableColumn column = new TableColumn(this, rs, excludeIndirectColumns, excludeColumns);\r\n\r\n columns.put(column.getName(), column);\r\n }\r\n }\r\n\r\n /**\r\n * Add a column that's defined in xml metadata.\r\n * Assumes that a column named colMeta.getName() doesn't already exist in <code>columns</code>.\r\n * @param colMeta\r\n * @return\r\n */\r\n protected TableColumn addColumn(TableColumnMeta colMeta) {\r\n TableColumn column = new TableColumn(this, colMeta);\r\n\r\n columns.put(column.getName(), column);\r\n\r\n return column;\r\n }\r\n\r\n /**\r\n * Initialize index information\r\n *\r\n * @throws SQLException\r\n */\r\n private void initIndexes() throws SQLException {\r\n if (isView() || isRemote())\r\n return;\r\n\r\n // first try to initialize using the index query spec'd in the .properties\r\n // do this first because some DB's (e.g. Oracle) do 'bad' things with getIndexInfo()\r\n // (they try to do a DDL analyze command that has some bad side-effects)\r\n if (initIndexes(properties.getProperty(\"selectIndexesSql\")))\r\n return;\r\n\r\n // couldn't, so try the old fashioned approach\r\n ResultSet rs = null;\r\n\r\n try {\r\n rs = db.getMetaData().getIndexInfo(null, getSchema(), getName(), false, true);\r\n\r\n while (rs.next()) {\r\n if (rs.getShort(\"TYPE\") != DatabaseMetaData.tableIndexStatistic)\r\n addIndex(rs);\r\n }\r\n } catch (SQLException exc) {\r\n logger.warning(\"Unable to extract index info for table '\" + getName() + \"' in schema '\" + getSchema() + \"': \" + exc);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n }\r\n }\r\n\r\n /**\r\n * Try to initialize index information based on the specified SQL\r\n *\r\n * @return boolean <code>true</code> if it worked, otherwise <code>false</code>\r\n */\r\n private boolean initIndexes(String selectIndexesSql) {\r\n if (selectIndexesSql == null)\r\n return false;\r\n\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = db.prepareStatement(selectIndexesSql, getName());\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n if (rs.getShort(\"TYPE\") != DatabaseMetaData.tableIndexStatistic)\r\n addIndex(rs);\r\n }\r\n } catch (SQLException sqlException) {\r\n logger.warning(\"Failed to query index information with SQL: \" + selectIndexesSql);\r\n logger.warning(sqlException.toString());\r\n return false;\r\n } finally {\r\n if (rs != null) {\r\n try {\r\n rs.close();\r\n } catch (Exception exc) {\r\n exc.printStackTrace();\r\n }\r\n }\r\n if (stmt != null) {\r\n try {\r\n stmt.close();\r\n } catch (Exception exc) {\r\n exc.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * @param indexName\r\n * @return\r\n */\r\n public TableIndex getIndex(String indexName) {\r\n return indexes.get(indexName);\r\n }\r\n\r\n /**\r\n * @param rs\r\n * @throws SQLException\r\n */\r\n private void addIndex(ResultSet rs) throws SQLException {\r\n String indexName = rs.getString(\"INDEX_NAME\");\r\n\r\n if (indexName == null)\r\n return;\r\n\r\n TableIndex index = getIndex(indexName);\r\n\r\n if (index == null) {\r\n index = new TableIndex(rs);\r\n\r\n indexes.put(index.getName(), index);\r\n }\r\n\r\n index.addColumn(getColumn(rs.getString(\"COLUMN_NAME\")), rs.getString(\"ASC_OR_DESC\"));\r\n }\r\n\r\n /**\r\n * Returns the schema that the table belongs to\r\n *\r\n * @return\r\n */\r\n public String getSchema() {\r\n return schema;\r\n }\r\n\r\n /**\r\n * Returns the name of the table\r\n *\r\n * @return\r\n */\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n /**\r\n * Object IDs are useful for tables such as DB/2 that many times\r\n * give error messages based on object ID and not name\r\n *\r\n * @param id\r\n */\r\n public void setId(Object id) {\r\n this.id = id;\r\n }\r\n\r\n /**\r\n * @see #setId(Object)\r\n *\r\n * @return\r\n */\r\n public Object getId() {\r\n return id;\r\n }\r\n\r\n /**\r\n * Returns the check constraints associated with this table\r\n *\r\n * @return\r\n */\r\n public Map<String, String> getCheckConstraints() {\r\n return checkConstraints;\r\n }\r\n\r\n /**\r\n * Returns the indexes that are applied to this table\r\n *\r\n * @return\r\n */\r\n public Set<TableIndex> getIndexes() {\r\n return new HashSet<TableIndex>(indexes.values());\r\n }\r\n\r\n /**\r\n * Returns a collection of table columns that have been identified as \"primary\"\r\n *\r\n * @return\r\n */\r\n public List<TableColumn> getPrimaryColumns() {\r\n return primaryKeys;\r\n }\r\n\r\n /**\r\n * @return Comments associated with this table, or <code>null</code> if none.\r\n */\r\n public String getComments() {\r\n return comments;\r\n }\r\n\r\n /**\r\n * Sets the comments that are associated with this table\r\n *\r\n * @param comments\r\n */\r\n public void setComments(String comments) {\r\n String cmts = (comments == null || comments.trim().length() == 0) ? null : comments.trim();\r\n\r\n // MySQL's InnoDB engine does some insane crap of storing erroneous details in\r\n // with table comments. Here I attempt to strip the \"crap\" out without impacting\r\n // other databases. Ideally this should happen in selectColumnCommentsSql (and\r\n // therefore isolate it to MySQL), but it's a bit too complex to do cleanly.\r\n if (cmts != null) {\r\n int crapIndex = cmts.indexOf(\"; InnoDB free: \");\r\n if (crapIndex == -1)\r\n crapIndex = cmts.startsWith(\"InnoDB free: \") ? 0 : -1;\r\n if (crapIndex != -1) {\r\n cmts = cmts.substring(0, crapIndex).trim();\r\n cmts = cmts.length() == 0 ? null : cmts;\r\n }\r\n }\r\n\r\n this.comments = cmts;\r\n }\r\n\r\n /**\r\n * Returns the {@link TableColumn} with the given name, or <code>null</code>\r\n * if it doesn't exist\r\n *\r\n * @param columnName\r\n * @return\r\n */\r\n public TableColumn getColumn(String columnName) {\r\n return columns.get(columnName);\r\n }\r\n\r\n /**\r\n * Returns <code>List</code> of <code>TableColumn</code>s in ascending column number order.\r\n *\r\n * @return\r\n */\r\n public List<TableColumn> getColumns() {\r\n Set<TableColumn> sorted = new TreeSet<TableColumn>(new ByColumnIdComparator());\r\n sorted.addAll(columns.values());\r\n return new ArrayList<TableColumn>(sorted);\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this table references no other tables..<p/>\r\n * Used in dependency analysis.\r\n * @return\r\n */\r\n public boolean isRoot() {\r\n for (TableColumn column : columns.values()) {\r\n if (column.isForeignKey()) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this table is referenced by no other tables.<p/>\r\n * Used in dependency analysis.\r\n * @return\r\n */\r\n public boolean isLeaf() {\r\n for (TableColumn column : columns.values()) {\r\n if (!column.getChildren().isEmpty()) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the maximum number of parents that this table has had before\r\n * any had been removed during dependency analysis\r\n *\r\n * @return\r\n */\r\n public int getMaxParents() {\r\n return maxParents;\r\n }\r\n\r\n /**\r\n * Notification that's called to indicate that a parent has been added to\r\n * this table\r\n */\r\n public void addedParent() {\r\n maxParents++;\r\n }\r\n\r\n /**\r\n * \"Unlink\" all of the parent tables from this table\r\n */\r\n public void unlinkParents() {\r\n for (TableColumn column : columns.values()) {\r\n column.unlinkParents();\r\n }\r\n }\r\n\r\n /**\r\n * Returns the maximum number of children that this table has had before\r\n * any had been removed during dependency analysis\r\n *\r\n * @return\r\n */\r\n public int getMaxChildren() {\r\n return maxChildren;\r\n }\r\n\r\n /**\r\n * Notification that's called to indicate that a child has been added to\r\n * this table\r\n */\r\n public void addedChild() {\r\n maxChildren++;\r\n }\r\n\r\n /**\r\n * \"Unlink\" all of the child tables from this table\r\n */\r\n public void unlinkChildren() {\r\n for (TableColumn column : columns.values()) {\r\n column.unlinkChildren();\r\n }\r\n }\r\n\r\n /**\r\n * Remove a single self referencing constraint if one exists.\r\n *\r\n * @return\r\n */\r\n public ForeignKeyConstraint removeSelfReferencingConstraint() {\r\n return remove(getSelfReferencingConstraint());\r\n }\r\n\r\n /**\r\n * Remove the specified {@link ForeignKeyConstraint} from this table.<p>\r\n *\r\n * This is a more drastic removal solution that was proposed by Remke Rutgers\r\n *\r\n * @param constraint\r\n */\r\n private ForeignKeyConstraint remove(ForeignKeyConstraint constraint) {\r\n if (constraint != null) {\r\n for (int i = 0; i < constraint.getChildColumns().size(); i++) {\r\n TableColumn childColumn = constraint.getChildColumns().get(i);\r\n TableColumn parentColumn = constraint.getParentColumns().get(i);\r\n childColumn.removeParent(parentColumn);\r\n parentColumn.removeChild(childColumn);\r\n }\r\n }\r\n return constraint;\r\n }\r\n\r\n /**\r\n * Return a self referencing constraint if one exists\r\n *\r\n * @return\r\n */\r\n private ForeignKeyConstraint getSelfReferencingConstraint() {\r\n for (TableColumn column : columns.values()) {\r\n for (TableColumn parentColumn : column.getParents()) {\r\n if (compareTo(parentColumn.getTable()) == 0) {\r\n return column.getParentConstraint(parentColumn);\r\n }\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Remove any non-real foreign keys\r\n *\r\n * @return\r\n */\r\n public List<ForeignKeyConstraint> removeNonRealForeignKeys() {\r\n List<ForeignKeyConstraint> nonReals = new ArrayList<ForeignKeyConstraint>();\r\n\r\n for (TableColumn column : columns.values()) {\r\n for (TableColumn parentColumn : column.getParents()) {\r\n ForeignKeyConstraint constraint = column.getParentConstraint(parentColumn);\r\n if (constraint != null && !constraint.isReal()) {\r\n nonReals.add(constraint);\r\n }\r\n }\r\n }\r\n\r\n // remove constraints outside of above loop to prevent\r\n // concurrent modification exceptions while iterating\r\n for (ForeignKeyConstraint constraint : nonReals) {\r\n remove(constraint);\r\n }\r\n\r\n return nonReals;\r\n }\r\n\r\n /**\r\n * Returns the number of tables that reference this table\r\n *\r\n * @return\r\n */\r\n public int getNumChildren() {\r\n int numChildren = 0;\r\n\r\n for (TableColumn column : columns.values()) {\r\n numChildren += column.getChildren().size();\r\n }\r\n\r\n return numChildren;\r\n }\r\n\r\n /**\r\n * Returns the number of non-implied children\r\n * @return\r\n */\r\n public int getNumNonImpliedChildren() {\r\n int numChildren = 0;\r\n\r\n for (TableColumn column : columns.values()) {\r\n for (TableColumn childColumn : column.getChildren()) {\r\n if (!column.getChildConstraint(childColumn).isImplied())\r\n ++numChildren;\r\n }\r\n }\r\n\r\n return numChildren;\r\n }\r\n\r\n /**\r\n * Returns the number of tables that are referenced by this table\r\n *\r\n * @return\r\n */\r\n public int getNumParents() {\r\n int numParents = 0;\r\n\r\n for (TableColumn column : columns.values()) {\r\n numParents += column.getParents().size();\r\n }\r\n\r\n return numParents;\r\n }\r\n\r\n /**\r\n * Returns the number of non-implied parents\r\n *\r\n * @return\r\n */\r\n public int getNumNonImpliedParents() {\r\n int numParents = 0;\r\n\r\n for (TableColumn column : columns.values()) {\r\n for (TableColumn parentColumn : column.getParents()) {\r\n if (!column.getParentConstraint(parentColumn).isImplied())\r\n ++numParents;\r\n }\r\n }\r\n\r\n return numParents;\r\n }\r\n\r\n /**\r\n * Remove one foreign key constraint.\r\n *\r\n * <p/>Used during dependency analysis phase.\r\n *\r\n * @return\r\n */\r\n public ForeignKeyConstraint removeAForeignKeyConstraint() {\r\n @SuppressWarnings(\"hiding\")\r\n final List<TableColumn> columns = getColumns();\r\n int numParents = 0;\r\n int numChildren = 0;\r\n // remove either a child or parent, choosing which based on which has the\r\n // least number of foreign key associations (when either gets to zero then\r\n // the table can be pruned)\r\n for (TableColumn column : columns) {\r\n numParents += column.getParents().size();\r\n numChildren += column.getChildren().size();\r\n }\r\n\r\n for (TableColumn column : columns) {\r\n ForeignKeyConstraint constraint;\r\n if (numParents <= numChildren)\r\n constraint = column.removeAParentFKConstraint();\r\n else\r\n constraint = column.removeAChildFKConstraint();\r\n if (constraint != null)\r\n return constraint;\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this is a view, <code>false</code> otherwise\r\n *\r\n * @return\r\n */\r\n public boolean isView() {\r\n return false;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this table is remote (in another schema), <code>false</code> otherwise\r\n * @return\r\n */\r\n public boolean isRemote() {\r\n return false;\r\n }\r\n\r\n /**\r\n * If this is a view it returns the SQL used to create the view (if it's available).\r\n * <code>null</code> if it's not a view or the SQL isn't available.\r\n * @return\r\n * @see #isView()\r\n */\r\n public String getViewSql() {\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns the number of rows contained in this table, or -1 if unable to determine\r\n * the number of rows.\r\n *\r\n * @return\r\n */\r\n public long getNumRows() {\r\n if (numRows == null) {\r\n numRows = Config.getInstance().isNumRowsEnabled() ? fetchNumRows() : -1;\r\n }\r\n\r\n return numRows;\r\n }\r\n\r\n /**\r\n * Explicitly set the number of rows in this table\r\n *\r\n * @param numRows\r\n */\r\n public void setNumRows(long numRows) {\r\n this.numRows = numRows;\r\n }\r\n\r\n /**\r\n * Fetch the number of rows contained in this table.\r\n *\r\n * returns -1 if unable to successfully fetch the row count\r\n *\r\n * @param db Database\r\n * @return long\r\n * @throws SQLException\r\n */\r\n protected long fetchNumRows() {\r\n if (properties == null) // some \"meta\" tables don't have associated properties\r\n return 0;\r\n\r\n SQLException originalFailure = null;\r\n\r\n String sql = properties.getProperty(\"selectRowCountSql\");\r\n if (sql != null) {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n\r\n try {\r\n stmt = db.prepareStatement(sql, getName());\r\n rs = stmt.executeQuery();\r\n\r\n while (rs.next()) {\r\n return rs.getLong(\"row_count\");\r\n }\r\n } catch (SQLException sqlException) {\r\n // don't die just because this failed\r\n \toriginalFailure = sqlException;\r\n } finally {\r\n if (rs != null) {\r\n try {\r\n rs.close();\r\n } catch (SQLException exc) {}\r\n }\r\n if (stmt != null) {\r\n try {\r\n stmt.close();\r\n } catch (SQLException exc) {}\r\n }\r\n }\r\n }\r\n\r\n // if we get here then we either didn't have custom SQL or it didn't work\r\n try {\r\n // '*' should work best for the majority of cases\r\n return fetchNumRows(\"count(*)\", false);\r\n } catch (SQLException try2Exception) {\r\n try {\r\n // except nested tables...try using '1' instead\r\n return fetchNumRows(\"count(1)\", false);\r\n } catch (SQLException try3Exception) {\r\n logger.warning(\"Unable to extract the number of rows for table \" + getName() + \", using '-1'\");\r\n if (originalFailure != null)\r\n logger.warning(originalFailure.toString());\r\n logger.warning(try2Exception.toString());\r\n logger.warning(try3Exception.toString());\r\n return -1;\r\n }\r\n }\r\n }\r\n\r\n protected long fetchNumRows(String clause, boolean forceQuotes) throws SQLException {\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n StringBuilder sql = new StringBuilder(\"select \");\r\n sql.append(clause);\r\n sql.append(\" from \");\r\n if (getSchema() != null) {\r\n sql.append(getSchema());\r\n sql.append('.');\r\n }\r\n\r\n if (forceQuotes) {\r\n String quote = db.getMetaData().getIdentifierQuoteString().trim();\r\n sql.append(quote + getName() + quote);\r\n } else\r\n sql.append(db.getQuotedIdentifier(getName()));\r\n\r\n try {\r\n stmt = db.getConnection().prepareStatement(sql.toString());\r\n rs = stmt.executeQuery();\r\n while (rs.next()) {\r\n return rs.getLong(1);\r\n }\r\n return -1;\r\n } catch (SQLException exc) {\r\n if (forceQuotes) // we tried with and w/o quotes...fail this attempt\r\n throw exc;\r\n\r\n return fetchNumRows(clause, true);\r\n } finally {\r\n if (rs != null)\r\n rs.close();\r\n if (stmt != null)\r\n stmt.close();\r\n }\r\n }\r\n\r\n /**\r\n * Update the table with the specified XML-derived metadata\r\n *\r\n * @param tableMeta\r\n */\r\n public void update(TableMeta tableMeta) {\r\n String newComments = tableMeta.getComments();\r\n if (newComments != null) {\r\n comments = newComments;\r\n }\r\n\r\n for (TableColumnMeta colMeta : tableMeta.getColumns()) {\r\n TableColumn col = getColumn(colMeta.getName());\r\n if (col == null) {\r\n if (tableMeta.getRemoteSchema() == null) {\r\n logger.warning(\"Unrecognized column '\" + colMeta.getName() + \"' for table '\" + getName() + '\\'');\r\n continue;\r\n }\r\n\r\n col = addColumn(colMeta);\r\n }\r\n\r\n // update the column with the changes\r\n col.update(colMeta);\r\n }\r\n }\r\n\r\n /**\r\n * Same as {@link #connectForeignKeys(Map, Database, Properties, Pattern, Pattern)},\r\n * but uses XML-based metadata\r\n *\r\n * @param tableMeta\r\n * @param tables\r\n * @param remoteTables\r\n */\r\n public void connect(TableMeta tableMeta, Map<String, Table> tables, Map<String, Table> remoteTables) {\r\n for (TableColumnMeta colMeta : tableMeta.getColumns()) {\r\n TableColumn col = getColumn(colMeta.getName());\r\n\r\n // go thru the new foreign key defs and associate them with our columns\r\n for (ForeignKeyMeta fk : colMeta.getForeignKeys()) {\r\n Table parent = fk.getRemoteSchema() == null ? tables.get(fk.getTableName())\r\n : remoteTables.get(fk.getRemoteSchema() + '.' + fk.getTableName());\r\n if (parent != null) {\r\n TableColumn parentColumn = parent.getColumn(fk.getColumnName());\r\n\r\n if (parentColumn == null) {\r\n logger.warning(parent.getName() + '.' + fk.getColumnName() + \" doesn't exist\");\r\n } else {\r\n /**\r\n * Merely instantiating a foreign key constraint ties it\r\n * into its parent and child columns (& therefore their tables)\r\n */\r\n new ForeignKeyConstraint(parentColumn, col) {\r\n @Override\r\n public String getName() {\r\n return \"Defined in XML\";\r\n }\r\n };\r\n }\r\n } else {\r\n logger.warning(\"Undefined table '\" + fk.getTableName() + \"' referenced by '\" + getName() + '.' + col.getName() + '\\'');\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return getName();\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if this table has no relationships\r\n *\r\n * @param withImpliedRelationships boolean\r\n * @return boolean\r\n */\r\n public boolean isOrphan(boolean withImpliedRelationships) {\r\n if (withImpliedRelationships)\r\n return getMaxParents() == 0 && getMaxChildren() == 0;\r\n\r\n for (TableColumn column : columns.values()) {\r\n for (TableColumn parentColumn : column.getParents()) {\r\n if (!column.getParentConstraint(parentColumn).isImplied())\r\n return false;\r\n }\r\n for (TableColumn childColumn : column.getChildren()) {\r\n if (!column.getChildConstraint(childColumn).isImplied())\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Compare this table to another table.\r\n * Results are based on 1: identity, 2: table name, 3: schema name<p/>\r\n *\r\n * This implementation was put in place to deal with analyzing multiple\r\n * schemas that contain identically named tables.\r\n *\r\n * @see {@link Comparable#compareTo(Object)}\r\n */\r\n public int compareTo(Table other) {\r\n if (other == this) // fast way out\r\n return 0;\r\n\r\n int rc = getName().compareToIgnoreCase(other.getName());\r\n if (rc == 0) {\r\n // should only get here if we're dealing with cross-schema references (rare)\r\n String ours = getSchema();\r\n String theirs = other.getSchema();\r\n if (ours != null && theirs != null)\r\n rc = ours.compareToIgnoreCase(theirs);\r\n else if (ours == null)\r\n rc = -1;\r\n else\r\n rc = 1;\r\n }\r\n\r\n return rc;\r\n }\r\n\r\n /**\r\n * Implementation of {@link Comparator} that sorts {@link TableColumn}s\r\n * by {@link TableColumn#getId() ID} (ignored if <code>null</code>)\r\n * followed by {@link TableColumn#getName() Name}.\r\n */\r\n private static class ByColumnIdComparator implements Comparator<TableColumn> {\r\n public int compare(TableColumn column1, TableColumn column2) {\r\n if (column1.getId() == null || column2.getId() == null)\r\n return column1.getName().compareToIgnoreCase(column2.getName());\r\n if (column1.getId() instanceof Number)\r\n return ((Number)column1.getId()).intValue() - ((Number)column2.getId()).intValue();\r\n return column1.getId().toString().compareToIgnoreCase(column2.getId().toString());\r\n }\r\n }\r\n}\r", "public class Dot {\r\n private static Dot instance = new Dot();\r\n private final Version version;\r\n private final Version supportedVersion = new Version(\"2.2.1\");\r\n private final Version badVersion = new Version(\"2.4\");\r\n private final String lineSeparator = System.getProperty(\"line.separator\");\r\n private String dotExe;\r\n private String format = \"png\";\r\n private String renderer;\r\n private final Set<String> validatedRenderers = Collections.synchronizedSet(new HashSet<String>());\r\n private final Set<String> invalidatedRenderers = Collections.synchronizedSet(new HashSet<String>());\r\n\r\n private Dot() {\r\n String versionText = null;\r\n // dot -V should return something similar to:\r\n // dot version 2.8 (Fri Feb 3 22:38:53 UTC 2006)\r\n // or sometimes something like:\r\n // dot - Graphviz version 2.9.20061004.0440 (Wed Oct 4 21:01:52 GMT 2006)\r\n String[] dotCommand = new String[] { getExe(), \"-V\" };\r\n\r\n try {\r\n Process process = Runtime.getRuntime().exec(dotCommand);\r\n BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));\r\n String versionLine = reader.readLine();\r\n\r\n // look for a number followed numbers or dots\r\n Matcher matcher = Pattern.compile(\"[0-9][0-9.]+\").matcher(versionLine);\r\n if (matcher.find()) {\r\n versionText = matcher.group();\r\n } else {\r\n if (Config.getInstance().isHtmlGenerationEnabled()) {\r\n System.err.println();\r\n System.err.println(\"Invalid dot configuration detected. '\" +\r\n getDisplayableCommand(dotCommand) + \"' returned:\");\r\n System.err.println(\" \" + versionLine);\r\n }\r\n }\r\n } catch (Exception validDotDoesntExist) {\r\n if (Config.getInstance().isHtmlGenerationEnabled()) {\r\n System.err.println(\"Failed to query Graphviz version information\");\r\n System.err.println(\" with: \" + getDisplayableCommand(dotCommand));\r\n System.err.println(\" \" + validDotDoesntExist);\r\n }\r\n }\r\n\r\n version = new Version(versionText);\r\n }\r\n\r\n public static Dot getInstance() {\r\n return instance;\r\n }\r\n\r\n public boolean exists() {\r\n return version.toString() != null;\r\n }\r\n\r\n public Version getVersion() {\r\n return version;\r\n }\r\n\r\n public boolean isValid() {\r\n return exists() && (getVersion().equals(supportedVersion) || getVersion().compareTo(badVersion) > 0);\r\n }\r\n\r\n public String getSupportedVersions() {\r\n return \"dot version \" + supportedVersion + \" or versions greater than \" + badVersion;\r\n }\r\n\r\n public boolean supportsCenteredEastWestEdges() {\r\n return getVersion().compareTo(new Version(\"2.6\")) >= 0;\r\n }\r\n\r\n /**\r\n * Set the image format to generate. Defaults to <code>png</code>.\r\n * See <a href='http://www.graphviz.org/doc/info/output.html'>http://www.graphviz.org/doc/info/output.html</a>\r\n * for valid formats.\r\n *\r\n * @param format image format to generate\r\n */\r\n public void setFormat(String format) {\r\n this.format = format;\r\n }\r\n\r\n /**\r\n * @see #setFormat(String)\r\n * @return\r\n */\r\n public String getFormat() {\r\n return format;\r\n }\r\n\r\n /**\r\n * Returns true if the installed dot requires specifying :gd as a renderer.\r\n * This was added when Win 2.15 came out because it defaulted to Cairo, which produces\r\n * better quality output, but at a significant speed and size penalty.<p>\r\n *\r\n * The intent of this property is to determine if it's ok to tack \":gd\" to\r\n * the format specifier. Earlier versions didn't require it and didn't know\r\n * about the option.\r\n *\r\n * @return\r\n */\r\n public boolean requiresGdRenderer() {\r\n return getVersion().compareTo(new Version(\"2.12\")) >= 0 && supportsRenderer(\":gd\");\r\n }\r\n\r\n /**\r\n * Set the renderer to use for the -Tformat[:renderer[:formatter]] dot option as specified\r\n * at <a href='http://www.graphviz.org/doc/info/command.html'>\r\n * http://www.graphviz.org/doc/info/command.html</a> where \"format\" is specified by\r\n * {@link #setFormat(String)}<p>\r\n * Note that the leading \":\" is required while :formatter is optional.\r\n *\r\n * @param renderer\r\n */\r\n public void setRenderer(String renderer) {\r\n this.renderer = renderer;\r\n }\r\n\r\n public String getRenderer() {\r\n return renderer != null && supportsRenderer(renderer) ? renderer\r\n : (requiresGdRenderer() ? \":gd\" : \"\");\r\n }\r\n\r\n /**\r\n * If <code>true</code> then generate output of \"higher quality\"\r\n * than the default (\"lower quality\").\r\n * Note that the default is intended to be \"lower quality\",\r\n * but various installations of Graphviz may have have different abilities.\r\n * That is, some might not have the \"lower quality\" libraries and others might\r\n * not have the \"higher quality\" libraries.\r\n */\r\n public void setHighQuality(boolean highQuality) {\r\n if (highQuality && supportsRenderer(\":cairo\")) {\r\n setRenderer(\":cairo\");\r\n } else if (supportsRenderer(\":gd\")) {\r\n setRenderer(\":gd\");\r\n }\r\n }\r\n\r\n /**\r\n * @see #setHighQuality(boolean)\r\n */\r\n public boolean isHighQuality() {\r\n return getRenderer().indexOf(\":cairo\") != -1;\r\n }\r\n\r\n /**\r\n * Returns <code>true</code> if the specified renderer is supported.\r\n * See {@link #setRenderer(String)} for renderer details.\r\n *\r\n * @param renderer\r\n * @return\r\n */\r\n public boolean supportsRenderer(@SuppressWarnings(\"hiding\") String renderer) {\r\n if (!exists())\r\n return false;\r\n\r\n if (validatedRenderers.contains(renderer))\r\n return true;\r\n\r\n if (invalidatedRenderers.contains(renderer))\r\n return false;\r\n\r\n try {\r\n String[] dotCommand = new String[] {\r\n getExe(),\r\n \"-T\" + getFormat() + ':'\r\n };\r\n Process process = Runtime.getRuntime().exec(dotCommand);\r\n BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream()));\r\n String line;\r\n while ((line = errors.readLine()) != null) {\r\n if (line.contains(getFormat() + renderer)) {\r\n validatedRenderers.add(renderer);\r\n }\r\n }\r\n process.waitFor();\r\n } catch (Exception exc) {\r\n exc.printStackTrace();\r\n }\r\n\r\n if (!validatedRenderers.contains(renderer)) {\r\n //System.err.println(\"\\nFailed to validate \" + getFormat() + \" renderer '\" + renderer + \"'. Reverting to detault renderer for \" + getFormat() + '.');\r\n invalidatedRenderers.add(renderer);\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the executable to use to run dot\r\n *\r\n * @return\r\n */\r\n private String getExe() {\r\n if (dotExe == null)\r\n {\r\n File gv = Config.getInstance().getGraphvizDir();\r\n\r\n if (gv == null) {\r\n // default to finding dot in the PATH\r\n dotExe = \"dot\";\r\n } else {\r\n // pull dot from the Graphviz bin directory specified\r\n dotExe = new File(new File(gv, \"bin\"), \"dot\").toString();\r\n }\r\n }\r\n\r\n return dotExe;\r\n }\r\n\r\n /**\r\n * Using the specified .dot file generates an image returning the image's image map.\r\n */\r\n public String generateDiagram(File dotFile, File diagramFile) throws DotFailure {\r\n StringBuilder mapBuffer = new StringBuilder(1024);\r\n\r\n BufferedReader mapReader = null;\r\n // this one is for executing. it can (hopefully) deal with funky things in filenames.\r\n String[] dotCommand = new String[] {\r\n getExe(),\r\n \"-T\" + getFormat() + getRenderer(),\r\n dotFile.toString(),\r\n \"-o\" + diagramFile,\r\n \"-Tcmapx\"\r\n };\r\n // this one is for display purposes ONLY.\r\n String commandLine = getDisplayableCommand(dotCommand);\r\n\r\n try {\r\n Process process = Runtime.getRuntime().exec(dotCommand);\r\n new ProcessOutputReader(commandLine, process.getErrorStream()).start();\r\n mapReader = new BufferedReader(new InputStreamReader(process.getInputStream()));\r\n String line;\r\n while ((line = mapReader.readLine()) != null) {\r\n mapBuffer.append(line);\r\n mapBuffer.append(lineSeparator);\r\n }\r\n int rc = process.waitFor();\r\n if (rc != 0)\r\n throw new DotFailure(\"'\" + commandLine + \"' failed with return code \" + rc);\r\n if (!diagramFile.exists())\r\n throw new DotFailure(\"'\" + commandLine + \"' failed to create output file\");\r\n\r\n // dot generates post-HTML 4.0.1 output...convert trailing />'s to >'s\r\n return mapBuffer.toString().replace(\"/>\", \">\");\r\n } catch (InterruptedException interrupted) {\r\n throw new RuntimeException(interrupted);\r\n } catch (DotFailure failed) {\r\n diagramFile.delete();\r\n throw failed;\r\n } catch (IOException failed) {\r\n diagramFile.delete();\r\n throw new DotFailure(\"'\" + commandLine + \"' failed with exception \" + failed);\r\n } finally {\r\n if (mapReader != null) {\r\n try {\r\n mapReader.close();\r\n } catch (IOException ignore) {}\r\n }\r\n }\r\n }\r\n\r\n public class DotFailure extends IOException {\r\n private static final long serialVersionUID = 3833743270181351987L;\r\n\r\n public DotFailure(String msg) {\r\n super(msg);\r\n }\r\n }\r\n\r\n private static String getDisplayableCommand(String[] command) {\r\n StringBuilder displayable = new StringBuilder();\r\n for (int i = 0; i < command.length; ++i) {\r\n displayable.append(command[i]);\r\n if (i + 1 < command.length)\r\n displayable.append(' ');\r\n }\r\n return displayable.toString();\r\n }\r\n\r\n private static class ProcessOutputReader extends Thread {\r\n private final BufferedReader processReader;\r\n private final String command;\r\n\r\n ProcessOutputReader(String command, InputStream processStream) {\r\n processReader = new BufferedReader(new InputStreamReader(processStream));\r\n this.command = command;\r\n setDaemon(true);\r\n }\r\n\r\n @Override\r\n public void run() {\r\n try {\r\n String line;\r\n while ((line = processReader.readLine()) != null) {\r\n // don't report port id unrecognized or unrecognized port\r\n if (line.indexOf(\"unrecognized\") == -1 && line.indexOf(\"port\") == -1)\r\n System.err.println(command + \": \" + line);\r\n }\r\n } catch (IOException ioException) {\r\n ioException.printStackTrace();\r\n } finally {\r\n try {\r\n processReader.close();\r\n } catch (Exception exc) {\r\n exc.printStackTrace(); // shouldn't ever get here...but...\r\n }\r\n }\r\n }\r\n }\r\n}", "public static class DotNodeConfig {\r\n private final boolean showColumns;\r\n private boolean showTrivialColumns;\r\n private final boolean showColumnDetails;\r\n private boolean showImpliedRelationships;\r\n\r\n /**\r\n * Nothing but table name and counts are displayed\r\n */\r\n public DotNodeConfig() {\r\n showColumns = showTrivialColumns = showColumnDetails = showImpliedRelationships = false;\r\n }\r\n\r\n public DotNodeConfig(boolean showTrivialColumns, boolean showColumnDetails) {\r\n showColumns = true;\r\n this.showTrivialColumns = showTrivialColumns;\r\n this.showColumnDetails = showColumnDetails;\r\n }\r\n}\r" ]
import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import net.sourceforge.schemaspy.Config; import net.sourceforge.schemaspy.Revision; import net.sourceforge.schemaspy.model.Database; import net.sourceforge.schemaspy.model.ForeignKeyConstraint; import net.sourceforge.schemaspy.model.Table; import net.sourceforge.schemaspy.model.TableColumn; import net.sourceforge.schemaspy.util.Dot; import net.sourceforge.schemaspy.util.LineWriter; import net.sourceforge.schemaspy.view.DotNode.DotNodeConfig;
/* * This file is a part of the SchemaSpy project (http://schemaspy.sourceforge.net). * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 John Currier * * SchemaSpy is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SchemaSpy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sourceforge.schemaspy.view; /** * Format table data into .dot format to feed to Graphvis' dot program. * * @author John Currier */ public class DotFormatter { private static DotFormatter instance = new DotFormatter(); private final int fontSize = Config.getInstance().getFontSize(); /** * Singleton - prevent creation */ private DotFormatter() { } public static DotFormatter getInstance() { return instance; } /** * Write real relationships (excluding implied) associated with the given table.<p> * Returns a set of the implied constraints that could have been included but weren't. */
public Set<ForeignKeyConstraint> writeRealRelationships(Table table, boolean twoDegreesOfSeparation, WriteStats stats, LineWriter dot) throws IOException {
2
anroOfCode/hijack-infinity
android/freqSweep-app/src/umich/framjack/apps/freqsweep/MainActivity.java
[ "public class FramingEngine {\n\tprivate IncomingPacketListener _incomingListener;\n\tprivate OutgoingByteListener _outgoingListener;\n\t\n\tprivate final int _receiveMax = 18;\n\t\n\tprivate enum ReceiveState { START, SIZE, DATA, DATA_ESCAPE};\n\tprivate ReceiveState _receiveState = ReceiveState.START;\n\tprivate ArrayList<Integer> _receiveBuffer;\n\tprivate int _receiveSize;\n\t\n\tprivate ArrayList<Integer> _transmitBuffer;\n\t\n\tpublic FramingEngine() {\n\t\t_receiveBuffer = new ArrayList<Integer>();\n\t\t_transmitBuffer = new ArrayList<Integer>();\n\t}\n\t\n\tpublic void receiveByte(int val) {\n\t\t//System.out.print(val + \" \");\n\t\tif (val == 0xDD && _receiveState != ReceiveState.DATA_ESCAPE) {\n\t\t\t_receiveState = ReceiveState.SIZE;\n\t\t\t_receiveBuffer.clear();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tswitch (_receiveState) {\n\t\t\tcase DATA:\n\t\t\t\tif (val == 0xCC) {\n\t\t\t\t\t_receiveState = ReceiveState.DATA_ESCAPE;\n\t\t\t\t\t_receiveSize--;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t_receiveBuffer.add(val);\n\t\t\t\tif (_receiveBuffer.size() == _receiveSize) {\n\t\t\t\t\tcheckPacket();\n\t\t\t\t\t_receiveState = ReceiveState.START;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase DATA_ESCAPE:\n\t\t\t\t_receiveState = ReceiveState.DATA;\n\t\t\t\t_receiveBuffer.add(val);\n\t\t\t\tif (_receiveBuffer.size() == _receiveSize) {\n\t\t\t\t\tcheckPacket();\n\t\t\t\t\t_receiveState = ReceiveState.START;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SIZE:\n\t\t\t\tif (val > _receiveMax) {\n\t\t\t\t\t_receiveState = ReceiveState.START;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t_receiveSize = val;\n\t\t\t\t_receiveState = ReceiveState.DATA;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tprivate void checkPacket() {\n\t\tint sum = 0;\n\t\tfor (int i = 0; i < _receiveBuffer.size() - 1; i++) {\n\t\t\t//System.out.print(Integer.toHexString(_receiveBuffer.get(i)) + \" \");\n\t\t\tsum += _receiveBuffer.get(i);\n\t\t}\n\t\t//System.out.println(Integer.toHexString(_receiveBuffer.get(_receiveBuffer.size() - 1)));\n\t\t\n\t\tif ((sum & 0xFF) == _receiveBuffer.get(_receiveBuffer.size() - 1)) {\n\t\t\tint[] retArray = new int[_receiveBuffer.size() - 1];\n\t\t\tfor (int i = 0; i < _receiveBuffer.size() - 1; i++) {\n\t\t\t\tretArray[i] = _receiveBuffer.get(i);\n\t\t\t}\n\t\t\t_incomingListener.IncomingPacketReceive(retArray);\n\t\t}\t\t\n\t}\n\t\n\tpublic void transmitByte(int val) {\n\t\tif (val == 0xCC) {\n\t\t\t_transmitBuffer.add(0xDD);\n\t\t}\n\t\t_transmitBuffer.add(val);\n\t}\n\t\n\tpublic void transmitEnd() {\n\t\tint[] toSend = new int[_transmitBuffer.size() + 3];\n\t\ttoSend[0] = 0xDD;\n\t\ttoSend[1] = _transmitBuffer.size() + 1;\n\t\tfor (int i = 0; i < _transmitBuffer.size(); i++) {\n\t\t\ttoSend[i + 2] = _transmitBuffer.get(i);\n\t\t\ttoSend[_transmitBuffer.size() + 2] += toSend[i + 2];\n\t\t}\n\t\t\n\t\ttoSend[_transmitBuffer.size() + 2] &= 0xFF;\n\t\t_transmitBuffer.clear();\n\t\t_outgoingListener.OutgoingByteTransmit(toSend);\n\t}\n\t\n\tpublic void registerIncomingPacketListener(IncomingPacketListener listener) {\n\t\t_incomingListener = listener;\n\t}\n\t\n\tpublic void registerOutgoingByteListener(OutgoingByteListener listener) {\n\t\t_outgoingListener = listener;\n\t}\n\t\n\tpublic interface IncomingPacketListener {\n\t\tpublic abstract void IncomingPacketReceive(int[] packet);\n\t}\n\t\n\tpublic interface OutgoingByteListener {\n\t\tpublic abstract void OutgoingByteTransmit(int[] outgoingRaw); \n\t}\n}", "public interface OnByteSentListener {\n\tpublic abstract void onByteSent();\n}", "public interface OnBytesAvailableListener {\n\tpublic abstract void onBytesAvailable(int count);\n}", "public class SerialDecoder {\n\tprivate AudioReceiver _audioReceiver;\n\t\n\tprivate enum TransmitState { IDLE, PENDING, DATA };\n\tprivate enum ReceiveState { IDLE, DATA, DATANEXT };\n\t\n\t// Receiver State\n\tprivate int _lastEdgeLength = 0;\n\t\n\tprivate int _currentEdgeLength = 0;\n\tprivate boolean _currentEdgeHigh = false;\n\t\n\t// FOR THE MSP430FR5969:\n\t//private int _threshold = 7;\n\t\n\t// FOR THE MSP430F1611:\n\tprivate int _threshold = 12;\n\t\n\tprivate int _deltaT = 0;\n\t\n\tprivate ReceiveState _rxState = ReceiveState.IDLE;\n\t\n\tprivate int _rxByte = 0;\n\tprivate int _rxBits = 0;\n\t\n\t// Transmit State\n\tprivate TransmitState _txState = TransmitState.IDLE;\n\tprivate int _txByte = 0;\n\tprivate int _txBytePosition = 0;\n\tprivate int _txBitPosition;\n\n\tprivate int _idleCycles = 20;\n\tprivate int _idleCycleCount = 0;\n\t\n\t// Byte Buffers\n\tprivate List<Integer> _incoming = new ArrayList<Integer>();\n\tprivate List<Integer> _outgoing = new ArrayList<Integer>();\n\t\n\t// Listeners for byte sent + byte received events\n\tprivate OnBytesAvailableListener _bytesAvailableListener = null;\n\tprivate OnByteSentListener _byteSentListener = null;\n\n\t\n\t//////////////////////////////\n\t// Transmit State Machine\n\t/////////////////////////////\n\tprivate boolean transmitIdle() {\n\t\treturn _txBitPosition == 1;\n\t}\n\t\n\tprivate boolean transmitPending() {\n\t\tif (_txBitPosition == 0) {\n\t\t\t_txState = TransmitState.DATA;\n\t\t\treturn transmitData();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\tprivate boolean transmitData() {\n\t\tboolean ret = ((_txByte >> _txBytePosition) & 0x1) == 1;\n\t\t\n\t\tif (_txBitPosition == 1) {\n\t\t\t_txBytePosition++;\n\t\t\t\n\t\t\tif (_txBytePosition == 10) {\n\n\t\t\t\tsynchronized(this) {\t\n\t\t\t\t\t_idleCycleCount = 0;\n\t\t\t\t\t_txState = TransmitState.IDLE;\n\t\t\t\t\t_txBytePosition = 0;\n\t\t\t\t\tnotifyByteSent();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tret = !ret;\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t/////////////////////////////\n\t// Receive State Machine\n\t/////////////////////////////\n\tprivate void receiveIdle() {\n\t\tif (_currentEdgeHigh == true &&\n\t\t\t\tisWithinThreshold(_currentEdgeLength,\n\t\t\t\t\t\t_lastEdgeLength * 2)) {\n\t\t\t\n\t\t\t_deltaT = _lastEdgeLength;\n\t\t\t\n\t\t\t_rxState = ReceiveState.DATA;\n\t\t\t\n\t\t\t_rxByte = 0;\n\t\t\t_rxBits = 1;\n\t\t}\n\t}\n\t\n\tprivate void receiveData() {\n\t\tif (isWithinThreshold(_currentEdgeLength, _deltaT)) {\n\t\t\t_rxState = ReceiveState.DATANEXT;\n\t\t}\n\t\telse if (isWithinThreshold(_currentEdgeLength, _deltaT * 2)) {\n\t\t\tif (((_rxByte >> (_rxBits - 1)) & 1) == 0) {\n\t\t\t\t_rxByte |= (1 << _rxBits);\n\t\t\t}\n\t\t\t_rxBits++;\n\t\t\tadvanceReceiveDataState();\n\t\t}\n\t\telse {\n\t\t\tSystem.out.println(\"EL: \" + _currentEdgeLength + \" DT: \" + _deltaT);\n\t\t\t//System.out.println(\"Error.\");\n\t\t\t_rxState = ReceiveState.IDLE;\n\t\t}\n\t}\n\t\n\tprivate void receiveDataNext() {\n\t\tif (isWithinThreshold(_currentEdgeLength, _deltaT)) {\n\t\t\tif (((_rxByte >> (_rxBits - 1)) & 1) == 1) {\n\t\t\t\t_rxByte |= (1 << _rxBits);\n\t\t\t}\n\t\t\t\n\t\t\t_rxBits++;\n\t\t\tadvanceReceiveDataState();\n\t\t}\n\t\telse {\n\t\t\tSystem.out.println(\"BEL: \" + _currentEdgeLength + \" DT: \" + _deltaT);\n\t\t\t_rxState = ReceiveState.IDLE;\n\t\t\t//System.out.println(\"Error.\");\n\t\t}\n\t}\n\n\t/////////////////////////////\n\t// Public Functions\n\t/////////////////////////////\n\t\n\tpublic SerialDecoder() {\n\t\t_audioReceiver = new AudioReceiver();\n\t\t_audioReceiver.registerIncomingSink(_incomingSink);\n\t\t_audioReceiver.registerOutgoingSource(_outgoingSink);\t\t\n\t}\n\t\n\tpublic void start() {\n\t\t_audioReceiver.startAudioIO();\t\t\n\t}\n\t\n\tpublic void stop() {\n\t\t_audioReceiver.stopAudioIO();\n\t}\n\t\n\tpublic void sendByte(int val) {\n\t\tsynchronized(this) {\n\t\t\t_outgoing.add(val);\n\t\t}\n\t}\n\t\n\tpublic int bytesAvailable() {\n\t\tsynchronized(this) {\n\t\t\treturn _incoming.size();\n\t\t}\n\t}\n\t\n\tpublic int readByte() {\n\t\tsynchronized(this) {\n\t\t\tif (_incoming.size() == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tint ret = _incoming.get(0);\n\t\t\t_incoming.remove(0);\n\t\t\treturn ret;\n\t\t}\n\t}\n\t\n\tpublic void setFreq(int freq) {\n\t\t_audioReceiver.setPowerFrequency(freq);\n\t}\n\t\n\t/////////////////////////////\n\t// Listener Functions\n\t/////////////////////////////\n\t// WARNING: These are not thread-safe. We are using a\n\t// guarantee by AudioInterface that events will occur\n\t// sequentially and originate from a single thread.\n\t\n\tpublic void registerBytesAvailableListener(OnBytesAvailableListener _listener) {\n\t\t_bytesAvailableListener = _listener;\n\t}\n\t\n\tpublic void registerByteSentListener(OnByteSentListener _listener) {\n\t\t_byteSentListener = _listener;\n\t}\n\t\n\tprivate void notifyBytesAvailable(int numberBytes) {\n\t\tif (_bytesAvailableListener != null) {\n\t\t\t_bytesAvailableListener.onBytesAvailable(numberBytes);\n\t\t}\n\t}\n\t\n\tprivate void notifyByteSent() {\n\t\tif (_byteSentListener != null) {\n\t\t\t_byteSentListener.onByteSent();\n\t\t}\n\t}\n\t\n\t/////////////////////////////\n\t// Helper Functions\n\t/////////////////////////////\n\t\n\tprivate boolean isWithinThreshold(int value, int desired) {\n\t\treturn value < desired + _threshold && value > desired - _threshold;\n\t}\n\t\n\tprivate byte calcParity(int in) {\n\t\tbyte parity = 0;\n\t\tfor (int i = 0; i < 8; i++) {\n\t\t\tparity ^= ((in >> i) & 1);\n\t\t}\t\n\t\treturn parity;\n\t}\n\t\n\tprivate void advanceReceiveDataState() {\n\t\tif (_rxBits == 10) {\n\t\t\tif (calcParity(_rxByte >> 1) == (_rxByte >> 9)) {\n\t\t\t\tsynchronized(this) {\n\t\t\t\t\t_incoming.add((_rxByte >> 1) & 0xFF);\n\t\t\t\t\tnotifyBytesAvailable(_incoming.size());\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSystem.out.println(\"checksum failed.\");\n\t\t\t}\n\t\t\t_rxState = ReceiveState.IDLE;\n\t\t}\n\t\telse {\n\t\t\t_rxState = ReceiveState.DATA;\n\t\t}\n\t}\n\n\t/////////////////////////////\n\t// AudioInterface Listeners\n\t////////////////////////////\n\t\n\tprivate IncomingSink _incomingSink = new IncomingSink() {\n\t\tpublic void handleNextBit(int transistionPeriod, boolean isHighToLow) {\n\t\t\t//System.out.println(\"Tran: \" + transistionPeriod + \" HL: \" + isHighToLow);\n\t\t\t_currentEdgeLength = transistionPeriod;\n\t\t\t_currentEdgeHigh = isHighToLow;\n\t\t\tswitch (_rxState) {\n\t\t\tcase DATA:\n\t\t\t\treceiveData();\n\t\t\t\tbreak;\n\t\t\tcase DATANEXT:\n\t\t\t\treceiveDataNext();\n\t\t\t\tbreak;\n\t\t\tcase IDLE:\n\t\t\t\treceiveIdle();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_lastEdgeLength = _currentEdgeLength;\n\t\t}\n\t};\n\t\n\tprivate OutgoingSource _outgoingSink = new OutgoingSource() {\n\t\tpublic boolean getNextBit() {\n\t\t\tboolean ret = false;\n\t\t\tswitch (_txState) {\n\t\t\tcase DATA:\n\t\t\t\tret = transmitData();\n\t\t\t\tbreak;\n\t\t\tcase IDLE:\n\t\t\t\tif(_idleCycleCount < _idleCycles) {\n\t\t\t\t\t_idleCycleCount++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsynchronized(SerialDecoder.this) {\n\t\t\t\t\tif (_outgoing.size() > 0 && _idleCycleCount == _idleCycles) {\n\t\t\t\t\t\tint byteToSend = _outgoing.get(0);\n\t\t\t\t\t\t_outgoing.remove(0);\n\t\t\t\t\t\t\n\t\t\t\t\t\tint parity = calcParity(byteToSend);\n\t\t\t\t\t\t_txByte = (byteToSend << 1) | (parity << 9);\n\t\t\t\t\t\t_txState = TransmitState.PENDING;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tret = transmitIdle();\n\t\t\t\tbreak;\n\t\t\tcase PENDING:\n\t\t\t\tret = transmitPending();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t_txBitPosition = _txBitPosition == 0 ? 1 : 0;\n\t\t\t\n\t\t\treturn ret;\n\t\t}\n\t};\n}", "public interface IncomingPacketListener {\n\tpublic abstract void IncomingPacketReceive(int[] packet);\n}", "public interface OutgoingByteListener {\n\tpublic abstract void OutgoingByteTransmit(int[] outgoingRaw); \n}" ]
import umich.framjack.core.FramingEngine; import umich.framjack.core.OnByteSentListener; import umich.framjack.core.OnBytesAvailableListener; import umich.framjack.core.SerialDecoder; import umich.framjack.core.FramingEngine.IncomingPacketListener; import umich.framjack.core.FramingEngine.OutgoingByteListener; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText;
package umich.framjack.apps.freqsweep; public class MainActivity extends Activity { private SerialDecoder _serialDecoder; private FramingEngine _framer; private boolean _nextFlag = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _framer = new FramingEngine(); _serialDecoder = new SerialDecoder(); _serialDecoder.registerBytesAvailableListener(_bytesAvailableListener); _serialDecoder.registerByteSentListener(_byteSentListener); _framer.registerIncomingPacketListener(_incomingPacketListener); _framer.registerOutgoingByteListener(_outgoingByteListener); final Button b1 = (Button)findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText startFreqEditText = (EditText)findViewById(R.id.startFreq); EditText endFreqEditText = (EditText)findViewById(R.id.endFreq); EditText msStepEditText = (EditText)findViewById(R.id.stepMs); EditText hzStepEditText = (EditText)findViewById(R.id.stepHz); final int startFreq = Integer.parseInt(startFreqEditText.getText().toString()); final int endFreq = Integer.parseInt(endFreqEditText.getText().toString()); final int msStep = Integer.parseInt(msStepEditText.getText().toString()); final int hzStep = Integer.parseInt(hzStepEditText.getText().toString()); b1.setText("Running..."); Thread t = new Thread(new Runnable() { @Override public void run() { int currentFreq = startFreq; while (currentFreq <= endFreq) { _serialDecoder.setFreq(currentFreq); currentFreq += hzStep; if (msStep == 0) { while (!_nextFlag) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } _nextFlag = false; } else { try { Thread.sleep(msStep); } catch (InterruptedException e) { e.printStackTrace(); } } } MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { b1.setText("Start"); } }); } }); t.start(); } }); final Button b2 = (Button)findViewById(R.id.button2); b2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { _nextFlag = true; } }); } @Override public void onPause() { _serialDecoder.stop(); super.onPause(); } @Override public void onResume() { _serialDecoder.start(); super.onResume(); } /////////////////////////////////////////////// // Listeners /////////////////////////////////////////////// private OutgoingByteListener _outgoingByteListener = new OutgoingByteListener() { public void OutgoingByteTransmit(int[] outgoingRaw) { synchronized (MainActivity.this) { //_pendingTransmitBytes += outgoingRaw.length; } for (int i = 0; i < outgoingRaw.length; i++) { _serialDecoder.sendByte(outgoingRaw[i]); } } }; private IncomingPacketListener _incomingPacketListener = new IncomingPacketListener() { public void IncomingPacketReceive(int[] packet) { for (int i = 0; i < packet.length; i++) { System.out.print(Integer.toHexString(packet[i]) + " "); } System.out.println(); //decodeAndUpdate(packet); } };
private OnByteSentListener _byteSentListener = new OnByteSentListener() {
1
CaMnter/EasyGank
app/src/main/java/com/camnter/easygank/data/DataManager.java
[ "public class BaseGankData implements Serializable {\n\n // 发布人\n @SerializedName(\"who\") public String who;\n\n // 发布时间\n @SerializedName(\"publishedAt\") public Date publishedAt;\n\n // 标题\n @SerializedName(\"desc\") public String desc;\n\n // 类型, 一般都是\"福利\"\n @SerializedName(\"type\") public String type;\n\n // 图片url\n @SerializedName(\"url\") public String url;\n\n // 是否可用\n @SerializedName(\"used\") public Boolean used;\n\n // 对象id\n @SerializedName(\"objectId\") public String objectId;\n\n // 创建时间\n @SerializedName(\"createdAt\") public Date createdAt;\n\n // 更新时间\n @SerializedName(\"updatedAt\") public Date updatedAt;\n}", "public class GankDaily extends Error implements Serializable {\n\n @SerializedName(\"results\") public DailyResults results;\n\n @SerializedName(\"category\") public ArrayList<String> category;\n\n public class DailyResults {\n\n @SerializedName(\"福利\") public ArrayList<BaseGankData> welfareData;\n\n @SerializedName(\"Android\") public ArrayList<BaseGankData> androidData;\n\n @SerializedName(\"iOS\") public ArrayList<BaseGankData> iosData;\n\n @SerializedName(\"前端\") public ArrayList<BaseGankData> jsData;\n\n @SerializedName(\"休息视频\") public ArrayList<BaseGankData> videoData;\n\n @SerializedName(\"拓展资源\") public ArrayList<BaseGankData> resourcesData;\n\n @SerializedName(\"App\") public ArrayList<BaseGankData> appData;\n\n @SerializedName(\"瞎推荐\") public ArrayList<BaseGankData> recommendData;\n }\n}", "public class DailyModel implements IDailyModel {\n\n private static final DailyModel ourInstance = new DailyModel();\n\n\n public static DailyModel getInstance() {\n return ourInstance;\n }\n\n\n private DailyModel() {\n }\n\n\n /**\n * 查询每日数据\n *\n * @param year year\n * @param month month\n * @param day day\n * @return Observable<GankDaily>\n */\n @Override public Observable<GankDaily> getDaily(int year, int month, int day) {\n return EasyGank.getInstance().getGankService().getDaily(year, month, day);\n }\n}", "public class DataModel implements IDataModel {\n\n private static final DataModel ourInstance = new DataModel();\n\n\n public static DataModel getInstance() {\n return ourInstance;\n }\n\n\n private DataModel() {\n }\n\n\n /**\n * 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据\n *\n * @param type 数据类型\n * @param size 数据个数\n * @param page 第几页\n * @return Observable<GankData>\n */\n @Override public Observable<GankData> getData(String type, int size, int page) {\n return EasyGank.getInstance().getGankService().getData(type, size, page);\n }\n}", "public class MainPresenter extends BasePresenter<MainView> {\n\n private EasyDate currentDate;\n private int page;\n\n private ReservoirUtils reservoirUtils;\n\n /**\n * 查每日干货需要的特殊的类\n */\n public class EasyDate implements Serializable {\n private Calendar calendar;\n\n public EasyDate(Calendar calendar) {\n this.calendar = calendar;\n }\n\n public int getYear() {\n return calendar.get(Calendar.YEAR);\n }\n\n public int getMonth() {\n return calendar.get(Calendar.MONTH) + 1;\n }\n\n public int getDay() {\n return calendar.get(Calendar.DAY_OF_MONTH);\n }\n\n public List<EasyDate> getPastTime() {\n List<EasyDate> easyDates = new ArrayList<>();\n for (int i = 0; i < GankApi.DEFAULT_DAILY_SIZE; i++) {\n /*\n * - (page * DateUtils.ONE_DAY) 翻到哪页再找 一页有DEFAULT_DAILY_SIZE这么长\n * - i * DateUtils.ONE_DAY 往前一天一天 找呀找\n */\n long time = this.calendar.getTimeInMillis() - ((page - 1) * GankApi.DEFAULT_DAILY_SIZE * DateUtils.ONE_DAY) - i * DateUtils.ONE_DAY;\n Calendar c = Calendar.getInstance();\n c.setTimeInMillis(time);\n EasyDate date = new EasyDate(c);\n easyDates.add(date);\n }\n return easyDates;\n }\n\n }\n\n\n public MainPresenter() {\n this.reservoirUtils = new ReservoirUtils();\n long time = System.currentTimeMillis();\n Calendar mCalendar = Calendar.getInstance();\n mCalendar.setTimeInMillis(time);\n this.currentDate = new EasyDate(mCalendar);\n this.page = 1;\n }\n\n /**\n * 设置查询第几页\n *\n * @param page page\n */\n public void setPage(int page) {\n this.page = page;\n }\n\n /**\n * 获取当前页数量\n *\n * @return page\n */\n public int getPage() {\n return page;\n }\n\n /**\n * 查询每日数据\n *\n * @param refresh 是否是刷新\n * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据\n */\n public void getDaily(final boolean refresh, final int oldPage) {\n /*\n * 切换数据源的话,尝试页数1\n */\n if (oldPage != GankTypeDict.DONT_SWITCH) {\n this.page = 1;\n }\n this.mCompositeSubscription.add(this.mDataManager.getDailyDataByNetwork(this.currentDate)\n .subscribe(new Subscriber<List<GankDaily>>() {\n @Override\n public void onCompleted() {\n if (MainPresenter.this.mCompositeSubscription != null)\n MainPresenter.this.mCompositeSubscription.remove(this);\n }\n\n @Override\n public void onError(Throwable e) {\n try {\n Logger.d(e.getMessage());\n } catch (Throwable e1) {\n e1.getMessage();\n } finally {\n if (refresh) {\n Type resultType = new TypeToken<List<GankDaily>>() {\n }.getType();\n MainPresenter.this.reservoirUtils.get(GankType.daily + \"\", resultType, new ReservoirGetCallback<List<GankDaily>>() {\n @Override\n public void onSuccess(List<GankDaily> object) {\n // 有缓存显示缓存数据\n if (oldPage != GankTypeDict.DONT_SWITCH) {\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily);\n }\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onGetDailySuccess(object, refresh);\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onFailure(e);\n }\n\n @Override\n public void onFailure(Exception e) {\n MainPresenter.this.switchFailure(oldPage, e);\n }\n });\n } else {\n// MainPresenter.this.switchFailure(oldPage, e);\n // 加载更多失败\n MainPresenter.this.getMvpView().onFailure(e);\n }\n }\n\n }\n\n @Override\n public void onNext(List<GankDaily> dailyData) {\n /*\n * 如果是切换数据源\n * page=1加载成功了\n * 即刚才的loadPage\n */\n if (oldPage != GankTypeDict.DONT_SWITCH) {\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily);\n }\n // 刷新缓存\n if (refresh)\n MainPresenter.this.reservoirUtils.refresh(GankType.daily + \"\", dailyData);\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onGetDailySuccess(dailyData, refresh);\n }\n }));\n }\n\n /**\n * * 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 )\n *\n * @param type GankType\n * @param refresh 是否是刷新\n * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据\n */\n public void getData(final int type, final boolean refresh, final int oldPage) {\n /*\n * 切换数据源的话,尝试页数1\n */\n if (oldPage != GankTypeDict.DONT_SWITCH) {\n this.page = 1;\n }\n String gankType = GankTypeDict.type2UrlTypeDict.get(type);\n if (gankType == null) return;\n this.mCompositeSubscription.add(this.mDataManager.getDataByNetWork(gankType, GankApi.DEFAULT_DATA_SIZE, this.page)\n .subscribe(new Subscriber<ArrayList<BaseGankData>>() {\n @Override\n public void onCompleted() {\n if (MainPresenter.this.mCompositeSubscription != null)\n MainPresenter.this.mCompositeSubscription.remove(this);\n }\n\n @Override\n public void onError(Throwable e) {\n try {\n Logger.d(e.getMessage());\n } catch (Throwable e1) {\n e1.getMessage();\n } finally {\n if (refresh) {\n Type resultType = new TypeToken<ArrayList<BaseGankData>>() {\n }.getType();\n MainPresenter.this.reservoirUtils.get(type + \"\", resultType, new ReservoirGetCallback<ArrayList<BaseGankData>>() {\n @Override\n public void onSuccess(ArrayList<BaseGankData> object) {\n // 有缓存显示缓存数据\n if (oldPage != GankTypeDict.DONT_SWITCH) {\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onSwitchSuccess(type);\n }\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onGetDataSuccess(object, refresh);\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onFailure(e);\n }\n\n @Override\n public void onFailure(Exception e) {\n MainPresenter.this.switchFailure(oldPage, e);\n }\n });\n } else {\n// MainPresenter.this.switchFailure(oldPage, e);\n // 加载更多失败\n MainPresenter.this.getMvpView().onFailure(e);\n }\n }\n }\n\n @Override\n public void onNext(ArrayList<BaseGankData> baseGankData) {\n /*\n * 如果是切换数据源\n * page=1加载成功了\n * 即刚才的loadPage\n */\n if (oldPage != GankTypeDict.DONT_SWITCH) {\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onSwitchSuccess(type);\n }\n // 刷新缓存\n if (refresh)\n MainPresenter.this.reservoirUtils.refresh(type + \"\", baseGankData);\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onGetDataSuccess(baseGankData, refresh);\n\n\n }\n }));\n\n }\n\n public void switchType(int type) {\n /*\n * 记录没切换前的数据的页数\n * 以防切换数据后,网络又跪导致的page对不上问题\n */\n int oldPage = this.page;\n switch (type) {\n case GankType.daily:\n this.getDaily(true, oldPage);\n break;\n case GankType.android:\n case GankType.ios:\n case GankType.js:\n case GankType.resources:\n case GankType.welfare:\n case GankType.video:\n case GankType.app:\n this.getData(type, true, oldPage);\n break;\n }\n }\n\n\n public void getDailyDetail(final GankDaily.DailyResults results) {\n this.mCompositeSubscription.add(this.mDataManager.getDailyDetailByDailyResults(results)\n .subscribe(new Subscriber<ArrayList<ArrayList<BaseGankData>>>() {\n @Override\n public void onCompleted() {\n if (MainPresenter.this.mCompositeSubscription != null)\n MainPresenter.this.mCompositeSubscription.remove(this);\n }\n\n @Override\n public void onError(Throwable e) {\n try {\n Logger.d(e.getMessage());\n } catch (Throwable e1) {\n e1.getMessage();\n }\n }\n\n @Override\n public void onNext(ArrayList<ArrayList<BaseGankData>> detail) {\n if (MainPresenter.this.getMvpView() != null) {\n // 相信福利一定有\n MainPresenter.this.getMvpView().getDailyDetail(\n DateUtils.date2String(results.welfareData.get(0).publishedAt.getTime(),\n Constant.DAILY_DATE_FORMAT), detail\n );\n }\n }\n }));\n }\n\n /**\n * 切换分类失败\n *\n * @param oldPage oldPage\n */\n private void switchFailure(int oldPage, Throwable e) {\n /*\n * 如果是切换数据源\n * 刚才尝试的page=1失败了的请求\n * 加载失败\n * 会影响到原来页面的page\n * 在这里执行复原page操作\n */\n if (oldPage != GankTypeDict.DONT_SWITCH)\n MainPresenter.this.page = oldPage;\n if (MainPresenter.this.getMvpView() != null)\n MainPresenter.this.getMvpView().onFailure(e);\n }\n\n\n}", "public class RxUtils {\n /**\n * {@link rx.Observable.Transformer} that transforms the source observable to subscribe in the\n * io thread and observe on the Android's UI thread.\n */\n private static Observable.Transformer ioToMainThreadSchedulerTransformer;\n\n\n static {\n ioToMainThreadSchedulerTransformer = createIOToMainThreadScheduler();\n }\n\n\n /**\n * Get {@link rx.Observable.Transformer} that transforms the source observable to subscribe in\n * the io thread and observe on the Android's UI thread.\n * <p>\n * Because it doesn't interact with the emitted items it's safe ignore the unchecked casts.\n *\n * @return {@link rx.Observable.Transformer}\n */\n @SuppressWarnings(\"unchecked\")\n private static <T> Observable.Transformer<T, T> createIOToMainThreadScheduler() {\n return tObservable -> tObservable.subscribeOn(Schedulers.io())\n .unsubscribeOn(\n Schedulers.computation()) // TODO: remove when https://github.com/square/okhttp/issues/1592 is fixed\n .observeOn(AndroidSchedulers.mainThread());\n }\n\n\n @SuppressWarnings(\"unchecked\")\n public static <T> Observable.Transformer<T, T> applyIOToMainThreadSchedulers() {\n return ioToMainThreadSchedulerTransformer;\n }\n}" ]
import java.util.ArrayList; import java.util.List; import rx.Observable; import com.camnter.easygank.bean.BaseGankData; import com.camnter.easygank.bean.GankDaily; import com.camnter.easygank.model.impl.DailyModel; import com.camnter.easygank.model.impl.DataModel; import com.camnter.easygank.presenter.MainPresenter; import com.camnter.easygank.utils.RxUtils;
/* * {EasyGank} Copyright (C) {2015} {CaMnter} * * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.camnter.easygank.data; /** * Description:DataManager * Created by:CaMnter * Time:2016-01-13 13:45 */ public class DataManager { private static DataManager dataManager; private DailyModel dailyModel;
private DataModel dataModel;
3
edouardhue/comeon
src/main/java/comeon/ui/actions/AddMediaAction.java
[ "public interface Core {\n\n String EXTERNAL_METADATA_KEY = \"external\";\n\n String[] PICTURE_EXTENSIONS = { \"jpg\", \"jpeg\" };\n\n String[] AUDIO_EXTENSIONS = { \"ogg\", \"flac\", \"wav\" };\n\n void addMedia(final File[] files, final Template defautTemplate, final ExternalMetadataSource<?> externalMetadataSource) throws IOException;\n\n void removeMedia(Media media);\n\n void removeAllMedia();\n\n Set<Media> getMedia();\n\n int countMediaToBeUploaded();\n\n void uploadMedia();\n\n void abort();\n}", "public interface Templates extends WithPreferences {\n\n List<Template> getTemplates();\n\n void setTemplates(List<Template> templates);\n\n void save() throws BackingStoreException;\n\n List<TemplateKind> getTemplateKinds();\n\n Charset[] getSupportedCharsets();\n}", "public final class TemplatesChangedEvent {\n private final List<Template> templates;\n\n public TemplatesChangedEvent(final List<Template> templates) {\n this.templates = Collections.unmodifiableList(templates);\n }\n\n public List<Template> getTemplates() {\n return templates;\n }\n}", "public final class AddMediaDialog extends JOptionPane {\n\n private static final long serialVersionUID = 1L;\n\n private static final ImageIcon ICON = new ImageIcon(Resources.getResource(\"comeon/ui/addmedia_huge.png\"));\n\n private final AddModel model;\n\n private final AddController controller;\n\n private final JDialog dialog;\n\n private final AddMediaPanel mediaPanel;\n\n public AddMediaDialog(final Templates templates) {\n this(templates, new File[0]);\n }\n\n public AddMediaDialog(final Templates templates, final File[] preselectedFiles) {\n super(null, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, ICON);\n this.controller = new AddController(templates);\n this.model = new AddModel();\n this.controller.registerModel(model);\n this.mediaPanel = new AddMediaPanel(controller);\n this.controller.registerView(mediaPanel);\n this.setMessage(this.mediaPanel);\n this.dialog = this.createDialog(UI.findInstance(), UI.BUNDLE.getString(\"action.addmedia.title\"));\n this.dialog.setIconImages(UI.ICON_IMAGES);\n this.model.setMediaFiles(preselectedFiles);\n }\n\n public int showDialog() {\n this.dialog.setVisible(true);\n return (Integer) this.getValue();\n }\n\n public AddModel getModel() {\n return model;\n }\n}", "public class AdderWorker extends CursorChangingWorker {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AdderWorker.class);\n\n private final AddModel model;\n\n private final Core core;\n\n public AdderWorker(final AddModel model, final Core core) {\n this.model = model;\n this.core = core;\n }\n\n @Override\n protected Void doInBackground() throws Exception {\n model.getTemplate().load();\n final File[] files = model.getMediaFiles();\n if (files.length > 0) {\n core.addMedia(files, model.getTemplate(), model.getExternalMetadataSource());\n }\n return null;\n }\n\n @Override\n protected void done() {\n super.done();\n try {\n super.get();\n } catch (final ExecutionException e) {\n LOGGER.warn(\"Adding media failed\", e);\n final Window window = UI.findInstance();\n JOptionPane.showMessageDialog(\n window,\n MessageFormat.format(UI.BUNDLE.getString(\"error.addmedia.failed\"), e.getCause().getLocalizedMessage()),\n UI.BUNDLE.getString(\"error.generic.title\"),\n JOptionPane.ERROR_MESSAGE);\n } catch (final InterruptedException e) {\n Thread.interrupted();\n }\n }\n}" ]
import com.google.common.eventbus.Subscribe; import com.google.inject.Inject; import com.google.inject.Singleton; import comeon.core.Core; import comeon.templates.Templates; import comeon.templates.TemplatesChangedEvent; import comeon.ui.add.AddMediaDialog; import comeon.ui.add.AdderWorker; import javax.swing.*; import java.awt.event.ActionEvent;
package comeon.ui.actions; @Singleton public final class AddMediaAction extends BaseAction { private static final long serialVersionUID = 1L; private final Templates templates; private final Core core; @Inject public AddMediaAction(final Templates templates, final Core core) { super("addmedia"); this.templates = templates; this.core = core; if (templates.getTemplates().isEmpty()) { this.setEnabled(false); } } @Override public void actionPerformed(final ActionEvent e) { SwingUtilities.invokeLater(() -> { final AddMediaDialog dialog = new AddMediaDialog(templates); final int value = dialog.showDialog(); if (value == JOptionPane.OK_OPTION) { new AdderWorker(dialog.getModel(), core).execute(); } }); } @Subscribe
public void handleTemplatesChanged(final TemplatesChangedEvent event) {
2
gizwits/GizOpenSource_AppKit_Android
src/com/gizwits/opensource/appkit/sharingdevice/SharedDeviceListAcitivity.java
[ "public class GosBaseActivity extends FragmentActivity {\n\n\t/** 设备热点默认密码 */\n\tpublic static String SoftAP_PSW = \"123456789\";\n\n\t/** 设备热点默认前缀 */\n\tpublic static String SoftAP_Start = \"XPG-GAgent\";\n\n\t/** 存储器默认名称 */\n\tpublic static final String SPF_Name = \"set\";\n\n\t/** Toast time */\n\tpublic int toastTime = 2000;\n\n\t/** 存储器 */\n\tpublic SharedPreferences spf;\n\n\t/** 等待框 */\n\tpublic ProgressDialog progressDialog;\n\n\t/** 标题栏 */\n\tpublic ActionBar actionBar;\n\n\t/** 实现WXEntryActivity与GosUserLoginActivity共用 */\n\tpublic static Handler baseHandler;\n\n\tpublic static boolean isclean = false;\n\n\tpublic void setBaseHandler(Handler basehandler) {\n\t\tif (null != basehandler) {\n\t\t\tbaseHandler = basehandler;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\n\t\t/**\n\t\t * 设置为竖屏\n\t\t */\n\t\tif (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {\n\t\t\tsetRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n\t\t}\n\n\t\tspf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);\n\t\tMessageCenter.getInstance(this);\n\t\t// 初始化\n\t\tsetProgressDialog();\n\t}\n\t\n\t\n\t\n\n\t/**\n\t * 添加ProductKeys\n\t * \n\t * @param productkeys\n\t * @return\n\t */\n\tpublic List<String> addProductKey(String[] productkeys) {\n\t\tList<String> productkeysList = new ArrayList<String>();\n\t\tfor (String productkey : productkeys) {\n\t\t\tproductkeysList.add(productkey);\n\t\t}\n\n\t\treturn productkeysList;\n\t}\n\n\t/**\n\t * 设置ActionBar(工具方法*开发用*)\n\t * \n\t * @param HBE\n\t * @param DSHE\n\t * @param Title\n\t */\n\tpublic void setActionBar(Boolean HBE, Boolean DSHE, int Title) {\n\n\t\tSpannableString ssTitle = new SpannableString(this.getString(Title));\n\t\tssTitle.setSpan(new ForegroundColorSpan(GosDeploy.setNavigationBarTextColor()), 0, ssTitle.length(),\n\t\t\t\tSpannable.SPAN_INCLUSIVE_EXCLUSIVE);\n\t\tactionBar = getActionBar();// 初始化ActionBar\n\t\tactionBar.setBackgroundDrawable(GosDeploy.setNavigationBarColor());\n\t\tactionBar.setHomeButtonEnabled(HBE);\n\t\tactionBar.setIcon(R.drawable.back_bt_);\n\t\tactionBar.setTitle(ssTitle);\n\t\tactionBar.setDisplayShowHomeEnabled(DSHE);\n\t}\n\n\t/**\n\t * 设置ActionBar(工具方法*GosAirlinkChooseDeviceWorkWiFiActivity.java中使用*)\n\t * \n\t * @param HBE\n\t * @param DSHE\n\t * @param Title\n\t */\n\tpublic void setActionBar(Boolean HBE, Boolean DSHE, CharSequence Title) {\n\n\t\tSpannableString ssTitle = new SpannableString(Title);\n\t\tssTitle.setSpan(new ForegroundColorSpan(GosDeploy.setNavigationBarTextColor()), 0, ssTitle.length(),\n\t\t\t\tSpannable.SPAN_INCLUSIVE_EXCLUSIVE);\n\t\tactionBar = getActionBar();// 初始化ActionBar\n\t\tactionBar.setBackgroundDrawable(GosDeploy.setNavigationBarColor());\n\t\tactionBar.setHomeButtonEnabled(HBE);\n\t\tactionBar.setIcon(R.drawable.back_bt_);\n\t\tactionBar.setTitle(ssTitle);\n\t\tactionBar.setDisplayShowHomeEnabled(DSHE);\n\t}\n\n\t/**\n\t * 设置ProgressDialog\n\t */\n\tpublic void setProgressDialog() {\n\t\tprogressDialog = new ProgressDialog(this);\n\t\tString loadingText = getString(R.string.loadingtext);\n\t\tprogressDialog.setMessage(loadingText);\n\t\tprogressDialog.setCanceledOnTouchOutside(false);\n\t}\n\n\t/**\n\t * 设置ProgressDialog\n\t * \n\t * @param Message\n\t * @param Cancelable\n\t * @param CanceledOnTouchOutside\n\t */\n\tpublic void setProgressDialog(String Message, boolean Cancelable, boolean CanceledOnTouchOutside) {\n\t\tprogressDialog = new ProgressDialog(this);\n\t\tprogressDialog.setMessage(Message);\n\t\tprogressDialog.setCancelable(Cancelable);\n\t\tprogressDialog.setCanceledOnTouchOutside(CanceledOnTouchOutside);\n\t}\n\n\t/**\n\t * 检查网络连通性(工具方法)\n\t * \n\t * @param context\n\t * @return\n\t */\n\tpublic boolean checkNetwork(Context context) {\n\t\tConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo net = conn.getActiveNetworkInfo();\n\t\tif (net != null && net.isConnected()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 验证手机格式.(工具方法)\n\t */\n\t// public boolean isMobileNO(String mobiles) {\n\t// /*\n\t// * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188\n\t// * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)\n\t// * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9\n\t// */\n\t// String telRegex = \"[1][3578]\\\\d{9}\";//\n\t// \"[1]\"代表第1位为数字1,\"[358]\"代表第二位可以为3、5、8中的一个,\"\\\\d{9}\"代表后面是可以是0~9的数字,有9位。\n\t// if (TextUtils.isEmpty(mobiles))\n\t// return false;\n\t// else\n\t// return !mobiles.matches(telRegex);\n\t// }\n\n\tpublic String toastError(GizWifiErrorCode errorCode) {\n\t\tString errorString = (String) getText(R.string.UNKNOWN_ERROR);\n\t\tswitch (errorCode) {\n\t\tcase GIZ_SDK_PARAM_FORM_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PARAM_FORM_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CLIENT_NOT_AUTHEN:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CLIENT_NOT_AUTHEN);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CLIENT_VERSION_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CLIENT_VERSION_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_UDP_PORT_BIND_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_UDP_PORT_BIND_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DAEMON_EXCEPTION:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DAEMON_EXCEPTION);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_PARAM_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PARAM_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_APPID_LENGTH_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APPID_LENGTH_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_LOG_PATH_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_LOG_PATH_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_LOG_LEVEL_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_LOG_LEVEL_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_SEND_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SEND_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_IS_RUNNING:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_TIMEOUT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_TIMEOUT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_DID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_DID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_MAC_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_MAC_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_SUBDEVICE_DID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_SUBDEVICE_DID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_PASSCODE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_PASSCODE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NOT_SUBSCRIBED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_SUBSCRIBED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NO_RESPONSE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NO_RESPONSE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NOT_READY:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_READY);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NOT_BINDED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_BINDED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND);\n\t\t\tbreak;\n\t\t// case GIZ_SDK_DEVICE_CONTROL_FAILED:\n\t\t// errorString= (String)\n\t\t// getText(R.string.GIZ_SDK_DEVICE_CONTROL_FAILED);\n\t\t// break;\n\t\tcase GIZ_SDK_DEVICE_GET_STATUS_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_GET_STATUS_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_BIND_DEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_BIND_DEVICE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_UNBIND_DEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_UNBIND_DEVICE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DNS_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DNS_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_M2M_CONNECTION_SUCCESS:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_M2M_CONNECTION_SUCCESS);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_TIMEOUT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_TIMEOUT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_REFUSED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_REFUSED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_CLOSED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_CLOSED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_SSL_HANDSHAKE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_SSL_HANDSHAKE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_INTERNET_NOT_REACHABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_INTERNET_NOT_REACHABLE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_ANSWER_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_SERVER_NO_ANSWER:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NO_ANSWER);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_REQUEST_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_REQUEST_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_OTHERWISE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_OTHERWISE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_MEMORY_MALLOC_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_MEMORY_MALLOC_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_THREAD_CREATE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_THREAD_CREATE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_USER_ID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_USER_ID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_TOKEN_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_TOKEN_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_ID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_ID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUPNAME_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUPNAME_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_PRODUCTKEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_PRODUCTKEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_FAILED_DELETE_DEVICE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_DELETE_DEVICE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_FAILED_ADD_DEVICE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_ADD_DEVICE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_GET_DEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_GET_DEVICE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DATAPOINT_NOT_DOWNLOAD:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_NOT_DOWNLOAD);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DATAPOINT_PARSE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_PARSE_FAILED);\n\t\t\tbreak;\n\t\t// case GIZ_SDK_NOT_INITIALIZED:\n\t\t// errorString= (String) getText(R.string.GIZ_SDK_SDK_NOT_INITIALIZED);\n\t\t// break;\n\t\tcase GIZ_SDK_APK_CONTEXT_IS_NULL:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APK_CONTEXT_IS_NULL);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_APK_PERMISSION_NOT_SET:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APK_PERMISSION_NOT_SET);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CHMOD_DAEMON_REFUSED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CHMOD_DAEMON_REFUSED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_EXEC_DAEMON_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_EXEC_DAEMON_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_EXEC_CATCH_EXCEPTION:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_EXEC_CATCH_EXCEPTION);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_APPID_IS_EMPTY:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APPID_IS_EMPTY);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_UNSUPPORTED_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_UNSUPPORTED_API);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_REQUEST_TIMEOUT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_REQUEST_TIMEOUT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DAEMON_VERSION_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DAEMON_VERSION_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_NOT_IN_SOFTAPMODE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_NOT_IN_SOFTAPMODE);\n\t\t\tbreak;\n\t\t// case GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE:\n\t\t// errorString= (String)\n\t\t// getText(R.string.GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE);\n\t\t// break;\n\t\tcase GIZ_SDK_RAW_DATA_TRANSMIT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_RAW_DATA_TRANSMIT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_PRODUCT_IS_DOWNLOADING:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PRODUCT_IS_DOWNLOADING);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_START_SUCCESS:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_START_SUCCESS);\n\t\t\tbreak;\n\t\tcase GIZ_SITE_PRODUCTKEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SITE_PRODUCTKEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SITE_DATAPOINTS_NOT_DEFINED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_DEFINED);\n\t\t\tbreak;\n\t\tcase GIZ_SITE_DATAPOINTS_NOT_MALFORME:\n\t\t\terrorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_MALFORME);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_MAC_ALREADY_REGISTERED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_MAC_ALREADY_REGISTERED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PRODUCT_KEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_KEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_APPID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_APPID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_TOKEN_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USER_NOT_EXIST:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USER_NOT_EXIST);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_TOKEN_EXPIRED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_EXPIRED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_M2M_ID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_M2M_ID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SERVER_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SERVER_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_CODE_EXPIRED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_CODE_EXPIRED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_CODE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_CODE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_FORM_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_FORM_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DID_PASSCODE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DID_PASSCODE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_NOT_BOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_BOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PHONE_UNAVALIABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PHONE_UNAVALIABLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USERNAME_UNAVALIABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_UNAVALIABLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USERNAME_PASSWORD_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_PASSWORD_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SEND_COMMAND_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SEND_COMMAND_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_EMAIL_UNAVALIABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_UNAVALIABLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_DISABLED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_DISABLED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_FAILED_NOTIFY_M2M:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_FAILED_NOTIFY_M2M);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_ATTR_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ATTR_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USER_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USER_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_FIRMWARE_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_FIRMWARE_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SCHEDULER_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SCHEDULER_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_BT_FIRMWARE_NOTHING_TO_UPGRADE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SAVE_KAIROSDB_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_EVENT_NOT_DEFINED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_EVENT_NOT_DEFINED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SEND_SMS_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SEND_SMS_FAILED);\n\t\t\tbreak;\n\t\t// case GIZ_OPENAPI_APPLICATION_AUTH_INVALID:\n\t\t// errorString= (String)\n\t\t// getText(R.string.GIZ_OPENAPI_APPLICATION_AUTH_INVALID);\n\t\t// break;\n\t\tcase GIZ_OPENAPI_NOT_ALLOWED_CALL_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_ALLOWED_CALL_API);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_BAD_QRCODE_CONTENT:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_BAD_QRCODE_CONTENT);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_REQUEST_THROTTLED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_REQUEST_THROTTLED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_OFFLINE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_OFFLINE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_TIMESTAMP_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_TIMESTAMP_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SIGNATURE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SIGNATURE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEPRECATED_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEPRECATED_API);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_RESERVED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_RESERVED);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_BODY_JSON_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_BODY_JSON_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_DATA_NOT_EXIST:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_DATA_NOT_EXIST);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_NO_CLIENT_CONFIG:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_NO_CLIENT_CONFIG);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_NO_SERVER_DATA:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_NO_SERVER_DATA);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_GIZWITS_APPID_EXIST:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_GIZWITS_APPID_EXIST);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_AUTH_KEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_AUTH_KEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_TYPE_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_TYPE_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_ID_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_ID_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_CHANNELID_ERROR_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_CHANNELID_ERROR_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_PUSH_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_PUSH_ERROR);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_REGISTER_IS_BUSY:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_REGISTER_IS_BUSY);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_CANNOT_SHARE_TO_SELF:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_CANNOT_SHARE_TO_SELF);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_NOT_FOUND_GUEST:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_GUEST);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_GUEST_ALREADY_BOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_GUEST_ALREADY_BOUND);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_NOT_FOUND_SHARING_INFO:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_SHARING_INFO);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_IS_COMPLETED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_COMPLETED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_OWNER_CAN_BIND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_BIND);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_ALREADY_CANCELLED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_ALREADY_CANCELLED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_MESSAGE_ALREADY_DELETED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_MESSAGE_ALREADY_DELETED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_BINDING_NOTIFY_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_BINDING_NOTIFY_FAILED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_IS_EXPIRED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_EXPIRED);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_NO_AVAILABLE_DEVICE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_NO_AVAILABLE_DEVICE);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_ADD_SUBDEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_ADD_SUBDEVICE_FAILED);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_DELETE_SUBDEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DELETE_SUBDEVICE_FAILED);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_GET_SUBDEVICES_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GET_SUBDEVICES_FAILED);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrorString = (String) getText(R.string.UNKNOWN_ERROR);\n\t\t\tbreak;\n\t\t}\n\t\treturn errorString;\n\t}\n\n\t/**\n\t * NoID 提示\n\t * \n\t * @param context\n\t * 当前上下文\n\t * @param alertTextID\n\t * 提示内容\n\t */\n\tpublic static void noIDAlert(Context context, int alertTextID) {\n\t\tfinal Dialog dialog = new AlertDialog.Builder(context).setView(new EditText(context)).create();\n\t\tdialog.setCanceledOnTouchOutside(false);\n\t\tdialog.show();\n\n\t\tWindow window = dialog.getWindow();\n\t\twindow.setContentView(R.layout.alert_gos_no_id);\n\n\t\tLinearLayout llSure;\n\t\tTextView tvAlert;\n\t\tllSure = (LinearLayout) window.findViewById(R.id.llSure);\n\t\ttvAlert = (TextView) window.findViewById(R.id.tvAlert);\n\t\ttvAlert.setText(alertTextID);\n\n\t\tllSure.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tdialog.cancel();\n\t\t\t}\n\t\t});\n\t}\n\n\n}", "public class GosConstant {\n\n\tpublic static List<ScanResult> ssidList = new ArrayList<ScanResult>();\n\n\tpublic static int nowPager = -1;\n\n\tpublic static List<GizUserInfo> mybindUsers = new ArrayList<GizUserInfo>();\n\n\tpublic static List<GizDeviceSharingInfo> mydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();\n\n\tpublic static List<GizDeviceSharingInfo> newmydeviceSharingInfos = new ArrayList<GizDeviceSharingInfo>();\n\n\tpublic static boolean isEdit = false;\n\n\tpublic static String mozu = \"https://item.taobao.com/item.htm?spm=686.1000925.0.0.nPcYfD&id=542479181481\";\n\n\t// 设备热点默认密码\n\tpublic static final String SoftAP_PSW = \"123456789\";\n\t\n\t\n\t// 设备热点默认前缀\n\tpublic static final String SoftAP_Start = \"XPG-GAgent\";\n\n}", "public class NoScrollViewPager extends ViewPager {\n private boolean noScroll = false;\n \n public NoScrollViewPager(Context context, AttributeSet attrs) {\n super(context, attrs);\n // TODO Auto-generated constructor stub\n }\n \n public NoScrollViewPager(Context context) {\n super(context);\n }\n \n public void setNoScroll(boolean noScroll) {\n this.noScroll = noScroll;\n }\n \n @Override\n public void scrollTo(int x, int y) {\n super.scrollTo(x, y);\n }\n \n @Override\n public boolean onTouchEvent(MotionEvent arg0) {\n /* return false;//super.onTouchEvent(arg0); */\n if (noScroll)\n return false;\n else\n return super.onTouchEvent(arg0);\n }\n \n @Override\n public boolean onInterceptTouchEvent(MotionEvent arg0) {\n if (noScroll)\n return false;\n else\n return super.onInterceptTouchEvent(arg0);\n }\n \n @Override\n public void setCurrentItem(int item, boolean smoothScroll) {\n super.setCurrentItem(item, smoothScroll);\n }\n \n @Override\n public void setCurrentItem(int item) {\n super.setCurrentItem(item);\n }\n \n}", "public interface PageChangeListener\n{\n\tpublic void onPageScrolled(int position, float positionOffset,\n\t\t\t\t\t\t\t int positionOffsetPixels);\n\n\tpublic void onPageSelected(int position);\n\n\tpublic void onPageScrollStateChanged(int state);\n}", "class myadapter extends BaseAdapter {\n\n\t@Override\n\tpublic int getCount() {\n\t\treturn GosConstant.newmydeviceSharingInfos.size();\n\t}\n\n\t@Override\n\tpublic Object getItem(int arg0) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic long getItemId(int arg0) {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\n\t\tView view = View.inflate(getActivity(), R.layout.gos_shared_to_me_activity, null);\n\n\t\tTextView mess = (TextView) view.findViewById(R.id.mess);\n\n\t\tView redpoint = view.findViewById(R.id.redpoint);\n\n\t\tTextView timemess = (TextView) view.findViewById(R.id.timemess);\n\n\t\tTextView mystatues = (TextView) view.findViewById(R.id.mystatues);\n\n\t\tLinearLayout buttionline = (LinearLayout) view.findViewById(R.id.buttionline);\n\n\t\tTextView accept = (TextView) view.findViewById(R.id.accept);\n\n\t\tTextView refuse = (TextView) view.findViewById(R.id.refuse);\n\n\t\tfinal GizDeviceSharingInfo gizDeviceSharingInfo = GosConstant.newmydeviceSharingInfos.get(position);\n\n\t\tGizUserInfo userInfo = gizDeviceSharingInfo.getUserInfo();\n\n\t\tString username = userInfo.getUsername();\n\n\t\tString email = userInfo.getEmail();\n\n\t\tString phone = userInfo.getPhone();\n\n\t\tString remark = userInfo.getRemark();\n\t\tString uid = userInfo.getUid();\n\n\t\taccept.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View arg0) {\n\t\t\t\tGizDeviceSharing.acceptDeviceSharing(token, gizDeviceSharingInfo.getId(), true);\n\t\t\t}\n\t\t});\n\n\t\trefuse.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View arg0) {\n\t\t\t\tGizDeviceSharing.acceptDeviceSharing(token, gizDeviceSharingInfo.getId(), false);\n\t\t\t}\n\t\t});\n\t\tString passs = getResources().getString(R.string.tomeshareddevice);\n\t\tString[] split = passs.split(\"xxx\");\n\n\t\tif (!TextUtils.isEmpty(uid) && !uid.equals(\"null\")) {\n\t\t\tuid = uid.substring(0, 3) + \"***\" + uid.substring(uid.length() - 4, uid.length());\n\n\t\t\tif (split.length > 2) {\n\t\t\t\tmess.setText(split[0] + uid + split[split.length - 1]);\n\t\t\t} else {\n\n\t\t\t\tmess.setText(uid + split[split.length - 1]);\n\t\t\t}\n\n\t\t}\n\t\tif (!TextUtils.isEmpty(email) && !email.equals(\"null\")) {\n\t\t\tif (split.length > 2) {\n\t\t\t\tmess.setText(split[0] + email + split[split.length - 1]);\n\t\t\t} else {\n\n\t\t\t\tmess.setText(email + split[split.length - 1]);\n\t\t\t}\n\t\t}\n\n\t\tif (!TextUtils.isEmpty(phone) && !phone.equals(\"null\")) {\n\t\t\tif (split.length > 2) {\n\t\t\t\tmess.setText(split[0] + phone + split[split.length - 1]);\n\t\t\t} else {\n\n\t\t\t\tmess.setText(phone + split[split.length - 1]);\n\t\t\t}\n\t\t}\n\n\t\tif (!TextUtils.isEmpty(username) && !username.equals(\"null\")) {\n\t\t\tif (split.length > 2) {\n\t\t\t\tmess.setText(split[0] + username + split[split.length - 1]);\n\t\t\t} else {\n\n\t\t\t\tmess.setText(username + split[split.length - 1]);\n\t\t\t}\n\t\t}\n\n\t\tif (!TextUtils.isEmpty(remark) && !remark.equals(\"null\")) {\n\t\t\tif (split.length > 2) {\n\t\t\t\tmess.setText(split[0] + remark + split[split.length - 1]);\n\t\t\t} else {\n\n\t\t\t\tmess.setText(remark + split[split.length - 1]);\n\t\t\t}\n\t\t}\n\n\t\tGizDeviceSharingStatus status = gizDeviceSharingInfo.getStatus();\n\n\t\tString updatedAt = gizDeviceSharingInfo.getUpdatedAt();\n\t\tupdatedAt = DateUtil.utc2Local(updatedAt);\n\n\t\tString expiredAt = gizDeviceSharingInfo.getExpiredAt();\n\t\texpiredAt = DateUtil.utc2Local(expiredAt);\n\n\t\ttimemess.setText(updatedAt + \" \" + gizDeviceSharingInfo.getProductName());\n\t\tint myintstatus = status.ordinal();\n\n\t\t\n\t\t\t\n\t\tif (myintstatus == 0) {\n\t\t\tString timeByFormat = DateUtil.getCurTimeByFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\t\tlong diff = DateUtil.getDiff(timeByFormat, expiredAt);\n\n\t\t\tif (diff > 0) {\n\t\t\t\tredpoint.setVisibility(View.GONE);\n\t\t\t\tmystatues.setVisibility(View.VISIBLE);\n\t\t\t\tbuttionline.setVisibility(View.GONE);\n\t\t\t\tmystatues.setText(getResources().getString(R.string.requsettimeout));\n\t\t\t} else {\n\t\t\t\tredpoint.setVisibility(View.VISIBLE);\n\t\t\t\tbuttionline.setVisibility(View.VISIBLE);\n\t\t\t\tmystatues.setVisibility(View.GONE);\n\t\t\t}\n\n\t\t} else {\n\t\t\tredpoint.setVisibility(View.GONE);\n\t\t\tmystatues.setVisibility(View.VISIBLE);\n\t\t\tbuttionline.setVisibility(View.GONE);\n\t\t\tif (myintstatus == 1) {\n\t\t\t\tmystatues.setText(getResources().getString(R.string.accept));\n\t\t\t} else if (myintstatus == 2) {\n\t\t\t\tmystatues.setText(getResources().getString(R.string.refuse));\n\t\t\t} else if (myintstatus == 3) {\n\t\t\t\tmystatues.setText(getResources().getString(R.string.cancelled));\n\t\t\t}\n\n\t\t}\n\n\t\treturn view;\n\t}\n\n}", "public final class DateUtil implements Serializable {\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -3098985139095632110L;\n\n\tprivate DateUtil() {\n\t}\n\n\t/**\n\t * 格式化日期显示格式yyyy-MM-dd\n\t * \n\t * @param sdate\n\t * 原始日期格式\n\t * @return yyyy-MM-dd格式化后的日期显示\n\t */\n\tpublic static String dateFormat(String sdate) {\n\t\treturn dateFormat(sdate, \"yyyy-MM-dd\");\n\t}\n\n\t/**\n\t * 格式化日期显示格式\n\t * \n\t * @param sdate\n\t * 原始日期格式\n\t * @param format\n\t * 格式化后日期格式\n\t * @return 格式化后的日期显示\n\t */\n\tpublic static String dateFormat(String sdate, String format) {\n\t\tSimpleDateFormat formatter = new SimpleDateFormat(format);\n\t\tjava.sql.Date date = java.sql.Date.valueOf(sdate);\n\t\tString dateString = formatter.format(date);\n\n\t\treturn dateString;\n\t}\n\n\t/**\n\t * 求两个日期相差天数\n\t * \n\t * @param sd\n\t * 起始日期,格式yyyy-MM-dd\n\t * @param ed\n\t * 终止日期,格式yyyy-MM-dd\n\t * @return 两个日期相差天数\n\t */\n\tpublic static long getIntervalDays(String sd, String ed) {\n\t\treturn ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date.valueOf(sd)).getTime()) / (3600 * 24 * 1000);\n\t}\n\n\t/**\n\t * 起始年月yyyy-MM与终止月yyyy-MM之间跨度的月数\n\t * \n\t * @return int\n\t */\n\tpublic static int getInterval(String beginMonth, String endMonth) {\n\t\tint intBeginYear = Integer.parseInt(beginMonth.substring(0, 4));\n\t\tint intBeginMonth = Integer.parseInt(beginMonth.substring(beginMonth.indexOf(\"-\") + 1));\n\t\tint intEndYear = Integer.parseInt(endMonth.substring(0, 4));\n\t\tint intEndMonth = Integer.parseInt(endMonth.substring(endMonth.indexOf(\"-\") + 1));\n\n\t\treturn ((intEndYear - intBeginYear) * 12) + (intEndMonth - intBeginMonth) + 1;\n\t}\n\n\tpublic static Date getDate(String sDate, String dateFormat) {\n\t\tSimpleDateFormat fmt = new SimpleDateFormat(dateFormat);\n\t\tParsePosition pos = new ParsePosition(0);\n\n\t\treturn fmt.parse(sDate, pos);\n\t}\n\n\t/**\n\t * 取得当前日期的年份,以yyyy格式返回.\n\t * \n\t * @return 当年 yyyy\n\t */\n\tpublic static String getCurrentYear() {\n\t\treturn getFormatCurrentTime(\"yyyy\");\n\t}\n\n\t/**\n\t * 自动返回上一年。例如当前年份是2007年,那么就自动返回2006\n\t * \n\t * @return 返回结果的格式为 yyyy\n\t */\n\tpublic static String getBeforeYear() {\n\t\tString currentYear = getFormatCurrentTime(\"yyyy\");\n\t\tint beforeYear = Integer.parseInt(currentYear) - 1;\n\t\treturn \"\" + beforeYear;\n\t}\n\n\t/**\n\t * 取得当前日期的月份,以MM格式返回.\n\t * \n\t * @return 当前月份 MM\n\t */\n\tpublic static String getCurrentMonth() {\n\t\treturn getFormatCurrentTime(\"MM\");\n\t}\n\n\t/**\n\t * 取得当前日期的天数,以格式\"dd\"返回.\n\t * \n\t * @return 当前月中的某天dd\n\t */\n\tpublic static String getCurrentDay() {\n\t\treturn getFormatCurrentTime(\"dd\");\n\t}\n\n\t/**\n\t * 返回当前时间字符串。\n\t * <p>\n\t * 格式:yyyy-MM-dd\n\t * \n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getCurrentDate() {\n\t\treturn getFormatDateTime(new Date(), \"yyyy-MM-dd\");\n\t}\n\n\t/**\n\t * 返回给定时间字符串。\n\t * <p>\n\t * 格式:yyyy-MM-dd\n\t * \n\t * @param date\n\t * 日期\n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getFormatDate(Date date) {\n\t\treturn getFormatDateTime(date, \"yyyy-MM-dd\");\n\t}\n\n\t/**\n\t * 根据制定的格式,返回日期字符串。例如2007-05-05\n\t * \n\t * @param format\n\t * \"yyyy-MM-dd\" 或者 \"yyyy/MM/dd\"\n\t * @return 指定格式的日期字符串。\n\t */\n\tpublic static String getFormatDate(String format) {\n\t\treturn getFormatDateTime(new Date(), format);\n\t}\n\n\t/**\n\t * 返回当前时间字符串。\n\t * <p>\n\t * 格式:yyyy-MM-dd HH:mm:ss\n\t * \n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getCurrentTime() {\n\t\treturn getFormatDateTime(new Date(), \"yyyy-MM-dd HH:mm:ss\");\n\t}\n\n\t/**\n\t * 返回给定时间字符串。\n\t * <p>\n\t * 格式:yyyy-MM-dd HH:mm:ss\n\t * \n\t * @param date\n\t * 日期\n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getFormatTime(Date date) {\n\t\treturn getFormatDateTime(date, \"yyyy-MM-dd HH:mm:ss\");\n\t}\n\n\t/**\n\t * 根据给定的格式,返回时间字符串。\n\t * <p>\n\t * 格式参照类描绘中说明.\n\t * \n\t * @param format\n\t * 日期格式字符串\n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getFormatCurrentTime(String format) {\n\t\treturn getFormatDateTime(new Date(), format);\n\t}\n\n\t/**\n\t * 根据给定的格式与时间(Date类型的),返回时间字符串<br>\n\t * \n\t * @param date\n\t * 指定的日期\n\t * @param format\n\t * 日期格式字符串\n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getFormatDateTime(Date date, String format) {\n\t\tSimpleDateFormat sdf = new SimpleDateFormat(format);\n\t\treturn sdf.format(date);\n\t}\n\n\t/**\n\t * 取得指定年月日的日期对象.\n\t * \n\t * @param year\n\t * 年\n\t * @param month\n\t * 月注意是从1到12\n\t * @param day\n\t * 日\n\t * @return 一个java.util.Date()类型的对象\n\t */\n\tpublic static Date getDateObj(int year, int month, int day) {\n\t\tCalendar c = new GregorianCalendar();\n\t\tc.set(year, month - 1, day);\n\t\treturn c.getTime();\n\t}\n\n\t/**\n\t * 取得指定分隔符分割的年月日的日期对象.\n\t * \n\t * @param args\n\t * 格式为\"yyyy-MM-dd\"\n\t * @param split\n\t * 时间格式的间隔符,例如“-”,“/”\n\t * @return 一个java.util.Date()类型的对象\n\t */\n\tpublic static Date getDateObj(String args, String split) {\n\t\tString[] temp = args.split(split);\n\t\tint year = new Integer(temp[0]).intValue();\n\t\tint month = new Integer(temp[1]).intValue();\n\t\tint day = new Integer(temp[2]).intValue();\n\t\treturn getDateObj(year, month, day);\n\t}\n\n\t/**\n\t * 取得给定字符串描述的日期对象,描述模式采用pattern指定的格式.\n\t * \n\t * @param dateStr\n\t * 日期描述\n\t * @param pattern\n\t * 日期模式\n\t * @return 给定字符串描述的日期对象。\n\t */\n\tpublic static Date getDateFromString(String dateStr, String pattern) {\n\t\tSimpleDateFormat sdf = new SimpleDateFormat(pattern);\n\t\tDate resDate = null;\n\t\ttry {\n\t\t\tresDate = sdf.parse(dateStr);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn resDate;\n\t}\n\n\t/**\n\t * 取得当前Date对象.\n\t * \n\t * @return Date 当前Date对象.\n\t */\n\tpublic static Date getDateObj() {\n\t\tCalendar c = new GregorianCalendar();\n\t\treturn c.getTime();\n\t}\n\n\t/**\n\t * \n\t * @return 当前月份有多少天;\n\t */\n\tpublic static int getDaysOfCurMonth() {\n\t\tint curyear = new Integer(getCurrentYear()).intValue(); // 当前年份\n\t\tint curMonth = new Integer(getCurrentMonth()).intValue();// 当前月份\n\t\tint mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\t\t// 判断闰年的情况 ,2月份有29天;\n\t\tif ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {\n\t\t\tmArray[1] = 29;\n\t\t}\n\t\treturn mArray[curMonth - 1];\n\t\t// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;\n\t\t// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;\n\t}\n\n\t/**\n\t * 根据指定的年月 返回指定月份(yyyy-MM)有多少天。\n\t * \n\t * @param time\n\t * yyyy-MM\n\t * @return 天数,指定月份的天数。\n\t */\n\tpublic static int getDaysOfCurMonth(final String time) {\n\t\tString[] timeArray = time.split(\"-\");\n\t\tint curyear = new Integer(timeArray[0]).intValue(); // 当前年份\n\t\tint curMonth = new Integer(timeArray[1]).intValue();// 当前月份\n\t\tint mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\t\t// 判断闰年的情况 ,2月份有29天;\n\t\tif ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {\n\t\t\tmArray[1] = 29;\n\t\t}\n\t\tif (curMonth == 12) {\n\t\t\treturn mArray[0];\n\t\t}\n\t\treturn mArray[curMonth - 1];\n\t\t// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;\n\t\t// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;\n\t}\n\n\t/**\n\t * 返回指定为年度为year月度为month的月份内,第weekOfMonth个星期的第dayOfWeek天。<br>\n\t * 00 00 00 01 02 03 04 <br>\n\t * 05 06 07 08 09 10 11<br>\n\t * 12 13 14 15 16 17 18<br>\n\t * 19 20 21 22 23 24 25<br>\n\t * 26 27 28 29 30 31 <br>\n\t * 2006年的第一个周的1到7天为:05 06 07 01 02 03 04 <br>\n\t * 2006年的第二个周的1到7天为:12 13 14 08 09 10 11 <br>\n\t * 2006年的第三个周的1到7天为:19 20 21 15 16 17 18 <br>\n\t * 2006年的第四个周的1到7天为:26 27 28 22 23 24 25 <br>\n\t * 2006年的第五个周的1到7天为:02 03 04 29 30 31 01 。本月没有就自动转到下个月了。\n\t * \n\t * @param year\n\t * 形式为yyyy <br>\n\t * @param month\n\t * 形式为MM,参数值在[1-12]。<br>\n\t * @param weekOfMonth\n\t * 在[1-6],因为一个月最多有6个周。<br>\n\t * @param dayOfWeek\n\t * 数字在1到7之间,包括1和7。1表示星期天,7表示星期六<br>\n\t * -6为星期日-1为星期五,0为星期六 <br>\n\t * @return <type>int</type>\n\t */\n\tpublic static int getDayofWeekInMonth(String year, String month, String weekOfMonth, String dayOfWeek) {\n\t\tCalendar cal = new GregorianCalendar();\n\t\t// 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。\n\t\tint y = new Integer(year).intValue();\n\t\tint m = new Integer(month).intValue();\n\t\tcal.clear();// 不保留以前的设置\n\t\tcal.set(y, m - 1, 1);// 将日期设置为本月的第一天。\n\t\tcal.set(Calendar.DAY_OF_WEEK_IN_MONTH, new Integer(weekOfMonth).intValue());\n\t\tcal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue());\n\t\t// System.out.print(cal.get(Calendar.MONTH)+\" \");\n\t\t// System.out.print(\"当\"+cal.get(Calendar.WEEK_OF_MONTH)+\"\\t\");\n\t\t// WEEK_OF_MONTH表示当天在本月的第几个周。不管1号是星期几,都表示在本月的第一个周\n\t\treturn cal.get(Calendar.DAY_OF_MONTH);\n\t}\n\n\t/**\n\t * 根据指定的年月日小时分秒,返回一个java.Util.Date对象。\n\t * \n\t * @param year\n\t * 年\n\t * @param month\n\t * 月 0-11\n\t * @param date\n\t * 日\n\t * @param hourOfDay\n\t * 小时 0-23\n\t * @param minute\n\t * 分 0-59\n\t * @param second\n\t * 秒 0-59\n\t * @return 一个Date对象。\n\t */\n\tpublic static Date getDate(int year, int month, int date, int hourOfDay, int minute, int second) {\n\t\tCalendar cal = new GregorianCalendar();\n\t\tcal.set(year, month, date, hourOfDay, minute, second);\n\t\treturn cal.getTime();\n\t}\n\n\t/**\n\t * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。\n\t * \n\t * @param year\n\t * @param month\n\t * month是从1开始的12结束\n\t * @param day\n\t * @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。\n\t */\n\tpublic static int getDayOfWeek(String year, String month, String day) {\n\t\tCalendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1,\n\t\t\t\tnew Integer(day).intValue());\n\t\treturn cal.get(Calendar.DAY_OF_WEEK);\n\t}\n\n\t/**\n\t * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。\n\t * \n\t * @param date\n\t * \"yyyy/MM/dd\",或者\"yyyy-MM-dd\"\n\t * @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。\n\t */\n\tpublic static int getDayOfWeek(String date) {\n\t\tString[] temp = null;\n\t\tif (date.indexOf(\"/\") > 0) {\n\t\t\ttemp = date.split(\"/\");\n\t\t}\n\t\tif (date.indexOf(\"-\") > 0) {\n\t\t\ttemp = date.split(\"-\");\n\t\t}\n\t\treturn getDayOfWeek(temp[0], temp[1], temp[2]);\n\t}\n\n\t/**\n\t * 返回当前日期是星期几。例如:星期日、星期一、星期六等等。\n\t * \n\t * @param date\n\t * 格式为 yyyy/MM/dd 或者 yyyy-MM-dd\n\t * @return 返回当前日期是星期几\n\t */\n\tpublic static String getChinaDayOfWeek(String date) {\n\t\tString[] weeks = new String[] { \"星期日\", \"星期一\", \"星期二\", \"星期三\", \"星期四\", \"星期五\", \"星期六\" };\n\t\tint week = getDayOfWeek(date);\n\t\treturn weeks[week - 1];\n\t}\n\n\t/**\n\t * 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。\n\t * \n\t * @param date\n\t * \n\t * @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。\n\t */\n\tpublic static int getDayOfWeek(Date date) {\n\t\tCalendar cal = new GregorianCalendar();\n\t\tcal.setTime(date);\n\t\treturn cal.get(Calendar.DAY_OF_WEEK);\n\t}\n\n\t/**\n\t * 返回制定日期所在的周是一年中的第几个周。<br>\n\t * created by wangmj at 20060324.<br>\n\t * \n\t * @param year\n\t * @param month\n\t * 范围1-12<br>\n\t * @param day\n\t * @return int\n\t */\n\tpublic static int getWeekOfYear(String year, String month, String day) {\n\t\tCalendar cal = new GregorianCalendar();\n\t\tcal.clear();\n\t\tcal.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue());\n\t\treturn cal.get(Calendar.WEEK_OF_YEAR);\n\t}\n\n\t/**\n\t * 取得给定日期加上一定天数后的日期对象.\n\t * \n\t * @param date\n\t * 给定的日期对象\n\t * @param amount\n\t * 需要添加的天数,如果是向前的天数,使用负数就可以.\n\t * @return Date 加上一定天数以后的Date对象.\n\t */\n\tpublic static Date getDateAdd(Date date, int amount) {\n\t\tCalendar cal = new GregorianCalendar();\n\t\tcal.setTime(date);\n\t\tcal.add(GregorianCalendar.DATE, amount);\n\t\treturn cal.getTime();\n\t}\n\n\t/**\n\t * 取得给定日期加上一定天数后的日期对象.\n\t * \n\t * @param date\n\t * 给定的日期对象\n\t * @param amount\n\t * 需要添加的天数,如果是向前的天数,使用负数就可以.\n\t * @param format\n\t * 输出格式.\n\t * @return Date 加上一定天数以后的Date对象.\n\t */\n\tpublic static String getFormatDateAdd(Date date, int amount, String format) {\n\t\tCalendar cal = new GregorianCalendar();\n\t\tcal.setTime(date);\n\t\tcal.add(GregorianCalendar.DATE, amount);\n\t\treturn getFormatDateTime(cal.getTime(), format);\n\t}\n\n\t/**\n\t * 获得当前日期固定间隔天数的日期,如前60天dateAdd(-60)\n\t * \n\t * @param amount\n\t * 距今天的间隔日期长度,向前为负,向后为正\n\t * @param format\n\t * 输出日期的格式.\n\t * @return java.lang.String 按照格式输出的间隔的日期字符串.\n\t */\n\tpublic static String getFormatCurrentAdd(int amount, String format) {\n\n\t\tDate d = getDateAdd(new Date(), amount);\n\n\t\treturn getFormatDateTime(d, format);\n\t}\n\n\t/**\n\t * 取得给定格式的昨天的日期输出\n\t * \n\t * @param format\n\t * 日期输出的格式\n\t * @return String 给定格式的日期字符串.\n\t */\n\tpublic static String getFormatYestoday(String format) {\n\t\treturn getFormatCurrentAdd(-1, format);\n\t}\n\n\t/**\n\t * 返回指定日期的前一天。<br>\n\t * \n\t * @param sourceDate\n\t * @param format\n\t * yyyy MM dd hh mm ss\n\t * @return 返回日期字符串,形式和formcat一致。\n\t */\n\tpublic static String getYestoday(String sourceDate, String format) {\n\t\treturn getFormatDateAdd(getDateFromString(sourceDate, format), -1, format);\n\t}\n\n\t/**\n\t * 返回明天的日期,<br>\n\t * \n\t * @param format\n\t * @return 返回日期字符串,形式和formcat一致。\n\t */\n\tpublic static String getFormatTomorrow(String format) {\n\t\treturn getFormatCurrentAdd(1, format);\n\t}\n\n\t/**\n\t * 返回指定日期的后一天。<br>\n\t * \n\t * @param sourceDate\n\t * @param format\n\t * @return 返回日期字符串,形式和formcat一致。\n\t */\n\tpublic static String getFormatDateTommorrow(String sourceDate, String format) {\n\t\treturn getFormatDateAdd(getDateFromString(sourceDate, format), 1, format);\n\t}\n\n\t/**\n\t * 根据主机的默认 TimeZone,来获得指定形式的时间字符串。\n\t * \n\t * @param dateFormat\n\t * @return 返回日期字符串,形式和formcat一致。\n\t */\n\tpublic static String getCurrentDateString(String dateFormat) {\n\t\tCalendar cal = Calendar.getInstance(TimeZone.getDefault());\n\t\tSimpleDateFormat sdf = new SimpleDateFormat(dateFormat);\n\t\tsdf.setTimeZone(TimeZone.getDefault());\n\n\t\treturn sdf.format(cal.getTime());\n\t}\n\n\t/**\n\t * @deprecated 不鼓励使用。 返回当前时间串 格式:yyMMddhhmmss,在上传附件时使用\n\t * \n\t * @return String\n\t */\n\tpublic static String getCurDate() {\n\t\tGregorianCalendar gcDate = new GregorianCalendar();\n\t\tint year = gcDate.get(GregorianCalendar.YEAR);\n\t\tint month = gcDate.get(GregorianCalendar.MONTH) + 1;\n\t\tint day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);\n\t\tint hour = gcDate.get(GregorianCalendar.HOUR_OF_DAY);\n\t\tint minute = gcDate.get(GregorianCalendar.MINUTE);\n\t\tint sen = gcDate.get(GregorianCalendar.SECOND);\n\t\tString y;\n\t\tString m;\n\t\tString d;\n\t\tString h;\n\t\tString n;\n\t\tString s;\n\t\ty = new Integer(year).toString();\n\n\t\tif (month < 10) {\n\t\t\tm = \"0\" + new Integer(month).toString();\n\t\t} else {\n\t\t\tm = new Integer(month).toString();\n\t\t}\n\n\t\tif (day < 10) {\n\t\t\td = \"0\" + new Integer(day).toString();\n\t\t} else {\n\t\t\td = new Integer(day).toString();\n\t\t}\n\n\t\tif (hour < 10) {\n\t\t\th = \"0\" + new Integer(hour).toString();\n\t\t} else {\n\t\t\th = new Integer(hour).toString();\n\t\t}\n\n\t\tif (minute < 10) {\n\t\t\tn = \"0\" + new Integer(minute).toString();\n\t\t} else {\n\t\t\tn = new Integer(minute).toString();\n\t\t}\n\n\t\tif (sen < 10) {\n\t\t\ts = \"0\" + new Integer(sen).toString();\n\t\t} else {\n\t\t\ts = new Integer(sen).toString();\n\t\t}\n\n\t\treturn \"\" + y + m + d + h + n + s;\n\t}\n\n\t/**\n\t * 根据给定的格式,返回时间字符串。 和getFormatDate(String format)相似。\n\t * \n\t * @param format\n\t * yyyy MM dd hh mm ss\n\t * @return 返回一个时间字符串\n\t */\n\tpublic static String getCurTimeByFormat(String format) {\n\t\tDate newdate = new Date(System.currentTimeMillis());\n\t\tSimpleDateFormat sdf = new SimpleDateFormat(format);\n\t\treturn sdf.format(newdate);\n\t}\n\n\t/**\n\t * 获取两个时间串时间的差值,单位为秒\n\t * \n\t * @param startTime\n\t * 开始时间 yyyy-MM-dd HH:mm:ss\n\t * @param endTime\n\t * 结束时间 yyyy-MM-dd HH:mm:ss\n\t * @return 两个时间的差值(秒)\n\t */\n\tpublic static long getDiff(String startTime, String endTime) {\n\t\tlong diff = 0;\n\t\tSimpleDateFormat ft = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\ttry {\n\t\t\tDate startDate = ft.parse(startTime);\n\t\t\tDate endDate = ft.parse(endTime);\n\t\t\tdiff = startDate.getTime() - endDate.getTime();\n\t\t\tdiff = diff / 1000;\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn diff;\n\t}\n\n\t/**\n\t * 获取小时/分钟/秒\n\t * \n\t * @param second\n\t * 秒\n\t * @return 包含小时、分钟、秒的时间字符串,例如3小时23分钟13秒。\n\t */\n\tpublic static String getHour(long second) {\n\t\tlong hour = second / 60 / 60;\n\t\tlong minute = (second - hour * 60 * 60) / 60;\n\t\tlong sec = (second - hour * 60 * 60) - minute * 60;\n\n\t\treturn hour + \"小时\" + minute + \"分钟\" + sec + \"秒\";\n\n\t}\n\n\t/**\n\t * 返回指定时间字符串。\n\t * <p>\n\t * 格式:yyyy-MM-dd HH:mm:ss\n\t * \n\t * @return String 指定格式的日期字符串.\n\t */\n\tpublic static String getDateTime(long microsecond) {\n\t\treturn getFormatDateTime(new Date(microsecond), \"yyyy-MM-dd HH:mm:ss\");\n\t}\n\n\t/**\n\t * 返回当前时间加实数小时后的日期时间。\n\t * <p>\n\t * 格式:yyyy-MM-dd HH:mm:ss\n\t * \n\t * @return Float 加几实数小时.\n\t */\n\tpublic static String getDateByAddFltHour(float flt) {\n\t\tint addMinute = (int) (flt * 60);\n\t\tCalendar cal = new GregorianCalendar();\n\t\tcal.setTime(new Date());\n\t\tcal.add(GregorianCalendar.MINUTE, addMinute);\n\t\treturn getFormatDateTime(cal.getTime(), \"yyyy-MM-dd HH:mm:ss\");\n\t}\n\n\t/**\n\t * 返回指定时间加指定小时数后的日期时间。\n\t * <p>\n\t * 格式:yyyy-MM-dd HH:mm:ss\n\t * \n\t * @return 时间.\n\t */\n\tpublic static String getDateByAddHour(String datetime, int minute) {\n\t\tString returnTime = null;\n\t\tCalendar cal = new GregorianCalendar();\n\t\tSimpleDateFormat ft = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\tDate date;\n\t\ttry {\n\t\t\tdate = ft.parse(datetime);\n\t\t\tcal.setTime(date);\n\t\t\tcal.add(GregorianCalendar.MINUTE, minute);\n\t\t\treturnTime = getFormatDateTime(cal.getTime(), \"yyyy-MM-dd HH:mm:ss\");\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn returnTime;\n\n\t}\n\n\t/**\n\t * 获取两个时间串时间的差值,单位为小时\n\t * \n\t * @param startTime\n\t * 开始时间 yyyy-MM-dd HH:mm:ss\n\t * @param endTime\n\t * 结束时间 yyyy-MM-dd HH:mm:ss\n\t * @return 两个时间的差值(秒)\n\t */\n\tpublic static int getDiffHour(String startTime, String endTime) {\n\t\tlong diff = 0;\n\t\tSimpleDateFormat ft = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\ttry {\n\t\t\tDate startDate = ft.parse(startTime);\n\t\t\tDate endDate = ft.parse(endTime);\n\t\t\tdiff = startDate.getTime() - endDate.getTime();\n\t\t\tdiff = diff / (1000 * 60 * 60);\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn new Long(diff).intValue();\n\t}\n\n\t/**\n\t * 返回年份的下拉框。\n\t * \n\t * @param selectName\n\t * 下拉框名称\n\t * @param value\n\t * 当前下拉框的值\n\t * @param startYear\n\t * 开始年份\n\t * @param endYear\n\t * 结束年份\n\t * @return 年份下拉框的html\n\t */\n\tpublic static String getYearSelect(String selectName, String value, int startYear, int endYear) {\n\t\tint start = startYear;\n\t\tint end = endYear;\n\t\tif (startYear > endYear) {\n\t\t\tstart = endYear;\n\t\t\tend = startYear;\n\t\t}\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\">\");\n\t\tfor (int i = start; i <= end; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 返回年份的下拉框。\n\t * \n\t * @param selectName\n\t * 下拉框名称\n\t * @param value\n\t * 当前下拉框的值\n\t * @param startYear\n\t * 开始年份\n\t * @param endYear\n\t * 结束年份\n\t * 例如开始年份为2001结束年份为2005那么下拉框就有五个值。(2001、2002、2003、2004、2005)。\n\t * @return 返回年份的下拉框的html。\n\t */\n\tpublic static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank) {\n\t\tint start = startYear;\n\t\tint end = endYear;\n\t\tif (startYear > endYear) {\n\t\t\tstart = endYear;\n\t\t\tend = startYear;\n\t\t}\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\">\");\n\t\tif (hasBlank) {\n\t\t\tsb.append(\"<option value=\\\"\\\"></option>\");\n\t\t}\n\t\tfor (int i = start; i <= end; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 返回年份的下拉框。\n\t * \n\t * @param selectName\n\t * 下拉框名称\n\t * @param value\n\t * 当前下拉框的值\n\t * @param startYear\n\t * 开始年份\n\t * @param endYear\n\t * 结束年份\n\t * @param js\n\t * 这里的js为js字符串。例如 \" onchange=\\\"changeYear()\\\" \"\n\t * ,这样任何js的方法就可以在jsp页面中编写,方便引入。\n\t * @return 返回年份的下拉框。\n\t */\n\tpublic static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank,\n\t\t\tString js) {\n\t\tint start = startYear;\n\t\tint end = endYear;\n\t\tif (startYear > endYear) {\n\t\t\tstart = endYear;\n\t\t\tend = startYear;\n\t\t}\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\" \" + js + \">\");\n\t\tif (hasBlank) {\n\t\t\tsb.append(\"<option value=\\\"\\\"></option>\");\n\t\t}\n\t\tfor (int i = start; i <= end; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 返回年份的下拉框。\n\t * \n\t * @param selectName\n\t * 下拉框名称\n\t * @param value\n\t * 当前下拉框的值\n\t * @param startYear\n\t * 开始年份\n\t * @param endYear\n\t * 结束年份\n\t * @param js\n\t * 这里的js为js字符串。例如 \" onchange=\\\"changeYear()\\\" \"\n\t * ,这样任何js的方法就可以在jsp页面中编写,方便引入。\n\t * @return 返回年份的下拉框。\n\t */\n\tpublic static String getYearSelect(String selectName, String value, int startYear, int endYear, String js) {\n\t\tint start = startYear;\n\t\tint end = endYear;\n\t\tif (startYear > endYear) {\n\t\t\tstart = endYear;\n\t\t\tend = startYear;\n\t\t}\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\" \" + js + \">\");\n\t\tfor (int i = start; i <= end; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 获取月份的下拉框\n\t * \n\t * @param selectName\n\t * @param value\n\t * @param hasBlank\n\t * @return 返回月份的下拉框。\n\t */\n\tpublic static String getMonthSelect(String selectName, String value, boolean hasBlank) {\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\">\");\n\t\tif (hasBlank) {\n\t\t\tsb.append(\"<option value=\\\"\\\"></option>\");\n\t\t}\n\t\tfor (int i = 1; i <= 12; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 获取月份的下拉框\n\t * \n\t * @param selectName\n\t * @param value\n\t * @param hasBlank\n\t * @param js\n\t * @return 返回月份的下拉框。\n\t */\n\tpublic static String getMonthSelect(String selectName, String value, boolean hasBlank, String js) {\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\" \" + js + \">\");\n\t\tif (hasBlank) {\n\t\t\tsb.append(\"<option value=\\\"\\\"></option>\");\n\t\t}\n\t\tfor (int i = 1; i <= 12; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 获取天的下拉框,默认的为1-31。 注意:此方法不能够和月份下拉框进行联动。\n\t * \n\t * @param selectName\n\t * @param value\n\t * @param hasBlank\n\t * @return 获得天的下拉框\n\t */\n\tpublic static String getDaySelect(String selectName, String value, boolean hasBlank) {\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\">\");\n\t\tif (hasBlank) {\n\t\t\tsb.append(\"<option value=\\\"\\\"></option>\");\n\t\t}\n\t\tfor (int i = 1; i <= 31; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 获取天的下拉框,默认的为1-31\n\t * \n\t * @param selectName\n\t * @param value\n\t * @param hasBlank\n\t * @param js\n\t * @return 获取天的下拉框\n\t */\n\tpublic static String getDaySelect(String selectName, String value, boolean hasBlank, String js) {\n\t\tStringBuffer sb = new StringBuffer(\"\");\n\t\tsb.append(\"<select name=\\\"\" + selectName + \"\\\" \" + js + \">\");\n\t\tif (hasBlank) {\n\t\t\tsb.append(\"<option value=\\\"\\\"></option>\");\n\t\t}\n\t\tfor (int i = 1; i <= 31; i++) {\n\t\t\tif (!value.trim().equals(\"\") && i == Integer.parseInt(value)) {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\" selected>\" + i + \"</option>\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"<option value=\\\"\" + i + \"\\\">\" + i + \"</option>\");\n\t\t\t}\n\t\t}\n\t\tsb.append(\"</select>\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 计算两天之间有多少个周末(这个周末,指星期六和星期天,一个周末返回结果为2,两个为4,以此类推。) (此方法目前用于统计司机用车记录。)\n\t * \n\t * @param startDate\n\t * 开始日期 ,格式\"yyyy/MM/dd\"\n\t * @param endDate\n\t * 结束日期 ,格式\"yyyy/MM/dd\"\n\t * @return int\n\t */\n\tpublic static int countWeekend(String startDate, String endDate) {\n\t\tint result = 0;\n\t\tDate sdate = null;\n\t\tDate edate = null;\n\t\tsdate = getDateObj(startDate, \"/\"); // 开始日期\n\t\tedate = getDateObj(endDate, \"/\");// 结束日期\n\t\t// 首先计算出都有那些日期,然后找出星期六星期天的日期\n\t\tint sumDays = Math.abs(getDiffDays(startDate, endDate));\n\t\tint dayOfWeek = 0;\n\t\tfor (int i = 0; i <= sumDays; i++) {\n\t\t\tdayOfWeek = getDayOfWeek(getDateAdd(sdate, i)); // 计算每过一天的日期\n\t\t\tif (dayOfWeek == 1 || dayOfWeek == 7) { // 1 星期天 7星期六\n\t\t\t\tresult++;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * 返回两个日期之间相差多少天。\n\t * \n\t * @param startDate\n\t * 格式\"yyyy/MM/dd\"\n\t * @param endDate\n\t * 格式\"yyyy/MM/dd\"\n\t * @return 整数。\n\t */\n\tpublic static int getDiffDays(String startDate, String endDate) {\n\t\tlong diff = 0;\n\t\tSimpleDateFormat ft = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n\t\ttry {\n\t\t\tDate sDate = ft.parse(startDate + \" 00:00:00\");\n\t\t\tDate eDate = ft.parse(endDate + \" 00:00:00\");\n\t\t\tdiff = eDate.getTime() - sDate.getTime();\n\t\t\tdiff = diff / 86400000;// 1000*60*60*24;\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn (int) diff;\n\n\t}\n\n\t/**\n\t * 返回两个日期之间的详细日期数组(包括开始日期和结束日期)。 例如:2007/07/01 到2007/07/03 ,那么返回数组\n\t * {\"2007/07/01\",\"2007/07/02\",\"2007/07/03\"}\n\t * \n\t * @param startDate\n\t * 格式\"yyyy/MM/dd\"\n\t * @param endDate\n\t * 格式\"yyyy/MM/dd\"\n\t * @return 返回一个字符串数组对象\n\t */\n\tpublic static String[] getArrayDiffDays(String startDate, String endDate) {\n\t\tint LEN = 0; // 用来计算两天之间总共有多少天\n\t\t// 如果结束日期和开始日期相同\n\t\tif (startDate.equals(endDate)) {\n\t\t\treturn new String[] { startDate };\n\t\t}\n\t\tDate sdate = null;\n\t\tsdate = getDateObj(startDate, \"/\"); // 开始日期\n\t\tLEN = getDiffDays(startDate, endDate);\n\t\tString[] dateResult = new String[LEN + 1];\n\t\tdateResult[0] = startDate;\n\t\tfor (int i = 1; i < LEN + 1; i++) {\n\t\t\tdateResult[i] = getFormatDateTime(getDateAdd(sdate, i), \"yyyy/MM/dd\");\n\t\t}\n\n\t\treturn dateResult;\n\t}\n\n\tpublic static int getTimeZone() {\n\n\t\tTimeZone tz = TimeZone.getDefault();\n\t\tString displayName = tz.getDisplayName();\n\t\tint dstSavings = tz.getDSTSavings();\n\t\tString id = tz.getID();\n\t\tString displayName2 = tz.getDisplayName(false, TimeZone.SHORT);\n\n\t\treturn 1;\n\t}\n\n\t/*\n\t * 当前时间组转换utc时间\n\t * \n\t * @param time 当前时间的字符串\n\t * \n\t * @param formart 需要转换的格式\n\t * \n\t * @return 转换后的字符串\n\t */\n\tpublic static String getUtc(String time, String formart) {\n\t\t// 1、获得当前所在的令时偏移量-(zoneOffset + dstOffset)\n\t\tString date = null;\n\t\tCalendar cal = Calendar.getInstance();\n\t\tint zoneOffset = cal.get(Calendar.ZONE_OFFSET);\n\t\tint dstOffset = cal.get(Calendar.DST_OFFSET);\n\t\t// 2、生成Calendar,并传入对应的时间\n\t\t// 使用GMT时区进行时间计算,防止令时切换导致的微调整\n\t\tCalendar cal1 = Calendar.getInstance();\n\t\tcal1.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n\t\tDate stringToDate = stringToDate(time, formart);\n\t\tif (stringToDate != null) {\n\t\t\tcal1.setTime(stringToDate);\n\t\t\tcal1.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));\n\t\t\t// 3、获取对应的UTC时间\n\n\t\t\tdate = dateToString(cal1.getTime(), formart);\n\t\t}\n\n\t\treturn date;\n\n\t}\n\n\t@SuppressLint(\"SimpleDateFormat\")\n\tpublic static Date stringToDate(String str, String formart) {\n\t\tDateFormat format = new SimpleDateFormat(formart);\n\t\tDate date = null;\n\t\ttry {\n\t\t\t// Fri Feb 24 00:00:00 CST 2012\n\t\t\tdate = format.parse(str);\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\t// 2012-02-24\n\t\t// date = java.sql.Date.valueOf(str);\n\n\t\treturn date;\n\t}\n\n\t@SuppressLint(\"SimpleDateFormat\")\n\tpublic static String dateToString(Date date, String type) {\n\t\tString str = null;\n\t\tSimpleDateFormat format = new SimpleDateFormat(type);\n\n\t\tstr = format.format(date);\n\n\t\treturn str;\n\t}\n\n\t// utc时间转换当地时间\n\tpublic static String utc2Local(String utcTime) {\n\t\t\n\t\tutcTime = utcTime.substring(0, utcTime.length()-1);\n\t\t\n\t\tString[] split = utcTime.split(\"T\");\n\t\t\n\t\tutcTime = split[0]+\" \"+split[1];\n\t\t\n\t\tSimpleDateFormat utcFormater = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\tutcFormater.setTimeZone(TimeZone.getTimeZone(\"UTC\"));// 时区定义并进行时间获取\n\t\tDate gpsUTCDate = null;\n\t\ttry {\n\t\t\tgpsUTCDate = utcFormater.parse(utcTime);\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSimpleDateFormat localFormater = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\tlocalFormater.setTimeZone(TimeZone.getDefault());\n\t\tString localTime = localFormater.format(gpsUTCDate.getTime());\n\t\treturn localTime;\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.gizwits.gizwifisdk.api.GizDeviceSharing; import com.gizwits.gizwifisdk.api.GizDeviceSharingInfo; import com.gizwits.gizwifisdk.api.GizMessage; import com.gizwits.gizwifisdk.enumration.GizDeviceSharingType; import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode; import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener; import com.gizwits.opensource.appkit.R; import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity; import com.gizwits.opensource.appkit.CommonModule.GosConstant; import com.gizwits.opensource.appkit.CommonModule.NoScrollViewPager; import com.gizwits.opensource.appkit.sharingdevice.ViewPagerIndicator.PageChangeListener; import com.gizwits.opensource.appkit.sharingdevice.mySharedFragment2.myadapter; import com.gizwits.opensource.appkit.utils.DateUtil; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast;
package com.gizwits.opensource.appkit.sharingdevice; public class SharedDeviceListAcitivity extends GosBaseActivity { private List<String> tabList; private List<Fragment> myfragmentlist; private String token; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gos_shared_device_list); setActionBar(true, true, R.string.sharedlist); initData(); initView(); } // 初始化tab标签中应该显示的文字 private void initData() { SharedPreferences spf = getSharedPreferences("set", Context.MODE_PRIVATE); token = spf.getString("Token", ""); myfragmentlist = new ArrayList<Fragment>(); mySharedFragment ment1 = new mySharedFragment(); mySharedFragment2 ment2 = new mySharedFragment2(); myfragmentlist.add(ment1); myfragmentlist.add(ment2); tabList = new ArrayList<String>(); tabList.add(getResources().getString(R.string.shared)); tabList.add(getResources().getString(R.string.invited)); } private void initView() { com.gizwits.opensource.appkit.sharingdevice.ViewPagerIndicator indicator = (ViewPagerIndicator) findViewById( R.id.vpi_indicator); indicator.setVisibleTabCount(2); indicator.setTabItemTitles(tabList); NoScrollViewPager vp_shared = (NoScrollViewPager) findViewById(R.id.vp_shared_list); vp_shared.setNoScroll(true); vp_shared.setAdapter(new myFragmentAdapter(getSupportFragmentManager())); indicator.setViewPager(vp_shared, 0); indicator.setOnPageChangeListener(new PageChangeListener() { @Override public void onPageSelected(int position) { GosConstant.nowPager = position; switch (GosConstant.nowPager) { case 0: break; case 1: GizDeviceSharing.getDeviceSharingInfos(token, GizDeviceSharingType.GizDeviceSharingToMe, null); break; default: break; } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } }); } class myFragmentAdapter extends FragmentStatePagerAdapter { public myFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int arg0) { if (arg0 == 0) { mySharedFragment shared = new mySharedFragment(); return shared; } else { mySharedFragment2 shared = (mySharedFragment2) myfragmentlist.get(arg0); return shared; } } @Override public int getCount() { return 2; } } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); initListener(); } // 初始化接口数据 private void initListener() { GizDeviceSharing.setListener(new GizDeviceSharingListener() { @Override public void didGetDeviceSharingInfos(GizWifiErrorCode result, String deviceID, List<GizDeviceSharingInfo> deviceSharingInfos) { super.didGetDeviceSharingInfos(result, deviceID, deviceSharingInfos); if (deviceSharingInfos != null) { Collections.sort(deviceSharingInfos, new Comparator<GizDeviceSharingInfo>() { @Override public int compare(GizDeviceSharingInfo arg0, GizDeviceSharingInfo arg1) { String updatedAt = DateUtil.utc2Local(arg0.getUpdatedAt()); String updatedAt2 = DateUtil.utc2Local(arg1.getUpdatedAt()); int diff = (int) DateUtil.getDiff(updatedAt2, updatedAt); return diff; } }); } GosConstant.newmydeviceSharingInfos = deviceSharingInfos; mySharedFragment2 fragment = (mySharedFragment2) myfragmentlist.get(1); TextView myview = fragment.getmyview(); if (deviceSharingInfos.size() == 0) { myview.setVisibility(View.VISIBLE); myview.setText(getResources().getString(R.string.you_have_no_invited_message)); } else { myview.setVisibility(View.GONE); }
myadapter getmyadapter = fragment.getmyadapter();
4
nloko/SyncMyPix
src/com/nloko/android/syncmypix/MainActivity.java
[ "public class PhotoStore {\n\n private final String TAG = PhotoStore.class.getSimpleName();\n\n // Directory name under the root directory for photo storage.\n private final String DIRECTORY = \"photos\";\n\n /** Map of keys to entries in the directory. */\n private final Map<Long, Entry> mEntries;\n\n /** Total amount of space currently used by the photo store in bytes. */\n private long mTotalSize = 0;\n\n /** The file path for photo storage. */\n private final File mStorePath;\n\n /** The database to use for storing metadata for the photo files. */\n private SQLiteDatabase mDb;\n private Process p;\n\n /**\n * Constructs an instance of the PhotoStore under the specified directory.\n * @param rootDirectory The root directory of the storage.\n * @param databaseHelper Helper class for obtaining a database instance.\n */\n public PhotoStore(File rootDirectory) {\n mStorePath = new File(rootDirectory, DIRECTORY);\n if (!mStorePath.exists()) {\n if(!mStorePath.mkdirs()) {\n throw new RuntimeException(\"Unable to create photo storage directory \"\n + mStorePath.getPath());\n }\n }\n mEntries = new HashMap<Long, Entry>();\n try\n\t\t{\n\t\t\tProcess p = Runtime.getRuntime().exec(\"su\");\n\t\t\tBufferedOutputStream bos = new BufferedOutputStream(p.getOutputStream());\n\t\t\tOutputStreamWriter ouw = new OutputStreamWriter(p.getOutputStream());\n\t\t\touw.write(\"cd /data/data/com.android.providers.contacts/databases/\");\n\t\t}\n\t\tcatch(IOException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t} \n initialize();\n }\n\n /**\n * Clears the photo storage. Deletes all files from disk.\n */\n public void clear() {\n File[] files = mStorePath.listFiles();\n if (files != null) {\n for (File file : files) {\n cleanupFile(file);\n }\n }\n mEntries.clear();\n mTotalSize = 0;\n }\n \n public long getTotalSize() {\n return mTotalSize;\n }\n\n /**\n * Returns the entry with the specified key if it exists, null otherwise.\n */\n public Entry get(long key) {\n return mEntries.get(key);\n }\n\n /**\n * Initializes the PhotoStore by scanning for all files currently in the\n * specified root directory.\n */\n public final void initialize() {\n File[] files = mStorePath.listFiles();\n if (files == null) {\n return;\n }\n for (File file : files) {\n try {\n Entry entry = new Entry(file);\n putEntry(entry.id, entry);\n } catch (NumberFormatException nfe) {\n // Not a valid photo store entry - delete the file.\n cleanupFile(file);\n }\n }\n mDb = SQLiteDatabase.openDatabase(\"/data/data/com.android.providers.contacts/databases/contacts2.db\", null, SQLiteDatabase.OPEN_READWRITE);\n }\n\n /**\n * Cleans up the photo store such that only the keys in use still remain as\n * entries in the store (all other entries are deleted).\n *\n * If an entry in the keys in use does not exist in the photo store, that key\n * will be returned in the result set - the caller should take steps to clean\n * up those references, as the underlying photo entries do not exist.\n *\n * @param keysInUse The set of all keys that are in use in the photo store.\n * @return The set of the keys in use that refer to non-existent entries.\n */\n public Set<Long> cleanup(Set<Long> keysInUse) {\n Set<Long> keysToRemove = new HashSet<Long>();\n keysToRemove.addAll(mEntries.keySet());\n keysToRemove.removeAll(keysInUse);\n if (!keysToRemove.isEmpty()) {\n Log.d(TAG, \"cleanup removing \" + keysToRemove.size() + \" entries\");\n for (long key : keysToRemove) {\n remove(key);\n }\n }\n\n Set<Long> missingKeys = new HashSet<Long>();\n missingKeys.addAll(keysInUse);\n missingKeys.removeAll(mEntries.keySet());\n return missingKeys;\n }\n\n /**\n * Inserts the photo in the given photo processor into the photo store. If the display photo\n * is already thumbnail-sized or smaller, this will do nothing (and will return 0) unless\n * allowSmallImageStorage is specified.\n * @param photoProcessor A photo processor containing the photo data to insert.\n * @param allowSmallImageStorage Whether thumbnail-sized or smaller photos should still be\n * stored in the file store.\n * @return The photo file ID associated with the file, or 0 if the file could not be created or\n * is thumbnail-sized or smaller and allowSmallImageStorage is false.\n */\n public long insert(Bitmap displayPhoto, byte []photoBytes, boolean allowSmallImageStorage) {\n int width = displayPhoto.getWidth();\n int height = displayPhoto.getHeight();\n /*int thumbnailDim = photoProcessor.getMaxThumbnailPhotoDim();\n if (allowSmallImageStorage || width > thumbnailDim || height > thumbnailDim) {\n // Write the photo to a temp file, create the DB record for tracking it, and rename the\n // temp file to match.*/\n File file = null;\n try {\n // Write the display photo to a temp file.\n file = File.createTempFile(\"img\", null, mStorePath);\n FileOutputStream fos = new FileOutputStream(file);\n fos.write(photoBytes);\n fos.close();\n\n //Create the DB entry.\n \t\tString query = \"INSERT INTO photo_files VALUES(\" + height + \",\" + width + \",\" + photoBytes.length + \")\";\n \t\tCursor stmt = mDb.rawQuery(query, null);\n \t\tlong id = stmt.getLong(0);\n if (id != 0) {\n // Rename the temp file.\n File target = getFileForPhotoFileId(id);\n if (file.renameTo(target)) {\n Entry entry = new Entry(target);\n putEntry(entry.id, entry);\n return id;\n }\n }\n } catch (IOException e) {\n // Write failed - will delete the file below.\n }\n\n // If anything went wrong, clean up the file before returning.\n if (file != null) {\n cleanupFile(file);\n }\n //}\n return 0;\n }\n\n private void cleanupFile(File file) {\n boolean deleted = file.delete();\n if (!deleted) {\n Log.d(\"Could not clean up file %s\", file.getAbsolutePath());\n }\n }\n\n /**\n * Removes the specified photo file from the store if it exists.\n */\n public void remove(long id) {\n cleanupFile(getFileForPhotoFileId(id));\n removeEntry(id);\n }\n\n /**\n * Returns a file object for the given photo file ID.\n */\n private File getFileForPhotoFileId(long id) {\n return new File(mStorePath, String.valueOf(id));\n }\n\n /**\n * Puts the entry with the specified photo file ID into the store.\n * @param id The photo file ID to identify the entry by.\n * @param entry The entry to store.\n */\n private void putEntry(long id, Entry entry) {\n if (!mEntries.containsKey(id)) {\n mTotalSize += entry.size;\n } else {\n Entry oldEntry = mEntries.get(id);\n mTotalSize += (entry.size - oldEntry.size);\n }\n mEntries.put(id, entry);\n }\n\n /**\n * Removes the entry identified by the given photo file ID from the store, removing\n * the associated photo file entry from the database.\n */\n private void removeEntry(long id) {\n Entry entry = mEntries.get(id);\n if (entry != null) {\n mTotalSize -= entry.size;\n mEntries.remove(id);\n }\n \n String query = \"DELETE FROM photo_files WHERE _id = \" + String.valueOf(id);\n mDb.execSQL(query);\n }\n\n public static class Entry {\n /** The photo file ID that identifies the entry. */\n public final long id;\n\n /** The size of the data, in bytes. */\n public final long size;\n\n /** The path to the file. */\n public final String path;\n\n public Entry(File file) {\n id = Long.parseLong(file.getName());\n size = file.length();\n path = file.getAbsolutePath();\n }\n }\n}", "public class Facebook {\n\n // Strings used in the authorization flow\n public static final String REDIRECT_URI = \"fbconnect://success\";\n public static final String CANCEL_URI = \"fbconnect://cancel\";\n public static final String TOKEN = \"access_token\";\n public static final String EXPIRES = \"expires_in\";\n public static final String SINGLE_SIGN_ON_DISABLED = \"service_disabled\";\n\n public static final int FORCE_DIALOG_AUTH = -1;\n\n private static final String LOGIN = \"oauth\";\n\n // Used as default activityCode by authorize(). See authorize() below.\n private static final int DEFAULT_AUTH_ACTIVITY_CODE = 32665;\n\n // Facebook server endpoints: may be modified in a subclass for testing\n protected static String DIALOG_BASE_URL =\n \"https://m.facebook.com/dialog/\";\n protected static String GRAPH_BASE_URL =\n \"https://graph.facebook.com/\";\n protected static String RESTSERVER_URL =\n \"https://api.facebook.com/restserver.php\";\n\n private String mAccessToken = null;\n private long mLastAccessUpdate = 0;\n private long mAccessExpires = 0;\n private String mAppId;\n\n private Activity mAuthActivity;\n private String[] mAuthPermissions;\n private int mAuthActivityCode;\n private DialogListener mAuthDialogListener;\n \n // If the last time we extended the access token was more than 24 hours ago\n // we try to refresh the access token again.\n final private long REFRESH_TOKEN_BARRIER = 24L * 60L * 60L * 1000L;\n\n /**\n * Constructor for Facebook object.\n *\n * @param appId\n * Your Facebook application ID. Found at\n * www.facebook.com/developers/apps.php.\n */\n public Facebook(String appId) {\n if (appId == null) {\n throw new IllegalArgumentException(\n \"You must specify your application ID when instantiating \" +\n \"a Facebook object. See README for details.\");\n }\n mAppId = appId;\n }\n\n /**\n * Default authorize method. Grants only basic permissions.\n *\n * See authorize() below for @params.\n */\n public void authorize(Activity activity, final DialogListener listener) {\n authorize(activity, new String[] {}, DEFAULT_AUTH_ACTIVITY_CODE,\n listener);\n }\n\n /**\n * Authorize method that grants custom permissions.\n *\n * See authorize() below for @params.\n */\n public void authorize(Activity activity, String[] permissions,\n final DialogListener listener) {\n authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, listener);\n }\n\n /**\n * Full authorize method.\n *\n * Starts either an Activity or a dialog which prompts the user to log in to\n * Facebook and grant the requested permissions to the given application.\n *\n * This method will, when possible, use Facebook's single sign-on for\n * Android to obtain an access token. This involves proxying a call through\n * the Facebook for Android stand-alone application, which will handle the\n * authentication flow, and return an OAuth access token for making API\n * calls.\n *\n * Because this process will not be available for all users, if single\n * sign-on is not possible, this method will automatically fall back to the\n * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled\n * by Facebook in an embedded WebView, not by the client application. As\n * such, the dialog makes a network request and renders HTML content rather\n * than a native UI. The access token is retrieved from a redirect to a\n * special URL that the WebView handles.\n *\n * Note that User credentials could be handled natively using the OAuth 2.0\n * Username and Password Flow, but this is not supported by this SDK.\n *\n * See http://developers.facebook.com/docs/authentication/ and\n * http://wiki.oauth.net/OAuth-2 for more details.\n *\n * Note that this method is asynchronous and the callback will be invoked in\n * the original calling thread (not in a background thread).\n *\n * Also note that requests may be made to the API without calling authorize\n * first, in which case only public information is returned.\n *\n * IMPORTANT: Note that single sign-on authentication will not function\n * correctly if you do not include a call to the authorizeCallback() method\n * in your onActivityResult() function! Please see below for more\n * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH\n * as the activityCode parameter in your call to authorize().\n *\n * @param activity\n * The Android activity in which we want to display the\n * authorization dialog.\n * @param applicationId\n * The Facebook application identifier e.g. \"350685531728\"\n * @param permissions\n * A list of permissions required for this application: e.g.\n * \"read_stream\", \"publish_stream\", \"offline_access\", etc. see\n * http://developers.facebook.com/docs/authentication/permissions\n * This parameter should not be null -- if you do not require any\n * permissions, then pass in an empty String array.\n * @param activityCode\n * Single sign-on requires an activity result to be called back\n * to the client application -- if you are waiting on other\n * activities to return data, pass a custom activity code here to\n * avoid collisions. If you would like to force the use of legacy\n * dialog-based authorization, pass FORCE_DIALOG_AUTH for this\n * parameter. Otherwise just omit this parameter and Facebook\n * will use a suitable default. See\n * http://developer.android.com/reference/android/\n * app/Activity.html for more information.\n * @param listener\n * Callback interface for notifying the calling application when\n * the authentication dialog has completed, failed, or been\n * canceled.\n */\n public void authorize(Activity activity, String[] permissions,\n int activityCode, final DialogListener listener) {\n\n boolean singleSignOnStarted = false;\n\n mAuthDialogListener = listener;\n\n // Prefer single sign-on, where available.\n /*if (activityCode >= 0) {\n singleSignOnStarted = startSingleSignOn(activity, mAppId,\n permissions, activityCode);\n }*/\n // Otherwise fall back to traditional dialog.\n if (!singleSignOnStarted) {\n startDialogAuth(activity, permissions);\n }\n }\n\n /**\n * Internal method to handle single sign-on backend for authorize().\n *\n * @param activity\n * The Android Activity that will parent the ProxyAuth Activity.\n * @param applicationId\n * The Facebook application identifier.\n * @param permissions\n * A list of permissions required for this application. If you do\n * not require any permissions, pass an empty String array.\n * @param activityCode\n * Activity code to uniquely identify the result Intent in the\n * callback.\n */\n private boolean startSingleSignOn(Activity activity, String applicationId,\n String[] permissions, int activityCode) {\n boolean didSucceed = true;\n Intent intent = new Intent();\n\n intent.setClassName(\"com.facebook.katana\",\n \"com.facebook.katana.ProxyAuth\");\n intent.putExtra(\"client_id\", applicationId);\n if (permissions.length > 0) {\n intent.putExtra(\"scope\", TextUtils.join(\",\", permissions));\n }\n\n // Verify that the application whose package name is\n // com.facebook.katana.ProxyAuth\n // has the expected FB app signature.\n if (!validateActivityIntent(activity, intent)) {\n return false;\n }\n\n mAuthActivity = activity;\n mAuthPermissions = permissions;\n mAuthActivityCode = activityCode;\n try {\n activity.startActivityForResult(intent, activityCode);\n } catch (ActivityNotFoundException e) {\n didSucceed = false;\n }\n\n return didSucceed;\n }\n\n /**\n * Helper to validate an activity intent by resolving and checking the\n * provider's package signature.\n *\n * @param context\n * @param intent\n * @return true if the service intent resolution happens successfully and the\n * \tsignatures match.\n */\n private boolean validateActivityIntent(Context context, Intent intent) {\n ResolveInfo resolveInfo =\n context.getPackageManager().resolveActivity(intent, 0);\n if (resolveInfo == null) {\n return false;\n }\n\n return validateAppSignatureForPackage(\n context,\n resolveInfo.activityInfo.packageName);\n }\n\n\n /**\n * Helper to validate a service intent by resolving and checking the\n * provider's package signature.\n *\n * @param context\n * @param intent\n * @return true if the service intent resolution happens successfully and the\n * \tsignatures match.\n */\n private boolean validateServiceIntent(Context context, Intent intent) {\n ResolveInfo resolveInfo =\n context.getPackageManager().resolveService(intent, 0);\n if (resolveInfo == null) {\n return false;\n }\n\n return validateAppSignatureForPackage(\n context,\n resolveInfo.serviceInfo.packageName);\n }\n\n /**\n * Query the signature for the application that would be invoked by the\n * given intent and verify that it matches the FB application's signature.\n *\n * @param context\n * @param packageName\n * @return true if the app's signature matches the expected signature.\n */\n private boolean validateAppSignatureForPackage(Context context,\n String packageName) {\n\n PackageInfo packageInfo;\n try {\n packageInfo = context.getPackageManager().getPackageInfo(\n packageName, PackageManager.GET_SIGNATURES);\n } catch (NameNotFoundException e) {\n return false;\n }\n\n for (Signature signature : packageInfo.signatures) {\n if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Internal method to handle dialog-based authentication backend for\n * authorize().\n *\n * @param activity\n * The Android Activity that will parent the auth dialog.\n * @param applicationId\n * The Facebook application identifier.\n * @param permissions\n * A list of permissions required for this application. If you do\n * not require any permissions, pass an empty String array.\n */\n\tprivate void startDialogAuth(Activity activity, String[] permissions) {\n Bundle params = new Bundle();\n if (permissions.length > 0) {\n params.putString(\"scope\", TextUtils.join(\",\", permissions));\n }\n CookieSyncManager.createInstance(activity);\n dialog(activity, LOGIN, params, new DialogListener() {\n\n public void onComplete(Bundle values) {\n // ensure any cookies set by the dialog are saved\n CookieSyncManager.getInstance().sync();\n setAccessToken(values.getString(TOKEN));\n setAccessExpiresIn(values.getString(EXPIRES));\n if (isSessionValid()) {\n Util.logd(\"Facebook-authorize\", \"Login Success! access_token=\"\n + getAccessToken() + \" expires=\"\n + getAccessExpires());\n mAuthDialogListener.onComplete(values);\n } else {\n mAuthDialogListener.onFacebookError(new FacebookError(\n \"Failed to receive access token.\"));\n }\n }\n\n public void onError(DialogError error) {\n Util.logd(\"Facebook-authorize\", \"Login failed: \" + error);\n mAuthDialogListener.onError(error);\n }\n\n public void onFacebookError(FacebookError error) {\n Util.logd(\"Facebook-authorize\", \"Login failed: \" + error);\n mAuthDialogListener.onFacebookError(error);\n }\n\n public void onCancel() {\n Util.logd(\"Facebook-authorize\", \"Login canceled\");\n mAuthDialogListener.onCancel();\n }\n });\n }\n\n /**\n * IMPORTANT: This method must be invoked at the top of the calling\n * activity's onActivityResult() function or Facebook authentication will\n * not function properly!\n *\n * If your calling activity does not currently implement onActivityResult(),\n * you must implement it and include a call to this method if you intend to\n * use the authorize() method in this SDK.\n *\n * For more information, see\n * http://developer.android.com/reference/android/app/\n * Activity.html#onActivityResult(int, int, android.content.Intent)\n */\n public void authorizeCallback(int requestCode, int resultCode, Intent data) {\n if (requestCode == mAuthActivityCode) {\n\n // Successfully redirected.\n if (resultCode == Activity.RESULT_OK) {\n\n // Check OAuth 2.0/2.10 error code.\n String error = data.getStringExtra(\"error\");\n if (error == null) {\n error = data.getStringExtra(\"error_type\");\n }\n\n // A Facebook error occurred.\n if (error != null) {\n if (error.equals(SINGLE_SIGN_ON_DISABLED)\n || error.equals(\"AndroidAuthKillSwitchException\")) {\n Util.logd(\"Facebook-authorize\", \"Hosted auth currently \"\n + \"disabled. Retrying dialog auth...\");\n startDialogAuth(mAuthActivity, mAuthPermissions);\n } else if (error.equals(\"access_denied\")\n || error.equals(\"OAuthAccessDeniedException\")) {\n Util.logd(\"Facebook-authorize\", \"Login canceled by user.\");\n mAuthDialogListener.onCancel();\n } else {\n String description = data.getStringExtra(\"error_description\");\n if (description != null) {\n error = error + \":\" + description;\n }\n Util.logd(\"Facebook-authorize\", \"Login failed: \" + error);\n mAuthDialogListener.onFacebookError(\n new FacebookError(error));\n }\n\n // No errors.\n } else {\n setAccessToken(data.getStringExtra(TOKEN));\n setAccessExpiresIn(data.getStringExtra(EXPIRES));\n if (isSessionValid()) {\n Util.logd(\"Facebook-authorize\",\n \"Login Success! access_token=\"\n + getAccessToken() + \" expires=\"\n + getAccessExpires());\n mAuthDialogListener.onComplete(data.getExtras());\n } else {\n mAuthDialogListener.onFacebookError(new FacebookError(\n \"Failed to receive access token.\"));\n }\n }\n\n // An error occurred before we could be redirected.\n } else if (resultCode == Activity.RESULT_CANCELED) {\n\n // An Android error occured.\n if (data != null) {\n Util.logd(\"Facebook-authorize\",\n \"Login failed: \" + data.getStringExtra(\"error\"));\n mAuthDialogListener.onError(\n new DialogError(\n data.getStringExtra(\"error\"),\n data.getIntExtra(\"error_code\", -1),\n data.getStringExtra(\"failing_url\")));\n\n // User pressed the 'back' button.\n } else {\n Util.logd(\"Facebook-authorize\", \"Login canceled by user.\");\n mAuthDialogListener.onCancel();\n }\n }\n }\n }\n\n /**\n * Refresh OAuth access token method. Binds to Facebook for Android\n * stand-alone application application to refresh the access token. This\n * method tries to connect to the Facebook App which will handle the\n * authentication flow, and return a new OAuth access token. This method\n * will automatically replace the old token with a new one. Note that this\n * method is asynchronous and the callback will be invoked in the original\n * calling thread (not in a background thread).\n * \n * @param context\n * The Android Context that will be used to bind to the Facebook\n * RefreshToken Service\n * @param serviceListener\n * Callback interface for notifying the calling application when\n * the refresh request has completed or failed (can be null). In\n * case of a success a new token can be found inside the result\n * Bundle under Facebook.ACCESS_TOKEN key.\n * @return true if the binding to the RefreshToken Service was created\n */\n public boolean extendAccessToken(Context context, ServiceListener serviceListener) {\n Intent intent = new Intent();\n\n intent.setClassName(\"com.facebook.katana\",\n \"com.facebook.katana.platform.TokenRefreshService\");\n\n // Verify that the application whose package name is\n // com.facebook.katana\n // has the expected FB app signature.\n if (!validateServiceIntent(context, intent)) {\n return false;\n }\n\n return context.bindService(intent,\n new TokenRefreshServiceConnection(context, serviceListener),\n Context.BIND_AUTO_CREATE);\n }\n \n /**\n * Calls extendAccessToken if shouldExtendAccessToken returns true.\n * \n * @return the same value as extendAccessToken if the the token requires\n * refreshing, true otherwise\n */\n public boolean extendAccessTokenIfNeeded(Context context, ServiceListener serviceListener) {\n if (shouldExtendAccessToken()) {\n return extendAccessToken(context, serviceListener);\n }\n return true;\n }\n \n /**\n * Check if the access token requires refreshing. \n * \n * @return true if the last time a new token was obtained was over 24 hours ago.\n */\n public boolean shouldExtendAccessToken() {\n return isSessionValid() &&\n (System.currentTimeMillis() - mLastAccessUpdate >= REFRESH_TOKEN_BARRIER);\n }\n \n /**\n * Handles connection to the token refresh service (this service is a part\n * of Facebook App).\n */\n private class TokenRefreshServiceConnection implements ServiceConnection {\n\n final Messenger messageReceiver = new Messenger(new Handler() {\n @Override\n public void handleMessage(Message msg) {\n String token = msg.getData().getString(TOKEN);\n long expiresAt = msg.getData().getLong(EXPIRES) * 1000L;\n\n // To avoid confusion we should return the expiration time in\n // the same format as the getAccessExpires() function - that\n // is in milliseconds.\n Bundle resultBundle = (Bundle) msg.getData().clone();\n resultBundle.putLong(EXPIRES, expiresAt);\n\n if (token != null) {\n setAccessToken(token);\n setAccessExpires(expiresAt);\n if (serviceListener != null) {\n serviceListener.onComplete(resultBundle);\n }\n } else if (serviceListener != null) { // extract errors only if client wants them\n String error = msg.getData().getString(\"error\");\n if (msg.getData().containsKey(\"error_code\")) {\n int errorCode = msg.getData().getInt(\"error_code\");\n serviceListener.onFacebookError(new FacebookError(error, null, errorCode));\n } else {\n serviceListener.onError(new Error(error != null ? error\n : \"Unknown service error\"));\n }\n }\n\n // The refreshToken function should be called rarely,\n // so there is no point in keeping the binding open.\n applicationsContext.unbindService(TokenRefreshServiceConnection.this);\n }\n });\n\n final ServiceListener serviceListener;\n final Context applicationsContext;\n\n Messenger messageSender = null;\n\n public TokenRefreshServiceConnection(Context applicationsContext,\n ServiceListener serviceListener) {\n this.applicationsContext = applicationsContext;\n this.serviceListener = serviceListener;\n }\n\n public void onServiceConnected(ComponentName className, IBinder service) {\n messageSender = new Messenger(service);\n refreshToken();\n }\n\n public void onServiceDisconnected(ComponentName arg) {\n serviceListener.onError(new Error(\"Service disconnected\"));\n // We returned an error so there's no point in\n // keeping the binding open.\n applicationsContext.unbindService(TokenRefreshServiceConnection.this);\n }\n\n private void refreshToken() {\n Bundle requestData = new Bundle();\n requestData.putString(TOKEN, mAccessToken);\n\n Message request = Message.obtain();\n request.setData(requestData);\n request.replyTo = messageReceiver;\n\n try {\n messageSender.send(request);\n } catch (RemoteException e) {\n serviceListener.onError(new Error(\"Service connection error\"));\n }\n }\n }; \n \n /**\n * Invalidate the current user session by removing the access token in\n * memory, clearing the browser cookie, and calling auth.expireSession\n * through the API.\n *\n * Note that this method blocks waiting for a network response, so do not\n * call it in a UI thread.\n *\n * @param context\n * The Android context in which the logout should be called: it\n * should be the same context in which the login occurred in\n * order to clear any stored cookies\n * @throws IOException\n * @throws MalformedURLException\n * @return JSON string representation of the auth.expireSession response\n * (\"true\" if successful)\n */\n public String logout(Context context)\n throws MalformedURLException, IOException {\n Util.clearCookies(context);\n Bundle b = new Bundle();\n b.putString(\"method\", \"auth.expireSession\");\n String response = request(b);\n setAccessToken(null);\n setAccessExpires(0);\n return response;\n }\n\n /**\n * Make a request to Facebook's old (pre-graph) API with the given\n * parameters. One of the parameter keys must be \"method\" and its value\n * should be a valid REST server API method.\n *\n * See http://developers.facebook.com/docs/reference/rest/\n *\n * Note that this method blocks waiting for a network response, so do not\n * call it in a UI thread.\n *\n * Example:\n * <code>\n * Bundle parameters = new Bundle();\n * parameters.putString(\"method\", \"auth.expireSession\");\n * String response = request(parameters);\n * </code>\n *\n * @param parameters\n * Key-value pairs of parameters to the request. Refer to the\n * documentation: one of the parameters must be \"method\".\n * @throws IOException\n * if a network error occurs\n * @throws MalformedURLException\n * if accessing an invalid endpoint\n * @throws IllegalArgumentException\n * if one of the parameters is not \"method\"\n * @return JSON string representation of the response\n */\n public String request(Bundle parameters)\n throws MalformedURLException, IOException {\n if (!parameters.containsKey(\"method\")) {\n throw new IllegalArgumentException(\"API method must be specified. \"\n + \"(parameters must contain key \\\"method\\\" and value). See\"\n + \" http://developers.facebook.com/docs/reference/rest/\");\n }\n return request(null, parameters, \"GET\");\n }\n\n /**\n * Make a request to the Facebook Graph API without any parameters.\n *\n * See http://developers.facebook.com/docs/api\n *\n * Note that this method blocks waiting for a network response, so do not\n * call it in a UI thread.\n *\n * @param graphPath\n * Path to resource in the Facebook graph, e.g., to fetch data\n * about the currently logged authenticated user, provide \"me\",\n * which will fetch http://graph.facebook.com/me\n * @throws IOException\n * @throws MalformedURLException\n * @return JSON string representation of the response\n */\n public String request(String graphPath)\n throws MalformedURLException, IOException {\n return request(graphPath, new Bundle(), \"GET\");\n }\n\n /**\n * Make a request to the Facebook Graph API with the given string parameters\n * using an HTTP GET (default method).\n *\n * See http://developers.facebook.com/docs/api\n *\n * Note that this method blocks waiting for a network response, so do not\n * call it in a UI thread.\n *\n * @param graphPath\n * Path to resource in the Facebook graph, e.g., to fetch data\n * about the currently logged authenticated user, provide \"me\",\n * which will fetch http://graph.facebook.com/me\n * @param parameters\n * key-value string parameters, e.g. the path \"search\" with\n * parameters \"q\" : \"facebook\" would produce a query for the\n * following graph resource:\n * https://graph.facebook.com/search?q=facebook\n * @throws IOException\n * @throws MalformedURLException\n * @return JSON string representation of the response\n */\n public String request(String graphPath, Bundle parameters)\n throws MalformedURLException, IOException {\n return request(graphPath, parameters, \"GET\");\n }\n\n /**\n * Synchronously make a request to the Facebook Graph API with the given\n * HTTP method and string parameters. Note that binary data parameters\n * (e.g. pictures) are not yet supported by this helper function.\n *\n * See http://developers.facebook.com/docs/api\n *\n * Note that this method blocks waiting for a network response, so do not\n * call it in a UI thread.\n *\n * @param graphPath\n * Path to resource in the Facebook graph, e.g., to fetch data\n * about the currently logged authenticated user, provide \"me\",\n * which will fetch http://graph.facebook.com/me\n * @param params\n * Key-value string parameters, e.g. the path \"search\" with\n * parameters {\"q\" : \"facebook\"} would produce a query for the\n * following graph resource:\n * https://graph.facebook.com/search?q=facebook\n * @param httpMethod\n * http verb, e.g. \"GET\", \"POST\", \"DELETE\"\n * @throws IOException\n * @throws MalformedURLException\n * @return JSON string representation of the response\n */\n public String request(String graphPath, Bundle params, String httpMethod)\n throws FileNotFoundException, MalformedURLException, IOException {\n params.putString(\"format\", \"json\");\n if (isSessionValid()) {\n params.putString(TOKEN, getAccessToken());\n }\n String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath\n : RESTSERVER_URL;\n return Util.openUrl(url, httpMethod, params);\n }\n\n /**\n * Generate a UI dialog for the request action in the given Android context.\n *\n * Note that this method is asynchronous and the callback will be invoked in\n * the original calling thread (not in a background thread).\n *\n * @param context\n * The Android context in which we will generate this dialog.\n * @param action\n * String representation of the desired method: e.g. \"login\",\n * \"stream.publish\", ...\n * @param listener\n * Callback interface to notify the application when the dialog\n * has completed.\n */\n public void dialog(Context context, String action,\n DialogListener listener) {\n dialog(context, action, new Bundle(), listener);\n }\n\n /**\n * Generate a UI dialog for the request action in the given Android context\n * with the provided parameters.\n *\n * Note that this method is asynchronous and the callback will be invoked in\n * the original calling thread (not in a background thread).\n *\n * @param context\n * The Android context in which we will generate this dialog.\n * @param action\n * String representation of the desired method: e.g. \"feed\" ...\n * @param parameters\n * String key-value pairs to be passed as URL parameters.\n * @param listener\n * Callback interface to notify the application when the dialog\n * has completed.\n */\n public void dialog(Context context, String action, Bundle parameters,\n final DialogListener listener) {\n\n String endpoint = DIALOG_BASE_URL + action;\n parameters.putString(\"display\", \"touch\");\n parameters.putString(\"redirect_uri\", REDIRECT_URI);\n\n if (action.equals(LOGIN)) {\n parameters.putString(\"type\", \"user_agent\");\n parameters.putString(\"client_id\", mAppId);\n } else {\n parameters.putString(\"app_id\", mAppId);\n }\n\n if (isSessionValid()) {\n parameters.putString(TOKEN, getAccessToken());\n }\n String url = endpoint + \"?\" + Util.encodeUrl(parameters);\n if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET)\n != PackageManager.PERMISSION_GRANTED) {\n Util.showAlert(context, \"Error\",\n \"Application requires permission to access the Internet\");\n } else {\n new FbDialog(context, url, listener).show();\n }\n }\n\n /**\n * @return boolean - whether this object has an non-expired session token\n */\n public boolean isSessionValid() {\n return (getAccessToken() != null) &&\n ((getAccessExpires() == 0) ||\n (System.currentTimeMillis() < getAccessExpires()));\n }\n\n /**\n * Retrieve the OAuth 2.0 access token for API access: treat with care.\n * Returns null if no session exists.\n *\n * @return String - access token\n */\n public String getAccessToken() {\n return mAccessToken;\n }\n\n /**\n * Retrieve the current session's expiration time (in milliseconds since\n * Unix epoch), or 0 if the session doesn't expire or doesn't exist.\n *\n * @return long - session expiration time\n */\n public long getAccessExpires() {\n return mAccessExpires;\n }\n\n /**\n * Set the OAuth 2.0 access token for API access.\n *\n * @param token - access token\n */\n public void setAccessToken(String token) {\n mAccessToken = token;\n mLastAccessUpdate = System.currentTimeMillis();\n }\n\n /**\n * Set the current session's expiration time (in milliseconds since Unix\n * epoch), or 0 if the session doesn't expire.\n *\n * @param time - timestamp in milliseconds\n */\n public void setAccessExpires(long time) {\n mAccessExpires = time;\n }\n\n /**\n * Set the current session's duration (in seconds since Unix epoch), or \"0\"\n * if session doesn't expire.\n *\n * @param expiresIn\n * - duration in seconds (or 0 if the session doesn't expire)\n */\n public void setAccessExpiresIn(String expiresIn) {\n if (expiresIn != null) {\n long expires = expiresIn.equals(\"0\")\n ? 0\n : System.currentTimeMillis() + Long.parseLong(expiresIn) * 1000L;\n setAccessExpires(expires);\n }\n }\n\n public String getAppId() {\n return mAppId;\n }\n\n public void setAppId(String appId) {\n mAppId = appId;\n }\n\n /**\n * Callback interface for dialog requests.\n *\n */\n public static interface DialogListener {\n\n /**\n * Called when a dialog completes.\n *\n * Executed by the thread that initiated the dialog.\n *\n * @param values\n * Key-value string pairs extracted from the response.\n */\n public void onComplete(Bundle values);\n\n /**\n * Called when a Facebook responds to a dialog with an error.\n *\n * Executed by the thread that initiated the dialog.\n *\n */\n public void onFacebookError(FacebookError e);\n\n /**\n * Called when a dialog has an error.\n *\n * Executed by the thread that initiated the dialog.\n *\n */\n public void onError(DialogError e);\n\n /**\n * Called when a dialog is canceled by the user.\n *\n * Executed by the thread that initiated the dialog.\n *\n */\n public void onCancel();\n\n }\n \n /**\n * Callback interface for service requests.\n */\n public static interface ServiceListener {\n\n /**\n * Called when a service request completes.\n * \n * @param values\n * Key-value string pairs extracted from the response.\n */\n public void onComplete(Bundle values);\n\n /**\n * Called when a Facebook server responds to the request with an error.\n */\n public void onFacebookError(FacebookError e);\n\n /**\n * Called when a Facebook Service responds to the request with an error.\n */\n public void onError(Error e);\n\n }\n\n public static final String FB_APP_SIGNATURE =\n \"30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310\"\n + \"b3009060355040613025553310b30090603550408130243413112301006035504\"\n + \"07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204\"\n + \"d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504\"\n + \"03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333\"\n + \"13231353231365a180f32303530303932353231353231365a307a310b30090603\"\n + \"55040613025553310b30090603550408130243413112301006035504071309506\"\n + \"16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c\"\n + \"653111300f060355040b130846616365626f6f6b311d301b06035504031314466\"\n + \"16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01\"\n + \"0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa\"\n + \"b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7\"\n + \"e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc\"\n + \"fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603\"\n + \"f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050\"\n + \"0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c\"\n + \"4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6\"\n + \"73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2\"\n + \"571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd\"\n + \"928a2\";\n\n}", "public static interface DialogListener {\n\n /**\n * Called when a dialog completes.\n *\n * Executed by the thread that initiated the dialog.\n *\n * @param values\n * Key-value string pairs extracted from the response.\n */\n public void onComplete(Bundle values);\n\n /**\n * Called when a Facebook responds to a dialog with an error.\n *\n * Executed by the thread that initiated the dialog.\n *\n */\n public void onFacebookError(FacebookError e);\n\n /**\n * Called when a dialog has an error.\n *\n * Executed by the thread that initiated the dialog.\n *\n */\n public void onError(DialogError e);\n\n /**\n * Called when a dialog is canceled by the user.\n *\n * Executed by the thread that initiated the dialog.\n *\n */\n public void onCancel();\n\n}", "public final class Log {\n\n\tpublic static boolean debug = false;\n\t\n\tpublic static void d(String tag, String message)\n\t{\n\t\tif (debug) {\n\t\t\tandroid.util.Log.d(tag, message);\n\t\t}\n\t}\n\t\n\tpublic static void w(String tag, String message)\n\t{\n\t\tandroid.util.Log.w(tag, message);\n\t}\n\t\n\tpublic static void e(String tag, String message)\n\t{\n\t\tandroid.util.Log.e(tag, message);\n\t}\n\t\n\tpublic static void v(String tag, String message)\n\t{\n\t\tandroid.util.Log.v(tag, message);\n\t}\n\t\n\tpublic static void i(String tag, String message)\n\t{\n\t\tandroid.util.Log.i(tag, message);\n\t}\n}", "public class LogCollector {\n\tprivate Thread mThread;\n\n\tprivate boolean mCollected = false;\n\tprivate boolean mCollecting = false;\n\t\n\tprivate StringBuilder mLog;\n\tprivate LogCollectorNotifier mNotifier;\n\tprivate LogHandler mHandler;\n\t\n\tpublic static final String TAG = \"LogCollector\";\n public static final String[] LOGCAT_CMD = new String[] { \"logcat\", \"-d\" };\n private static final int BUFFER_SIZE = 1024;\n\n private static class LogHandler extends Handler {\n \tprivate LogCollector mCollector;\n \t\n \tpublic static final int COMPLETED = 1;\n \tpublic static final int ERROR = 2;\n \t\n \tpublic LogHandler(LogCollector collector) {\n \t\tsuper();\n \t\tmCollector = collector;\n \t}\n \t\n\t\t@Override\n\t\tpublic void handleMessage(Message msg) {\n\t\t\tsuper.handleMessage(msg);\n\t\t\tif (mCollector == null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tLogCollectorNotifier notifier = mCollector.mNotifier;\n\t\t\t\n\t\t\tswitch(msg.what) {\n\t\t\t\tcase COMPLETED:\n\t\t\t\t\tmCollector.mCollected = true;\n\t\t\t\t\tmCollector.mCollecting = false;\n\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\tnotifier.onComplete();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase ERROR:\n\t\t\t\t\tmCollector.mCollected = false;\n\t\t\t\t\tmCollector.mCollecting = false;\n\t\t\t\t\tif (notifier != null) {\n\t\t\t\t\t\tnotifier.onError();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n }\n \n public void destroy() {\n \t//stopCollecting();\n \t//mHandler = null;\n \t//mThread = null;\n }\n \n\t@Override\n\tprotected void finalize() throws Throwable {\n\t\tLog.d(TAG, \"FINALIZED\");\n\t\tsuper.finalize();\n\t}\n\n\tpublic LogCollector() {\n\t\tmHandler = new LogHandler(this);\n\t}\n\t\n\tpublic void setNotifier(LogCollectorNotifier notifier) {\n\t\tmNotifier = notifier;\n\t}\n\t\n\tpublic boolean isCollecting() {\n\t\treturn mCollecting;\n\t}\n\t\n\tpublic boolean isCollected() {\n\t\treturn mCollected;\n\t}\n\t\n\tpublic void stopCollecting() {\n\t\tif (mThread != null && mThread.isAlive()) {\n\t\t\tmThread.interrupt();\n\t\t}\n\t}\n\t\n\tpublic String getLog() {\n\t\tif (mCollected) {\n\t\t\tif (mLog != null) {\n\t\t\t\treturn mLog.toString();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic void appendMessage(String msg) {\n\t\tif (mCollected) {\n\t\t\tif (mLog != null) {\n\t\t\t\tStringBuffer buffer = new StringBuffer();\n\t\t\t\tString separator = System.getProperty(\"line.separator\");\n\t\t\t\tbuffer.append(msg);\n\t\t\t\tbuffer.append(separator);\n\t\t\t\tbuffer.append(separator);\n\t\t\t\t\n\t\t\t\tmLog.insert(0, buffer.toString());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void collect() {\n\t\tmCollected = false;\n\t\t\n\t\tmThread = new Thread(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tProcess proc = null;\n\t\t\t\tBufferedReader reader = null;\n\t\t\t\ttry {\n\t\t\t\t\tproc = Runtime.getRuntime().exec(LOGCAT_CMD);\n\t\t\t\t\treader = new BufferedReader(new InputStreamReader(proc.getInputStream()), BUFFER_SIZE);\n\t\t\t\t\t\n\t\t\t\t\tString line;\n\t\t\t\t\tString separator = System.getProperty(\"line.separator\");\n\t\t\t\t\t\n\t\t\t\t\t// Initialize and add Android info\n\t\t\t\t\tmLog = new StringBuilder();\n\t\t\t\t\tmLog.append(\"Model: \" + Build.MODEL);\n\t\t\t\t\tmLog.append(separator);\n\t\t\t\t\tmLog.append(\"Display: \" + Build.DISPLAY);\n\t\t\t\t\tmLog.append(separator);\n\t\t\t\t\tmLog.append(\"Release: \" + Build.VERSION.RELEASE);\n\t\t\t\t\tmLog.append(separator);\n\t\t\t\t\tmLog.append(separator);\n\t\t\t\t\t\n\t\t\t\t\twhile((line = reader.readLine()) != null) {\n\t\t\t\t\t\tmLog.append(line);\n\t\t\t\t\t\tmLog.append(separator);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tLog.d(TAG, \"collected log\");\n\t\t\t\t\tif (mHandler != null) {\n\t\t\t\t\t\tmHandler.sendEmptyMessage(LogHandler.COMPLETED);\n\t\t\t\t\t}\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tif (mHandler != null) {\n\t\t\t\t\t\tmHandler.sendEmptyMessage(LogHandler.ERROR);\n\t\t\t\t\t}\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} finally {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (reader != null) {\n\t\t\t\t\t\t\treader.close();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (proc != null) {\n\t\t\t\t\t\t\tproc.destroy();\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t});\n\t\t\n\t\tmCollecting = true;\n\t\tmThread.start();\n\t}\n}", "public interface LogCollectorNotifier {\n\tvoid onError();\n\tvoid onComplete();\n}", "public final class Utils {\n\n\tprivate static final String TAG = \"Utils\";\n\tprivate Utils() {}\n\tpublic static int determineOsVersion()\n\t{\n\t\treturn Integer.parseInt(Build.VERSION.SDK);\n\t}\n\t\n\tpublic static String join(String[] array, char separator)\n\t{\n\t\tif (array == null) {\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tStringBuffer sb = new StringBuffer();\n\t\t\n\t\tfor(int i = 0; i < array.length; i++) {\n\t\t\tsb.append(array[i]);\n\t\t\tsb.append(separator);\n\t\t}\n\t\t\n\t\treturn sb.toString();\n\t}\n\t\n\tpublic static boolean hasInternetConnection(Context context)\n\t{\n\t\tif (context == null) {\n\t\t\tthrow new IllegalArgumentException(\"context\");\n\t\t}\n\t\t\n\t\tConnectivityManager connMgr=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo info=connMgr.getActiveNetworkInfo();\n\n\t\treturn(info!=null && info.isConnected()); \n\t}\n\t\n public static String getMd5Hash(byte[] input) \n {\n \t if (input == null) {\n \t\t throw new IllegalArgumentException(\"input\");\n \t }\n \t \n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n byte[] messageDigest = md.digest(input);\n BigInteger number = new BigInteger(1,messageDigest);\n //String md5 = number.toString(16);\n StringBuffer md5 = new StringBuffer();\n md5.append(number.toString(16));\n\n while (md5.length() < 32) {\n //md5 = \"0\" + md5;\n md5.insert(0, \"0\");\n }\n \n return md5.toString();\n } \n catch(NoSuchAlgorithmException e) {\n \t Log.e(\"MD5\", e.getMessage());\n return null;\n }\n }\n \n\tpublic static String buildNameSelection (String field, String firstName, String lastName)\n\t{\n\t\tif (field == null) {\n\t\t\tthrow new IllegalArgumentException (\"field\");\n\t\t}\n\t\t\n\t\tif (firstName == null) {\n\t\t\tthrow new IllegalArgumentException (\"firstName\");\n\t\t}\n\t\t\n\t\tif (lastName == null) {\n\t\t\tthrow new IllegalArgumentException (\"lastName\");\n\t\t}\n\t\t\n\t\t// escape single quotes\n\t\tfirstName = firstName.replace(\"'\", \"''\");\n\t\tlastName = lastName.replace(\"'\", \"''\");\n\t\t\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(String.format(\"%s = '%s %s' OR \", field, firstName, lastName));\n\t\tsb.append(String.format(\"%s = '%s, %s' OR \", field, lastName, firstName));\n\t\tsb.append(String.format(\"%s = '%s,%s'\", field, lastName, firstName));\n\t\t\n\t\treturn sb.toString();\n\t}\n\t\n\tpublic static byte[] getByteArrayFromInputStream(InputStream is)\n\t{\n\t\tif (is == null) {\n\t\t\tthrow new IllegalArgumentException(\"is\");\n\t\t}\n\t\t\n\t\tint size = 8192;\n\t\tint read = 0;\n\t\tByteArrayOutputStream bytes = new ByteArrayOutputStream(size);\n\t\tbyte[] buffer = new byte[size];\n\t\tbyte[] array = null;\n\t\t\n\t\ttry {\n\t\t\twhile ((read = is.read(buffer, 0, buffer.length)) > 0) {\n\t\t\t\tbytes.write(buffer, 0, read);\n\t\t\t}\n\t\t}\n\t\tcatch (IOException ex) {\n\t\t\treturn null;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (bytes != null) {\n\t\t\t\t\tarray = bytes.toByteArray();\n\t\t\t\t \tbytes.close();\n\t\t\t\t}\n\t\t\t} catch (IOException e) {}\n\t\t}\n\t\t\n\t\treturn array;\n\t}\n\n\tpublic static Bitmap centerCrop (Bitmap bitmap, int destHeight, int destWidth)\n\t{\n\t\tBitmap resized;\n\t\tif (bitmap.getHeight() > bitmap.getWidth()) {\n\t\t\tresized = resize(bitmap, 0, destWidth);\n\t\t}\n\t\telse {\n\t\t\tresized = resize(bitmap, destHeight, 0);\n\t\t}\n\t\t\n\t\treturn crop(resized, destWidth, destWidth);\n\t}\n\t\n\tpublic static Bitmap crop(Bitmap bitmapToCrop, int destHeight, int destWidth)\n\t{\n int width = bitmapToCrop.getWidth();\n int height = bitmapToCrop.getHeight();\n if (width <= destWidth && height <= destHeight) {\n \treturn bitmapToCrop;\n }\n \n Bitmap b = Bitmap.createBitmap(destHeight, destWidth, Bitmap.Config.RGB_565);\n Canvas c1 = new Canvas(b);\n\n int midpointX = width / 2;\n int midpointY = height / 2;\n \n Rect r = new Rect(midpointX - destWidth / 2, \n \t\tmidpointY - destHeight / 2,\n \t\tmidpointX + destWidth / 2, \n \t\tmidpointY + destHeight / 2);\n \n int left = 0; //(width / 2) - (bitmapToCrop.getWidth() / 2);\n int top = 0; //(height / 2) - (bitmapToCrop.getWidth() / 2);\n c1.drawBitmap(bitmapToCrop, r, new Rect(left, top, left\n + destWidth, top + destHeight), null);\n\n return b;\n\t}\n\t\n\tpublic static Bitmap resize(Bitmap bitmap, int maxHeight, int maxWidth)\n\t{\n\t\tif (bitmap == null) {\n\t\t\tthrow new IllegalArgumentException(\"bitmap\");\n\t\t}\n\t\t\n\t\tint height = bitmap.getHeight();\n\t\tint width = bitmap.getWidth();\n\n\t\tif ((maxHeight > 0 && height <= maxHeight) && (maxWidth > 0 && width <= maxWidth)) {\n\t\t\treturn bitmap;\n\t\t}\n\t\t\n\t\tint newHeight = height;\n\t\tint newWidth = width;\n\t\t\n\t\tfloat ratio;\n\t\t\n\t\tif (newHeight > maxHeight && maxHeight > 0) {\n\t\t\tratio = (float)newWidth / (float)newHeight;\n\t\t\tnewHeight = maxHeight;\n\t\t\tnewWidth = Math.round(ratio * (float)newHeight);\n\t\t}\n\t\t\n\t\tif (newWidth > maxWidth && maxWidth > 0) {\n\t\t\tratio = (float)newHeight / (float)newWidth;\n\t\t\tnewWidth = maxWidth;\n\t\t\tnewHeight = Math.round(ratio * (float)newWidth);\n\t\t}\n\t\t\n\t\tfloat scaleWidth = ((float) newWidth) / width; \n\t\tfloat scaleHeight = ((float) newHeight) / height;\n\t\tMatrix matrix = new Matrix(); \n\t\tmatrix.postScale(scaleWidth, scaleHeight);\n\n\t\treturn Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); \n\t}\n\t\n\tpublic static InputStream downloadPictureAsStream (String url, int retries) throws IOException\n\t{\n\t\tif (url == null) {\n \t\tthrow new IllegalArgumentException (\"url\");\n \t}\n\t\t\n\t\tInputStream image = null;\n\t\tfor(int i=0; i<=retries; i++) {\n\t\t\t//Log.d(TAG, \"try \"+i);\n\t\t\ttry {\n\t\t\t\tif ((image = downloadPictureAsStream(url)) != null) break;\n\t\t\t} catch (IOException e) {\n\t\t\t\tif (i == retries) throw e;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn image;\n\t}\n\n\tpublic static InputStream downloadPictureAsStream (String url) throws IOException\n\t{\n\t\tif (url == null) {\n \t\tthrow new IllegalArgumentException (\"url\");\n \t}\n \t\n\t\tHttpClient httpclient = null;\n\t\tInputStream stream = null;\n \ttry {\n \t\tHttpParams params = new BasicHttpParams();\n \t\t// Set the timeout in milliseconds until a connection is established.\n \t\tHttpConnectionParams.setConnectionTimeout(params, 5000);\n \t\t// Set the default socket timeout (SO_TIMEOUT) \n \t\t// in milliseconds which is the timeout for waiting for data.\n \t\tHttpConnectionParams.setSoTimeout(params, 10000);\n \t\t\n httpclient = new DefaultHttpClient(params);\n HttpGet httpget = new HttpGet(url); \n \n HttpResponse response = httpclient.execute(httpget);\n HttpEntity entity = response.getEntity();\n if (entity != null) {\n \tBufferedHttpEntity buff = new BufferedHttpEntity(entity);\n \tstream = buff.getContent();\n //\timage = BitmapFactory.decodeStream(stream);\n }\n \t} catch (IOException ex) {\n\t \tLog.e(null, android.util.Log.getStackTraceString(ex));\n\t \tthrow ex;\n \t} finally {\n\t \ttry {\n\t\t \tif (httpclient != null) {\n\t\t \t\thttpclient.getConnectionManager().shutdown();\n\t\t \t}\n\t\t \tif (stream != null) {\n\t\t \t\tstream.close();\n\t\t \t}\n\t \t} catch (Exception e) {}\n\t }\n\t \n \treturn stream;\n\t}\n\t\n\tpublic static byte[] bitmapToJpeg(Bitmap bitmap, int quality)\n\t{\n\t\tif (bitmap == null) {\n \t\tthrow new IllegalArgumentException (\"bitmap\");\n \t}\n\t\t\n\t\tbyte[] image = null;\n\t\t\n\t\ttry {\n\t\t\tByteArrayOutputStream bytes = new ByteArrayOutputStream();\n\t\t\t\t\n\t\t\tbitmap.compress(Bitmap.CompressFormat.JPEG, quality, bytes);\n\t\t\timage = bytes.toByteArray();\n\t\t\tbytes.close();\n\t\t} catch (IOException e) {}\n\n\t\treturn image;\n\t}\n\t\n\tpublic static byte[] bitmapToPNG(Bitmap bitmap)\n\t{\n\t\tif (bitmap == null) {\n \t\tthrow new IllegalArgumentException (\"bitmap\");\n \t}\n\t\t\n\t\tbyte[] image = null;\n\t\n\t\ttry {\n\t\t\tByteArrayOutputStream bytes = new ByteArrayOutputStream();\n\t\t\t\t\n\t\t\tbitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);\n\t\t\timage = bytes.toByteArray();\n\t\t\tbytes.close();\n\t\t} catch (IOException e) {}\n\n\t\treturn image;\n\t}\n\t\n\tpublic static void setBoolean (SharedPreferences settings, String key, boolean value)\n {\n \tif (settings == null) {\n \t\tthrow new IllegalArgumentException (\"settings\");\n \t}\n \t\n \tif (key == null) {\n \t\tthrow new IllegalArgumentException (\"key\");\n \t}\n \n SharedPreferences.Editor editor = settings.edit();\n editor.putBoolean(key, value);\n\n // Don't forget to commit your edits!!!\n editor.commit();\n }\n\t\n\tpublic static void setString (SharedPreferences settings, String key, String value)\n {\n \tif (settings == null) {\n \t\tthrow new IllegalArgumentException (\"settings\");\n \t}\n \t\n \tif (key == null) {\n \t\tthrow new IllegalArgumentException (\"key\");\n \t}\n \t\n SharedPreferences.Editor editor = settings.edit();\n editor.putString(key, value);\n\n // Don't forget to commit your edits!!!\n editor.commit();\n }\n\t\n\tpublic static void setInt (SharedPreferences settings, String key, int value)\n {\n \tif (settings == null) {\n \t\tthrow new IllegalArgumentException (\"settings\");\n \t}\n \t\n \tif (key == null) {\n \t\tthrow new IllegalArgumentException (\"key\");\n \t}\n \t\n SharedPreferences.Editor editor = settings.edit();\n editor.putInt(key, value);\n\n // Don't forget to commit your edits!!!\n editor.commit();\n }\n\t\n\tpublic static void setLong (SharedPreferences settings, String key, long value)\n {\n \tif (settings == null) {\n \t\tthrow new IllegalArgumentException (\"settings\");\n \t}\n \t\n \tif (key == null) {\n \t\tthrow new IllegalArgumentException (\"key\");\n \t}\n \t\n SharedPreferences.Editor editor = settings.edit();\n editor.putLong(key, value);\n\n // Don't forget to commit your edits!!!\n editor.commit();\n }\n\n}", "public final class ConfirmSyncDialog extends AlertDialog {\n\n\tpublic ConfirmSyncDialog(Context context) {\n\t\tsuper(context);\n\t\t\n\t\tinitialize(context);\n\t}\n\n\tprivate void initialize(Context context)\n\t{\n\t\tSyncMyPixPreferences prefs = new SyncMyPixPreferences(context);\n\t\t\n\t\tString msg = \"Social Network: \" + prefs.getSource() + \"\\n\" +\n\t\t\t\t\t \"Skip if non-SyncMyPix picture: \" + translateBool(prefs.getSkipIfExists()) + \"\\n\" +\n\t\t\t\t\t \"Skip if multiple contacts: \" + translateBool(prefs.getSkipIfConflict()) + \"\\n\" +\n\t\t\t\t\t \"Smart name matching: \" + translateBool(prefs.getIntelliMatch()) + \"\\n\" +\n\t\t\t\t\t \"Use maximum resolution available: \" + translateBool(prefs.getMaxQuality()) + \"\\n\" +\n\t\t\t\t\t \"Crop 96px square: \" + translateBool(prefs.getCropSquare()) + \"\\n\";\n\t\t\n\t\tthis.setTitle(\"Confirm Settings\");\n\t\tthis.setIcon(android.R.drawable.ic_dialog_alert);\n\t\t\n\t\tTextView view = new TextView(context);\n\t\tview.setPadding(4, 4, 4, 4);\n\t\tview.setTextSize(12);\n\t\tview.setTextColor(Color.WHITE);\n\t\tview.setText(msg);\n\t\t\n\t\tthis.setView(view);\n\t\t//this.setMessage(msg);\n\t\t\n\t\tthis.setCancelable(false);\n\t}\n\t\n\tpublic void setProceedButtonListener(DialogInterface.OnClickListener listener)\n\t{\n\t\tthis.setButton(DialogInterface.BUTTON_POSITIVE, \"Proceed\", listener);\n\t}\n\t\n\tpublic void setCancelButtonListener(DialogInterface.OnClickListener listener)\n\t{\n\t\tthis.setButton(DialogInterface.BUTTON_NEGATIVE, \"Cancel\", listener);\n\t}\n\t\n\tprivate String translateBool(boolean value)\n\t{\n\t\treturn value ? \"Yes\" : \"No\";\n\t}\n}" ]
import java.io.IOException; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.net.MalformedURLException; import com.android.providers.contacts.PhotoStore; import com.facebook.android.DialogError; import com.facebook.android.Facebook; import com.facebook.android.Facebook.DialogListener; import com.facebook.android.FacebookError; import com.nloko.android.Log; import com.nloko.android.LogCollector; import com.nloko.android.LogCollectorNotifier; import com.nloko.android.Utils; import com.nloko.android.syncmypix.views.ConfirmSyncDialog; import com.nloko.android.syncmypix.facebook.*; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener;
fbClient.authorize(self, new DialogListener() { public void onComplete(Bundle values) {sync();} public void onFacebookError(FacebookError error) {try { loggedIn = false; Toast.makeText(self, "Error on facebook sync again!", Toast.LENGTH_SHORT).show(); fbClient.logout(self); } catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }} public void onError(DialogError e) {try { loggedIn = false; Toast.makeText(self, "Error on facebook sync again!", Toast.LENGTH_SHORT).show(); fbClient.logout(self); } catch(MalformedURLException e1) { e1.printStackTrace(); } catch(IOException e1) { e1.printStackTrace(); }} public void onCancel() {loggedIn = false;} }); } else sync(); //} } }); ImageButton settings = (ImageButton) findViewById(R.id.settingsButton); settings.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(getApplicationContext(), SettingsActivity.class); startActivity(i); } }); ImageButton results = (ImageButton) findViewById(R.id.resultsButton); results.setOnClickListener(new OnClickListener() { public void onClick(View v) { showResults(); } }); ImageButton about = (ImageButton) findViewById(R.id.aboutButton); about.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(ABOUT_DIALOG); } }); mHelpButton = (ImageButton) findViewById(R.id.help); mHelpButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.help_link))); startActivity(i); } }); mDeleteButton = (ImageButton) findViewById(R.id.delete); mDeleteButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DELETE_DIALOG); loggedIn = false; if(fbClient != null) try { fbClient.logout(self); } catch(MalformedURLException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) { return; } switch(requestCode) { case SOCIAL_NETWORK_LOGIN: sync(); break; } } // TODO This is needless filler, REMOVE private void logout() { Utils.setString(getSharedPreferences(SettingsActivity.PREFS_NAME, 0), "session_key", null); Utils.setString(getSharedPreferences(SettingsActivity.PREFS_NAME, 0), "secret", null); Utils.setString(getSharedPreferences(SettingsActivity.PREFS_NAME, 0), "uid", null); } private void sendLog() {
final LogCollector collector = new LogCollector();
4
maksim-m/Popular-Movies-App
app/src/main/java/me/maxdev/popularmoviesapp/ui/detail/MovieDetailFragment.java
[ "public class PopularMoviesApp extends Application {\n\n private NetworkComponent networkComponent;\n\n @Override\n public void onCreate() {\n super.onCreate();\n networkComponent = DaggerNetworkComponent.builder()\n .appModule(new AppModule(this))\n .networkModule(new NetworkModule())\n .build();\n }\n\n public NetworkComponent getNetworkComponent() {\n return networkComponent;\n }\n\n}", "public class MovieReviewsResponse {\n @SerializedName(\"id\")\n private long movieId;\n\n @SerializedName(\"page\")\n private int page;\n\n @SerializedName(\"results\")\n private ArrayList<MovieReview> results;\n\n @SerializedName(\"total_pages\")\n private int totalPages;\n\n public MovieReviewsResponse(long movieId, int page, ArrayList<MovieReview> results, int totalPages) {\n this.movieId = movieId;\n this.page = page;\n this.results = results;\n this.totalPages = totalPages;\n }\n\n public long getMovieId() {\n return movieId;\n }\n\n public int getPage() {\n return page;\n }\n\n public ArrayList<MovieReview> getResults() {\n return results;\n }\n\n public int getTotalPages() {\n return totalPages;\n }\n}", "public class MovieVideosResponse {\n @SerializedName(\"id\")\n private long movieId;\n\n @SerializedName(\"results\")\n private ArrayList<MovieVideo> results;\n\n public MovieVideosResponse(long movieId, ArrayList<MovieVideo> results) {\n this.movieId = movieId;\n this.results = results;\n }\n\n public long getMovieId() {\n return movieId;\n }\n\n public ArrayList<MovieVideo> getResults() {\n return results;\n }\n}", "public interface TheMovieDbService {\n\n @GET(\"movie/{id}/videos\")\n Observable<MovieVideosResponse> getMovieVideos(@Path(\"id\") long movieId);\n\n @GET(\"movie/{id}/reviews\")\n Observable<MovieReviewsResponse> getMovieReviews(@Path(\"id\") long movieId);\n\n @GET(\"discover/movie\")\n Observable<DiscoverAndSearchResponse<Movie>> discoverMovies(@Query(\"sort_by\") String sortBy,\n @Query(\"page\") Integer page);\n\n @GET(\"search/movie\")\n Observable<DiscoverAndSearchResponse<Movie>> searchMovies(@Query(\"query\") String query,\n @Query(\"page\") Integer page);\n\n}", "@SuppressWarnings(\"PMD.GodClass\")\npublic class Movie implements Parcelable {\n\n public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {\n @Override\n public Movie createFromParcel(Parcel source) {\n return new Movie(source);\n }\n\n @Override\n public Movie[] newArray(int size) {\n return new Movie[size];\n }\n };\n\n @SerializedName(\"id\")\n private long id;\n\n @SerializedName(\"original_title\")\n private String originalTitle;\n\n @SerializedName(\"overview\")\n private String overview;\n\n @SerializedName(\"release_date\")\n private String releaseDate;\n\n @SerializedName(\"poster_path\")\n private String posterPath;\n\n @SerializedName(\"popularity\")\n private double popularity;\n\n @SerializedName(\"title\")\n private String title;\n\n @SerializedName(\"vote_average\")\n private double averageVote;\n\n @SerializedName(\"vote_count\")\n private long voteCount;\n\n @SerializedName(\"backdrop_path\")\n private String backdropPath;\n\n public Movie(long id, String title) {\n this.id = id;\n this.title = title;\n }\n\n protected Movie(Parcel in) {\n this.id = in.readLong();\n this.originalTitle = in.readString();\n this.overview = in.readString();\n this.releaseDate = in.readString();\n this.posterPath = in.readString();\n this.popularity = in.readDouble();\n this.title = in.readString();\n this.averageVote = in.readDouble();\n this.voteCount = in.readLong();\n this.backdropPath = in.readString();\n }\n\n public static Movie fromCursor(Cursor cursor) {\n long id = cursor.getLong(cursor.getColumnIndex(MoviesContract.MovieEntry._ID));\n String title = cursor.getString(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_TITLE));\n Movie movie = new Movie(id, title);\n movie.setOriginalTitle(\n cursor.getString(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_ORIGINAL_TITLE)));\n movie.setOverview(\n cursor.getString(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_OVERVIEW)));\n movie.setReleaseDate(\n cursor.getString(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_RELEASE_DATE)));\n movie.setPosterPath(\n cursor.getString(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_POSTER_PATH)));\n movie.setPopularity(\n cursor.getDouble(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_POPULARITY)));\n movie.setAverageVote(\n cursor.getDouble(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_AVERAGE_VOTE)));\n movie.setVoteCount(\n cursor.getLong(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_VOTE_COUNT)));\n movie.setBackdropPath(\n cursor.getString(cursor.getColumnIndex(MoviesContract.MovieEntry.COLUMN_BACKDROP_PATH)));\n return movie;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getOriginalTitle() {\n return originalTitle;\n }\n\n public void setOriginalTitle(String originalTitle) {\n this.originalTitle = originalTitle;\n }\n\n public String getOverview() {\n return overview;\n }\n\n public void setOverview(String overview) {\n this.overview = overview;\n }\n\n public String getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(String releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n public String getPosterPath() {\n return posterPath;\n }\n\n public void setPosterPath(String posterPath) {\n this.posterPath = posterPath;\n }\n\n public double getPopularity() {\n return popularity;\n }\n\n public void setPopularity(double popularity) {\n this.popularity = popularity;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public double getAverageVote() {\n return averageVote;\n }\n\n public void setAverageVote(double averageVote) {\n this.averageVote = averageVote;\n }\n\n public long getVoteCount() {\n return voteCount;\n }\n\n public void setVoteCount(long voteCount) {\n this.voteCount = voteCount;\n }\n\n public String getBackdropPath() {\n return backdropPath;\n }\n\n public void setBackdropPath(String backdropPath) {\n this.backdropPath = backdropPath;\n }\n\n @Override\n public String toString() {\n return \"[\" + this.id + \", \" + this.title + \"]\";\n }\n\n //CHECKSTYLE:OFF\n @Override\n @SuppressWarnings(\"PMD\")\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Movie movie = (Movie) o;\n\n if (id != movie.id) return false;\n if (Double.compare(movie.popularity, popularity) != 0) return false;\n if (Double.compare(movie.averageVote, averageVote) != 0) return false;\n if (voteCount != movie.voteCount) return false;\n if (originalTitle != null ? !originalTitle.equals(movie.originalTitle) : movie.originalTitle != null)\n return false;\n if (overview != null ? !overview.equals(movie.overview) : movie.overview != null) return false;\n if (releaseDate != null ? !releaseDate.equals(movie.releaseDate) : movie.releaseDate != null) return false;\n if (posterPath != null ? !posterPath.equals(movie.posterPath) : movie.posterPath != null) return false;\n if (title != null ? !title.equals(movie.title) : movie.title != null) return false;\n return backdropPath != null ? backdropPath.equals(movie.backdropPath) : movie.backdropPath == null;\n\n }\n\n @Override\n @SuppressWarnings(\"PMD\")\n public int hashCode() {\n int result;\n long temp;\n result = (int) (id ^ (id >>> 32));\n result = 31 * result + (originalTitle != null ? originalTitle.hashCode() : 0);\n result = 31 * result + (overview != null ? overview.hashCode() : 0);\n result = 31 * result + (releaseDate != null ? releaseDate.hashCode() : 0);\n result = 31 * result + (posterPath != null ? posterPath.hashCode() : 0);\n temp = Double.doubleToLongBits(popularity);\n result = 31 * result + (int) (temp ^ (temp >>> 32));\n result = 31 * result + (title != null ? title.hashCode() : 0);\n temp = Double.doubleToLongBits(averageVote);\n result = 31 * result + (int) (temp ^ (temp >>> 32));\n result = 31 * result + (int) (voteCount ^ (voteCount >>> 32));\n result = 31 * result + (backdropPath != null ? backdropPath.hashCode() : 0);\n return result;\n }\n //CHECKSTYLE:ON\n\n public ContentValues toContentValues() {\n ContentValues values = new ContentValues();\n values.put(MoviesContract.MovieEntry._ID, id);\n values.put(MoviesContract.MovieEntry.COLUMN_ORIGINAL_TITLE, originalTitle);\n values.put(MoviesContract.MovieEntry.COLUMN_OVERVIEW, overview);\n values.put(MoviesContract.MovieEntry.COLUMN_RELEASE_DATE, releaseDate);\n values.put(MoviesContract.MovieEntry.COLUMN_POSTER_PATH, posterPath);\n values.put(MoviesContract.MovieEntry.COLUMN_POPULARITY, popularity);\n values.put(MoviesContract.MovieEntry.COLUMN_TITLE, title);\n values.put(MoviesContract.MovieEntry.COLUMN_AVERAGE_VOTE, averageVote);\n values.put(MoviesContract.MovieEntry.COLUMN_VOTE_COUNT, voteCount);\n values.put(MoviesContract.MovieEntry.COLUMN_BACKDROP_PATH, backdropPath);\n return values;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeLong(this.id);\n dest.writeString(this.originalTitle);\n dest.writeString(this.overview);\n dest.writeString(this.releaseDate);\n dest.writeString(this.posterPath);\n dest.writeDouble(this.popularity);\n dest.writeString(this.title);\n dest.writeDouble(this.averageVote);\n dest.writeLong(this.voteCount);\n dest.writeString(this.backdropPath);\n }\n}", "public class MovieReview implements Parcelable {\n\n public static final Parcelable.Creator<MovieReview> CREATOR = new Parcelable.Creator<MovieReview>() {\n @Override\n public MovieReview createFromParcel(Parcel source) {\n return new MovieReview(source);\n }\n\n @Override\n public MovieReview[] newArray(int size) {\n return new MovieReview[size];\n }\n };\n\n @SerializedName(\"id\")\n private String reviewId;\n\n @SerializedName(\"author\")\n private String author;\n\n @SerializedName(\"url\")\n private String reviewUrl;\n\n @SerializedName(\"content\")\n private String content;\n\n public MovieReview(String reviewId) {\n this.reviewId = reviewId;\n }\n\n protected MovieReview(Parcel in) {\n this.reviewId = in.readString();\n this.author = in.readString();\n this.reviewUrl = in.readString();\n this.content = in.readString();\n }\n\n public String getReviewId() {\n return reviewId;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public String getReviewUrl() {\n return reviewUrl;\n }\n\n public void setReviewUrl(String reviewUrl) {\n this.reviewUrl = reviewUrl;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n //CHECKSTYLE:OFF\n @Override\n @SuppressWarnings(\"PMD\")\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n MovieReview review = (MovieReview) o;\n\n if (reviewId != null ? !reviewId.equals(review.reviewId) : review.reviewId != null) return false;\n if (author != null ? !author.equals(review.author) : review.author != null) return false;\n if (reviewUrl != null ? !reviewUrl.equals(review.reviewUrl) : review.reviewUrl != null) return false;\n return content != null ? content.equals(review.content) : review.content == null;\n\n }\n\n @Override\n @SuppressWarnings(\"PMD\")\n public int hashCode() {\n int result = reviewId != null ? reviewId.hashCode() : 0;\n result = 31 * result + (author != null ? author.hashCode() : 0);\n result = 31 * result + (reviewUrl != null ? reviewUrl.hashCode() : 0);\n result = 31 * result + (content != null ? content.hashCode() : 0);\n return result;\n }\n //CHECKSTYLE:ON\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.reviewId);\n dest.writeString(this.author);\n dest.writeString(this.reviewUrl);\n dest.writeString(this.content);\n }\n}", "@SuppressWarnings(\"PMD.GodClass\")\npublic class MovieVideo implements Parcelable {\n\n public static final Parcelable.Creator<MovieVideo> CREATOR = new Parcelable.Creator<MovieVideo>() {\n @Override\n public MovieVideo createFromParcel(Parcel source) {\n return new MovieVideo(source);\n }\n\n @Override\n public MovieVideo[] newArray(int size) {\n return new MovieVideo[size];\n }\n };\n\n private static final String SITE_YOUTUBE = \"YouTube\";\n\n @SerializedName(\"id\")\n private String videoId;\n @SerializedName(\"iso_639_1\")\n private String languageCode;\n @SerializedName(\"iso_3166_1\")\n private String countryCode;\n @SerializedName(\"key\")\n private String key;\n @SerializedName(\"name\")\n private String name;\n @SerializedName(\"site\")\n private String site;\n @SerializedName(\"size\")\n private int size;\n @SerializedName(\"type\")\n private String type;\n\n public MovieVideo(String videoId) {\n this.videoId = videoId;\n }\n\n protected MovieVideo(Parcel in) {\n this.videoId = in.readString();\n this.languageCode = in.readString();\n this.countryCode = in.readString();\n this.key = in.readString();\n this.name = in.readString();\n this.site = in.readString();\n this.size = in.readInt();\n this.type = in.readString();\n }\n\n public String getVideoId() {\n return videoId;\n }\n\n public void setVideoId(String videoId) {\n this.videoId = videoId;\n }\n\n public String getLanguageCode() {\n return languageCode;\n }\n\n public void setLanguageCode(String languageCode) {\n this.languageCode = languageCode;\n }\n\n public String getCountryCode() {\n return countryCode;\n }\n\n public void setCountryCode(String countryCode) {\n this.countryCode = countryCode;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getSite() {\n return site;\n }\n\n public void setSite(String site) {\n this.site = site;\n }\n\n public int getSize() {\n return size;\n }\n\n public void setSize(int size) {\n this.size = size;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public boolean isYoutubeVideo() {\n return site.toLowerCase(Locale.US).equals(SITE_YOUTUBE.toLowerCase(Locale.US));\n }\n\n //CHECKSTYLE:OFF\n @Override\n @SuppressWarnings(\"PMD\")\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n MovieVideo video = (MovieVideo) o;\n\n if (size != video.size) return false;\n if (videoId != null ? !videoId.equals(video.videoId) : video.videoId != null) return false;\n if (languageCode != null ? !languageCode.equals(video.languageCode) : video.languageCode != null) return false;\n if (countryCode != null ? !countryCode.equals(video.countryCode) : video.countryCode != null) return false;\n if (key != null ? !key.equals(video.key) : video.key != null) return false;\n if (name != null ? !name.equals(video.name) : video.name != null) return false;\n if (site != null ? !site.equals(video.site) : video.site != null) return false;\n return type != null ? type.equals(video.type) : video.type == null;\n\n }\n\n @Override\n @SuppressWarnings(\"PMD\")\n public int hashCode() {\n int result = videoId != null ? videoId.hashCode() : 0;\n result = 31 * result + (languageCode != null ? languageCode.hashCode() : 0);\n result = 31 * result + (countryCode != null ? countryCode.hashCode() : 0);\n result = 31 * result + (key != null ? key.hashCode() : 0);\n result = 31 * result + (name != null ? name.hashCode() : 0);\n result = 31 * result + (site != null ? site.hashCode() : 0);\n result = 31 * result + size;\n result = 31 * result + (type != null ? type.hashCode() : 0);\n return result;\n }\n //CHECKSTYLE:ON\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this.videoId);\n dest.writeString(this.languageCode);\n dest.writeString(this.countryCode);\n dest.writeString(this.key);\n dest.writeString(this.name);\n dest.writeString(this.site);\n dest.writeInt(this.size);\n dest.writeString(this.type);\n }\n\n}", "public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {\n\n private int mItemOffset;\n\n public ItemOffsetDecoration(int itemOffset) {\n mItemOffset = itemOffset;\n }\n\n public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {\n this(context.getResources().getDimensionPixelSize(itemOffsetId));\n }\n\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n super.getItemOffsets(outRect, view, parent, state);\n outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset);\n }\n}" ]
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.trello.rxlifecycle.components.support.RxFragment; import java.util.ArrayList; import java.util.Locale; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import me.maxdev.popularmoviesapp.PopularMoviesApp; import me.maxdev.popularmoviesapp.R; import me.maxdev.popularmoviesapp.api.MovieReviewsResponse; import me.maxdev.popularmoviesapp.api.MovieVideosResponse; import me.maxdev.popularmoviesapp.api.TheMovieDbService; import me.maxdev.popularmoviesapp.data.Movie; import me.maxdev.popularmoviesapp.data.MovieReview; import me.maxdev.popularmoviesapp.data.MovieVideo; import me.maxdev.popularmoviesapp.ui.ItemOffsetDecoration; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
} private void updateMovieReviewsCard() { if (reviewsAdapter == null || reviewsAdapter.getItemCount() == 0) { cardMovieReviews.setVisibility(View.GONE); } else { cardMovieReviews.setVisibility(View.VISIBLE); } } private void setupCardElevation(View view) { ViewCompat.setElevation(view, convertDpToPixel(getResources().getInteger(R.integer.movie_detail_content_elevation_in_dp))); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (videosAdapter.getItemCount() != 0) { outState.putParcelableArrayList(MOVIE_VIDEOS_KEY, videosAdapter.getMovieVideos()); } if (reviewsAdapter.getItemCount() != 0) { outState.putParcelableArrayList(MOVIE_REVIEWS_KEY, reviewsAdapter.getMovieReviews()); } } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { videosAdapter.setMovieVideos(savedInstanceState.getParcelableArrayList(MOVIE_VIDEOS_KEY)); reviewsAdapter.setMovieReviews(savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_KEY)); } } private void loadMovieVideos() { theMovieDbService.getMovieVideos(movie.getId()) .compose(bindToLifecycle()) .subscribeOn(Schedulers.newThread()) .map(MovieVideosResponse::getResults) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<ArrayList<MovieVideo>>() { @Override public void onCompleted() { // do nothing } @Override public void onError(Throwable e) { Log.e(LOG_TAG, e.getMessage()); updateMovieVideosCard(); } @Override public void onNext(ArrayList<MovieVideo> movieVideos) { videosAdapter.setMovieVideos(movieVideos); updateMovieVideosCard(); } }); } private void loadMovieReviews() { theMovieDbService.getMovieReviews(movie.getId()) .compose(bindToLifecycle()) .subscribeOn(Schedulers.newThread()) .map(MovieReviewsResponse::getResults) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<ArrayList<MovieReview>>() { @Override public void onCompleted() { // do nothing } @Override public void onError(Throwable e) { Log.e(LOG_TAG, e.getMessage()); updateMovieReviewsCard(); } @Override public void onNext(ArrayList<MovieReview> movieReviews) { reviewsAdapter.setMovieReviews(movieReviews); updateMovieReviewsCard(); } }); } private void initViews() { Glide.with(this) .load(POSTER_IMAGE_BASE_URL + POSTER_IMAGE_SIZE + movie.getPosterPath()) .crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(movieImagePoster); movieOriginalTitle.setText(movie.getOriginalTitle()); movieUserRating.setText(String.format(Locale.US, "%.1f", movie.getAverageVote())); movieUserRating.setTextColor(getRatingColor(movie.getAverageVote())); String releaseDate = String.format(getString(me.maxdev.popularmoviesapp.R.string.movie_detail_release_date), movie.getReleaseDate()); movieReleaseDate.setText(releaseDate); movieOverview.setText(movie.getOverview()); } @ColorInt private int getRatingColor(double averageVote) { if (averageVote >= VOTE_PERFECT) { return ContextCompat.getColor(getContext(), R.color.vote_perfect); } else if (averageVote >= VOTE_GOOD) { return ContextCompat.getColor(getContext(), R.color.vote_good); } else if (averageVote >= VOTE_NORMAL) { return ContextCompat.getColor(getContext(), R.color.vote_normal); } else { return ContextCompat.getColor(getContext(), R.color.vote_bad); } } private void initVideosList() { videosAdapter = new MovieVideosAdapter(getContext()); videosAdapter.setOnItemClickListener((itemView, position) -> onMovieVideoClicked(position)); movieVideos.setAdapter(videosAdapter); movieVideos.setItemAnimator(new DefaultItemAnimator());
movieVideos.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.movie_item_offset));
7
bit-man/SwissArmyJavaGit
javagit/src/main/java/edu/nyu/cs/javagit/client/cli/CliGitCheckout.java
[ "public final class JavaGitConfiguration {\n\n /*\n * The path to our git binaries. Default to null, which means that the git command is available\n * via the system PATH environment variable.\n */\n private static File gitPath = null;\n\n /*\n * The version string fpr the locally-installed git binaries.\n */\n private static GitVersion gitVersion = null;\n\n /**\n * Constructor - private because this is an all-static class.\n */\n private JavaGitConfiguration() {\n\n }\n\n /**\n * Sets the {@link #gitVersion} field.\n * <br/>\n * This function gets called in one of two ways:\n * <br/>\n * 1) When client code sets the path to the git binaries explicitly by calling {@link #setGitPath(java.io.File)},\n * this function is used to determine if the path is usable or not. In this case, the\n * <code>File</code> path argument will be the new path to the git binaries.\n * <br/>\n * 2) When client code calls {@link #getGitVersion()} and the path has not been set explicitly, we\n * call this function to figure out the version. In this case, the <code>File</code> path\n * argument will be null.\n *\n *\n * @param path\n * <code>File</code> object representing the directory containing the git binaries. If\n * null, the previously-set path is used (if any). It must contain either an absolute\n * path, or a valid path relative to the current working directory.\n * @throws JavaGitException\n * Thrown if git is not found at the provided path.\n */\n private static void determineGitVersion(File path) throws JavaGitException {\n\n /*\n * If they already set the path explicitly, or are in the process of doing so (via the path\n * argument), make sure to prefix the git call with it. If they didn't, assume it's blank.\n */\n String gitPrefix = \"\";\n if (path != null) {\n // We got a path passed in as an argument.\n gitPrefix = path.getAbsolutePath() + File.separator;\n } else if (gitPath != null) {\n // They didn't pass in a path, but previously set it explicitly via setGitPath.\n gitPrefix = getGitCommandPrefix();\n }\n\n String gitCommand = gitPrefix + \"git\";\n if (!(gitPrefix.equals(\"\"))) {\n // If we've got a full path to the git binary here, ensure it actually exists.\n if (!(new File(gitCommand).exists())) {\n throw new JavaGitException(100002, ExceptionMessageMap.getMessage(\"100002\"));\n }\n }\n\n List<String> commandLine = new ArrayList<String>();\n commandLine.add(gitCommand);\n commandLine.add(\"--version\");\n\n // Now run the actual git version command.\n try {\n // We're passing in a working directory of null, which is \"don't care\" to runCommand\n gitVersion = (GitVersion) ProcessUtilities.runCommand(null, commandLine,\n new GitVersionParser());\n } catch (Exception e) {\n throw new JavaGitException(100001, ExceptionMessageMap.getMessage(\"100001\"));\n }\n\n String version = gitVersion.toString();\n if (!(isValidVersionString(version))) {\n throw new JavaGitException(100001, ExceptionMessageMap.getMessage(\"100001\"));\n }\n\n }\n\n /**\n * Return the complete string necessary to invoke git on the command line. Could be an absolute\n * path to git, or if the path was never set explicitly, just \"git\".\n * \n * @return <code>String</code> containing the path to git, ending with the git executable's name\n * itself.\n */\n public static String getGitCommand() {\n return getGitCommandPrefix() + \"git\";\n }\n\n /**\n * Return an absolute path capable of being dropped in front of the command-line git invocation.\n * If the path hasn't been set explicitly, just return the empty string and assume git is in this\n * process' PATH environment variable.\n * \n * @return The <code>String</code> that points to the git executable.\n */\n public static String getGitCommandPrefix() {\n return ((gitPath == null) ? \"\" : (gitPath.getAbsolutePath() + File.separator));\n }\n\n /**\n * Accessor method for the <code>File</code> object representing the path to git. If the git\n * path is never set explicitly, this will return null.\n * \n * @return <code>File</code> object pointing at the directory containing git.\n */\n public static File getGitPath() {\n return gitPath;\n }\n\n /**\n * Returns the version number of the underlying git binaries. If this method is called and we\n * don't know the version yet, it tries to figure it out. (The version gets set if\n * {@link #setGitPath(File) setGitPath} was previously called.)\n * \n * @return The git version <code>String</code>.\n */\n public static String getGitVersion() throws JavaGitException {\n return getGitVersionObject().toString();\n }\n\n\n public static GitVersion getGitVersionObject() throws JavaGitException {\n // If the version hasn't been found yet, let's do some lazy initialization here.\n if (gitVersion == null) {\n determineGitVersion(gitPath);\n }\n\n return gitVersion;\n }\n\n /**\n * Judge the validity of a given git version string. This can be difficult to do, as there seems\n * to be no deliberately-defined git version format. So, here we do a minimal sanity check for two\n * things: 1. The first character in the version is a number. 2. There's at least one period in\n * the version string.\n * \n * @param version\n * @return true if the version passed as argument is valid\n */\n private static boolean isValidVersionString(String version) {\n /*\n * Git version strings can vary, so let's do a minimal sanity check for two things: 1. The first\n * character in the version is a number. 2. There's at least one period in the version string.\n * \n * TODO (rs2705): Make this more sophisticated by parsing out a major/minor version number, and\n * ensuring it's >= some minimally-required version.\n */\n try {\n Integer.parseInt(version.substring(0, 1));\n } catch (NumberFormatException e) {\n // First character in the version string was not a valid number!\n return false;\n }\n\n if (version.indexOf(\".\") == -1) {\n // The version string doesn't contain a period!\n return false;\n }\n\n return true;\n }\n\n /**\n * Called when client code wants to explicitly tell us where to find git on their filesystem. If\n * never called, we assume that git is in a directory in the PATH environment variable for this\n * process. Passing null as the path argument will unset an explicitly-set path and revert to\n * looking for git in the PATH.\n * \n * @param path\n * <code>File</code> object representing the directory containing the git binaries. It\n * must contain either an absolute path, or a valid path relative to the current working\n * directory.\n * @throws IOException\n * Thrown if the provided path does not exist.\n * @throws JavaGitException\n * Thrown if git does not exist at the provided path, or the provided path is not a\n * directory.\n */\n public static void setGitPath(File path) throws IOException, JavaGitException {\n if (path != null) {\n CheckUtilities.checkFileValidity(path);\n\n if (!(path.isDirectory())) {\n throw new JavaGitException(020002, ExceptionMessageMap.getMessage(\"020002\") + \" { path=[\"\n + path.getPath() + \"] }\");\n }\n }\n\n try {\n determineGitVersion(path);\n } catch (Exception e) {\n // The path that was passed in doesn't work. Catch any errors and throw this one instead.\n throw new JavaGitException(100002, ExceptionMessageMap.getMessage(\"100002\") + \" { path=[\"\n + path.getPath() + \"] }\", e);\n }\n\n // Make sure we're hanging onto an absolute path.\n gitPath = (path != null) ? path.getAbsoluteFile() : null;\n }\n\n /**\n * Convenience method for setting the path with a <code>String</code> instead of a\n * <code>File</code>.\n * \n * TODO (rs2705): Enforce the requirement below that the path be absolute. Is there a simple way\n * to do this in an OS-independent fashion?\n * \n * @param path\n * Absolute path to git binaries installed on the system. The path must be absolute since\n * it needs to persist for the life of the client code, even if the working directory\n * changes. Throws a NullPointerException if path is null, or an IllegalArgumentException\n * if it's the empty string.\n * @throws IOException\n * Thrown if the provided path does not exist.\n * @throws JavaGitException\n * Thrown if we cannot find git at the path provided.\n */\n public static void setGitPath(String path) throws IOException, JavaGitException {\n CheckUtilities.checkStringArgument(path, \"path\");\n setGitPath(new File(path));\n }\n\n /*\n * <code>GitVersionParser</code> parses the output of the <code>git --version</code> command.\n * It is also used to determine if the git binaries are accessible via the command line.\n * \n * TODO (rs2705): Write unit tests for this class.\n */\n private static class GitVersionParser implements IParser {\n // The version of git that we parse out.\n private String version = \"\";\n\n // Whether or not we saw a valid version string.\n private boolean parsedCorrectly = true;\n\n // We only care about parsing the first line of our input - watch that here.\n private boolean sawLine = false;\n\n /**\n * Returns the <code>GitVersion</code> object that's essentially just a wrapper around\n * the git version number.\n * \n * @return The response object containing the version number.\n */\n public CommandResponse getResponse() throws JavaGitException {\n if (!(parsedCorrectly)) {\n throw new JavaGitException(100001, ExceptionMessageMap.getMessage(\"100001\"));\n }\n return new GitVersion(version);\n }\n\n /**\n * Parses the output of <code>git --version</code>. Expects to see: \"git version XYZ\".\n * \n * @param line\n * <code>String</code> containing the line to be parsed.\n */\n public void parseLine(String line) {\n if (!(sawLine)) {\n sawLine = true;\n parsedCorrectly = (line.trim().indexOf(\"git version \") == 0);\n if (parsedCorrectly) {\n version = line.replaceAll(\"git version \", \"\");\n }\n }\n }\n\n public void processExitCode(int code) {\n }\n \n }\n\n}", "public class Ref {\n\n /*\n * TODO (jhl388): add the field \"isCurrentBranch\" to indicate if the ref is the current working\n * branch. Refs of the current working branch and all HEAD refs should have the value \"true\". All\n * other refs should have the value \"false\".\n */\n\n /**\n * An enumeration of the types of refs.\n */\n public static enum RefType {\n BRANCH, HEAD, REMOTE, SHA1, TAG\n }\n\n /** The HEAD commit. */\n public static final Ref HEAD;\n\n /** The prior HEAD commit. */\n public static final Ref HEAD_1;\n\n static {\n HEAD = new Ref();\n HEAD.refType = RefType.HEAD;\n HEAD.headOffset = 0;\n\n HEAD_1 = new Ref();\n HEAD_1.refType = RefType.HEAD;\n HEAD_1.headOffset = 1;\n }\n\n // The type of this ref.\n private Ref.RefType refType;\n\n /*\n * If the ref's type is HEAD, this is the number of commits back from the head of the current\n * working branch.\n */\n private int headOffset = -1;\n\n // If the ref's type is BRANCH, REMOTE, SHA1, or TAG, this is the name of the ref.\n private String name = null;\n\n /*\n * If the ref's type is REMOTE, this is the name of the remote repository iff a repository name is\n * associated with the remote name.\n */\n private String repositoryName = null;\n\n /**\n * Creates a <code>Ref</code> of type <code>BRANCH</code>.\n * \n * @param name\n * The branch name of this ref. If the value is null, a <code>NullPointerException</code>\n * is thrown. If the value has length zero, an <code>IllegalArgumentException</code> is\n * thrown.\n * @return A <code>Ref</code> instance of type <code>BRANCH</code>.\n */\n public static Ref createBranchRef(String name) {\n CheckUtilities.checkStringArgument(name, \"name\");\n\n Ref cn = new Ref();\n cn.refType = RefType.BRANCH;\n cn.name = name;\n return cn;\n }\n\n /**\n * Creates a <code>Ref</code> of type <code>HEAD</code>.\n * \n * @param headOffset\n * The offset of the commit back from the HEAD commit on the current working branch. If\n * the value is less than zero, an <code>IllegalArgumentException</code> is thrown.\n * @return A <code>Ref</code> instance of type <code>HEAD</code>.\n */\n public static Ref createHeadRef(int headOffset) {\n CheckUtilities.checkIntArgumentGreaterThan(headOffset, -1, \"headOffset\");\n\n if (0 == headOffset) {\n return HEAD;\n } else if (1 == headOffset) {\n return HEAD_1;\n }\n\n Ref cn = new Ref();\n cn.refType = RefType.HEAD;\n cn.headOffset = headOffset;\n return cn;\n }\n\n /**\n * Creates a <code>Ref</code> of type <code>REMOTE</code>.\n * \n * @param repositoryName\n * The remote repository name of this ref. If the value is blank or null, the value will\n * be maintained as null.\n * @param name\n * The remote branch name of this ref. If the value is null, a\n * <code>NullPointerException</code> is thrown. If the value has length zero, an\n * <code>IllegalArgumentException</code> is thrown.\n * @return A <code>Ref</code> instance of type <code>REMOTE</code>.\n */\n public static Ref createRemoteRef(String repositoryName, String name) {\n CheckUtilities.checkStringArgument(name, \"name\");\n\n Ref cn = new Ref();\n cn.refType = RefType.REMOTE;\n cn.name = name;\n\n if (null != repositoryName && repositoryName.length() > 0) {\n cn.repositoryName = repositoryName;\n }\n\n return cn;\n }\n\n /**\n * Creates a <code>Ref</code> of type <code>SHA1</code>.\n * \n * @param name\n * The SHA1 name of this ref. The value can be a short name or the full SHA1 value. If\n * the value is null, a <code>NullPointerException</code> is thrown. If the value has\n * length zero, an <code>IllegalArgumentException</code> is thrown.\n * @return A <code>Ref</code> instance of type <code>SHA1</code>.\n */\n public static Ref createSha1Ref(String name) {\n CheckUtilities.checkStringArgument(name, \"name\");\n\n Ref cn = new Ref();\n cn.refType = RefType.SHA1;\n cn.name = name;\n return cn;\n }\n\n /**\n * Creates a <code>Ref</code> of type <code>TAG</code>.\n * \n * @param name\n * The tag name of this ref. If the value is null, a <code>NullPointerException</code>\n * is thrown. If the value has length zero, an <code>IllegalArgumentException</code> is\n * thrown.\n * @return A <code>Ref</code> instance of type <code>TAG</code>.\n */\n public static Ref createTagRef(String name) {\n CheckUtilities.checkStringArgument(name, \"name\");\n\n Ref cn = new Ref();\n cn.refType = RefType.TAG;\n cn.name = name;\n return cn;\n }\n\n /**\n * Gets the type of the <code>Ref</code> instance.\n * \n * @return The type of the <code>Ref<code> instance.\n */\n public Ref.RefType getRefType() {\n return refType;\n }\n\n /**\n * Gets the offset of the commit back from the HEAD commit on the current working branch for this\n * <code>Ref</code> instance.\n * \n * @return If the type of this <code>Ref</code> is not <code>HEAD</code>, then -1 is\n * returned. Otherwise, the offset of the commit back from the HEAD commit on the current\n * working branch is returned.\n */\n public int getHeadOffset() {\n return headOffset;\n }\n\n /**\n * Gets the name of this ref.\n * \n * @return If the type of this <code>Ref</code> is not <code>BRANCH</code>,\n * <code>REMOTE</code>, <code>SHA1</code> or <code>TAG</code>, then null is\n * returned. Otherwise, the name of this ref is returned.\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets the repository name of this ref.\n * \n * @return If the type of this <code>Ref</code> is not <code>REMOTE</code>, then null is\n * returned. If the type of this <code>Ref</code> is <code>REMOTE</code> and there is\n * no associated repository name, then null is returned. Otherwise, the repository name of\n * this ref is returned.\n */\n public String getRepositoryName() {\n return repositoryName;\n }\n\n @Override\n public String toString() {\n if (RefType.HEAD == refType) {\n if (0 == headOffset) {\n return \"HEAD\";\n } else if (1 == headOffset) {\n return \"HEAD^1\";\n } else {\n return \"HEAD~\" + Integer.toString(headOffset);\n }\n } else if (RefType.BRANCH == refType || RefType.SHA1 == refType || RefType.TAG == refType) {\n return name;\n } else if (RefType.REMOTE == refType) {\n if (null != repositoryName) {\n return repositoryName + \"/\" + name;\n } else {\n return name;\n }\n } else {\n return \"\";\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof Ref)) {\n return false;\n }\n\n Ref cn = (Ref) o;\n\n if (!CheckUtilities.checkObjectsEqual(refType, cn.getRefType())) {\n return false;\n }\n if (!CheckUtilities.checkObjectsEqual(name, cn.getName())) {\n return false;\n }\n if (!CheckUtilities.checkObjectsEqual(repositoryName, cn.getRepositoryName())) {\n return false;\n }\n if (cn.getHeadOffset() != headOffset) {\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int ret = refType.hashCode() + headOffset;\n ret += (null == name) ? 0 : name.hashCode();\n ret += (null == repositoryName) ? 0 : repositoryName.hashCode();\n return ret;\n }\n\n}", "public static enum RefType {\n BRANCH, HEAD, REMOTE, SHA1, TAG\n}", "public class GitCheckoutResponseImpl extends GitCheckoutResponse {\n\n /**\n * Sets the new branch name that is created by &lt;git-checkout&gt using -b option\n * \n * @param newBranch\n * Name of the new branch created\n */\n public void setNewBranch(Ref newBranch) {\n this.newBranch = newBranch;\n }\n\n /**\n * Sets the branch to the branch, to which the &lt;git-checkout&gt switched the repository to.\n * This branch should already be existing in the repository. To create a new branch and switch to\n * it, use the -b option while running &lt;git-checkout&gt.\n * \n * @param branch\n */\n public void setBranch(Ref branch) {\n this.branch = branch;\n }\n\n /**\n * Adds the modified file to the list of modifiedFiles. When a file is modified locally but has\n * not been committed to the repository and if we try to switch the branch to another branch, the\n * &lt;git-checkout&gt fails and outputs the list of modified files that are not yet committed\n * unless -f option is used by &lt;git-checkout&gt.\n * \n * @param file\n */\n public void addModifiedFile(File file) {\n modifiedFiles.add(file);\n }\n\n /**\n * Adds the newly added file to the list of addedFiles. A newly added file is the one that is\n * added by &lt;git-add&gt; command but had not been committed.\n * \n * @param file\n */\n public void addAddedFile(File file) {\n addedFiles.add(file);\n }\n\n /**\n * Adds the locally deleted file to the list of deletedFiles. A locally deleted file is one that\n * has been removed but has not been removed from repository using &lt;git-rm&gt; command.\n * \n * @param file\n */\n public void addDeletedFile(File file) {\n deletedFiles.add(file);\n }\n\n}", "public interface IGitCheckout {\n\n /**\n * Checks out either an existing branch or new branch from the repository.\n * \n * @param repositoryPath\n * Path to the root of the repository\n * @param options\n * <code>GitCheckoutOptions</code> object used for passing options to\n * &lt;git-checkout&gt;\n * @param branch\n * Name of the base branch that need to be checked out or if the new branch is being\n * checkout based on this base branch.\n * @param paths\n * <code>List</code> of files that are specifically to be checked out.\n * @return GitCheckoutResponse object\n * @throws JavaGitException thrown if -\n * <ul>\n * <li>if options passed are not correct.</li>\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath, GitCheckoutOptions options, Ref branch,\n List<File> paths) throws JavaGitException, IOException;\n\n /**\n * Checks out either an existing branch or new branch from the repository.\n * \n * @param repositoryPath\n * Path to the root of the repository\n * @param options\n * <code>GitCheckoutOptions</code> object used for passing options to\n * &lt;git-checkout&gt;\n * @param branch\n * Name of the base branch that need to be checked out or if the new branch is being\n * checkout based on this base branch.\n * @param file\n * Single file that need to be checked out from the git repository\n * @return GitCheckoutResponse object\n * @throws JavaGitException thrown if -\n * <ul>\n * <li>if options passed are not correct.</li>\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath, GitCheckoutOptions options, Ref branch,\n File file) throws JavaGitException, IOException;\n\n /**\n * Checks out either an existing branch or new branch from the repository.\n * \n * @param repositoryPath\n * Path to the root of the repository\n * @param options\n * <code>GitCheckoutOptions</code> object used for passing options to\n * &lt;git-checkout&gt;\n * @param branch\n * Name of the base branch that need to be checked out or if the new branch is being\n * checkout based on this base branch.\n * @return GitCheckoutResponse< object\n * @throws JavaGitException thrown if -\n * <ul>\n * <li>if options passed are not correct.</li>\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath, GitCheckoutOptions options, Ref branch)\n throws JavaGitException, IOException;\n\n /**\n * Vanilla version of &lt;git-checkout&gt; where no options and no branch info is passed to it and\n * files are checked out from current branch.\n * \n * @param repositoryPath\n * path to the root of the repository\n * @throws JavaGitException thrown if -\n * <ul>\n * <li>if options passed are not correct.</li>\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath) throws JavaGitException, IOException;\n\n /**\n * Checks out an existing branch with no options provided.\n * \n * @param repositoryPath\n * path to the root of the repository\n * @param branch\n * name of the base branch that need to be checked out\n * @return GitCheckoutResponse object\n * @throws JavaGitException thrown if -\n * <ul>\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath, Ref branch) throws JavaGitException,\n IOException;\n\n /**\n * &lt;git-checkout&gt; where a list of files is given to be checked out from current branch of\n * the repository.\n * \n * @param repositoryPath\n * path to the root of the repository\n * @param paths\n * list of file paths or directory that need to be checked out from git repository.\n * @return GitCheckoutResponse object\n * @throws JavaGitException thrown if -\n * <ul>\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath, List<File> paths)\n throws JavaGitException, IOException;\n\n /**\n * &lt;git-checkout&gt; where a list of files is given to be checked out with tree-ish option set.\n * \n * @param repositoryPath\n * path to the root of the repository\n * @param treeIsh\n * RefType object\n * @param paths\n * List of files to be checked out.\n * @return GitCheckoutResponse object\n * @throws JavaGitException thrown if -\n * <li>if the output for &lt;git-checkout&gt; command generated an error.</li>\n * <li>if processBuilder not able to run the command.</li>\n * </ul>\n * @throws IOException thrown if -\n * <ul>\n * <li>paths given do not have proper permissions.</li>\n * <li>paths given do not exist at all.</li>\n * </ul>\n */\n public GitCheckoutResponse checkout(File repositoryPath, Ref treeIsh, List<File> paths)\n throws JavaGitException, IOException;\n}", "public class CheckUtilities {\n\n /**\n * Checks that the specified filename exists. This assumes that the above check for string\n * validity has already been run and the path/filename is neither null or of size 0.\n * \n * @param filename\n * File or directory path\n */\n public static void checkFileValidity(String filename) throws IOException {\n File file = new File(filename);\n if (!file.exists()) {\n throw new IOException(ExceptionMessageMap.getMessage(\"020001\") + \" { filename=[\" + filename\n + \"] }\");\n }\n }\n\n /**\n * Checks that the specified file exists.\n * \n * @param file\n * File or directory path\n */\n public static void checkFileValidity(File file) throws IOException {\n if (!file.exists()) {\n throw new IOException(ExceptionMessageMap.getMessage(\"020001\") + \" { filename=[\"\n + file.getName() + \"] }\");\n }\n }\n\n /**\n * Checks that the int to check is greater than <code>lowerBound</code>. If the int to check is\n * not greater than <code>lowerBound</code>, an <code>IllegalArgumentException</code> is\n * thrown.\n * \n * @param toCheck\n * The int to check.\n * @param lowerBound\n * The lower bound to check against.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkIntArgumentGreaterThan(int toCheck, int lowerBound, String variableName) {\n if (lowerBound >= toCheck) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000004\") + \" { toCheck=[\"\n + toCheck + \"], lowerBound=[\" + lowerBound + \"], variableName=[\" + variableName + \"] }\");\n }\n }\n\n /**\n * Performs a null check on the specified object. If the object is null, a\n * <code>NullPointerException</code> is thrown.\n * \n * @param obj\n * The object to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkNullArgument(Object obj, String variableName) {\n if (null == obj) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000003\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n\n /**\n * Checks a <code>List&lt;?&gt;</code> argument to make sure it is not null, has length > 0, and\n * none of its elements are null. If the <code>List&lt;?&gt;</code> or any contained instance is\n * null, a <code>NullPointerException</code> is thrown. If the <code>List&lt;?&gt;</code> or\n * any contained instance has length zero, an <code>IllegalArgumentException</code> is thrown.\n * \n * @param list\n * The list to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkNullListArgument(List<?> list, String variableName) {\n // TODO (jhl388): Write a unit test for this method.\n if (null == list) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000005\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n if (list.size() == 0) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000005\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n for (int i = 0; i < list.size(); i++) {\n checkNullArgument(list.get(i), variableName);\n }\n }\n\n /**\n * Checks that two lists are equal, specifically: they are both null or the both contain the same\n * elements.\n * \n * @param l1\n * The first list to check.\n * @param l2\n * The second list to check.\n * @return True if one of the following conditions hold:\n * <ol>\n * <li>Both lists are null</li>\n * <li>a) Neither list is null; b) for each element in list 1 an equivalent element\n * exists in list 2; and c) for each element in list 2, an equivalent element exists in\n * list 1</li>\n * </ol>\n */\n public static boolean checkListsEqual(List<?> l1, List<?> l2) {\n \n // TODO (jhl388): write a test case for this method.\n \n if (null != l1 && null == l2) {\n return false;\n }\n \n if (null == l1 && null != l2) {\n return false;\n }\n \n if (null != l1) {\n for (Object e : l1) {\n if (!l2.contains(e)) {\n return false;\n }\n }\n \n for (Object e : l2) {\n if (!l1.contains(e)) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Checks to see if two objects are equal. The Object.equal() method is used to check for\n * equality.\n * \n * @param o1\n * The first object to check.\n * @param o2\n * The second object to check.\n * @return True if the two objects are equal. False if the objects are not equal.\n */\n public static boolean checkObjectsEqual(Object o1, Object o2) {\n if (null != o1 && !o1.equals(o2)) {\n return false;\n }\n\n if (null == o1 && null != o2) {\n return false;\n }\n\n return true;\n }\n\n /**\n * Checks a <code>String</code> argument to make sure it is not null and contains one or more\n * characters. If the <code>String</code> is null, a <code>NullPointerException</code> is\n * thrown. If the <code>String</code> has length zero, an <code>IllegalArgumentException</code>\n * is thrown.\n * \n * @param str\n * The string to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkStringArgument(String str, String variableName) {\n if (null == str) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000001\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n if (str.length() == 0) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000001\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n\n /**\n * Checks a <code>List&lt;String&gt;</code> argument to make sure it is not null, none of its\n * elements are null, and all its elements contain one or more characters. If the\n * <code>List&lt;String&gt;</code> or a contained <code>String</code> is null, a\n * <code>NullPointerException</code> is thrown. If the <code>List&lt;String&gt;</code> or a\n * contained <code>String</code> has length zero, an <code>IllegalArgumentException</code> is\n * thrown.\n * \n * @param str\n * The <code>List&lt;String&gt;</code> to check.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkStringListArgument(List<String> str, String variableName) {\n if (null == str) {\n throw new NullPointerException(ExceptionMessageMap.getMessage(\"000002\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n if (str.size() == 0) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000002\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n for (int i = 0; i < str.size(); i++) {\n checkStringArgument(str.get(i), variableName);\n }\n }\n\n /**\n * Checks if two unordered lists are equal.\n * \n * @param l1\n * The first list to test.\n * @param l2\n * The second list to test.\n * @return True if:\n * <ul>\n * <li>both lists are null or</li>\n * <li>both lists are the same length, there exists an equivalent object in l2 for all\n * objects in l1, and there exists an equivalent object in l1 for all objects in l2</li>\n * </ul>\n * False otherwise.\n */\n public static boolean checkUnorderedListsEqual(List<?> l1, List<?> l2) {\n if (null == l1 && null != l2) {\n return false;\n }\n\n if (null != l1 && null == l2) {\n return false;\n }\n\n if (l1.size() != l2.size()) {\n return false;\n }\n\n for (Object o : l1) {\n if (!l2.contains(o)) {\n return false;\n }\n }\n\n for (Object o : l2) {\n if (!l1.contains(o)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Check if the index provided to list is within the range i.e. positive and less than the size of\n * the <List>. If the index is less than 0 or greater than equal to the size of the list then\n * <code>IndexOutOfBoundsException</code> is thrown.\n * \n * @param list\n * <List> for which the index is being verified.\n * @param index\n * Index in the list.\n */\n public static void checkIntIndexInListRange(List<?> list, int index) {\n checkIntInRange(index, 0, list.size());\n }\n\n /**\n * A general range check utility for checking whether a given &lt;integer&gt; value is between a\n * given start and end indexes. This is a helper method for other methods such as\n * checkIntIndexInListRange or can also be used independently by external objects.\n * \n * @param index\n * Given index that is being checked for validity between start and end.\n * @param start\n * index should be greater than or equal to start.\n * @param end\n * index should be less than end.\n */\n public static void checkIntInRange(int index, int start, int end) {\n if (index < start) {\n throw new IndexOutOfBoundsException(ExceptionMessageMap.getMessage(\"000006\") + \" { index=[\"\n + index + \"], start=[\" + start + \"], end=[\" + end + \"] }\");\n }\n if (index >= end) {\n throw new IndexOutOfBoundsException(ExceptionMessageMap.getMessage(\"000006\") + \" { index=[\"\n + index + \"], start=[\" + start + \"], end=[\" + end + \"] }\");\n }\n }\n\n /**\n * Checks a <code>List</code> argument to make sure that all the <code>Ref</code> in the list \n * are of same <code>refType</code> type. If there is a mismatch \n * <code>IllegalArgumentException</code> is thrown.\n * \n * @param list\n * The <code>List</code> to check.\n * @param type\n * The <code>refType</code> check against.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void validateListRefType(List<Ref> list, Ref.RefType type, String variableName) {\n // TODO (ns1344): Write a unit test for this method.\n checkNullListArgument(list, variableName);\n for (Ref ref : list) {\n validateArgumentRefType(ref, type, variableName);\n }\n }\n\n /**\n * Checks a <code>Ref</code> argument to make sure that it is of given <code>refType</code> type.\n * If not <code>IllegalArgumentException</code> is thrown.\n * \n * @param name\n * The argument to check.\n * @param type\n * The <code>refType</code> to check against.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void validateArgumentRefType(Ref name, Ref.RefType type, String variableName) {\n checkNullArgument(name, variableName);\n if (name.getRefType() != type) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"100000\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n \n /**\n * Checks a <code>File</code> argument to make sure that it is a directory. If not \n * <code>IllegalArgumentException</code> is thrown.\n * \n * @param fileName\n * The <code>File</code> to be checked.\n * @param variableName\n * The name of the variable being checked; for use in exception messages.\n */\n public static void checkDirectoryArgument(File fileName, String variableName) {\n checkNullArgument(fileName, variableName);\n if (!fileName.isDirectory()) {\n throw new IllegalArgumentException(ExceptionMessageMap.getMessage(\"000007\")\n + \" { variableName=[\" + variableName + \"] }\");\n }\n }\n}", "public class ExceptionMessageMap {\n\n private static Map<String, String> MESSAGE_MAP;\n\n static {\n MESSAGE_MAP = new HashMap<String, String>();\n\n MESSAGE_MAP.put(\"000001\", \"000001: A String argument was not specified but is required.\");\n MESSAGE_MAP.put(\"000002\", \"000002: A List<String> argument was not specified but is required.\");\n MESSAGE_MAP.put(\"000003\", \"000003: An Object argument was not specified but is required.\");\n MESSAGE_MAP.put(\"000004\",\n \"000004: The int argument is not greater than the lower bound (lowerBound < toCheck).\");\n MESSAGE_MAP.put(\"000005\",\n \"000005: An List<?> argument was not specified or is empty but is required.\");\n MESSAGE_MAP.put(\"000006\",\n \"000006: The int argument is outside the allowable range (start <= index < end).\");\n MESSAGE_MAP.put(\"000007\",\"000007: The argument should be a directory.\");\n\n MESSAGE_MAP.put(\"000100\", \"000100: Invalid option combination for git-commit command.\");\n MESSAGE_MAP.put(\"000110\", \"000110: Invalid option combination for git-add command.\");\n MESSAGE_MAP.put(\"000120\", \"000120: Invalid option combination for git-branch command.\");\n MESSAGE_MAP.put(\"000130\", \"000130: Invalid option combination for git-checkout command.\");\n \n MESSAGE_MAP.put(\"020001\", \"020001: File or path does not exist.\");\n MESSAGE_MAP.put(\"020002\", \"020002: File or path is not a directory.\");\n\n MESSAGE_MAP.put(\"020100\", \"020100: Unable to start sub-process.\");\n MESSAGE_MAP.put(\"020101\", \"020101: Error reading input from the sub-process.\");\n\n MESSAGE_MAP.put(\"100000\", \"100000: Incorrect refType type.\");\n MESSAGE_MAP.put(\"100001\", \"100001: Error retrieving git version.\");\n MESSAGE_MAP.put(\"100002\", \"100002: Invalid path to git specified.\");\n\n MESSAGE_MAP.put(\"401000\", \"401000: Error calling git-add.\");\n MESSAGE_MAP.put(\"401001\", \"401001: Error fatal pathspec error while executing git-add.\");\n\n MESSAGE_MAP.put(\"410000\", \"410000: Error calling git-commit.\");\n\n MESSAGE_MAP.put(\"404000\", \"404000: Error calling git-branch. \");\n\n MESSAGE_MAP.put(\"424000\", \"424000: Error calling git-mv. \");\n\n MESSAGE_MAP.put(\"424001\", \"424001: Error calling git-mv for dry-run. \");\n\n MESSAGE_MAP.put(\"420001\", \"420001: Error calling git log\");\n\n MESSAGE_MAP.put(\"432000\", \"432000: Error calling git-reset.\");\n\n MESSAGE_MAP.put(\"418000\", \"418000: Error calling git init.\");\n\n MESSAGE_MAP.put(\"434000\", \"434000: Error calling git-rm.\");\n\n MESSAGE_MAP.put(\"406000\", \"406000: Error calling git-checkout\");\n MESSAGE_MAP.put(\"406001\", \"406001: Error not a treeIsh RefType\");\n\n MESSAGE_MAP.put(\"438000\", \"438000: Error calling git-status\");\n\n MESSAGE_MAP.put(\"442001\", \"442001: No git, or wrong, major version number.\");\n MESSAGE_MAP.put(\"442002\", \"442002: No git, or wrong, minor version number.\");\n MESSAGE_MAP.put(\"442003\", \"442003: No git, or wrong, major release version number.\");\n MESSAGE_MAP.put(\"442004\", \"442004: Wrong minor release version number.\");\n }\n\n /**\n * Gets the error message for the specified code.\n * \n * @param code\n * The error code for which to get the associated error message.\n * @return The error message for the specified code.\n */\n public static String getMessage(String code) {\n String str = MESSAGE_MAP.get(code);\n if (null == str) {\n return \"NO MESSAGE FOR ERROR CODE. { code=[\" + code + \"] }\";\n }\n return str;\n }\n\n}" ]
import java.util.List; import java.util.Scanner; import edu.nyu.cs.javagit.api.JavaGitConfiguration; import edu.nyu.cs.javagit.api.JavaGitException; import edu.nyu.cs.javagit.api.Ref; import edu.nyu.cs.javagit.api.Ref.RefType; import edu.nyu.cs.javagit.api.commands.GitCheckoutOptions; import edu.nyu.cs.javagit.api.commands.GitCheckoutResponse; import edu.nyu.cs.javagit.client.GitCheckoutResponseImpl; import edu.nyu.cs.javagit.client.IGitCheckout; import edu.nyu.cs.javagit.utilities.CheckUtilities; import edu.nyu.cs.javagit.utilities.ExceptionMessageMap; import java.io.File; import java.io.IOException; import java.util.ArrayList;
throw new JavaGitException(120, "Both --notrack and --track options are set"); } if (options.optTrack()) { command.add("--track"); } if (options.optNoTrack()) { command.add("--no-track"); } command.add("-b"); command.add(newBranch.getName()); } if (options.optL()) { command.add("-l"); } if (options.optM()) { command.add("-m"); } } /** * Parser class to parse the output generated by &lt;git-checkout&gt; and return a * <code>GitCheckoutResponse</code> object. */ public static class GitCheckoutParser implements IParser { private static final char QUOTE_CHAR = '"'; private static final char SINGLE_QUOTE_CHAR = '\''; private int lineNum; private GitCheckoutResponseImpl response; private List<ErrorDetails> errors; public GitCheckoutParser() { lineNum = 0; response = new GitCheckoutResponseImpl(); errors = new ArrayList<ErrorDetails>(); } public void parseLine(String line) { if (line == null || line.length() == 0) { return; } ++lineNum; if (!isErrorLine(line)) { parseSwitchedToBranchLine(line); parseFilesInfo(line); } } private boolean isErrorLine(String line) { if (line.startsWith("error") || line.startsWith("fatal")) { setError(lineNum, line); return true; } return false; } public void parseSwitchedToBranchLine(String line) { if (line.startsWith("Switched to branch")) { getSwitchedToBranch(line); } else if (line.startsWith("Switched to a new branch")) { getSwitchedToNewBranch(line); } } private void getSwitchedToBranch(String line) { String branchName = extractBranchName(line); Ref branch = Ref.createBranchRef(branchName); response.setBranch(branch); } private void getSwitchedToNewBranch(String line) { String newBranchName = extractBranchName(line); Ref newBranch = Ref.createBranchRef(newBranchName); response.setNewBranch(newBranch); } private String extractBranchName(String line) { int startIndex = line.indexOf(QUOTE_CHAR); int endIndex = line.indexOf(QUOTE_CHAR, startIndex + 1); return (startIndex == -1 || endIndex == -1) ? extractBranchName(line, SINGLE_QUOTE_CHAR) : extractBranchName(line, QUOTE_CHAR); } private String extractBranchName(String line, char delim) { int startIndex = line.indexOf(delim); int endIndex = line.indexOf(delim, startIndex + 1); return line.substring(startIndex, endIndex + 1); } private void parseFilesInfo(String line) { if (Pattern.MODIFIED.matches(line)) { File file = new File(extractFileName(line)); response.addModifiedFile(file); return; } if (Pattern.DELETED.matches(line)) { File file = new File(extractFileName(line)); response.addDeletedFile(file); return; } if (Pattern.ADDED.matches(line)) { File file = new File(extractFileName(line)); response.addAddedFile(file); } } private String extractFileName(String line) { String filename = null; Scanner scanner = new Scanner(line); while (scanner.hasNext()) { filename = scanner.next(); } return filename; } public void processExitCode(int code) { } public GitCheckoutResponse getResponse() throws JavaGitException { if (errors.size() > 0) {
throw new JavaGitException(406000, ExceptionMessageMap.getMessage("406000") +
6
zeromq/jzmq-api
src/main/java/org/zeromq/api/Context.java
[ "public class CloneClientBuilder {\n public class Spec {\n public String primaryAddress;\n public String backupAddress;\n public int primaryPort;\n public int backupPort;\n public String subtree;\n public long heartbeatInterval = 1000L;\n }\n\n private ManagedContext context;\n private Spec spec = new Spec();\n\n public CloneClientBuilder(ManagedContext context) {\n this.context = context;\n }\n\n public CloneClientBuilder withPrimaryAddress(String primaryAddress) {\n spec.primaryAddress = primaryAddress;\n return this;\n }\n\n public CloneClientBuilder withBackupAddress(String backupAddress) {\n spec.backupAddress = backupAddress;\n return this;\n }\n\n public CloneClientBuilder withPrimaryPort(int primaryPort) {\n spec.primaryPort = primaryPort;\n return this;\n }\n\n public CloneClientBuilder withBackupPort(int backupPort) {\n spec.backupPort = backupPort;\n return this;\n }\n\n public CloneClientBuilder withSubtree(String subtree) {\n spec.subtree = subtree;\n return this;\n }\n\n public CloneClientBuilder withHeartbeatInterval(long heartbeatInterval) {\n spec.heartbeatInterval = heartbeatInterval;\n return this;\n }\n\n public CloneClient build() {\n CloneClient cloneClient = new CloneClientImpl(context, spec.heartbeatInterval);\n if (spec.subtree != null) {\n cloneClient.subscribe(spec.subtree);\n }\n if (spec.primaryAddress != null) {\n cloneClient.connect(spec.primaryAddress, spec.primaryPort);\n }\n if (spec.backupAddress != null) {\n cloneClient.connect(spec.backupAddress, spec.backupPort);\n }\n \n return cloneClient;\n }\n}", "public class CloneServerBuilder {\n public class Spec {\n public BinaryStarReactor.Mode mode;\n public String primaryAddress;\n public String backupAddress;\n public int primaryPort;\n public int backupPort;\n public int primaryBstarPort;\n public int backupBstarPort;\n public long heartbeatInterval = 1000;\n }\n\n private ManagedContext context;\n private Spec spec = new Spec();\n\n public CloneServerBuilder(ManagedContext context) {\n this.context = context;\n }\n\n public CloneServerBuilder withMode(BinaryStarReactor.Mode mode) {\n spec.mode = mode;\n return this;\n }\n\n public CloneServerBuilder withPrimaryAddress(String primaryAddress) {\n spec.primaryAddress = primaryAddress;\n return this;\n }\n\n public CloneServerBuilder withBackupAddress(String backupAddress) {\n spec.backupAddress = backupAddress;\n return this;\n }\n\n public CloneServerBuilder withPrimaryPort(int primaryPort) {\n spec.primaryPort = primaryPort;\n return this;\n }\n\n public CloneServerBuilder withBackupPort(int backupPort) {\n spec.backupPort = backupPort;\n return this;\n }\n\n public CloneServerBuilder withPrimaryBinaryStarPort(int primaryBstarPort) {\n spec.primaryBstarPort = primaryBstarPort;\n return this;\n }\n\n public CloneServerBuilder withBackupBinaryStarPort(int backupBstarPort) {\n spec.backupBstarPort = backupBstarPort;\n return this;\n }\n\n public CloneServerBuilder withHeartbeatInterval(long heartbeatInterval) {\n spec.heartbeatInterval = heartbeatInterval;\n return this;\n }\n\n public CloneServer build() {\n String peerAddress;\n int localPort, peerPort, localBstarPort, peerBstarPort;\n if (spec.mode == BinaryStarReactor.Mode.PRIMARY) {\n localPort = spec.primaryPort;\n peerAddress = spec.backupAddress;\n peerPort = spec.backupPort;\n localBstarPort = spec.primaryBstarPort;\n peerBstarPort = spec.backupBstarPort;\n } else {\n localPort = spec.backupPort;\n peerAddress = spec.primaryAddress;\n peerPort = spec.primaryPort;\n localBstarPort = spec.backupBstarPort;\n peerBstarPort = spec.primaryBstarPort;\n }\n\n CloneServerImpl cloneServer = new CloneServerImpl(context, spec.mode, peerAddress, localPort, peerPort, localBstarPort, peerBstarPort);\n cloneServer.setHeartbeatInterval(spec.heartbeatInterval);\n\n return cloneServer;\n }\n}", "public class DeviceBuilder {\n public class Spec {\n public DeviceType deviceType;\n public String frontend;\n public String backend;\n }\n \n private ManagedContext context;\n private Spec spec = new Spec();\n\n public DeviceBuilder(ManagedContext context, DeviceType deviceType) {\n this.context = context;\n spec.deviceType = deviceType;\n }\n\n public DeviceBuilder withFrontendUrl(String frontend) {\n spec.frontend = frontend;\n return this;\n }\n\n public DeviceBuilder withBackendUrl(String backend) {\n spec.backend = backend;\n return this;\n }\n\n public void start() {\n switch (spec.deviceType) {\n case STREAMER:\n startStreamer();\n break;\n case FORWARDER:\n startForwarder();\n break;\n case QUEUE:\n startQueue();\n break;\n }\n }\n\n private void startStreamer() {\n Socket frontend = context.buildSocket(SocketType.PULL)\n .bind(spec.frontend);\n\n Socket backend = context.buildSocket(SocketType.PUSH)\n .bind(spec.backend);\n\n context.forward(frontend, backend);\n }\n\n private void startForwarder() {\n Socket frontend = context.buildSocket(SocketType.XSUB)\n .bind(spec.frontend);\n\n Socket backend = context.buildSocket(SocketType.XPUB)\n .bind(spec.backend);\n\n context.forward(frontend, backend);\n }\n\n private void startQueue() {\n Socket frontend = context.buildSocket(SocketType.ROUTER)\n .bind(spec.frontend);\n\n Socket backend = context.buildSocket(SocketType.DEALER)\n .bind(spec.backend);\n\n context.forward(frontend, backend);\n }\n}", "public class PollerBuilder {\n\n private final ManagedContext context;\n private final Map<Pollable, PollListener> pollablesAndListeners = new LinkedHashMap<>();\n\n public PollerBuilder(ManagedContext context) {\n this.context = context;\n }\n\n public PollerBuilder withPollable(Pollable pollable, PollListener listener) {\n pollablesAndListeners.put(pollable, listener);\n return this;\n }\n\n /*\n * Socket Pollables.\n */\n\n public PollerBuilder withInPollable(Socket socket, PollListener listener) {\n return withPollable(context.newPollable(socket, PollerType.POLL_IN), listener);\n }\n\n public PollerBuilder withOutPollable(Socket socket, PollListener listener) {\n return withPollable(context.newPollable(socket, PollerType.POLL_OUT), listener);\n }\n\n public PollerBuilder withErrorPollable(Socket socket, PollListener listener) {\n return withPollable(context.newPollable(socket, PollerType.POLL_ERROR), listener);\n }\n\n public PollerBuilder withInOutPollable(Socket socket, PollListener listener) {\n return withPollable(context.newPollable(socket, PollerType.POLL_IN, PollerType.POLL_OUT), listener);\n }\n\n public PollerBuilder withAllPollable(Socket socket, PollListener listener) {\n return withPollable(context.newPollable(socket, PollerType.POLL_IN, PollerType.POLL_OUT, PollerType.POLL_ERROR), listener);\n }\n\n /*\n * SelectableChannel Pollables.\n */\n\n public PollerBuilder withInPollable(SelectableChannel channel, PollListener listener) {\n return withPollable(context.newPollable(channel, PollerType.POLL_IN), listener);\n }\n\n public PollerBuilder withOutPollable(SelectableChannel channel, PollListener listener) {\n return withPollable(context.newPollable(channel, PollerType.POLL_OUT), listener);\n }\n\n public PollerBuilder withErrorPollable(SelectableChannel channel, PollListener listener) {\n return withPollable(context.newPollable(channel, PollerType.POLL_ERROR), listener);\n }\n\n public PollerBuilder withInOutPollable(SelectableChannel channel, PollListener listener) {\n return withPollable(context.newPollable(channel, PollerType.POLL_IN, PollerType.POLL_OUT), listener);\n }\n\n public PollerBuilder withAllPollable(SelectableChannel channel, PollListener listener) {\n return withPollable(context.newPollable(channel, PollerType.POLL_IN, PollerType.POLL_OUT, PollerType.POLL_ERROR), listener);\n }\n\n @Deprecated\n public Poller create() {\n return build();\n }\n\n public Poller build() {\n return new PollerImpl(context, pollablesAndListeners);\n }\n}", "public class SocketBuilder implements Bindable, Connectable {\n private static final String[] EMPTY_ADDITIONAL_URLS = new String[0];\n\n protected ManagedContext context;\n protected SocketSpec socketSpec;\n\n public class SocketSpec {\n public long swapSize;\n public int linger;\n public int sendHighwatermark;\n public int receiveHighWatermark;\n public int receiveTimeout = -1;\n public int sendTimeout = -1;\n public SocketType socketType;\n public TransportType transportType;\n public byte[] identity;\n public Backgroundable backgroundable;\n }\n\n public SocketBuilder(ManagedContext context, SocketType socketType) {\n this.socketSpec = new SocketSpec();\n this.socketSpec.socketType = socketType;\n this.context = context;\n }\n\n /**\n * Returns the underlying socket type\n * \n * @return socket type\n */\n public SocketType getSocketType() {\n return socketSpec.socketType;\n }\n\n /**\n * Set the linger period for the specified socket. The linger period determines how long pending which have yet to\n * sent to a peer shall linger in memory after a socket is closed.\n * \n * @param lingerMS the linger period in millis\n * @return builder object\n * @deprecated The linger option has only integer range, use {@link SocketBuilder#withLinger(int)} instead.\n */\n @Deprecated\n public SocketBuilder withLinger(long lingerMS) {\n getSocketSpec().linger = Long.valueOf(lingerMS).intValue();\n return this;\n }\n\n /**\n * Set the linger period for the specified socket. The linger period determines how long pending which have yet to\n * sent to a peer shall linger in memory after a socket is closed.\n *\n * @param lingerMS the linger period in millis\n * @return builder object\n */\n public SocketBuilder withLinger(int lingerMS) {\n getSocketSpec().linger = lingerMS;\n return this;\n }\n\n /**\n * Returns the linger period in millis\n * \n * @return linger period\n */\n public int getLinger() {\n return getSocketSpec().linger;\n }\n\n /**\n * Set the socket identity of the specified socket. Socket identity determines if existing 0MQ infrastructure\n * (message queues, forwarding devices) shall be identified with a specific application and persist across multiple\n * runs of the application.\n * \n * If the socket has no identity, each run of the application is completely independent of other runs.\n * \n * The identity can only be between 0 and 256 bytes long exclusive.\n * \n * @param identity the identity\n * @return builder object\n */\n public SocketBuilder withIdentity(byte[] identity) {\n getSocketSpec().identity = identity;\n return this;\n }\n\n /**\n * Return the identity of the socket\n * \n * @return the identity\n */\n public byte[] getIdentity() {\n return getSocketSpec().identity;\n }\n\n /**\n * The swap option shall set the disk offload (swap) size for the specified socket. A socket which has a positive\n * value may exceed it's high water mark; in the case of outstanding messages, they shall be offloaded to storage on\n * disk.\n * \n * @param swapSize swap in bytes\n * @return builder object\n */\n public SocketBuilder withSwap(long swapSize) {\n getSocketSpec().swapSize = swapSize;\n return this;\n }\n\n /**\n * Return the swap size in bytes\n * \n * @return the swap size\n */\n public long getSwap() {\n return getSocketSpec().swapSize;\n }\n\n /**\n * Set the send high watermark.\n * \n * @param sendHWM The send high watermark\n * @return builder object\n * @deprecated This option uses integer range, use {@link SocketBuilder#withSendHighWatermark(int)} instead.\n */\n @Deprecated\n public SocketBuilder withSendHighWatermark(long sendHWM) {\n getSocketSpec().sendHighwatermark = Long.valueOf(sendHWM).intValue();\n return this;\n }\n\n /**\n * Set the send high watermark.\n *\n * @param sendHWM The send high watermark\n * @return builder object\n */\n public SocketBuilder withSendHighWatermark(int sendHWM) {\n getSocketSpec().sendHighwatermark = sendHWM;\n return this;\n }\n\n /**\n * Get the send high watermark.\n * \n * @return send high watermark\n */\n public int getSendHighWaterMark() {\n return getSocketSpec().sendHighwatermark;\n }\n\n /**\n * The RECVHWM option shall set the high water mark (HWM) for inbound messages on the specified socket. The HWM is a\n * hard limit on the maximum number of outstanding 0MQ shall queue in memory for any single peer that the specified\n * socket is communicating with.\n * \n * If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, 0MQ\n * shall take appropriate action such as blocking or dropping sent messages. Refer to the individual socket\n * descriptions in <a href=\"http://api.zeromq.org/3-2:zmq-socket\">zmq_socket(3)</a> for details on the exact action\n * taken for each socket type.\n * \n * @param receiveHWM recv high water mark\n * @return builder object\n * @deprecated This option uses integer range, use {@link #withReceiveHighWatermark(int)} instead.\n */\n @Deprecated\n public SocketBuilder withReceiveHighWatermark(long receiveHWM) {\n getSocketSpec().receiveHighWatermark = Long.valueOf(receiveHWM).intValue();\n return this;\n }\n\n /**\n * The RECVHWM option shall set the high water mark (HWM) for inbound messages on the specified socket. The HWM is a\n * hard limit on the maximum number of outstanding 0MQ shall queue in memory for any single peer that the specified\n * socket is communicating with.\n *\n * If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, 0MQ\n * shall take appropriate action such as blocking or dropping sent messages. Refer to the individual socket\n * descriptions in <a href=\"http://api.zeromq.org/3-2:zmq-socket\">zmq_socket(3)</a> for details on the exact action\n * taken for each socket type.\n *\n * @param receiveHWM recv high water mark\n * @return builder object\n */\n public SocketBuilder withReceiveHighWatermark(int receiveHWM) {\n getSocketSpec().receiveHighWatermark = receiveHWM;\n return this;\n }\n\n /**\n * Returns the receive high water mark.\n * \n * @return receive high water mark\n */\n public int getReceiveHighWaterMark() {\n return getSocketSpec().receiveHighWatermark;\n }\n\n public SocketSpec getSocketSpec() {\n return socketSpec;\n }\n\n public SocketBuilder withReceiveTimeout(int receiveTimeout) {\n getSocketSpec().receiveTimeout = receiveTimeout;\n return this;\n }\n\n public SocketBuilder withSendTimeout(int sendTimeout) {\n getSocketSpec().sendTimeout = sendTimeout;\n return this;\n }\n\n public SocketBuilder withBackgroundable(Backgroundable backgroundable) {\n getSocketSpec().backgroundable = backgroundable;\n return this;\n }\n\n //todo should these be here & removed from the subclasses? They appear to all be the same implementations.\n /**\n * {@inheritDoc}\n */\n @Override\n public Socket connect(String url) {\n return connect(url, EMPTY_ADDITIONAL_URLS);\n }\n\n @Override\n public Socket connect(String url, String... additionalUrls) {\n ZMQ.Socket socket = createConnectableSocketWithStandardSettings();\n connect(socket, url, additionalUrls);\n return newManagedSocket(socket);\n }\n\n protected void connect(ZMQ.Socket socket, String url, String[] additionalUrls) {\n socket.connect(url);\n for (String s : additionalUrls) {\n socket.connect(s);\n }\n }\n\n protected ZMQ.Socket createConnectableSocketWithStandardSettings() {\n ZMQ.Context zmqContext = context.getZMQContext();\n ZMQ.Socket socket;\n try {\n socket = zmqContext.socket(this.getSocketType().getType());\n socket.setLinger(getLinger());\n socket.setSndHWM(getSendHighWaterMark());\n socket.setRcvHWM(getReceiveHighWaterMark());\n socket.setReceiveTimeOut(getSocketSpec().receiveTimeout);\n socket.setSendTimeOut(getSocketSpec().sendTimeout);\n if (this.getIdentity() != null && this.getIdentity().length > 0) {\n socket.setIdentity(this.getIdentity());\n }\n } catch (ZMQException ex) {\n throw ZMQExceptions.wrap(ex);\n }\n return socket;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Socket bind(String url) {\n return bind(url, EMPTY_ADDITIONAL_URLS);\n }\n\n @Override\n public Socket bind(String url, String... additionalUrls) {\n ZMQ.Socket socket = createBindableSocketWithStandardSettings();\n bind(socket, url, additionalUrls);\n return newManagedSocket(socket);\n }\n\n protected void bind(ZMQ.Socket socket, String url, String[] additionalUrls) {\n socket.bind(url);\n for (String s : additionalUrls) {\n socket.bind(s);\n }\n }\n\n protected ZMQ.Socket createBindableSocketWithStandardSettings() {\n ZMQ.Context zmqContext = context.getZMQContext();\n ZMQ.Socket socket;\n try {\n socket = zmqContext.socket(this.getSocketType().getType());\n socket.setLinger(this.getLinger());\n socket.setRcvHWM(this.getReceiveHighWaterMark());\n socket.setSndHWM(this.getSendHighWaterMark());\n socket.setReceiveTimeOut(getSocketSpec().receiveTimeout);\n socket.setSendTimeOut(getSocketSpec().sendTimeout);\n if (this.getIdentity() != null && this.getIdentity().length > 0) {\n socket.setIdentity(this.getIdentity());\n }\n } catch (ZMQException ex) {\n throw ZMQExceptions.wrap(ex);\n }\n return socket;\n }\n\n protected Socket newManagedSocket(ZMQ.Socket socket) {\n ManagedSocket managedSocket = new ManagedSocket(context, socket);\n if (getSocketSpec().backgroundable != null) {\n context.fork(managedSocket, getSocketSpec().backgroundable);\n }\n return managedSocket;\n }\n\n /**\n * Coerce the SocketBuilder to be Subscribable.\n * \n * @return This builder object as a Subscribable\n */\n public Subscribable asSubscribable() {\n return (Subscribable) this;\n }\n\n /**\n * Coerce the SocketBuilder to be Routable.\n * \n * @return This builder object as a Routable\n */\n public Routable asRoutable() {\n return (RouterSocketBuilder) this;\n }\n}" ]
import org.zeromq.jzmq.beacon.BeaconReactorBuilder; import org.zeromq.jzmq.bstar.BinaryStarReactorBuilder; import org.zeromq.jzmq.bstar.BinaryStarSocketBuilder; import org.zeromq.jzmq.clone.CloneClientBuilder; import org.zeromq.jzmq.clone.CloneServerBuilder; import org.zeromq.jzmq.device.DeviceBuilder; import org.zeromq.jzmq.poll.PollerBuilder; import org.zeromq.jzmq.reactor.ReactorBuilder; import org.zeromq.jzmq.sockets.SocketBuilder; import java.io.Closeable; import java.nio.channels.SelectableChannel;
package org.zeromq.api; /** * A ØMQ context is thread safe and may be shared among as many application threads as necessary, without any additional * locking required on the part of the caller. */ public interface Context extends Closeable { /** * Create a ØMQ Socket of type SocketType * * @param type socket type * @return A builder for constructing and connecting ØMQ Sockets */ SocketBuilder buildSocket(SocketType type); /** * @return The ØMQ version, in a pretty-printed String. */ String getVersionString(); /** * @return The ØMQ version, in integer form. */ int getFullVersion(); /** * Create a new Poller, which will allow callback-based polling of Sockets. * * @return A builder for constructing ØMQ Pollers * @see Pollable * @see PollerType */ PollerBuilder buildPoller(); /** * Create a new Reactor, which will allow event-driven and timer-based * polling of Sockets. * * @return A builder for constructing a Reactor */ ReactorBuilder buildReactor(); /** * Create a new BinaryStarReactor, which will create one half of an HA-pair * with event-driven polling of a client Socket. * * @return A builder for constructing a BinaryStarReactor */ BinaryStarReactorBuilder buildBinaryStarReactor(); /** * Create a ØMQ Socket, backed by a background agent that is connecting * to a BinaryStarReactor HA-pair. * * @return A builder for constructing connecting a BinaryStarReactor client Socket */ BinaryStarSocketBuilder buildBinaryStarSocket(); /** * Create a new CloneServer, which will create one half of an HA-pair * for distributing key/value data to clients. * * @return A builder for constructing a CloneServer */ CloneServerBuilder buildCloneServer(); /** * Create a new CloneClient, connected to an HA-pair, for publishing key/value data * to anonymous peers. * * @return A builder for constructing a CloneClient */
CloneClientBuilder buildCloneClient();
0
karthicks/gremlin-ogm
gremlin-objects/src/main/java/org/apache/tinkerpop/gremlin/object/reflect/Label.java
[ "@Data\n@ToString\n@NoArgsConstructor\n@Accessors(fluent = true, chain = true)\n@EqualsAndHashCode(callSuper = true, of = {})\npublic abstract class Edge extends Element {\n\n /**\n * The object representation of the \"from\" vertex.\n */\n @Hidden\n private Vertex from;\n /**\n * The object representation of the \"to\" vertex.\n */\n @Hidden\n private Vertex to;\n\n /**\n * The id of the \"from\" vertex.\n */\n @Hidden\n private Object fromId;\n /**\n * The id of the \"to\" vertex.\n */\n @Hidden\n private Object toId;\n\n @Hidden\n private List<Connection> cachedConnections;\n\n protected abstract List<Connection> connections();\n\n\n /**\n * Return the underlying gremlin edge.\n */\n public org.apache.tinkerpop.gremlin.structure.Edge delegate() {\n return (org.apache.tinkerpop.gremlin.structure.Edge) delegate;\n }\n\n\n /**\n * Return the \"from\" vertex as the given type.\n */\n public <V extends Vertex> V fromAs(Class<V> vertexType) {\n return Parser.as(from.delegate(), vertexType);\n }\n\n /**\n * Return the \"to\" vertex as the given type.\n */\n public <V extends Vertex> V toAs(Class<V> vertexType) {\n return Parser.as(to.delegate(), vertexType);\n }\n\n /**\n * Does the edge have a connection between the given vertices?\n */\n @SuppressWarnings(\"PMD.CloseResource\")\n public boolean connects(Vertex from, Vertex to) {\n return connects(from.getClass(), to.getClass());\n }\n\n /**\n * Does the edge have a connection between the given vertex types?\n */\n @SuppressWarnings(\"PMD.CloseResource\")\n public boolean connects(Class<? extends Vertex> fromClass, Class<? extends Vertex> toClass) {\n Connection connection = Connection.of(fromClass, toClass);\n if (cachedConnections == null) {\n cachedConnections = connections();\n }\n return cachedConnections.contains(connection);\n }\n\n /**\n * A function denoting a {@code GraphTraversal} that starts at edges, and ends at vertices.\n */\n public interface ToVertex extends SubTraversal<\n org.apache.tinkerpop.gremlin.structure.Edge,\n org.apache.tinkerpop.gremlin.structure.Vertex> {\n\n }\n\n public static class Exceptions extends Element.Exceptions {\n\n private Exceptions() {}\n\n public static IllegalStateException missingEdgeVertex(\n Direction direction, Edge edge, org.apache.tinkerpop.gremlin.structure.Vertex vertex) {\n return missingEdgeVertex(direction, edge, vertex.toString());\n }\n\n public static IllegalStateException missingEdgeVertex(\n Direction direction, Edge edge, AnyTraversal anyTraversal) {\n return missingEdgeVertex(direction, edge, anyTraversal.toString());\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static IllegalStateException missingEdgeVertex(\n Direction direction, Edge edge, SubTraversal... subTraversals) {\n return missingEdgeVertex(direction, edge, Arrays.asList(subTraversals).toString());\n }\n\n public static IllegalStateException missingEdgeVertex(Direction direction, Edge edge,\n String vertexString) {\n return new IllegalStateException(\n String.format(\"%s vertex (%s) doesn't exist for edge %s\",\n direction.equals(Direction.OUT) ? \"Outgoing\" : \"Incoming\", vertexString,\n edge));\n }\n\n public static IllegalStateException invalidEdgeConnection(Edge edge) {\n return new IllegalStateException(\n String.format(\"Edge connects an invalid pair of vertices\", edge));\n }\n }\n}", "@Slf4j\n@ToString\n@NoArgsConstructor\n@SuppressWarnings({\"rawtypes\", \"PMD.TooManyStaticImports\"})\npublic class Element implements Comparable<Element> {\n\n public static final long serialVersionUID = 1L;\n public final ElementTo.Element withLabel = traversal -> traversal.hasLabel(label());\n @Setter\n protected org.apache.tinkerpop.gremlin.structure.Element delegate;\n @Getter\n @Setter\n @Alias(key = \"id\")\n private Object userSuppliedId;\n public final ElementTo.Element withId = traversal -> traversal.hasId(id());\n\n public Element(Element other) {\n this.setUserSuppliedId(other.id());\n }\n\n /**\n * Compose the given {@link SubTraversal} in the given order.\n */\n @SuppressWarnings(\"unchecked\")\n protected static <E> ElementTo<E> compose(SubTraversal<?, ?>... subTraversals) {\n return traversal -> {\n for (SubTraversal subTraversal : subTraversals) {\n traversal = (GraphTraversal<\n org.apache.tinkerpop.gremlin.structure.Element,\n org.apache.tinkerpop.gremlin.structure.Element>) subTraversal.apply(traversal);\n }\n return (GraphTraversal) traversal;\n };\n }\n\n /**\n * This is final since you can override the label through the {@link Alias} annotation\n */\n public final String label() {\n return Label.of(getClass());\n }\n\n /**\n * If the graph supports user supplied ids, then we will derive the id based on the primary and\n * ordering key fields of the element, ergo this is final.\n */\n @SuppressWarnings({\"PMD.ShortMethodName\"})\n public final Object id() {\n if (userSuppliedId != null) {\n return userSuppliedId;\n }\n if (delegate != null) {\n return delegate.id();\n }\n return null;\n }\n\n /**\n * Generate a {@link SubTraversal} that matches the value of the given key in this element.\n */\n @SneakyThrows\n @SuppressWarnings({\"PMD.ShortMethodName\"})\n public ElementTo.Element s(String key) {\n Field propertyField = field(getClass(), key);\n return Has.of(label(), propertyKey(propertyField), propertyValue(propertyField, this));\n }\n\n /**\n * @throws {@link Exceptions#requiredKeysMissing(Class, String)} if a key is missing\n */\n public void validate() {\n Keys.id(this);\n }\n\n /**\n * Changes the maximum number of elements for which reflection metadata will be cached. If the\n * limit is hit, the least recently used element is kicked out.\n */\n public static void cache(long numberOfElements) {\n elementCacheSize = numberOfElements;\n }\n\n /**\n * Classes that extend the {@link Element} should use the {@code @EqualsAndHashCode(of={},\n * callSuper=true)} annotation, so that we can ignore any fields marked as {@code Hidden}.\n *\n * By including {@code of={}} in that annotation, the derived class essentially excludes all of\n * it's fields, so as to avoid double-checking each field. If {@code of={}} is not present, and if\n * the derived class contains any instance-specific {@link SubTraversal}s or {@code\n * AnyTraversal}s, then they will need to either be marked as {@code transient} or start with a\n * {@code $} symbol, so that the {@code lombok} processor can ignore those lambda objects.\n */\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (!(other instanceof Element)) {\n return false;\n }\n Element that = (Element) other;\n if (this.id() != null &&\n that.id() != null &&\n this.id().getClass().equals(that.id().getClass()) &&\n !this.id().equals(that.id())) {\n return false;\n }\n return compareTo(that) == 0;\n }\n\n @Override\n @SneakyThrows\n public int hashCode() {\n List<Field> primaryKeyFields = primaryKeyFields(getClass());\n int hashCode = 0;\n for (Field primaryKeyField : primaryKeyFields) {\n Object value = primaryKeyField.get(this);\n if (value == null) {\n continue;\n }\n hashCode += value.hashCode();\n }\n return hashCode;\n }\n\n /**\n * Compare against the given element, using the values of the fields, in {@link\n * org.apache.tinkerpop.gremlin.object.reflect.Fields#BY_KEYS} order.\n */\n @Override\n public int compareTo(Element that) {\n return valuesOf(fields(getClass())).compare(this, that);\n }\n\n /**\n * Check if this element exists in the given collection. If it defines {@code PrimaryKey}s or\n * {@code OrderingKey}s, then those are compared. If not, then all fields are considered.\n */\n public boolean existsIn(Collection<? extends Element> elements) {\n final List<Field> fields = keyFields(getClass());\n if (fields.isEmpty()) {\n fields.addAll(fields(getClass()));\n }\n return elements.stream()\n .anyMatch(element -> valuesOf(fields).compare(element, this) == 0);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static final Comparator<Element> valuesOf(List<Field> fields) {\n return (left, right) -> {\n if (!left.getClass().equals(right.getClass())) {\n return -1;\n }\n for (Field field : fields) {\n try {\n Object thisValue = field.get(left);\n Object thatValue = field.get(right);\n\n if (thisValue == null) {\n if (thatValue != null) {\n return -1;\n }\n } else {\n if (thatValue == null) {\n return 1;\n }\n int difference;\n if (thisValue instanceof Comparable) {\n difference = ((Comparable) thisValue).compareTo(thatValue);\n } else {\n difference = thisValue.hashCode() - thatValue.hashCode();\n }\n if (difference != 0) {\n return difference;\n }\n }\n } catch (IllegalAccessException iae) {\n return -1;\n }\n }\n return 0;\n };\n }\n\n public static class Exceptions {\n\n protected Exceptions() {\n // The protected access modifier allows for sub-classing.\n }\n\n public static IllegalStateException elementAlreadyExists(Element element) {\n return new IllegalStateException(\n String.format(\"The element '%s' with the id '%s' already exists\",\n element.label(), Properties.id(element)));\n }\n\n public static IllegalStateException removingDetachedElement(Element element) {\n return new IllegalStateException(\n String.format(\"Cannot remove detached element: %s\", element));\n }\n\n public static IllegalArgumentException requiredKeysMissing(Class<? extends Element> elementType,\n String fieldName) {\n return new IllegalArgumentException(\n String.format(\"The mandatory key '%s' for element '%s' is null\",\n fieldName, name(elementType)));\n }\n\n public static IllegalArgumentException invalidAnnotationType(Class<?> type) {\n return new IllegalArgumentException(\n String.format(\"The annotation type '%s' is not supported\", name(type)));\n }\n\n public static InstantiationException invalidCollectionType(Class<?> type) {\n return new InstantiationException(\n String.format(\"The collection type '%s' is not supported\", name(type)));\n }\n\n public static InstantiationException unknownElementType(Class<?> type) {\n return new InstantiationException(\n String.format(\"The collection type '%s' is not supported\", name(type)));\n }\n\n public static ClassCastException invalidTimeType(Class targetClass, Object timeValue) {\n return new ClassCastException(\n String.format(\"The time value '%s' is not of the desired '%s' type\", targetClass,\n timeValue));\n }\n }\n}", "@SuppressWarnings({\"PMD.ShortMethodName\"})\npublic static boolean is(Class<?> type, Object that) {\n return that != null && is(type, that.getClass());\n}", "public static String name(Class<?> type) {\n return type.getSimpleName();\n}", "public static String alias(AnnotatedElement element, Function<Alias, String> property) {\n Alias alias = element.getAnnotation(Alias.class);\n if (alias == null) {\n return null;\n }\n String value = property.apply(alias);\n return isNotEmpty(value) ? value : null;\n}" ]
import org.apache.commons.lang3.text.WordUtils; import org.apache.tinkerpop.gremlin.object.model.Alias; import org.apache.tinkerpop.gremlin.object.structure.Edge; import org.apache.tinkerpop.gremlin.object.structure.Element; import static org.apache.tinkerpop.gremlin.object.reflect.Classes.is; import static org.apache.tinkerpop.gremlin.object.reflect.Classes.name; import static org.apache.tinkerpop.gremlin.object.reflect.Fields.alias;
/* * 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 org.apache.tinkerpop.gremlin.object.reflect; /** * The label of a vertex (or edge) object can be obtained through the {@link Label#of} methods. * * <p> * By default, the label of a vertex is the same as it's object's simple class name, and that of an * edge is the same, except it's uncapitalized. If you wish to override this default naming * convention, you may annotate the class with a {@link Alias#label()} value. * * @author Karthick Sankarachary (http://github.com/karthicks) */ public final class Label { private Label() {} @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } @SuppressWarnings("PMD.ShortMethodName") public static String of(Class<? extends Element> elementType) { String label = alias(elementType, Alias::label); if (label == null) {
label = name(elementType);
3
5GSD/AIMSICDL
AIMSICD/src/main/java/zz/aimsicd/lite/ui/fragments/CellInfoFragment.java
[ "public class BaseInflaterAdapter<T> extends BaseAdapter {\n\n private final List<T> m_items = new ArrayList<>();\n\n private IAdapterViewInflater<T> m_viewInflater;\n\n public BaseInflaterAdapter(IAdapterViewInflater<T> viewInflater) {\n m_viewInflater = viewInflater;\n }\n\n public BaseInflaterAdapter(List<T> items, IAdapterViewInflater<T> viewInflater) {\n m_items.addAll(items);\n m_viewInflater = viewInflater;\n }\n\n public void setViewInflater(IAdapterViewInflater<T> viewInflater, boolean notifyChange) {\n m_viewInflater = viewInflater;\n\n if (notifyChange) {\n notifyDataSetChanged();\n }\n }\n\n public void addItem(T item, boolean notifyChange) {\n m_items.add(item);\n\n if (notifyChange) {\n notifyDataSetChanged();\n }\n }\n\n public void addItems(List<T> items, boolean notifyChange) {\n m_items.addAll(items);\n\n if (notifyChange) {\n notifyDataSetChanged();\n }\n }\n\n public void clear(boolean notifyChange) {\n m_items.clear();\n\n if (notifyChange) {\n notifyDataSetChanged();\n }\n }\n\n @Override\n public int getCount() {\n return m_items.size();\n }\n\n @Override\n public Object getItem(int pos) {\n return getTItem(pos);\n }\n\n public T getTItem(int pos) {\n return m_items.get(pos);\n }\n\n @Override\n public long getItemId(int pos) {\n return pos;\n }\n\n @Override\n public View getView(int pos, View convertView, ViewGroup parent) {\n return m_viewInflater != null ? m_viewInflater.inflate(this, pos, convertView, parent)\n : null;\n }\n}", "public class CardItemData {\n // OLD (in old DB tables)\n private final String mCellID;\n private final String mLac;\n private final String mMcc;\n private final String mMnc;\n private final String mNet;\n private final String mSignal;\n private final String mAvgSigStr;\n private final String mSamples;\n private final String mLat;\n private final String mLng;\n private final String mCountry;\n private final String mPsc;\n private final String mTimestamp;\n private final String mRecordId;\n\n // NEW (in new DB tables)\n/*\n private final String mtime;\n private final String mLAC;\n private final String mCID;\n private final String mPSC;\n private final String mgpsd_lat;\n private final String mgpsd_lon;\n private final String mgpsd_accu;\n private final String mDF_id;\n private final String mDF_description;\n*/\n\n\n // OLD items in old DB table structure\n\n public CardItemData(Cell cell, String recordId) {\n\n if (cell.getCID() != Integer.MAX_VALUE && cell.getCID() != -1) {\n mCellID = \"CID: \" + cell.getCID() + \" (0x\" + Integer.toHexString(cell.getCID()) + \")\";\n } else {\n mCellID = \"N/A\";\n }\n\n if (cell.getLAC() != Integer.MAX_VALUE && cell.getLAC() != -1) {\n mLac = \"LAC: \" + cell.getLAC();\n } else {\n mLac = \"N/A\";\n }\n\n if (cell.getMCC() != Integer.MAX_VALUE && cell.getMCC() != 0) {\n mMcc = \"MCC: \" + cell.getMCC();\n } else {\n mMcc = \"N/A\";\n }\n\n if (cell.getMNC() != Integer.MAX_VALUE && cell.getMNC() != 0) {\n mMnc = \"MNC: \" + cell.getMNC();\n } else {\n mMnc = \"N/A\";\n }\n\n if (cell.getNetType() != Integer.MAX_VALUE && cell.getNetType() != -1) {\n mNet = \"Type: \" + cell.getNetType() + \" - \" + cell.getRAT();\n } else {\n mNet = \"N/A\";\n }\n\n if (cell.getPSC() != Integer.MAX_VALUE && cell.getPSC() != -1) {\n mPsc = \"PSC: \" + cell.getPSC();\n } else {\n mPsc = \"N/A\";\n }\n\n if (cell.getRssi() != Integer.MAX_VALUE && cell.getRssi() != -1) {\n mSignal = \"RSSI: \" + cell.getRssi();\n } else if (cell.getDBM() != Integer.MAX_VALUE && cell.getDBM() != -1) {\n mSignal = \"dBm: \" + cell.getDBM();\n } else {\n mSignal = \"N/A\";\n }\n // NEW (in new DB tables)\n\n\n // end New\n\n mLat = \"N/A\";\n mLng = \"N/A\";\n mAvgSigStr = \"N/A\";\n mSamples = \"N/A\";\n mCountry = \"N/A\";\n mTimestamp = \"N/A\";\n mRecordId = recordId;\n\n // NEW (in new DB tables)\n\n // end New\n\n }\n\n public CardItemData(String cellID, String lac, String mcc, String mnc, String lat, String lng,\n String avgSigStr, String samples, String recordId) {\n mCellID = cellID;\n mLac = lac;\n mMcc = mcc;\n mMnc = mnc;\n mNet = \"Network Type: N/A\";\n mLat = lat;\n mLng = lng;\n mSignal = \"Signal: N/A\";\n mAvgSigStr = avgSigStr;\n mSamples = samples;\n mPsc = \"PSC: N/A\";\n mCountry = \"Country: N/A\";\n mTimestamp = \"Timestamp: N/A\";\n mRecordId = recordId;\n }\n\n public CardItemData(String cellID, String psc, String mcc, String mnc, String signal,\n String recordId) {\n mCellID = cellID;\n mLac = \"LAC: N/A\";\n mMcc = mcc;\n mMnc = mnc;\n mLat = \"Latitude: N/A\";\n mLng = \"Longitude: N/A\";\n mNet = \"Network Type: N/A\";\n mAvgSigStr = \"Avg Signal: N/A\";\n mSamples = \"Samples: N/A\";\n mSignal = signal;\n mPsc = psc;\n mCountry = \"Country: N/A\";\n mTimestamp = \"Timestamp: N/A\";\n mRecordId = recordId;\n }\n\n public CardItemData(String cellID, String lac, String mcc, String mnc, String signal,\n String psc, String timestamp, String recordId) {\n mCellID = cellID;\n mLac = lac;\n mMcc = mcc;\n mMnc = mnc;\n mLat = \"Latitude: N/A\";\n mLng = \"Longitude: N/A\";\n mNet = \"Network Type: N/A\";\n mSignal = signal;\n mPsc = psc;\n mAvgSigStr = \"Avg Signal: N/A\";\n mSamples = \"Samples: N/A\";\n mTimestamp = timestamp;\n mCountry = \"Country: N/A\";\n mRecordId = recordId;\n }\n\n public CardItemData(int type, String cellID, String lac, String mcc, String mnc, String signal,\n String timestamp, String recordId) {\n mCellID = cellID;\n mLac = lac;\n mMcc = mcc;\n mMnc = mnc;\n mLat = \"Latitude: N/A\";\n mLng = \"Longitude: N/A\";\n mNet = \"Network Type: N/A\";\n mSignal = signal;\n mAvgSigStr = \"Avg Signal: N/A\";\n mSamples = \"Samples: N/A\";\n mTimestamp = timestamp;\n mPsc = \"PSC: N/A\";\n mCountry = \"Country: N/A\";\n mRecordId = recordId;\n }\n\n public CardItemData(String cellID, String lac, String net, String lat, String lng,\n String signal, String recordId) {\n mCellID = cellID;\n mLac = lac;\n mNet = net;\n mMcc = \"MCC: N/A\";\n mMnc = \"MNC: N/A\";\n mLat = lat;\n mLng = lng;\n mSignal = signal;\n mAvgSigStr = \"Avg Signal: N/A\";\n mSamples = \"Samples: N/A\";\n mPsc = \"PSC: N/A\";\n mCountry = \"Country: N/A\";\n mTimestamp = \"Timestamp: N/A\";\n mRecordId = recordId;\n }\n\n public CardItemData(String country, String mcc, String lat, String lng, String recordId) {\n mCellID = \"CellID: N/A\";\n mLac = \"LAC: N/A\";\n mCountry = country;\n mMcc = mcc;\n mMnc = \"MNC: N/A\";\n mNet = \"Network Type: N/A\";\n mSignal = \"Signal: N/A\";\n mLat = lat;\n mLng = lng;\n mAvgSigStr = \"Avg Signal: N/A\";\n mSamples = \"Samples: N/A\";\n mPsc = \"PSC: N/A\";\n mTimestamp = \"Timestamp: N/A\";\n mRecordId = recordId;\n }\n\n public String getCellID() {\n return mCellID;\n }\n\n public String getLac() {\n return mLac;\n }\n\n public String getMcc() {\n return mMcc;\n }\n\n public String getMnc() {\n return mMnc;\n }\n\n public String getNet() {\n return mNet;\n }\n\n public String getSignal() {\n return mSignal;\n }\n\n public String getAvgSigStr() {\n return mAvgSigStr;\n }\n\n public String getSamples() {\n return mSamples;\n }\n\n public String getLat() {\n return mLat;\n }\n\n public String getLng() {\n return mLng;\n }\n\n public String getCountry() {\n return mCountry;\n }\n\n public String getRecordId() {\n return mRecordId;\n }\n\n public String getPsc() {\n return mPsc;\n }\n\n public String getTimestamp() {\n return mTimestamp;\n }\n\n // NEW (in new DB tables)\n // EventLog\n\n //public String getAccu() {\n // return mAccu;\n //}\n\n}", "public class CellCardInflater implements IAdapterViewInflater<CardItemData> {\n\n @Override\n public View inflate(final BaseInflaterAdapter<CardItemData> adapter,\n final int pos, View convertView, ViewGroup parent) {\n ViewHolder holder;\n\n if (convertView == null) {\n LayoutInflater inflater = LayoutInflater.from(parent.getContext());\n convertView = inflater.inflate(R.layout.cell_items, parent, false);\n holder = new ViewHolder(convertView);\n } else {\n holder = (ViewHolder) convertView.getTag();\n }\n\n final CardItemData item = adapter.getTItem(pos);\n holder.updateDisplay(item);\n\n return convertView;\n }\n\n private class ViewHolder {\n\n // OLD (in old DB tables)\n private final View mRootView;\n private final TextView mCellID;\n private final TextView mPsc;\n private final TextView mLac;\n private final TextView mMcc;\n private final TextView mMnc;\n private final TextView mNet;\n private final TextView mLat;\n private final TextView mLng;\n private final TextView mSignal;\n private final TextView mRecordId;\n\n /*// NEW (in new DB tables)\n private final View mRootView;\n private final TextView mtime;\n private final TextView mLAC;\n private final TextView mCID;\n private final TextView mPSC;\n private final TextView mgpsd_lat;\n private final TextView mgpsd_lon;\n private final TextView mgpsd_accu;\n private final TextView mDF_id;\n private final TextView mDF_description;\n */\n\n // OLD (in old DB tables)\n ViewHolder(View rootView) {\n mRootView = rootView;\n mCellID = (TextView) mRootView.findViewById(R.id.cellID);\n mCellID.setVisibility(View.GONE);\n mPsc = (TextView) mRootView.findViewById(R.id.psc);\n mPsc.setVisibility(View.GONE);\n mLac = (TextView) mRootView.findViewById(R.id.lac);\n mLac.setVisibility(View.GONE);\n mMcc = (TextView) mRootView.findViewById(R.id.mcc);\n mMcc.setVisibility(View.GONE);\n mMnc = (TextView) mRootView.findViewById(R.id.mnc);\n mMnc.setVisibility(View.GONE);\n mNet = (TextView) mRootView.findViewById(R.id.net);\n mNet.setVisibility(View.GONE);\n mLat = (TextView) mRootView.findViewById(R.id.lat);\n mLat.setVisibility(View.GONE);\n mLng = (TextView) mRootView.findViewById(R.id.lng);\n mLng.setVisibility(View.GONE);\n mSignal = (TextView) mRootView.findViewById(R.id.signal);\n mSignal.setVisibility(View.GONE);\n mRecordId = (TextView) mRootView.findViewById(R.id.record_id);\n\n // NEW (in new DB tables)\n\n\n rootView.setTag(this);\n }\n\n public void updateDisplay(CardItemData item) {\n if (!item.getCellID().contains(\"N/A\")) {\n mCellID.setVisibility(View.VISIBLE);\n mCellID.setText(item.getCellID());\n }\n\n if (!item.getPsc().contains(\"N/A\")) {\n mPsc.setVisibility(View.VISIBLE);\n mPsc.setText(item.getPsc());\n }\n\n if (!item.getLac().contains(\"N/A\")) {\n mLac.setVisibility(View.VISIBLE);\n mLac.setText(item.getLac());\n }\n\n if (!item.getNet().contains(\"N/A\")) {\n mNet.setVisibility(View.VISIBLE);\n mNet.setText(item.getNet());\n }\n\n if (!item.getLat().contains(\"N/A\")) {\n mLat.setVisibility(View.VISIBLE);\n mLat.setText(item.getLat());\n }\n\n if (!item.getLng().contains(\"N/A\")) {\n mLng.setVisibility(View.VISIBLE);\n mLng.setText(item.getLng());\n }\n\n if (!item.getMcc().contains(\"N/A\")) {\n mMcc.setVisibility(View.VISIBLE);\n mMcc.setText(item.getMcc());\n }\n\n if (!item.getMnc().contains(\"N/A\")) {\n mMnc.setVisibility(View.VISIBLE);\n mMnc.setText(item.getMnc());\n }\n\n if (!item.getSignal().contains(\"N/A\")) {\n mSignal.setVisibility(View.VISIBLE);\n mSignal.setText(item.getSignal());\n }\n\n mRecordId.setText(item.getRecordId());\n }\n }\n}", "public class RilExecutor {\n\n public static final String TAG = \"AICDL\";\n public static final String mTAG = \"RilExecutor\";\n\n public boolean mMultiRilCompatible;\n\n /*\n * Samsung MultiRil Implementation\n */\n\n // E:V:A 2014-12-18\n // This function as implemented here , only works on Samsung Galaxy S2 GT-I9100\n // and possibly on the S3 GT-I9300 and the P7100. It currently depend on:\n // 1. baseband is an Intel XMM modem\n // 2. gsm.version.ril-impl = \"Samsung RIL (IPC) v2.0\"\n // However, it should be possible to extend this to the latest devices\n // and those also using Qualcomm basebands\n //\n // Q: How does it work?\n // A: It uses the internal BP ServiceMode function on the BP and forwards the info\n // to the AP ServiceMode wrapper App. that is known by various other names, such as:\n //\n // FactoryTest, FactoryTest_FB, serviceModeApp_FB, ServiceModeApp_RIL,\n // SecFactoryPhoneTest, Factory_RIL, ServiceMode etc etc.\n //\n // The protocol to make these forwarded messages are through IPC messages via\n // the RIL QMI interface on /dev/socket/rild | ril-debug ...or something like that.\n\n private static final int ID_REQUEST_START_SERVICE_MODE_COMMAND = 1;\n private static final int ID_REQUEST_FINISH_SERVICE_MODE_COMMAND = 2;\n private static final int ID_REQUEST_PRESS_A_KEY = 3;\n private static final int ID_REQUEST_REFRESH = 4;\n private static final int ID_RESPONSE = 101;\n private static final int ID_RESPONSE_FINISH_SERVICE_MODE_COMMAND = 102;\n private static final int ID_RESPONSE_PRESS_A_KEY = 103;\n private static final int REQUEST_TIMEOUT = 10000; // ms\n\n private final ConditionVariable mRequestCondvar = new ConditionVariable();\n private final Object mLastResponseLock = new Object();\n private volatile List<String> mLastResponse;\n private DetectResult mRilExecutorDetectResult;\n private OemCommands mOemCommands;\n private OemRilExecutor mRequestExecutor;\n private HandlerThread mHandlerThread;\n private Handler mHandler;\n\n public RilExecutor(Context context) {\n mOemCommands = OemCommands.getInstance(context);\n mRequestExecutor = new SamsungMulticlientRilExecutor();\n mRilExecutorDetectResult = mRequestExecutor.detect();\n if (!mRilExecutorDetectResult.available) {\n mMultiRilCompatible = false;\n Log.e(TAG, mTAG + \"Samsung Multiclient RIL not available: \" + mRilExecutorDetectResult.error);\n mRequestExecutor = null;\n } else {\n mRequestExecutor.start();\n mMultiRilCompatible = true;\n // Samsung MultiRil Initialization\n mHandlerThread = new HandlerThread(\"ServiceModeSeqHandler\");\n mHandlerThread.start();\n\n Looper l = mHandlerThread.getLooper();\n if (l != null) {\n mHandler = new Handler(l, new MyHandler());\n }\n }\n\n }\n\n public void stop() {\n //Samsung MultiRil Cleanup\n if (mRequestExecutor != null) {\n mRequestExecutor.stop();\n mRequestExecutor = null;\n mHandler = null;\n mHandlerThread.quit();\n mHandlerThread = null;\n }\n }\n\n\n /**\n * Check the status of the RIL Executor\n *\n * @return DetectResult providing access status of the RIL Executor\n */\n public DetectResult getRilExecutorStatus() {\n return mRilExecutorDetectResult;\n }\n\n\n /**\n * Service Mode Command Helper to call with Timeout value\n *\n * @return executeServiceModeCommand adding REQUEST_TIMEOUT\n */\n private List<String> executeServiceModeCommand(int type, int subtype,\n java.util.Collection<KeyStep> keySeqence) {\n return executeServiceModeCommand(type, subtype, keySeqence, REQUEST_TIMEOUT);\n }\n\n /**\n * Service Mode Command Helper to call with Timeout value\n *\n * @return executeServiceModeCommand adding REQUEST_TIMEOUT\n */\n private synchronized List<String> executeServiceModeCommand(int type, int subtype,\n java.util.Collection<KeyStep> keySeqence, int timeout) {\n if (mRequestExecutor == null) {\n return Collections.emptyList();\n }\n\n mRequestCondvar.close();\n mHandler.obtainMessage(ID_REQUEST_START_SERVICE_MODE_COMMAND,\n type,\n subtype,\n keySeqence).sendToTarget();\n if (!mRequestCondvar.block(timeout)) {\n Log.e(TAG, mTAG + \"request timeout\");\n return Collections.emptyList();\n } else {\n synchronized (mLastResponseLock) {\n return mLastResponse;\n }\n }\n }\n\n /**\n * Executes and receives the Ciphering Information request using\n * the RIL Executor\n *\n * @return String list response from RIL Executor\n */\n public List<String> getCipheringInfo() {\n return executeServiceModeCommand(\n OemCommands.OEM_SM_TYPE_TEST_MANUAL,\n OemCommands.OEM_SM_TYPE_SUB_CIPHERING_PROTECTION_ENTER,\n null\n );\n }\n\n /**\n * Executes and receives the Neighbouring Cell request using\n * the RIL Executor\n *\n * @return String list response from RIL Executor\n */\n public List<String> getNeighbours() {\n KeyStep getNeighboursKeySeq[] = new KeyStep[]{\n new KeyStep('\\0', false),\n new KeyStep('1', false), // [1] DEBUG SCREEN\n new KeyStep('4', true), // [4] NEIGHBOUR CELL\n };\n\n return executeServiceModeCommand(\n OemCommands.OEM_SM_TYPE_TEST_MANUAL,\n OemCommands.OEM_SM_TYPE_SUB_ENTER,\n Arrays.asList(getNeighboursKeySeq)\n );\n\n }\n\n private static class KeyStep {\n\n public final char keychar;\n public final boolean captureResponse;\n KeyStep(char keychar, boolean captureResponse) {\n this.keychar = keychar;\n this.captureResponse = captureResponse;\n }\n\n public static final KeyStep KEY_START_SERVICE_MODE = new KeyStep('\\0', true);\n }\n\n private class MyHandler implements Handler.Callback {\n\n private int mCurrentType;\n private int mCurrentSubtype;\n private Queue<KeyStep> mKeySequence;\n\n @Override\n public boolean handleMessage(Message msg) {\n byte[] requestData;\n Message responseMsg;\n KeyStep lastKeyStep;\n\n switch (msg.what) {\n case ID_REQUEST_START_SERVICE_MODE_COMMAND:\n mCurrentType = msg.arg1;\n mCurrentSubtype = msg.arg2;\n mKeySequence = new ArrayDeque<>(3);\n if (msg.obj != null) {\n // Fixme: unchecked cast\n mKeySequence.addAll((java.util.Collection<KeyStep>) msg.obj);\n } else {\n mKeySequence.add(KeyStep.KEY_START_SERVICE_MODE);\n }\n synchronized (mLastResponseLock) {\n mLastResponse = new ArrayList<>();\n }\n requestData = mOemCommands.getEnterServiceModeData(\n mCurrentType, mCurrentSubtype, OemCommands.OEM_SM_ACTION);\n responseMsg = mHandler.obtainMessage(ID_RESPONSE);\n mRequestExecutor.invokeOemRilRequestRaw(requestData, responseMsg);\n break;\n case ID_REQUEST_FINISH_SERVICE_MODE_COMMAND:\n requestData = mOemCommands.getEndServiceModeData(mCurrentType);\n responseMsg = mHandler.obtainMessage(ID_RESPONSE_FINISH_SERVICE_MODE_COMMAND);\n mRequestExecutor.invokeOemRilRequestRaw(requestData, responseMsg);\n break;\n case ID_REQUEST_PRESS_A_KEY:\n requestData = mOemCommands.getPressKeyData(msg.arg1, OemCommands.OEM_SM_ACTION);\n responseMsg = mHandler.obtainMessage(ID_RESPONSE_PRESS_A_KEY);\n mRequestExecutor.invokeOemRilRequestRaw(requestData, responseMsg);\n break;\n case ID_REQUEST_REFRESH:\n requestData = mOemCommands.getPressKeyData('\\0', OemCommands.OEM_SM_QUERY);\n responseMsg = mHandler.obtainMessage(ID_RESPONSE);\n mRequestExecutor.invokeOemRilRequestRaw(requestData, responseMsg);\n break;\n case ID_RESPONSE:\n lastKeyStep = mKeySequence.poll();\n try {\n RawResult result = (RawResult) msg.obj;\n if (result == null) {\n Log.e(TAG, mTAG + \"result is null\");\n break;\n }\n if (result.exception != null) {\n Log.e(TAG, mTAG + \"\", result.exception);\n break;\n }\n if (result.result == null) {\n Log.i(TAG, mTAG + \"No need to refresh\");\n break;\n }\n if (lastKeyStep.captureResponse) {\n synchronized (mLastResponseLock) {\n mLastResponse\n .addAll(Helpers.unpackByteListOfStrings(result.result));\n }\n }\n } finally {\n if (mKeySequence.isEmpty()) {\n mHandler.obtainMessage(ID_REQUEST_FINISH_SERVICE_MODE_COMMAND)\n .sendToTarget();\n } else {\n mHandler.obtainMessage(ID_REQUEST_PRESS_A_KEY,\n mKeySequence.element().keychar, 0).sendToTarget();\n }\n }\n break;\n case ID_RESPONSE_PRESS_A_KEY:\n mHandler.sendMessageDelayed(mHandler.obtainMessage(ID_REQUEST_REFRESH), 10);\n break;\n case ID_RESPONSE_FINISH_SERVICE_MODE_COMMAND:\n mRequestCondvar.open();\n break;\n\n }\n return true;\n }\n }\n}", "public class AimsicdService extends InjectionService {\n\n public static final String TAG = \"AICDL\";\n public static final String mTAG = \"XXX\";\n\n\n public static boolean isGPSchoiceChecked;\n public static final String GPS_REMEMBER_CHOICE = \"remember choice\";\n SharedPreferences gpsPreferences;\n\n // /data/data/com.SecUpwN.AIMSICD/shared_prefs/com.SecUpwN.AIMSICD_preferences.xml\n public static final String SHARED_PREFERENCES_BASENAME = \"zz.aimsicd.lite_preferences\";\n public static final String UPDATE_DISPLAY = \"UPDATE_DISPLAY\";\n\n /*\n * System and helper declarations\n */\n private final AimscidBinder mBinder = new AimscidBinder();\n private static final Handler timerHandler = new Handler();\n\n private CellTracker mCellTracker;\n private AccelerometerMonitor mAccelerometerMonitor;\n private SignalStrengthTracker signalStrengthTracker;\n private LocationTracker mLocationTracker;\n private RilExecutor mRilExecutor;\n private SmsDetector smsdetector;\n\n private boolean isLocationRequestShowing = false;\n\n @Override\n public IBinder onBind(Intent intent) {\n return mBinder;\n }\n\n public class AimscidBinder extends Binder {\n public AimsicdService getService() {\n return AimsicdService.this;\n }\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n setTheme(R.style.AppTheme);\n\n signalStrengthTracker = new SignalStrengthTracker(getBaseContext());\n\n mAccelerometerMonitor = new AccelerometerMonitor(this, new Runnable() {\n @Override\n public void run() {\n // movement detected, so enable GPS\n Runnable runnable = new Runnable() {\n @Override\n public void run() {\n timerHandler.post(new Runnable() {\n @Override\n public void run() {\n mLocationTracker.start();\n }\n });\n }\n };\n new Thread(runnable).start();\n\n signalStrengthTracker.onSensorChanged();\n\n // check again in a while to see if GPS should be disabled\n // this runnable also re-enables this movement sensor\n timerHandler.postDelayed(batterySavingRunnable, AccelerometerMonitor.MOVEMENT_THRESHOLD_MS);\n }\n });\n\n mLocationTracker = new LocationTracker(this, mLocationListener);\n mRilExecutor = new RilExecutor(this);\n mCellTracker = new CellTracker(this, signalStrengthTracker);\n\n Log.i(TAG, mTAG + \"Service launched successfully.\");\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n gpsPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n isGPSchoiceChecked = gpsPreferences.getBoolean(GPS_REMEMBER_CHOICE, false);\n return START_STICKY;\n\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n mCellTracker.stop();\n mLocationTracker.stop();\n mAccelerometerMonitor.stop();\n mRilExecutor.stop();\n\n if (SmsDetector.getSmsDetectionState()) {\n smsdetector.stopSmsDetection();\n }\n Log.i(TAG, mTAG + \"Service destroyed.\");\n }\n\n public GeoLocation lastKnownLocation() {\n return mLocationTracker.lastKnownLocation();\n }\n\n public RilExecutor getRilExecutor() {\n return mRilExecutor;\n }\n\n public CellTracker getCellTracker() {\n return mCellTracker;\n }\n\n public Cell getCell() {\n return mCellTracker.getDevice().mCell;\n }\n\n public void setCell(Cell cell) {\n mCellTracker.getDevice().mCell = cell;\n }\n\n public boolean isTrackingCell() {\n return mCellTracker.isTrackingCell();\n }\n\n public boolean isMonitoringCell() {\n return mCellTracker.isMonitoringCell();\n }\n\n public void setCellMonitoring(boolean monitor) {\n mCellTracker.setCellMonitoring(monitor);\n }\n\n // SMS Detection Thread\n public boolean isSmsTracking() {\n return SmsDetector.getSmsDetectionState();\n }\n\n public void startSmsTracking() {\n if (!isSmsTracking()) {\n Log.i(TAG, mTAG + \"Sms Detection Thread Started\");\n smsdetector = new SmsDetector(this);\n smsdetector.startSmsDetection();\n }\n }\n\n public void stopSmsTracking() {\n if (isSmsTracking()) {\n smsdetector.stopSmsDetection();\n Log.i(TAG, mTAG + \"Sms Detection Thread Stopped\");\n }\n }\n\n // while tracking a cell, manage the power usage by switching off GPS if no movement\n private final Runnable batterySavingRunnable = new Runnable() {\n @Override\n public void run() {\n if (mCellTracker.isTrackingCell()) {\n // if no movement in a while, shut off GPS. Gets re-enabled when there is movement\n if (mAccelerometerMonitor.notMovedInAWhile() ||\n mLocationTracker.notMovedInAWhile()) {\n mLocationTracker.stop();\n }\n mAccelerometerMonitor.start();\n }\n }\n };\n\n /**\n * Cell Information Tracking and database logging\n *\n * @param track Enable/Disable tracking\n */\n public void setCellTracking(boolean track) {\n mCellTracker.setCellTracking(track);\n\n if (track) {\n mLocationTracker.start();\n mAccelerometerMonitor.start();\n } else {\n mLocationTracker.stop();\n mAccelerometerMonitor.stop();\n }\n }\n\n public void checkLocationServices() {\n if (mCellTracker.isTrackingCell() && !mLocationTracker.isGPSOn() && !isGPSchoiceChecked) {\n enableLocationServices();\n }\n }\n\n private void enableLocationServices() {\n if (isLocationRequestShowing) {\n return; // only show dialog once\n }\n\n LayoutInflater dialogInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);\n // https://possiblemobile.com/2013/05/layout-inflation-as-intended/\n // This is an AlertDialog so null is ok:\n @SuppressLint(\"InflateParams\")\n View dialogView = dialogInflater.inflate(R.layout.dialog_request_gps, null, false);\n CheckBox rememberChoice = (CheckBox) dialogView.findViewById(R.id.check_choice);\n Button notNow = (Button) dialogView.findViewById(R.id.not_now_button);\n Button enableGPS = (Button) dialogView.findViewById(R.id.enable_gps_button);\n\n final AlertDialog alertDialog = new AlertDialog.Builder(this)\n /*.setMessage(R.string.location_error_message)\n .setTitle(R.string.location_error_title)*/\n .setView(dialogView)\n .setCancelable(false)\n /*.setPositiveButton(R.string.text_ok, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n isLocationRequestShowing = false;\n Intent gpsSettings = new Intent(\n android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n gpsSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n startActivity(gpsSettings);\n }\n })\n .setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n isLocationRequestShowing = false;\n setCellTracking(false);\n }\n })*/\n .create();\n\n rememberChoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n\n if (isChecked) {\n isGPSchoiceChecked = true;\n gpsPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = gpsPreferences.edit();\n editor.putBoolean(GPS_REMEMBER_CHOICE, isGPSchoiceChecked);\n editor.apply();\n\n } else {\n isGPSchoiceChecked = false;\n }\n }\n });\n\n notNow.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n isLocationRequestShowing = false;\n setCellTracking(false);\n alertDialog.cancel();\n alertDialog.dismiss();\n }\n });\n\n enableGPS.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n isLocationRequestShowing = false;\n Intent gpsSettings = new Intent(\n android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n gpsSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n alertDialog.cancel();\n alertDialog.dismiss();\n startActivity(gpsSettings);\n }\n });\n\n alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);\n alertDialog.show();\n isLocationRequestShowing = true;\n }\n\n LocationListener mLocationListener = new LocationListener() {\n @Override\n public void onLocationChanged(Location loc) {\n timerHandler.postDelayed(batterySavingRunnable, AccelerometerMonitor.MOVEMENT_THRESHOLD_MS);\n mCellTracker.onLocationChanged(loc);\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n if (mCellTracker.isTrackingCell() && provider.equals(LocationManager.GPS_PROVIDER) && !isGPSchoiceChecked) {\n enableLocationServices();\n }\n }\n\n @Override\n public void onProviderEnabled(String s) {\n\n }\n\n @Override\n public void onStatusChanged(String s, int i, Bundle bundle) {\n\n }\n };\n}", "public class CellTracker implements SharedPreferences.OnSharedPreferenceChangeListener {\n\n public static final String TAG = \"AICDL\";\n public static final String mTAG = \"CellTracker: \";\n\n public static Cell mMonitorCell;\n public static String OCID_API_KEY = null; // see getOcidKey()\n public static int PHONE_TYPE; //\n public static int LAST_DB_BACKUP_VERSION; //\n public static long REFRESH_RATE; // [s] The DeviceInfo refresh rate (arrays.xml)\n public static final String SILENT_SMS = \"SILENT_SMS_DETECTED\";\n\n private boolean CELL_TABLE_CLEANSED; // default is FALSE for \"boolean\", and NULL for \"Boolean\".\n private final int NOTIFICATION_ID = 1;\n private final Device mDevice = new Device();\n\n private static TelephonyManager tm;\n private final SignalStrengthTracker signalStrengthTracker;\n private PhoneStateListener mPhoneStateListener;\n private SharedPreferences prefs;\n private TinyDB tinydb; // Used to simplify SharedPreferences usage above\n\n //=====================================================\n // Tracking and Alert Declarations\n //=====================================================\n private boolean mMonitoringCell;\n private boolean mTrackingCell;\n private boolean mChangedLAC;\n private boolean mCellIdNotInOpenDb;\n private boolean mTypeZeroSmsDetected;\n private boolean mVibrateEnabled;\n private int mVibrateMinThreatLevel;\n private LinkedBlockingQueue<NeighboringCellInfo> neighboringCellBlockingQueue;\n\n private final AIMSICDDbAdapter dbHelper;\n private static Context context;\n\n public CellTracker(Context context, SignalStrengthTracker sst) {\n this.context = context;\n this.signalStrengthTracker = sst;\n\n // Creating tinydb here to avoid: \"TinyDb tinydb = new TinyDb(context);\"\n // every time we need to use tinydb in this class.\n tinydb = TinyDB.getInstance();\n\n // TelephonyManager provides system details\n tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);\n\n // Shared Preferences\n prefs = context.getSharedPreferences(AimsicdService.SHARED_PREFERENCES_BASENAME, 0);\n prefs.registerOnSharedPreferenceChangeListener(this);\n loadPreferences();\n setNotification();\n\n PHONE_TYPE = tm.getPhoneType(); // PHONE_TYPE_GSM/CDMA/SIP/NONE\n\n dbHelper = new AIMSICDDbAdapter(context);\n\n // Remove all but the last DBi_bts entry, after:\n // (a) starting CellTracker for the first time or\n // (b) having cleared the preferences.\n // Subsequent runs are prevented by a hidden boolean preference. See: loadPreferences()\n if (!CELL_TABLE_CLEANSED) {\n dbHelper.cleanseCellTable();\n SharedPreferences.Editor prefsEditor;\n prefsEditor = prefs.edit();\n prefsEditor.putBoolean(context.getString(R.string.pref_cell_table_cleansed), true); // set to true\n prefsEditor.apply();\n }\n mDevice.refreshDeviceInfo(tm, context); // Telephony Manager\n mMonitorCell = new Cell();\n }\n\n public boolean isTrackingCell() {\n return mTrackingCell;\n }\n\n public boolean isMonitoringCell() {\n return mMonitoringCell;\n }\n\n\n /**\n * Description: Cell Information Monitoring\n * TODO: What exactly are we monitoring here??\n * TODO: Is this related to the Tracking/Monitoring in the menu drawer?\n *\n * @param monitor Enable/Disable monitoring\n */\n public void setCellMonitoring(boolean monitor) {\n if (monitor) {\n mMonitoringCell = true;\n Helpers.msgShort(context, context.getString(R.string.monitoring_cell_information));\n } else {\n mMonitoringCell = false;\n Helpers.msgShort(context, context.getString(R.string.stopped_monitoring_cell_information));\n }\n setNotification();\n }\n\n public Device getDevice() {\n return mDevice;\n }\n\n\n\n public void stop() {\n if (isMonitoringCell()) {\n setCellMonitoring(false);\n }\n if (isTrackingCell()) {\n setCellTracking(false);\n }\n\n cancelNotification();\n tm.listen(mCellSignalListener, PhoneStateListener.LISTEN_NONE);\n prefs.unregisterOnSharedPreferenceChangeListener(this);\n\n }\n\n /**\n * Description: Cell Information Tracking and database logging\n *\n * TODO: update this!!\n *\n * If the \"tracking\" option is enabled (as it is by default) then we are keeping\n * a record (tracking) of the device location \"gpsd_lat/lon\", the connection\n * signal strength (rx_signal) and data activity (?) and data connection state (?).\n *\n * The items included in these are stored in the \"DBi_measure\" table.\n *\n * DATA_ACTIVITY:\n * DATA_CONNECTION_STATE:\n *\n *\n * UI/function: Drawer: \"Toggle Cell Tracking\"\n *\n * Issues:\n *\n * Notes: TODO: We also need to listen and log for:\n *\n * [ ] LISTEN_CALL_STATE:\n * CALL_STATE_IDLE\n * CALL_STATE_OFFHOOK\n * CALL_STATE_RINGING\n *\n * [ ] LISTEN_SERVICE_STATE:\n * STATE_EMERGENCY_ONLY\n * STATE_IN_SERVICE\n * STATE_OUT_OF_SERVICE\n * STATE_POWER_OFF\n *\n * @param track Enable/Disable tracking\n */\n public void setCellTracking(boolean track) {\n if (track) {\n tm.listen(mCellSignalListener,\n PhoneStateListener.LISTEN_CELL_LOCATION | // gpsd_lat/lon ?\n PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | // rx_signal\n PhoneStateListener.LISTEN_DATA_ACTIVITY | // No,In,Ou,IO,Do\n PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | // Di,Ct,Cd,Su\n PhoneStateListener.LISTEN_CELL_INFO // !? (Need API 17)\n );\n mTrackingCell = true;\n Helpers.msgShort(context, context.getString(R.string.tracking_cell_information));\n } else {\n tm.listen(mCellSignalListener, PhoneStateListener.LISTEN_NONE);\n mDevice.mCell.setLon(0.0);\n mDevice.mCell.setLat(0.0);\n mDevice.setCellInfo(\"[0,0]|nn|nn|\"); //default entries into \"locationinfo\"::Connection\n mTrackingCell = false;\n Helpers.msgShort(context, context.getString(R.string.stopped_tracking_cell_information));\n }\n setNotification();\n }\n\n /**\n * Description: This handles the settings/choices and default preferences, when changed.\n * From the default file:\n * preferences.xml\n * And saved in the file:\n * /data/data/com.SecUpwN.AIMSICD/shared_prefs/zz.aimsicd.lite_preferences.xml\n *\n * NOTE: - For more code transparency we have added TinyDB.java as a\n * wrapper to SharedPreferences usage. Please try to use this instead.\n *\n * @param sharedPreferences\n * @param key\n */\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {\n final String KEY_UI_ICONS = context.getString(R.string.pref_ui_icons_key);\n final String REFRESH = context.getString(R.string.pref_refresh_key);\n final String DB_VERSION = context.getString(R.string.pref_last_database_backup_version);\n final String OCID_KEY = context.getString(R.string.pref_ocid_key);\n final String VIBRATE_ENABLE = context.getString(R.string.pref_notification_vibrate_enable);\n final String VIBRATE_MIN_LEVEL = context.getString(R.string.pref_notification_vibrate_min_level);\n\n if (key.equals(KEY_UI_ICONS)) {\n // Update Notification to display selected icon type\n setNotification();\n } else if (key.equals(REFRESH)) {\n String refreshRate = sharedPreferences.getString(REFRESH, \"1\");\n if (refreshRate.isEmpty()) {\n refreshRate = \"1\"; // Set default to: 1 second\n }\n\n int rate = Integer.parseInt(refreshRate);\n long t;\n switch (rate) {\n case 1:\n t = 15L; // Automatic refresh rate is 15 seconds\n break;\n default:\n t = (long) rate; // Default is 1 sec (from above)\n break;\n }\n REFRESH_RATE = TimeUnit.SECONDS.toMillis(t);\n } else if (key.equals(DB_VERSION)) {\n LAST_DB_BACKUP_VERSION = sharedPreferences.getInt(DB_VERSION, 1);\n } else if (key.equals(OCID_KEY)) {\n getOcidKey();\n } else if (key.equals(VIBRATE_ENABLE)) {\n mVibrateEnabled = sharedPreferences.getBoolean(VIBRATE_ENABLE, true);\n } else if (key.equals(VIBRATE_MIN_LEVEL)) {\n mVibrateMinThreatLevel = Integer.valueOf(sharedPreferences.getString(VIBRATE_MIN_LEVEL, String.valueOf(Status.MEDIUM.ordinal())));\n }\n }\n\n public void getOcidKey() {\n final String OCID_KEY = context.getString(R.string.pref_ocid_key);\n OCID_API_KEY = prefs.getString(OCID_KEY, BuildConfig.OPEN_CELLID_API_KEY);\n //if (OCID_API_KEY == null) {\n if (OCID_API_KEY.isEmpty()) {\n OCID_API_KEY = \"NA\";\n }\n }\n\n /**\n * Description: Updates Neighbouring Cell details\n *\n * TODO: add more details...\n *\n *\n */\n public List<Cell> updateNeighbouringCells() {\n List<Cell> neighboringCells = new ArrayList<>();\n List<NeighboringCellInfo> neighboringCellInfo = tm.getNeighboringCellInfo();\n\n if (neighboringCellInfo == null) {\n neighboringCellInfo = new ArrayList<>();\n }\n\n Boolean nclp = tinydb.getBoolean(\"nc_list_present\"); // Is NC list present? (default is false)\n\n //if nclp = true then check for neighboringCellInfo\n //if (neighboringCellInfo != null && neighboringCellInfo.size() == 0 && nclp) {\n //if (!neighboringCellInfo.isEmpty() && neighboringCellInfo.size() == 0 && nclp) {\n if (neighboringCellInfo.size() == 0 && nclp) {\n\n Log.i(TAG, mTAG + \"NeighbouringCellInfo is empty: start polling...\");\n\n // Try to poll the neighboring cells for a few seconds\n neighboringCellBlockingQueue = new LinkedBlockingQueue<>(100); // Max 100 NC's before blocking (?)\n\n // ToDo: rename... (We don't use API's <18 anymore.)\n DeviceApi18.startListening(tm, phoneStatelistener);\n\n // ToDo: Move or remove. This should now be done by getAllCellInfo() in new RadioAPI \"collector\" module.\n for (int i = 0; i < 10 && neighboringCellInfo.size() == 0; i++) {\n try {\n Log.d(TAG, mTAG + \"NeighbouringCellInfo empty: trying \" + i);\n NeighboringCellInfo info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS);\n if (info == null) {\n neighboringCellInfo = tm.getNeighboringCellInfo();\n if (neighboringCellInfo != null) {\n if (neighboringCellInfo.size() > 0) {\n // Can we think of a better log message here?\n Log.d(TAG, mTAG + \"NeighbouringCellInfo found on \" + i + \" try. (time based)\");\n break;\n } else {\n continue;\n }\n }\n }\n List<NeighboringCellInfo> cellInfoList =\n new ArrayList<>(neighboringCellBlockingQueue.size() + 1);\n while (info != null) {\n cellInfoList.add(info);\n info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS);\n }\n neighboringCellInfo = cellInfoList;\n } catch (InterruptedException e) {\n Log.e(TAG, mTAG + \"Interrupted BlockingQueue Exception: \" + e);\n }\n }\n }\n\n //log.debug(mTAG + \": neighbouringCellInfo size: \" + neighboringCellInfo.size());\n\n // Add NC list to DBi_measure:nc_list\n for (NeighboringCellInfo neighbourCell : neighboringCellInfo) {\n Log.i(TAG, mTAG + \"NeighbouringCellInfo -\" +\n \" LAC:\" + neighbourCell.getLac() +\n \" CID:\" + neighbourCell.getCid() +\n \" PSC:\" + neighbourCell.getPsc() +\n \" RSSI:\" + neighbourCell.getRssi());\n\n final Cell cell = new Cell(\n neighbourCell.getCid(),\n neighbourCell.getLac(),\n neighbourCell.getRssi(),\n neighbourCell.getPsc(),\n neighbourCell.getNetworkType(), false);\n neighboringCells.add(cell);\n }\n return neighboringCells;\n }\n\n\n /**\n * Description: This snippet sets a global variable (SharedPreference) to indicate\n * if Neighboring cells info CAN be obtained or has been obtained\n * previously. If it has been and suddenly there are none, we can\n * raise a flag of CID being suspicious.\n *\n * The logic is:\n *\n * IF NC has never been seen on device:\n * - NC list is NOT supported on this AOS/HW, so we do nothing.\n * IF NC has been seen before,\n * - NC list IS supported on this AOS/HW, so we set:\n * nc_list_present : \"true\"\n * IF NC list has been seen before AND current CID doesn't provide\n * one, we raise an alarm or flag.\n *\n *\n * Notes: a) Not sure where to place this test, but let's try it here..\n * b) In TinyDB, the getBoolean() returns \"false\" by default, if empty.\n *\n * c) This will be called on every cell change (ref: issue #346)\n * d) *** https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/383\n *\n * Issue:\n * [ ] We need a timer or \"something\" to reverse a positive detection once\n * we're out and away from the fake BTS cell.\n * [ ] We need to add this to EventLog\n * [ ] We need to add detection tickers etc...\n * [ ] Attention to the spelling of \"neighbor\" (USA) Vs. \"neighbour\" (Eng world)\n * [x] We need to use a global and persistent variable and not a system property\n *\n */\n public void checkForNeighbourCount(CellLocation location) {\n Log.i(TAG, mTAG + \"CheckForNeighbourCount()\");\n\n Integer ncls = 0; // NC list size\n if (tm != null && tm.getNeighboringCellInfo() != null) { // See # 383\n ncls = tm.getNeighboringCellInfo().size();\n }\n Boolean nclp = tinydb.getBoolean(\"nc_list_present\"); // NC list present? (default is false)\n\n if (ncls > 0) {\n Log.d(TAG, mTAG + \"NeighbouringCellInfo size: \" + ncls);\n if (!nclp) {\n Log.d(TAG, mTAG + \"Setting nc_list_present to: true\");\n tinydb.putBoolean(\"nc_list_present\", true);\n }\n } else if (ncls == 0 && nclp) {\n // Detection 7a\n Log.i(TAG, mTAG + \"ALERT: No neighboring cells detected for CID: \" + mDevice.mCell.getCID());\n vibrate(100, Status.MEDIUM);\n dbHelper.toEventLog(4, \"No neighboring cells detected\"); // (DF_id, DF_desc)\n } else {\n // Todo: remove cid string when working.\n Log.d(TAG, mTAG + \"NC list not supported by AOS on this device. Nothing to do.\");\n Log.d(TAG, mTAG + \": Setting nc_list_present to: false\");\n tinydb.putBoolean(\"nc_list_present\", false);\n }\n }\n\n /**\n * I removed the timer that activated this code and now the code will be run when\n * the cell changes so it will detect faster rather than using a timer that might\n * miss an imsi catcher, also says cpu rather than refreshing every x seconds.\n *\n * original comments below from xLaMbChOpSx\n *\n *\n * Description: (From xLaMbChOpSx commit comment)\n *\n * Initial implementation for detection method 1 to compare the CID & LAC with the Cell\n * Information Table contents as an initial implementation for detection of a changed LAC,\n * once OCID issues (API key use etc) have been finalised this detection method can be\n * extended to include checking of external data.\n *\n * REMOVED: refresh timer info\n *\n * As I have no real way of testing this I require testing by other project members who\n * do have access to equipment or an environment where a changing LAC can be simulated\n * thus confirming the accuracy of this implementation.\n *\n * Presently this will only invoke the MEDIUM threat level through the notification and\n * does not fully implement the capturing and score based method as per the issue details\n * once further testing is complete the alert and tracking of information can be refined.\n *\n * See:\n * https://github.com/xLaMbChOpSx/Android-IMSI-Catcher-Detector/commit/43ae77e2a0cad10dfd50f92da5a998f9ece95b38\n * https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/91#issuecomment-64391732\n *\n * Short explanation:\n *\n * This is a polling mechanism for getting the LAC/CID and location\n * info for the currently connected cell.\n *\n * Variables:\n * FIXED: now updates on cell change rather than a timer\n * There is a \"timer\" here (REFRESH_RATE), what exactly is it timing?\n * \"Every REFRESH_RATE seconds, get connected cell details.\"\n *\n * Notes:\n * a) Check if CellID (CID) is in DBe_import (OpenCell) database (issue #91)\n * See news in: issue #290 and compare to AIMSICDDbAdapter.java\n *\n * Issues: [ ] We shouldn't do any detection here!\n * [ ] We might wanna use a listener to do this?\n * Are there any reasons why not using a listener?\n *\n * ChangeLog:\n * 2015-03-03 E:V:A Changed getProp() to use TinyDB (SharedPreferences)\n * 2015-0x-xx banjaxbanjo Update: ??? (hey dude what did you do?)\n *\n */\n public void compareLac(CellLocation location) {\n switch (mDevice.getPhoneID()) {\n\n case TelephonyManager.PHONE_TYPE_NONE:\n case TelephonyManager.PHONE_TYPE_SIP:\n case TelephonyManager.PHONE_TYPE_GSM:\n GsmCellLocation gsmCellLocation = (GsmCellLocation) location;\n if (gsmCellLocation != null) {\n mMonitorCell.setLAC(gsmCellLocation.getLac());\n mMonitorCell.setCID(gsmCellLocation.getCid());\n\n // Check if LAC is ok\n boolean lacOK = dbHelper.checkLAC(mMonitorCell);\n if (!lacOK) {\n mChangedLAC = true;\n dbHelper.toEventLog(1, \"Changing LAC\");\n\n // Detection Logs are made in checkLAC()\n vibrate(100, Status.MEDIUM);\n } else {\n mChangedLAC = false;\n }\n\n // Check if CID is in DBe_import DB (issue #91)\n if (tinydb.getBoolean(\"ocid_downloaded\")) {\n if (!dbHelper.openCellExists(mMonitorCell.getCID())) {\n dbHelper.toEventLog(2, \"CID not in DBe_import\");\n\n Log.i(TAG, mTAG + \"ALERT: Connected to unknown CID not in DBe_import: \" + mMonitorCell.getCID());\n vibrate(100, Status.MEDIUM);\n\n mCellIdNotInOpenDb = true;\n } else {\n mCellIdNotInOpenDb = false;\n }\n }\n }\n break;\n\n case TelephonyManager.PHONE_TYPE_CDMA:\n CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) location;\n if (cdmaCellLocation != null) {\n mMonitorCell.setLAC(cdmaCellLocation.getNetworkId());\n mMonitorCell.setCID(cdmaCellLocation.getBaseStationId());\n\n boolean lacOK = dbHelper.checkLAC(mMonitorCell);\n if (!lacOK) {\n mChangedLAC = true;\n /*dbHelper.insertEventLog(\n MiscUtils.getCurrentTimeStamp(),\n mMonitorCell.getLAC(),\n mMonitorCell.getCID(),\n mMonitorCell.getPSC(),//This is giving weird values like 21478364... is this right?\n String.valueOf(mMonitorCell.getLat()),\n String.valueOf(mMonitorCell.getLon()),\n (int)mMonitorCell.getAccuracy(),\n 1,\n \"Changing LAC\"\n );*/\n dbHelper.toEventLog(1, \"Changing LAC\");\n } else {\n mChangedLAC = false;\n }\n }\n }\n setNotification();\n }\n\n /**\n * Check device's current cell location's LAC against local database AND verify cell's CID\n * exists in the OCID database.\n *\n * @see #compareLac(CellLocation)\n */\n public void compareLacAndOpenDb() {\n compareLac(tm.getCellLocation());\n }\n\n // Where is this used?\n private void handlePhoneStateChange() {\n List<NeighboringCellInfo> neighboringCellInfo = tm.getNeighboringCellInfo();\n if (neighboringCellInfo == null || neighboringCellInfo.size() == 0) {\n return;\n }\n\n Log.i(TAG, mTAG + \"NeighbouringCellInfo empty - event based polling succeeded!\");\n tm.listen(phoneStatelistener, PhoneStateListener.LISTEN_NONE);\n if (neighboringCellInfo == null) {\n neighboringCellInfo = new ArrayList<>();\n }\n neighboringCellBlockingQueue.addAll(neighboringCellInfo);\n }\n\n public void refreshDevice() {\n mDevice.refreshDeviceInfo(tm, context);\n }\n\n /**\n * Description: Process User Preferences\n * This loads the default Settings/Preferences as set in:\n * preferences.xml\n * and:\n * /data/data/com.SecUpwN.AIMSICD/shared_prefs/com.SecUpwN.AIMSICD_preferences.xml\n *\n * TODO: Please add more info\n *\n */\n private void loadPreferences() {\n // defaults are given by: getBoolean(key, default if not exist)\n boolean trackFemtoPref = prefs.getBoolean(context.getString(R.string.pref_femto_detection_key), false);\n boolean trackCellPref = prefs.getBoolean(context.getString(R.string.pref_enable_cell_key), true);\n boolean monitorCellPref = prefs.getBoolean(context.getString(R.string.pref_enable_cell_monitoring_key), true);\n\n LAST_DB_BACKUP_VERSION = prefs.getInt(context.getString(R.string.pref_last_database_backup_version), 1);\n CELL_TABLE_CLEANSED = prefs.getBoolean(context.getString(R.string.pref_cell_table_cleansed), false);\n String refreshRate = prefs.getString(context.getString(R.string.pref_refresh_key), \"1\");\n this.mVibrateEnabled = prefs.getBoolean(context.getString(R.string.pref_notification_vibrate_enable), true);\n this.mVibrateMinThreatLevel = Integer.valueOf(prefs.getString(context.getString(R.string.pref_notification_vibrate_min_level), String.valueOf(Status.MEDIUM.ordinal())));\n\n // Default to Automatic (\"1\")\n if (refreshRate.isEmpty()) {\n refreshRate = \"1\";\n }\n\n int rate = Integer.parseInt(refreshRate);\n long t;\n if (rate == 1) {\n t = 15L; // Automatic refresh rate is 15 seconds\n } else {\n t = ((long) rate); // Default is 1 sec (from above)\n }\n\n REFRESH_RATE = TimeUnit.SECONDS.toMillis(t);\n getOcidKey();\n\n if (trackCellPref) {\n setCellTracking(true);\n }\n if (monitorCellPref) {\n setCellMonitoring(true);\n }\n }\n\n\n /**\n * Description: TODO: add more info\n *\n * This SEEM TO add entries to the \"locationinfo\" DB table in the ??\n *\n * Issues:\n *\n * [ ] We see that \"Connection\" items are messed up. What is the purpose of these?\n *\n * $ sqlite3.exe -header -csv aimsicd.db 'select * from locationinfo;'\n * _id,Lac,CellID,Net,Lat,Lng,Signal,Connection,Timestamp\n * 1,10401,6828111,10, 54.6787,25.2869, 24, \"[10401,6828111,126]No|Di|HSPA|\", \"2015-01-21 20:45:10\"\n *\n * [ ] TODO: CDMA has to extract the MCC and MNC using something like:\n *\n * String mccMnc = phoneMgr.getNetworkOperator();\n * String cdmaMcc = \"\";\n * String cdmaMnc = \"\";\n * if (mccMnc != null && mccMnc.length() >= 5) {\n * cdmaMcc = mccMnc.substring(0, 3);\n * cdmaMnc = mccMnc.substring(3, 5);\n } }\n *\n * ChangeLog:\n *\n * 2015-01-22 E:V:A Changed what appears to be a typo in the character\n * following getNetworkTypeName(), \"|\" to \"]\"\n * 2015-01-24 E:V:A FC WTF!? Changed back ^ to \"|\". (Where is this info parsed?)\n *\n */\n private final PhoneStateListener mCellSignalListener = new PhoneStateListener() {\n public void onCellLocationChanged(CellLocation location) {\n\n checkForNeighbourCount(location);\n compareLac(location);\n refreshDevice();\n mDevice.setNetID(tm);\n mDevice.getNetworkTypeName();\n\n switch (mDevice.getPhoneID()) {\n\n case TelephonyManager.PHONE_TYPE_NONE:\n case TelephonyManager.PHONE_TYPE_SIP:\n case TelephonyManager.PHONE_TYPE_GSM:\n GsmCellLocation gsmCellLocation = (GsmCellLocation) location;\n if (gsmCellLocation != null) {\n //TODO @EVA where are we sending this setCellInfo data?\n\n //TODO\n /*@EVA\n Is it a good idea to dump all cells to db because if we spot a known cell\n with different lac then this will also be dump to db.\n\n */\n mDevice.setCellInfo(\n gsmCellLocation.toString() + // ??\n mDevice.getDataActivityTypeShort() + \"|\" + // No,In,Ou,IO,Do\n mDevice.getDataStateShort() + \"|\" + // Di,Ct,Cd,Su\n mDevice.getNetworkTypeName() + \"|\" // HSPA,LTE etc\n );\n\n mDevice.mCell.setLAC(gsmCellLocation.getLac()); // LAC\n mDevice.mCell.setCID(gsmCellLocation.getCid()); // CID\n if (gsmCellLocation.getPsc() != -1) {\n mDevice.mCell.setPSC(gsmCellLocation.getPsc()); // PSC\n }\n\n /*\n Add cell if gps is not enabled\n when gps enabled lat lon will be updated\n by function below\n\n */\n }\n break;\n\n case TelephonyManager.PHONE_TYPE_CDMA:\n CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) location;\n if (cdmaCellLocation != null) {\n mDevice.setCellInfo(\n cdmaCellLocation.toString() + // ??\n mDevice.getDataActivityTypeShort() + \"|\" + // No,In,Ou,IO,Do\n mDevice.getDataStateShort() + \"|\" + // Di,Ct,Cd,Su\n mDevice.getNetworkTypeName() + \"|\" // HSPA,LTE etc\n );\n mDevice.mCell.setLAC(cdmaCellLocation.getNetworkId()); // NID\n mDevice.mCell.setCID(cdmaCellLocation.getBaseStationId()); // BID\n mDevice.mCell.setSID(cdmaCellLocation.getSystemId()); // SID\n mDevice.mCell.setMNC(cdmaCellLocation.getSystemId()); // MNC <== BUG!??\n mDevice.setNetworkName(tm.getNetworkOperatorName()); // ??\n }\n }\n\n }\n\n /**\n * Description: TODO: add more info\n *\n * Issues:\n *\n * [ ] Getting and comparing signal strengths between different RATs can be very\n * tricky, since they all return different ranges of values. AOS doesn't\n * specify very clearly what exactly is returned, even though people have\n * a good idea, by trial and error.\n *\n * See note in : SignalStrengthTracker.java\n *\n * Notes:\n *\n *\n *\n */\n public void onSignalStrengthsChanged(SignalStrength signalStrength) {\n // Update Signal Strength\n if (signalStrength.isGsm()) {\n int dbm;\n if (signalStrength.getGsmSignalStrength() <= 2 ||\n signalStrength.getGsmSignalStrength() == NeighboringCellInfo.UNKNOWN_RSSI) {\n // Unknown signal strength, get it another way\n String[] bits = signalStrength.toString().split(\" \");\n dbm = Integer.parseInt(bits[9]);\n } else {\n dbm = signalStrength.getGsmSignalStrength();\n }\n mDevice.setSignalDbm(dbm);\n } else {\n int evdoDbm = signalStrength.getEvdoDbm();\n int cdmaDbm = signalStrength.getCdmaDbm();\n\n // Use lowest signal to be conservative\n mDevice.setSignalDbm((cdmaDbm < evdoDbm) ? cdmaDbm : evdoDbm);\n }\n // Send it to signal tracker\n signalStrengthTracker.registerSignalStrength(mDevice.mCell.getCID(), mDevice.getSignalDBm());\n //signalStrengthTracker.isMysterious(mDevice.mCell.getCID(), mDevice.getSignalDBm());\n }\n\n // In DB: No,In,Ou,IO,Do\n public void onDataActivity(int direction) {\n switch (direction) {\n case TelephonyManager.DATA_ACTIVITY_NONE:\n mDevice.setDataActivityTypeShort(\"No\");\n mDevice.setDataActivityType(\"None\");\n break;\n case TelephonyManager.DATA_ACTIVITY_IN:\n mDevice.setDataActivityTypeShort(\"In\");\n mDevice.setDataActivityType(\"In\");\n break;\n case TelephonyManager.DATA_ACTIVITY_OUT:\n mDevice.setDataActivityTypeShort(\"Ou\");\n mDevice.setDataActivityType(\"Out\");\n break;\n case TelephonyManager.DATA_ACTIVITY_INOUT:\n mDevice.setDataActivityTypeShort(\"IO\");\n mDevice.setDataActivityType(\"In-Out\");\n break;\n case TelephonyManager.DATA_ACTIVITY_DORMANT:\n mDevice.setDataActivityTypeShort(\"Do\");\n mDevice.setDataActivityType(\"Dormant\");\n break;\n }\n }\n\n // In DB: Di,Ct,Cd,Su\n public void onDataConnectionStateChanged(int state) {\n switch (state) {\n case TelephonyManager.DATA_DISCONNECTED:\n mDevice.setDataState(\"Disconnected\");\n mDevice.setDataStateShort(\"Di\");\n break;\n case TelephonyManager.DATA_CONNECTING:\n mDevice.setDataState(\"Connecting\");\n mDevice.setDataStateShort(\"Ct\");\n break;\n case TelephonyManager.DATA_CONNECTED:\n mDevice.setDataState(\"Connected\");\n mDevice.setDataStateShort(\"Cd\");\n break;\n case TelephonyManager.DATA_SUSPENDED:\n mDevice.setDataState(\"Suspended\");\n mDevice.setDataStateShort(\"Su\");\n break;\n }\n }\n\n };\n\n /**\n * Description: Add entries to the \"DBi_measure\" DB table\n *\n * Issues:\n * [ ]\n *\n * Notes: (a)\n *\n *\n * TODO: Remove OLD notes below, once we have new ones relevant to our new table\n *\n * From \"locationinfo\":\n *\n * $ sqlite3.exe -header aimsicd.db 'select * from locationinfo;'\n * _id|Lac|CellID|Net|Lat|Lng|Signal|Connection|Timestamp\n * 1|10401|6828xxx|10|54.67874392|25.28693531|24|[10401,6828320,126]No|Di|HSPA||2015-01-21 20:45:10\n *\n * From \"cellinfo\":\n *\n * $ sqlite3.exe -header aimsicd.db 'select * from cellinfo;'\n * _id|Lac|CellID|Net|Lat|Lng|Signal|Mcc|Mnc|Accuracy|Speed|Direction|NetworkType|MeasurementTaken|OCID_SUBMITTED|Timestamp\n * 1|10401|6828xxx|10|54.67874392|25.28693531|24|246|2|69.0|0.0|0.0|HSPA|82964|0|2015-01-21 20:45:10\n *\n * Issues:\n *\n */\n public void onLocationChanged(Location loc) {\n\n DeviceApi18.loadCellInfo(tm, mDevice);\n\n if (!mDevice.mCell.isValid()) {\n CellLocation cellLocation = tm.getCellLocation();\n if (cellLocation != null) {\n switch (mDevice.getPhoneID()) {\n\n case TelephonyManager.PHONE_TYPE_NONE:\n case TelephonyManager.PHONE_TYPE_SIP:\n case TelephonyManager.PHONE_TYPE_GSM:\n GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;\n mDevice.mCell.setCID(gsmCellLocation.getCid()); // CID\n mDevice.mCell.setLAC(gsmCellLocation.getLac()); // LAC\n mDevice.mCell.setPSC(gsmCellLocation.getPsc()); // PSC\n break;\n\n case TelephonyManager.PHONE_TYPE_CDMA:\n CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;\n mDevice.mCell.setCID(cdmaCellLocation.getBaseStationId()); // BSID ??\n mDevice.mCell.setLAC(cdmaCellLocation.getNetworkId()); // NID\n mDevice.mCell.setSID(cdmaCellLocation.getSystemId()); // SID\n mDevice.mCell.setMNC(cdmaCellLocation.getSystemId()); // MNC <== BUG!??\n\n break;\n }\n }\n }\n\n if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0 && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {\n\n mDevice.mCell.setLon(loc.getLongitude()); // gpsd_lon\n mDevice.mCell.setLat(loc.getLatitude()); // gpsd_lat\n mDevice.mCell.setSpeed(loc.getSpeed()); // speed // TODO: Remove, we're not using it!\n mDevice.mCell.setAccuracy(loc.getAccuracy()); // gpsd_accu\n mDevice.mCell.setBearing(loc.getBearing()); // -- [deg]?? // TODO: Remove, we're not using it!\n mDevice.setLastLocation(loc); //\n\n // Store last known location in preference\n SharedPreferences.Editor prefsEditor;\n prefsEditor = prefs.edit();\n prefsEditor.putString(context.getString(R.string.data_last_lat_lon),\n String.valueOf(loc.getLatitude()) + \":\" + String.valueOf(loc.getLongitude()));\n prefsEditor.apply();\n\n // This only logs a BTS if we have GPS lock\n // Test: ~~Is correct behaviour? We should consider logging all cells, even without GPS.~~\n //if (mTrackingCell) {\n // This also checks that the lac are cid are not in DB before inserting\n dbHelper.insertBTS(mDevice.mCell);\n //}\n }\n }\n\n /**\n * Cancel and remove the persistent notification\n */\n public void cancelNotification() {\n NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID);\n }\n\n /**\n * Description: Set or update the Detection/Status Notification\n * TODO: Need to add status HIGH (Orange) and SKULL (Black)\n *\n * Issues:\n * See: https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/wiki/Status-Icons\n * and: https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/11#issuecomment-44670204\n *\n * [ ] We need to standardize the \"contentText\" and \"tickerText\" format\n *\n * [ ] From #91: https://github.com/SecUpwN/Android-IMSI-Catcher-Detector/issues/91\n *\n * Problem:\n * Having multiple notifications will cause an issue with\n * notifications themselves AND tickerText. It seems that the\n * most recent notification raised would overwrite any previous,\n * notification or tickerText. This results in loss of information\n * for any notification before the last one.\n *\n * Possible Solution:\n * Perhaps arranging a queue implementation to deal with text\n * being passed into tickerText only when any previous text has\n * been entirely displayed.\n *\n * Dependencies: Status.java, CellTracker.java, Icon.java ( + others?)\n *\n */\n private void setNotification() {\n String tickerText;\n String contentText = \"Phone Type \" + mDevice.getPhoneType();\n\n if (mTypeZeroSmsDetected) {\n getApplication().setCurrentStatus(Status.DANGER, mVibrateEnabled, mVibrateMinThreatLevel);\n } else if (mChangedLAC) {\n getApplication().setCurrentStatus(Status.MEDIUM, mVibrateEnabled, mVibrateMinThreatLevel);\n contentText = context.getString(R.string.hostile_service_area_changing_lac_detected);\n } else if (mCellIdNotInOpenDb) {\n getApplication().setCurrentStatus(Status.MEDIUM, mVibrateEnabled, mVibrateMinThreatLevel);\n contentText = context.getString(R.string.cell_id_doesnt_exist_in_db);\n } else if (mTrackingCell || mMonitoringCell) {\n getApplication().setCurrentStatus(Status.OK, mVibrateEnabled, mVibrateMinThreatLevel);\n if (mTrackingCell) {\n contentText = context.getString(R.string.cell_tracking_active);\n } \n if (mMonitoringCell) {\n contentText = context.getString(R.string.cell_monitoring_active);\n } else {\n getApplication().setCurrentStatus(Status.IDLE, mVibrateEnabled, mVibrateMinThreatLevel);\n }\n } else {\n getApplication().setCurrentStatus(Status.IDLE, mVibrateEnabled, mVibrateMinThreatLevel);\n }\n\n\n Status status = getApplication().getStatus();\n switch (status) {\n case IDLE: // GRAY\n contentText = context.getString(R.string.phone_type) + mDevice.getPhoneType();\n tickerText = context.getResources().getString(R.string.app_name_short) + \" \" + context.getString(R.string.status_idle_description);\n break;\n\n case OK: // GREEN\n tickerText = context.getResources().getString(R.string.app_name_short) + \" \" + context.getString(R.string.status_ok_description);\n break;\n\n case MEDIUM: // YELLOW\n // Initialize tickerText as the app name string\n // See multiple detection comments above.\n tickerText = context.getResources().getString(R.string.app_name_short);\n if (mChangedLAC) {\n //Append changing LAC text\n contentText = context.getString(R.string.hostile_service_area_changing_lac_detected);\n tickerText += \" - \" + contentText;\n // See #264 and ask He3556\n //} else if (mNoNCList) {\n // tickerText += \" - BTS doesn't provide any neighbors!\";\n // contentText = \"CID: \" + cellid + \" is not providing a neighboring cell list!\";\n\n } else if (mCellIdNotInOpenDb) {\n //Append Cell ID not existing in external db text\n contentText = context.getString(R.string.cell_id_doesnt_exist_in_db);\n tickerText += \" - \" + contentText;\n }\n break;\n\n case DANGER: // RED\n tickerText = context.getResources().getString(R.string.app_name_short) + \" - \" + context.getString(R.string.alert_threat_detected); // Hmm, this is vague!\n if (mTypeZeroSmsDetected) {\n contentText = context.getString(R.string.alert_silent_sms_detected);\n }\n\n break;\n default:\n tickerText = context.getResources().getString(R.string.main_app_name);\n break;\n }\n\n // TODO: Explanation (see above)\n Intent notificationIntent = new Intent(context, MainActivity.class);\n notificationIntent.putExtra(\"silent_sms\", mTypeZeroSmsDetected);\n notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_FROM_BACKGROUND);\n\n PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);\n\n String iconType = prefs.getString(context.getString(R.string.pref_ui_icons_key), \"SENSE\").toUpperCase(Locale.US);\n int iconResId = Icon.getIcon(Icon.Type.valueOf(iconType), status);\n Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), iconResId);\n\n //int color = context.getResources().getColor(status.getColor());\n int color = ContextCompat.getColor(context, status.getColor());\n\n Notification mBuilder = new NotificationCompat.Builder(context)\n .setSmallIcon(R.drawable.tower48)\n .setColor(color)\n .setLargeIcon(largeIcon)\n .setTicker(tickerText)\n .setContentTitle(context.getString(R.string.status) + \" \" + context.getString(status.getName()))\n .setContentInfo(context.getResources().getString(R.string.app_name_short))\n .setContentText(contentText)\n .setOngoing(true)\n .setAutoCancel(false)\n .setContentIntent(contentIntent)\n .build();\n\n NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, mBuilder);\n\n }\n\n private AppAIMSICD getApplication() {\n return AppAIMSICD.getInstance();\n }\n\n /**\n * Vibrator helper method, will check current preferences (vibrator enabled, min threat level to vibrate)\n * and act appropriately\n */\n private void vibrate(int msec, Status threatLevel) {\n if (mVibrateEnabled && (threatLevel == null || threatLevel.ordinal() >= mVibrateMinThreatLevel)) {\n Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);\n v.vibrate(msec);\n }\n }\n\n //=================================================================================================\n // See issues: #6, #457, #489\n //\n // Summary: We can detect femtocells by other means, using network data that we already have!\n // The below code section was copied and modified with permission from\n // Femtocatcher at: https://github.com/iSECPartners/femtocatcher\n //\n //=================================================================================================\n\n // Removed!\n\n //=================================================================================================\n // END Femtocatcher code\n //=================================================================================================\n\n final PhoneStateListener phoneStatelistener = new PhoneStateListener() {\n private void handle() {\n handlePhoneStateChange();\n }\n @Override\n public void onServiceStateChanged(ServiceState serviceState) {\n handle();\n }\n @Override\n public void onDataConnectionStateChanged(int state) {\n handle();\n }\n @Override\n public void onDataConnectionStateChanged(int state, int networkType) {\n handle();\n }\n @Override\n public void onSignalStrengthsChanged(SignalStrength signalStrength) {\n handle();\n }\n @Override\n public void onCellInfoChanged(List<CellInfo> cellInfo) {\n handle();\n }\n\n @Override\n public void onCellLocationChanged(CellLocation location) {\n handle();\n }\n\n };\n\n /**\n * Used in SmsDetector.java\n */\n public Cell getMonitorCell() {\n return mMonitorCell;\n }\n\n\n}", "public class Cell implements Parcelable {\n\n public static final String TAG = \"AICDL\";\n public static final String mTAG = \"XXX\";\n\n public static final String INVALID_PSC = \"invalid\";\n\n // Cell Specific Variables\n private int cid; // Cell Identification code\n private int lac; // Location Area Code\n private int mcc; // Mobile Country Code\n private int mnc; // Mobile Network Code\n private int dbm; // [dBm] RX signal \"power\"\n private int psc; // Primary Scrambling Code\n private int rssi; // Relative Signal Strength Indicator [dBm, asu etc.]\n private int timingAdvance; // Timing Advance [LTE,GSM]\n private int sid; // Cell-ID for [CDMA]\n private long timestamp; // time\n\n // Tracked Cell Specific Variables\n private int netType;\n private double speed; //\n private double accuracy; //\n private double bearing; //\n private double lon;\n private double lat;\n\n {\n cid = Integer.MAX_VALUE;\n lac = Integer.MAX_VALUE;\n mcc = Integer.MAX_VALUE;\n mnc = Integer.MAX_VALUE;\n dbm = Integer.MAX_VALUE;\n psc = Integer.MAX_VALUE;\n rssi = Integer.MAX_VALUE;\n timingAdvance = Integer.MAX_VALUE;\n sid = Integer.MAX_VALUE;\n netType = Integer.MAX_VALUE;\n lon = 0.0;\n lat = 0.0;\n speed = 0.0;\n accuracy = 0.0;\n bearing = 0.0;\n }\n\n public Cell() {\n }\n\n public Cell(int cid, int lac, int mcc, int mnc, int dbm, long timestamp) {\n super();\n this.cid = cid;\n this.lac = lac;\n this.mcc = mcc;\n this.mnc = mnc;\n this.dbm = dbm;\n this.rssi = Integer.MAX_VALUE;\n this.psc = Integer.MAX_VALUE;\n this.timestamp = timestamp;\n this.timingAdvance = Integer.MAX_VALUE;\n this.sid = Integer.MAX_VALUE;\n this.netType = Integer.MAX_VALUE;\n this.lon = 0.0;\n this.lat = 0.0;\n this.speed = 0.0;\n this.accuracy = 0.0;\n this.bearing = 0.0;\n }\n\n public Cell(int cid, int lac, int signal, int psc, int netType, boolean dbm) {\n this.cid = cid;\n this.lac = lac;\n this.mcc = Integer.MAX_VALUE;\n this.mnc = Integer.MAX_VALUE;\n\n if (dbm) {\n this.dbm = signal;\n } else {\n this.rssi = signal;\n }\n this.psc = psc;\n\n this.netType = netType;\n this.timingAdvance = Integer.MAX_VALUE;\n this.sid = Integer.MAX_VALUE;\n this.lon = 0.0;\n this.lat = 0.0;\n this.speed = 0.0;\n this.accuracy = 0.0;\n this.bearing = 0.0;\n this.timestamp = SystemClock.currentThreadTimeMillis();\n }\n\n public Cell(int cid, int lac, int mcc, int mnc, int dbm, double accuracy, double speed,\n double bearing, int netType, long timestamp) {\n this.cid = cid;\n this.lac = lac;\n this.mcc = mcc;\n this.mnc = mnc;\n this.dbm = dbm;\n this.rssi = Integer.MAX_VALUE;\n this.timingAdvance = Integer.MAX_VALUE;\n this.sid = Integer.MAX_VALUE;\n this.accuracy = accuracy;\n this.speed = speed;\n this.bearing = bearing;\n this.netType = netType;\n this.timestamp = timestamp;\n }\n\n /**\n * Current Cell ID\n *\n * @return int representing the Cell ID from GSM or CDMA devices\n */\n public int getCID() {\n return this.cid;\n }\n\n /**\n * Sets current Cell ID\n *\n * @param cid Cell ID\n */\n public void setCID(int cid) {\n this.cid = cid;\n }\n\n /**\n * Location Area Code (LAC) of current Cell\n *\n * @return int Current cells Location Area Code\n */\n public int getLAC() {\n return this.lac;\n }\n\n /**\n * Set Location Area Code (LAC) of current Cell\n *\n * @param lac Location Area Code\n */\n public void setLAC(int lac) {\n this.lac = lac;\n }\n\n /**\n * Mobile Country Code (Mcc) of current Cell\n *\n * @return int Current cells Mobile Country Code\n */\n public int getMCC() {\n return this.mcc;\n }\n\n /**\n * Set Mobile Country Code (Mcc) of current Cell\n *\n * @param mcc Mobile Country Code\n */\n public void setMCC(int mcc) {\n this.mcc = mcc;\n }\n\n /**\n * Mobile Network Code (Mnc) of current Cell\n *\n * @return int Current cells Mobile Network Code\n */\n public int getMNC() {\n return this.mnc;\n }\n\n /**\n * Set Mobile Network Code (Mnc) of current Cell\n *\n * @param mnc Mobile Network Code\n */\n public void setMNC(int mnc) {\n this.mnc = mnc;\n }\n\n /**\n * Primary Scrambling Code (PSC) of current Cell\n *\n * @return int Current cells Primary Scrambling Code\n */\n public int getPSC() {\n return this.psc;\n }\n\n /**\n * Set Primary Scrambling Code (PSC) of current Cell\n *\n * @param psc Primary Scrambling Code\n */\n public void setPSC(int psc) {\n if (psc == -1) {\n this.psc = Integer.MAX_VALUE;\n } else {\n this.psc = psc;\n }\n }\n\n /**\n * Radio Access Technology (RAT)\n *\n * Some places in the app refers to this as the Network Type.\n *\n * For our purposes, network types displayed to the user is referred to as RAT.\n *\n * @return Current cell's Radio Access Technology (e.g. UMTS, GSM) or null if not known\n */\n public String getRAT() {\n return getRatFromInt(this.netType);\n }\n\n /**\n * CDMA System ID\n *\n * @return System ID or Integer.MAX_VALUE if not supported\n */\n public int getSID() {\n return this.sid;\n }\n\n /**\n * Set CDMA System ID (SID) of current Cell\n *\n * @param sid CDMA System ID\n */\n public void setSID(int sid) {\n this.sid = sid;\n }\n\n /**\n * Signal Strength Measurement (dBm)\n *\n * @return Signal Strength Measurement (dBm)\n */\n public int getDBM() {\n return dbm;\n }\n\n /**\n * Set Signal Strength (dBm) of current Cell\n *\n * @param dbm Signal Strength (dBm)\n */\n public void setDBM(int dbm) {\n this.dbm = dbm;\n }\n\n /**\n * Longitude Geolocation of current Cell\n *\n * @return Longitude\n */\n public double getLon() {\n return this.lon;\n }\n\n /**\n * Set Longitude Geolocation of current Cell\n *\n * @param lon Longitude\n */\n public void setLon(double lon) {\n this.lon = lon;\n }\n\n /**\n * Latitude Geolocation of current Cell\n *\n * @return Latitude\n */\n public double getLat() {\n return this.lat;\n }\n\n /**\n * Set Latitude Geolocation of current Cell\n *\n * @param lat Latitude\n */\n public void setLat(double lat) {\n this.lat = lat;\n }\n\n /**\n * Ground speed in metres/second\n *\n * @return Ground speed or 0.0 if unavailable\n */\n public double getSpeed() {\n return this.speed;\n }\n\n /**\n * Set current ground speed in metres/second\n *\n * @param speed Ground Speed\n */\n public void setSpeed(double speed) {\n this.speed = speed;\n }\n\n /**\n * Accuracy of location in metres\n *\n * @return Location accuracy in metres or 0.0 if unavailable\n */\n public double getAccuracy() {\n return this.accuracy;\n }\n\n /**\n * Set current location accuracy in metres\n *\n * @param accuracy Location accuracy\n */\n public void setAccuracy(double accuracy) {\n this.accuracy = accuracy;\n }\n\n /**\n * Set current Bearing\n *\n * @param bearing Current bearing\n */\n public void setBearing(double bearing) {\n this.bearing = bearing;\n }\n\n /**\n * LTE Timing Advance\n *\n * @return LTE Timing Advance or Integer.MAX_VALUE if unavailable\n */\n public int getTimingAdvance() {\n return this.timingAdvance;\n }\n\n /**\n * Set current LTE Timing Advance\n *\n * @param ta Current LTE Timing Advance\n */\n public void setTimingAdvance(int ta) {\n this.timingAdvance = ta;\n }\n\n /**\n * Network Type\n *\n * @return string representing device Network Type\n */\n public int getNetType() {\n return this.netType;\n }\n\n /**\n * Set current Network Type\n *\n * @param netType Current Network Type\n */\n public void setNetType(int netType) {\n this.netType = netType;\n }\n\n /**\n * Timestamp of current cell information\n *\n * @return Timestamp\n */\n public long getTimestamp() {\n return this.timestamp;\n }\n\n /**\n * Set current cell information timestamp\n *\n * @param timestamp Current cell information timestamp\n */\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n /**\n * Received Signal Strength\n *\n * @return Received Signal Strength Indicator (RSSI)\n */\n public int getRssi() {\n return this.rssi;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + cid;\n result = prime * result + lac;\n result = prime * result + mcc;\n result = prime * result + mnc;\n if (psc != -1) {\n result = prime * result + psc;\n }\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (((Object) this).getClass() != obj.getClass()) {\n return false;\n }\n Cell other = (Cell) obj;\n if (this.psc != Integer.MAX_VALUE) {\n return this.cid == other.getCID() && this.lac == other.getLAC() && this.mcc == other\n .getMCC() && this.mnc == other.getMNC() && this.psc == other.getPSC();\n } else {\n return this.cid == other.getCID() && this.lac == other.getLAC() && this.mcc == other\n .getMCC() && this.mnc == other.getMNC();\n }\n }\n\n public String toString() {\n StringBuilder result = new StringBuilder();\n\n result.append(\"CID - \").append(cid).append(\"\\n\");\n result.append(\"LAC - \").append(lac).append(\"\\n\");\n result.append(\"MCC - \").append(mcc).append(\"\\n\");\n result.append(\"MNC - \").append(mnc).append(\"\\n\");\n result.append(\"DBm - \").append(dbm).append(\"\\n\");\n result.append(\"PSC - \").append(validatePscValue(psc)).append(\"\\n\");\n result.append(\"Type - \").append(netType).append(\"\\n\");\n result.append(\"Lon - \").append(lon).append(\"\\n\");\n result.append(\"Lat - \").append(lat).append(\"\\n\");\n\n return result.toString();\n }\n\n public boolean isValid() {\n return this.getCID() != Integer.MAX_VALUE && this.getLAC() != Integer.MAX_VALUE;\n }\n\n /**\n * Get a human-readable string of RAT/Network Type\n *\n * Frustratingly it looks like the app uses RAT & Network Type interchangably with both either\n * being an integer representation (TelephonyManager's constants) or a human-readable string.\n *\n * @param netType The integer representation of the network type, via TelephonyManager\n * @return Human-readable representation of network type (e.g. \"EDGE\", \"LTE\")\n */\n public static String getRatFromInt(int netType) {\n switch (netType) {\n case TelephonyManager.NETWORK_TYPE_1xRTT:\n return \"1xRTT\";\n case TelephonyManager.NETWORK_TYPE_CDMA:\n return \"CDMA\";\n case TelephonyManager.NETWORK_TYPE_EDGE:\n return \"EDGE\";\n case TelephonyManager.NETWORK_TYPE_EHRPD:\n return \"eHRPD\";\n case TelephonyManager.NETWORK_TYPE_EVDO_0:\n return \"EVDO rev. 0\";\n case TelephonyManager.NETWORK_TYPE_EVDO_A:\n return \"EVDO rev. A\";\n case TelephonyManager.NETWORK_TYPE_EVDO_B:\n return \"EVDO rev. B\";\n case TelephonyManager.NETWORK_TYPE_GPRS:\n return \"GPRS\";\n case TelephonyManager.NETWORK_TYPE_HSDPA:\n return \"HSDPA\";\n case TelephonyManager.NETWORK_TYPE_HSPA:\n return \"HSPA\";\n case TelephonyManager.NETWORK_TYPE_HSPAP:\n return \"HSPA+\";\n case TelephonyManager.NETWORK_TYPE_HSUPA:\n return \"HSUPA\";\n case TelephonyManager.NETWORK_TYPE_IDEN:\n return \"iDen\";\n case TelephonyManager.NETWORK_TYPE_LTE:\n return \"LTE\";\n case TelephonyManager.NETWORK_TYPE_UMTS:\n return \"UMTS\";\n case TelephonyManager.NETWORK_TYPE_UNKNOWN:\n return \"Unknown\";\n default:\n return String.valueOf(netType);\n }\n }\n\n public static String validatePscValue(Context c, String psc) {\n return validatePscValue(c, Integer.parseInt(psc));\n }\n\n /**\n * Validate PSC is in bounds, return i18n'd \"Unknown\" if invalid\n *\n * @see #validatePscValue(int)\n *\n * @param c Used for getString translations\n * @param psc\n * @return PSC or \"Unknown \"if invalid\n */\n public static String validatePscValue(Context c, int psc) {\n String s = validatePscValue(psc);\n if (s.equals(INVALID_PSC)) {\n return c.getString(R.string.unknown);\n }\n return s;\n }\n\n public static String validatePscValue(String psc) {\n return validatePscValue(Integer.parseInt(psc));\n }\n\n /**\n * Validate PSC is in bounds\n *\n * Database import stores cell's PSC as \"666\" if its absent in OCID. This method will return\n * \"invalid\" instead.\n *\n * Use this method to translate/i18n a cell's missing PSC value.\n *\n * @param psc\n * @return PSC or \"invalid\" untranslated string if invalid\n */\n public static String validatePscValue(int psc) {\n if (psc < 0 || psc > 511) {\n return INVALID_PSC;\n }\n return String.valueOf(psc);\n }\n\n // Parcelling\n public Cell(Parcel in) {\n String[] data = new String[15];\n\n in.readStringArray(data);\n cid = Integer.valueOf(data[0]);\n lac = Integer.valueOf(data[1]);\n mcc = Integer.valueOf(data[2]);\n mnc = Integer.valueOf(data[3]);\n dbm = Integer.valueOf(data[4]);\n psc = Integer.valueOf(data[5]);\n rssi = Integer.valueOf(data[6]);\n timingAdvance = Integer.valueOf(data[7]);\n sid = Integer.valueOf(data[8]);\n netType = Integer.valueOf(data[9]);\n lon = Double.valueOf(data[10]);\n lat = Double.valueOf(data[11]);\n speed = Double.valueOf(data[12]);\n accuracy = Double.valueOf(data[13]);\n bearing = Double.valueOf(data[14]);\n }\n\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeStringArray(new String[]{\n String.valueOf(this.cid),\n String.valueOf(this.lac),\n String.valueOf(this.mcc),\n String.valueOf(this.mnc),\n String.valueOf(this.dbm),\n String.valueOf(this.psc),\n String.valueOf(this.rssi),\n String.valueOf(this.timingAdvance),\n String.valueOf(this.sid),\n String.valueOf(this.netType),\n String.valueOf(this.lon),\n String.valueOf(this.lat),\n String.valueOf(this.speed),\n String.valueOf(this.accuracy),\n String.valueOf(this.bearing)});\n }\n\n public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {\n public Cell createFromParcel(Parcel in) {\n return new Cell(in);\n }\n\n public Cell[] newArray(int size) {\n return new Cell[size];\n }\n };\n}", " public class Helpers {\n\n public static final String TAG = \"AICDL\";\n public static final String mTAG = \"Helpers: \";\n\n private static final int CHARS_PER_LINE = 34;\n\n /**\n * Description: Long toast message\n * Notes: A proxy method to the Toaster class. This also takes care of using the Toaster's Singleton.\n */\n public static void msgLong(Context context, String msg) {\n Toaster.msgLong(context, msg);\n }\n\n /**\n * Description: Short toast message\n * Notes: A proxy method to the Toaster class. This also takes care of using the Toaster's Singleton.\n */\n public static void msgShort(Context context, String msg) {\n Toaster.msgShort(context, msg);\n }\n\n /**\n * Description:\n */\n public static void sendMsg(Context context, String msg) {\n Toaster.msgLong(context, msg);\n }\n\n /**\n * Checks if Network connectivity is available to download OpenCellID data\n * Requires: android:name=\"android.permission.ACCESS_NETWORK_STATE\"\n */\n public static Boolean isNetAvailable(Context context) {\n try {\n ConnectivityManager cM = (ConnectivityManager)\n context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo wifiInfo = cM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);\n NetworkInfo mobileInfo = cM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);\n if (wifiInfo != null && mobileInfo != null) {\n return wifiInfo.isConnected() || mobileInfo.isConnected();\n }\n } catch (Exception e) {\n Log.e(TAG, mTAG + e.getMessage(), e);\n }\n return false;\n }\n\n /**\n * Description: Requests Cell data from OpenCellID.org (OCID).\n *\n * Notes:\n *\n * The free OCID API has a download limit of 1000 BTSs for each download.\n * Thus we need to carefully select the area we choose to download and make sure it is\n * centered on the current GPS location. (It is also possible to query the number of\n * cells in a particular bounding box (bbox), and use that.)\n *\n * The bbox is described in the OCID API here:\n * http://wiki.opencellid.org/wiki/API#Getting_the_list_of_cells_in_a_specified_area\n *\n * In an urban area, we could try to limit ourselves to an area radius of ~2 Km.\n * The (GSM) Timing Advance is limiting us to 35 Km.\n *\n * The OCID API payload:\n *\n * required: key=<apiKey>&BBOX=<latmin>,<lonmin>,<latmax>,<lonmax>\n * optional: &mcc=<mcc>&mnc=<mnc>&lac=<lac>&radio=<radio>\n * &limit=<limit>&offset=<offset>&format=<format>\n *\n * Our API query is using: (Lat1,Lon1, Lat2,Lon2, mcc,mnc,lac)\n *\n * Issues:\n *\n * [ ] A too restrictive payload leads to many missing BTS in area, but a too liberal\n * payload would return many less relevant ones and would cause us to reach the\n * OCID API 1000 BTS download limit much faster. The solution would be to make the\n * BBOX smaller, but that in turn, would result in the loss of some more distant,\n * but still available towers. Possibly making them appears as RED, even when they\n * are neither fake nor IMSI-catchers. However, a more realistic BTS picture is\n * more useful, especially when sharing that info across different devices using\n * on different RAT and MNO.\n *\n * [ ] We need a smarter way to handle the downloading of the BTS data. The OCID API\n * allows for finding how many cells are contained in a query. We can the use this\n * info to loop the max query size to get all those cells. The Query format is:\n *\n * GET: http://<WebServiceURL>/cell/getInAreaSize\n *\n * The OCID API payload:\n *\n * required: key=<apiKey>&BBOX=<latmin>,<lonmin>,<latmax>,<lonmax>\n * optional: &mcc=<mcc>&mnc=<mnc>&lac=<lac>&radio=<radio>&format=<format>\n *\n * result: JSON:\n * {\n * count: 123\n * }\n *\n * [x] Q: How is the BBOX actually calculated from the \"radius\"?\n * A: It's calculated as an inscribed circle to a square of 2*R on each side.\n * See ./utils/GeoLocation.java\n *\n * Dependencies: GeoLocation.java\n *\n * Used:\n * @param cell Current Cell Information\n *\n */\n public static void getOpenCellData(InjectionAppCompatActivity injectionActivity, Cell cell, char type) {\n getOpenCellData(injectionActivity, cell, type, null);\n }\n public static void getOpenCellData(InjectionAppCompatActivity injectionActivity, Cell cell, char type, final AimsicdService service) {\n if (Helpers.isNetAvailable(injectionActivity)) {\n if (!\"NA\".equals(CellTracker.OCID_API_KEY)) {\n double earthRadius = 6371.01; // [Km]\n int radius = 2; // [Km] // Use a 2 Km radius with center at GPS location.\n\n if (Double.doubleToRawLongBits(cell.getLat()) != 0 &&\n Double.doubleToRawLongBits(cell.getLon()) != 0) {\n //New GeoLocation object to find bounding Coordinates\n GeoLocation currentLoc = GeoLocation.fromDegrees(cell.getLat(), cell.getLon());\n\n //Calculate the Bounding Box Coordinates using an N Km \"radius\" //0=min, 1=max\n GeoLocation[] boundingCoords = currentLoc.boundingCoordinates(radius, earthRadius);\n String boundParameter;\n\n //Request OpenCellID data for Bounding Coordinates (0 = min, 1 = max)\n boundParameter = String.valueOf(boundingCoords[0].getLatitudeInDegrees()) + \",\"\n + String.valueOf(boundingCoords[0].getLongitudeInDegrees()) + \",\"\n + String.valueOf(boundingCoords[1].getLatitudeInDegrees()) + \",\"\n + String.valueOf(boundingCoords[1].getLongitudeInDegrees());\n\n Log.i(TAG, mTAG + \"OCID BBOX is set to: \" + boundParameter + \" with radius \" + radius + \" Km.\");\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"http://www.opencellid.org/cell/getInArea?key=\")\n .append(CellTracker.OCID_API_KEY).append(\"&BBOX=\")\n .append(boundParameter);\n\n Log.i(TAG, mTAG + \"OCID MCC is set to: \" + cell.getMCC());\n if (cell.getMCC() != Integer.MAX_VALUE) {\n sb.append(\"&mcc=\").append(cell.getMCC());\n }\n Log.i(TAG, mTAG + \"OCID MNC is set to: \" + cell.getMNC());\n if (cell.getMNC() != Integer.MAX_VALUE) {\n sb.append(\"&mnc=\").append(cell.getMNC());\n }\n\n sb.append(\"&format=csv\");\n new RequestTask(injectionActivity, type, new RequestTask.AsyncTaskCompleteListener() {\n @Override\n public void onAsyncTaskSucceeded() {\n Log.i(TAG, mTAG + \"RequestTask's OCID download was successful. Callback rechecking connected cell against database\");\n service.getCellTracker().compareLacAndOpenDb();\n }\n\n @Override\n public void onAsyncTaskFailed(String result) { }\n }).execute(sb.toString());\n }\n } else {\n Fragment myFragment = injectionActivity.getSupportFragmentManager().findFragmentByTag(String.valueOf(DrawerMenu.ID.MAIN.ALL_CURRENT_CELL_DETAILS));\n if (myFragment instanceof MapFragment) {\n ((MapFragment) myFragment).setRefreshActionButtonState(false);\n }\n Helpers.sendMsg(injectionActivity, injectionActivity.getString(zz.aimsicd.lite.R.string.no_opencellid_key_detected));\n }\n } else {\n Fragment myFragment = injectionActivity.getSupportFragmentManager().findFragmentByTag(String.valueOf(DrawerMenu.ID.MAIN.ALL_CURRENT_CELL_DETAILS));\n if (myFragment instanceof MapFragment) {\n ((MapFragment) myFragment).setRefreshActionButtonState(false);\n }\n\n final AlertDialog.Builder builder = new AlertDialog.Builder(injectionActivity);\n builder.setTitle(R.string.no_network_connection_title)\n .setMessage(R.string.no_network_connection_message);\n builder.create().show();\n }\n }\n\n /**\n * Return a String List representing response from invokeOemRilRequestRaw\n *\n * @param aob Byte array response from invokeOemRilRequestRaw\n */\n public static List<String> unpackByteListOfStrings(byte aob[]) {\n\n if (aob.length == 0) {\n // WARNING: This one is very chatty!\n Log.i(TAG, mTAG + \"invokeOemRilRequestRaw: byte-list response Length = 0\");\n return Collections.emptyList();\n }\n int lines = aob.length / CHARS_PER_LINE;\n String[] display = new String[lines];\n\n for (int i = 0; i < lines; i++) {\n int offset, byteCount;\n offset = i * CHARS_PER_LINE + 2;\n byteCount = 0;\n\n if (offset + byteCount >= aob.length) {\n Log.e(TAG, mTAG + \"Unexpected EOF\");\n break;\n }\n while (aob[offset + byteCount] != 0 && (byteCount < CHARS_PER_LINE)) {\n byteCount += 1;\n if (offset + byteCount >= aob.length) {\n Log.e(TAG, mTAG + \"Unexpected EOF\");\n break;\n }\n }\n display[i] = new String(aob, offset, byteCount).trim();\n }\n int newLength = display.length;\n while (newLength > 0 && TextUtils.isEmpty(display[newLength - 1])) {\n newLength -= 1;\n }\n return Arrays.asList(Arrays.copyOf(display, newLength));\n }\n\n public static String getSystemProp(Context context, String prop, String def) {\n String result = null;\n try {\n result = SystemPropertiesReflection.get(context, prop);\n } catch (IllegalArgumentException iae) {\n Log.e(TAG, mTAG + \"Failed to get system property: \" + prop, iae);\n }\n return result == null ? def : result;\n }\n\n public static String convertStreamToString(InputStream is) throws Exception {\n BufferedReader reader = new BufferedReader(new InputStreamReader(is));\n StringBuilder sb = new StringBuilder();\n String line;\n while ((line = reader.readLine()) != null) {\n sb.append(line).append(\"\\n\");\n }\n reader.close();\n return sb.toString();\n }\n\n /**\n * Description: Deletes the entire database by removing internal SQLite DB file\n *\n\n *\n * Dependencies: Used in AIMSICD.java\n *\n * Notes: See Android developer info: http://tinyurl.com/psz8vmt\n *\n * WARNING!\n * This deletes the entire database, thus any subsequent DB access will FC app.\n * Therefore we need to either restart app or run AIMSICDDbAdapter, to rebuild DB.\n * See: #581\n *\n * In addition, since SQLite is kept in memory during lifetime of App, and\n * is using Journaling, we have to restart app in order to clear old data\n * already in memory.\n *\n * @param pContext Context of Activity\n */\n public static void askAndDeleteDb(final Context pContext) {\n AlertDialog lAlertDialog = new AlertDialog.Builder(pContext)\n .setNegativeButton(zz.aimsicd.lite.R.string.open_cell_id_button_cancel, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n }\n })\n .setPositiveButton(R.string.open_cell_id_button_ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n // Probably put in try/catch in case file removal fails...\n pContext.stopService(new Intent(pContext, AimsicdService.class));\n pContext.deleteDatabase(\"aimsicd.db\");\n new AIMSICDDbAdapter(pContext);\n pContext.startService(new Intent(pContext, AimsicdService.class));\n msgLong(pContext, pContext.getString(R.string.delete_database_msg_success));\n }\n })\n .setMessage(pContext.getString(R.string.clear_database_question))\n .setTitle(R.string.clear_database)\n .setCancelable(false)\n .setIcon(R.drawable.ic_action_delete_database).create();\n lAlertDialog.show();\n }\n}" ]
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.text.TextUtils; import android.view.View; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TableRow; import android.widget.TextView; import android.support.v4.widget.SwipeRefreshLayout; import java.util.List; import java.util.concurrent.TimeUnit; import zz.aimsicd.lite.R; import zz.aimsicd.lite.adapters.BaseInflaterAdapter; import zz.aimsicd.lite.adapters.CardItemData; import zz.aimsicd.lite.adapters.CellCardInflater; import zz.aimsicd.lite.rilexecutor.RilExecutor; import zz.aimsicd.lite.service.AimsicdService; import zz.aimsicd.lite.service.CellTracker; import zz.aimsicd.lite.utils.Cell; import zz.aimsicd.lite.utils.Helpers; import io.freefair.android.injection.annotation.InjectView; import io.freefair.android.injection.annotation.XmlLayout; import io.freefair.android.injection.app.InjectionFragment;
/* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project * ----------------------------------------------------------- * LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o * ----------------------------------------------------------- */ /* This was introduced by Aussie in the Pull Request Commit: * https://github.com/xLaMbChOpSx/Android-IMSI-Catcher-Detector/commit/6d8719ab356a3ecbd0b526a9ded0cabb17ab2021 * * Where he writes: * "" * Advanced Cell Fragment added to display the Neighbouring Cell information in two ways firstly * through telephony manager methods which does not work on Samsung Devices, a fallback is available * through the methods developed by Alexey and will display if these are successful. * Ciphering Indicator also uses Alexey's methods and will display on Samsung devices. * "" */ package zz.aimsicd.lite.ui.fragments; /** * Description: This class updates the CellInfo fragment. This is also known as * the Neighboring Cells info, which is using the MultiRilClient to * show neighboring cells on the older Samsung Galaxy S2/3 series. * It's refresh rate is controlled in the settings by: * * arrays.xml: * pref_refresh_entries (the names) * pref_refresh_values (the values in seconds) * * * Dependencies: Seem that this is intimately connected to: CellTracker.java service... * * ToDo: * [ ] (1) Use an IF check, in order not to run the MultiRilClient on non supported devices * as this will cause excessive logcat spam. * [ ] (2) Might wanna make the refresh rate lower/higher depending on support * */ @XmlLayout(zz.aimsicd.lite.R.layout.fragment_cell_info) public class CellInfoFragment extends InjectionFragment implements SwipeRefreshLayout.OnRefreshListener { public static final int STOCK_REQUEST = 1; public static final int SAMSUNG_MULTIRIL_REQUEST = 2; private AimsicdService mAimsicdService; private RilExecutor rilExecutor; private boolean mBound; private Context mContext; private final Handler timerHandler = new Handler(); private List<Cell> neighboringCells; @InjectView(zz.aimsicd.lite.R.id.list_view) private ListView lv; @InjectView(zz.aimsicd.lite.R.id.swipeRefreshLayout) private SwipeRefreshLayout swipeRefreshLayout; private BaseInflaterAdapter<CardItemData> mBaseInflaterAdapter; private CellInfoAdapter mCellInfoAdapter; private final Runnable timerRunnable = new Runnable() { @Override public void run() { updateUI(); timerHandler.postDelayed(this, CellTracker.REFRESH_RATE); } }; @Override public void onPause() { super.onPause(); timerHandler.removeCallbacks(timerRunnable); } @Override public void onResume() { super.onResume(); if (!mBound) { // Bind to LocalService Intent intent = new Intent(mContext, AimsicdService.class); mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } // Refresh display if preference (pref_refresh_values) is not set to manual (0) // For automatic it is "1" and defined in: // CellTracker.java :: onSharedPreferenceChanged() if (CellTracker.REFRESH_RATE != 0) { timerHandler.postDelayed(timerRunnable, 0);
Helpers.msgShort(mContext, mContext.getString(zz.aimsicd.lite.R.string.refreshing_every) + " " +
7
ypresto/miniguava
miniguava-collect-immutables/src/main/java/net/ypresto/miniguava/collect/immutables/ImmutableList.java
[ "public static int checkElementIndex(int index, int size) {\n return checkElementIndex(index, size, \"index\");\n}", "public static void checkPositionIndexes(int start, int end, int size) {\n // Carefully optimized for execution by hotspot (explanatory comment above)\n if (start < 0 || end < start || end > size) {\n throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));\n }\n}", "static <T> T[] arraysCopyOf(T[] original, int newLength) {\n T[] copy = newArray(original, newLength);\n System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));\n return copy;\n}", "static Object[] checkElementsNotNull(Object... array) {\n return checkElementsNotNull(array, array.length);\n}", "static final ImmutableList<Object> EMPTY =\n new RegularImmutableList<Object>(ObjectArrays.EMPTY_ARRAY);", "public abstract class UnmodifiableIterator<E> implements Iterator<E> {\n /** Constructor for use by subclasses. */\n protected UnmodifiableIterator() {}\n\n /**\n * Guaranteed to throw an exception and leave the underlying data unmodified.\n *\n * @throws UnsupportedOperationException always\n * @deprecated Unsupported operation.\n */\n @Deprecated\n @Override\n public final void remove() {\n throw new UnsupportedOperationException();\n }\n}", "public abstract class UnmodifiableListIterator<E> extends UnmodifiableIterator<E>\n implements ListIterator<E> {\n /** Constructor for use by subclasses. */\n protected UnmodifiableListIterator() {}\n\n /**\n * Guaranteed to throw an exception and leave the underlying data unmodified.\n *\n * @throws UnsupportedOperationException always\n * @deprecated Unsupported operation.\n */\n @Deprecated\n @Override\n public final void add(E e) {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Guaranteed to throw an exception and leave the underlying data unmodified.\n *\n * @throws UnsupportedOperationException always\n * @deprecated Unsupported operation.\n */\n @Deprecated\n @Override\n public final void set(E e) {\n throw new UnsupportedOperationException();\n }\n}", "@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.MOVED, from = \"collect package\")\npublic abstract class AbstractIndexedListIterator<E> extends UnmodifiableListIterator<E> {\n private final int size;\n private int position;\n\n /**\n * Returns the element with the specified index. This method is called by\n * {@link #next()}.\n */\n protected abstract E get(int index);\n\n /**\n * Constructs an iterator across a sequence of the given size whose initial\n * position is 0. That is, the first call to {@link #next()} will return the\n * first element (or throw {@link NoSuchElementException} if {@code size} is\n * zero).\n *\n * @throws IllegalArgumentException if {@code size} is negative\n */\n protected AbstractIndexedListIterator(int size) {\n this(size, 0);\n }\n\n /**\n * Constructs an iterator across a sequence of the given size with the given\n * initial position. That is, the first call to {@link #nextIndex()} will\n * return {@code position}, and the first call to {@link #next()} will return\n * the element at that index, if available. Calls to {@link #previous()} can\n * retrieve the preceding {@code position} elements.\n *\n * @throws IndexOutOfBoundsException if {@code position} is negative or is\n * greater than {@code size}\n * @throws IllegalArgumentException if {@code size} is negative\n */\n protected AbstractIndexedListIterator(int size, int position) {\n checkPositionIndex(position, size);\n this.size = size;\n this.position = position;\n }\n\n @Override\n public final boolean hasNext() {\n return position < size;\n }\n\n @Override\n public final E next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return get(position++);\n }\n\n @Override\n public final int nextIndex() {\n return position;\n }\n\n @Override\n public final boolean hasPrevious() {\n return position > 0;\n }\n\n @Override\n public final E previous() {\n if (!hasPrevious()) {\n throw new NoSuchElementException();\n }\n return get(--position);\n }\n\n @Override\n public final int previousIndex() {\n return position - 1;\n }\n}" ]
import java.util.Collections; import java.util.List; import java.util.RandomAccess; import javax.annotation.Nullable; import static net.ypresto.miniguava.base.Preconditions.checkElementIndex; import static net.ypresto.miniguava.base.Preconditions.checkPositionIndexes; import static net.ypresto.miniguava.collect.immutables.ObjectArrays.arraysCopyOf; import static net.ypresto.miniguava.collect.immutables.ObjectArrays.checkElementsNotNull; import static net.ypresto.miniguava.collect.immutables.RegularImmutableList.EMPTY; import net.ypresto.miniguava.collect.UnmodifiableIterator; import net.ypresto.miniguava.collect.UnmodifiableListIterator; import net.ypresto.miniguava.collect.internal.AbstractIndexedListIterator; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.Collection;
/* * Copyright (C) 2007 The Guava Authors * * 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 net.ypresto.miniguava.collect.immutables; /** * A {@link List} whose contents will never change, with many other important properties detailed at * {@link ImmutableCollection}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> * immutable collections</a>. * * @see ImmutableMap * @see ImmutableSet * @author Kevin Bourrillion * @since 2.0 */ // miniguava: Removed copyOf(Iterable) and copyOf(Iterator). @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableList<E> extends ImmutableCollection<E> implements List<E>, RandomAccess { /** * Returns the empty immutable list. This set behaves and performs comparably * to {@link Collections#emptyList}, and is preferable mainly for consistency * and maintainability of your code. */ // Casting to any type is safe because the list will never hold any elements. @SuppressWarnings("unchecked") public static <E> ImmutableList<E> of() { return (ImmutableList<E>) EMPTY; } /** * Returns an immutable list containing a single element. This list behaves * and performs comparably to {@link Collections#singleton}, but will not * accept a null element. It is preferable mainly for consistency and * maintainability of your code. * * @throws NullPointerException if {@code element} is null */ public static <E> ImmutableList<E> of(E element) { return new SingletonImmutableList<E>(element); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2) { return construct(e1, e2); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3) { return construct(e1, e2, e3); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) { return construct(e1, e2, e3, e4); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) { return construct(e1, e2, e3, e4, e5); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6) { return construct(e1, e2, e3, e4, e5, e6); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) { return construct(e1, e2, e3, e4, e5, e6, e7); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) { return construct(e1, e2, e3, e4, e5, e6, e7, e8); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) { return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) { return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11) { return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); } // These go up to eleven. After that, you just get the varargs form, and // whatever warnings might come along with it. :( /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any element is null * @since 3.0 (source-compatible since 2.0) */ public static <E> ImmutableList<E> of( E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10, E e11, E e12, E... others) { Object[] array = new Object[12 + others.length]; array[0] = e1; array[1] = e2; array[2] = e3; array[3] = e4; array[4] = e5; array[5] = e6; array[6] = e7; array[7] = e8; array[8] = e9; array[9] = e10; array[10] = e11; array[11] = e12; System.arraycopy(others, 0, array, 12, others.length); return construct(array); } /** * Returns an immutable list containing the given elements, in order. * * <p>Despite the method name, this method attempts to avoid actually copying * the data when it is safe to do so. The exact circumstances under which a * copy will or will not be performed are undocumented and subject to change. * * <p>Note that if {@code list} is a {@code List<String>}, then {@code * ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>} * containing each of the strings in {@code list}, while * ImmutableList.of(list)} returns an {@code ImmutableList<List<String>>} * containing one element (the given list itself). * * <p>This method is safe to use even when {@code elements} is a synchronized * or concurrent collection that is currently being modified by another * thread. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableList<E> copyOf(Collection<? extends E> elements) { if (elements instanceof ImmutableCollection) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableList<E> list = ((ImmutableCollection<E>) elements).asList(); return list.isPartialView() ? ImmutableList.<E>asImmutableList(list.toArray()) : list; } return construct(elements.toArray()); } /** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any of {@code elements} is null * @since 3.0 */ public static <E> ImmutableList<E> copyOf(E[] elements) { switch (elements.length) { case 0: return ImmutableList.of(); case 1: return new SingletonImmutableList<E>(elements[0]); default: return new RegularImmutableList<E>(checkElementsNotNull(elements.clone())); } } /** * Views the array as an immutable list. Checks for nulls; does not copy. */ private static <E> ImmutableList<E> construct(Object... elements) { return asImmutableList(checkElementsNotNull(elements)); } /** * Views the array as an immutable list. Does not check for nulls; does not copy. * * <p>The array must be internally created. */ static <E> ImmutableList<E> asImmutableList(Object[] elements) { return asImmutableList(elements, elements.length); } /** * Views the array as an immutable list. Copies if the specified range does not cover the complete * array. Does not check for nulls. */ static <E> ImmutableList<E> asImmutableList(Object[] elements, int length) { switch (length) { case 0: return of(); case 1: @SuppressWarnings("unchecked") // collection had only Es in it ImmutableList<E> list = new SingletonImmutableList<E>((E) elements[0]); return list; default: if (length < elements.length) {
elements = arraysCopyOf(elements, length);
2
atolcd/alfresco-audit-share
audit-share-platform/src/main/java/com/atolcd/alfresco/repo/jscript/ShareStats.java
[ "public class AtolVolumetryEntry {\n\tprivate long id = 0;\n\tprivate String siteId = \"\";\n\tprivate long siteSize = 0;\n\tprivate int folderCount = 0;\n\tprivate int fileCount = 0;\n\tprivate long atTime = 0;\n\n\tpublic AtolVolumetryEntry() {\n\t}\n\n\tpublic AtolVolumetryEntry(String siteId, long siteSize, int folderCount, int fileCount, long atTime) {\n\t\tthis.siteId = siteId;\n\t\tthis.siteSize = siteSize;\n\t\tthis.folderCount = folderCount;\n\t\tthis.fileCount = fileCount;\n\t\tthis.atTime = atTime;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getSiteId() {\n\t\treturn siteId;\n\t}\n\n\tpublic void setSiteId(String siteId) {\n\t\tthis.siteId = siteId;\n\t}\n\n\tpublic long getSiteSize() {\n\t\treturn siteSize;\n\t}\n\n\tpublic void setSiteSize(long siteSize) {\n\t\tthis.siteSize = siteSize;\n\t}\n\n\tpublic int getFolderCount() {\n\t\treturn folderCount;\n\t}\n\n\tpublic void setFolderCount(int folderCount) {\n\t\tthis.folderCount = folderCount;\n\t}\n\n\tpublic int getFileCount() {\n\t\treturn fileCount;\n\t}\n\n\tpublic void setFileCount(int fileCount) {\n\t\tthis.fileCount = fileCount;\n\t}\n\n\tpublic long getAtTime() {\n\t\treturn atTime;\n\t}\n\n\tpublic void setAtTime(long atTime) {\n\t\tthis.atTime = atTime;\n\t}\n}", "public class AuditQueryParameters {\n private String siteId;\n private List<String> sitesId;\n private String appName;\n private List<String> appNames;\n private String actionName;\n private List<String> actionNames;\n private String object;\n private long dateFrom;\n private long dateTo;\n private String slicedDates;\n private String userId;\n private List<String> userIds;\n private int limit;\n private String nodeType;\n private List<String> nodeTypes;\n private List<String> groupsMembers;\n\n public AuditQueryParameters() {\n siteId = null;\n sitesId = null;\n appName = null;\n appNames = null;\n actionName = null;\n actionNames = null;\n object = null;\n dateFrom = 0;\n dateTo = 0;\n slicedDates = null;\n userId = null;\n userIds = null;\n nodeType = null;\n nodeTypes = null;\n groupsMembers = null;\n }\n\n public String getSlicedDates() {\n return slicedDates;\n }\n\n public void setSlicedDates(String slicedDates) {\n this.slicedDates = slicedDates;\n }\n\n public List<String> getSitesId() {\n return sitesId;\n }\n\n public void setSitesId(List<String> sitesId) {\n if (sitesId == null || sitesId.isEmpty()) {\n this.sitesId = null;\n } else {\n this.sitesId = sitesId;\n }\n }\n\n public void setSitesId(String sitesId) {\n if (sitesId != null) {\n String[] sitesToken = sitesId.split(\",\");\n this.sitesId = new ArrayList<String>(sitesToken.length);\n for (String token : sitesToken) {\n this.sitesId.add(token);\n }\n }\n }\n\n public String getSiteId() {\n return siteId;\n }\n\n public void setSiteId(String siteId) {\n this.siteId = siteId;\n }\n\n public String getAppName() {\n return appName;\n }\n\n public void setAppName(String appName) {\n this.appName = appName;\n }\n\n public List<String> getAppNames() {\n return appNames;\n }\n\n public void setAppNames(String appNames) {\n if (appNames != null) {\n String[] appNamesToken = appNames.split(\",\");\n this.appNames = new ArrayList<String>(appNamesToken.length);\n for (String token : appNamesToken) {\n this.appNames.add(token);\n }\n }\n }\n\n public String getActionName() {\n return actionName;\n }\n\n public void setActionName(String actionName) {\n this.actionName = actionName;\n }\n\n public List<String> getActionNames() {\n return actionNames;\n }\n\n public void setActionNames(String actionNames) {\n if (actionNames != null) {\n String[] actionNamesToken = actionNames.split(\",\");\n this.actionNames = new ArrayList<String>(actionNamesToken.length);\n for (String token : actionNamesToken) {\n this.actionNames.add(token);\n }\n }\n }\n\n public String getUserId() {\n return userId;\n }\n\n public void setUserId(String userId) {\n this.userId = userId;\n }\n\n public List<String> getUserIds() {\n return userIds;\n }\n\n public void setUserIds(String userIds) {\n if (userIds != null) {\n String[] userIdsToken = userIds.split(\",\");\n this.userIds = new ArrayList<String>(userIdsToken.length);\n for (String token : userIdsToken) {\n this.userIds.add(token);\n }\n }\n }\n\n public long getDateFrom() {\n return dateFrom;\n }\n\n public void setDateFrom(long dateFrom) {\n this.dateFrom = dateFrom;\n }\n\n public void setDateFrom(String dateFrom) {\n if (dateFrom == null || \"\".equals(dateFrom)) {\n this.dateFrom = 0;\n } else {\n this.dateFrom = Long.parseLong(dateFrom);\n }\n }\n\n public long getDateTo() {\n return dateTo;\n }\n\n public void setDateTo(long dateTo) {\n this.dateTo = dateTo;\n }\n\n public void setDateTo(String dateTo) {\n if (dateTo == null || \"\".equals(dateTo)) {\n this.dateTo = 0;\n } else {\n this.dateTo = Long.parseLong(dateTo);\n }\n }\n\n public String getObject() {\n return object;\n }\n\n public void setObject(String object) {\n this.object = object;\n }\n\n public int getLimit() {\n return limit;\n }\n\n public void setLimit(int limit) {\n this.limit = limit;\n }\n\n public String getNodeType() {\n return nodeType;\n }\n\n public void setNodeType(String nodeType) {\n this.nodeType = nodeType;\n }\n\n public List<String> getNodeTypes() {\n return nodeTypes;\n }\n\n public void setNodeTypes(List<String> nodeTypes) {\n if (nodeTypes == null || nodeTypes.isEmpty()) {\n this.nodeTypes = null;\n } else {\n this.nodeTypes = nodeTypes;\n }\n }\n\n public void setNodeTypes(String nodeTypes) {\n if (nodeTypes != null) {\n String[] nodeTypesToken = nodeTypes.split(\",\");\n this.nodeTypes = new ArrayList<String>(nodeTypesToken.length);\n for (String token : nodeTypesToken) {\n this.nodeTypes.add(token);\n }\n }\n }\n\n public List<String> getGroupsMembers() {\n return groupsMembers;\n }\n\n public void setGroupsMembers(List<String> groupsMembers) {\n if (groupsMembers == null || groupsMembers.isEmpty()) {\n this.groupsMembers = Collections.emptyList();\n } else {\n this.groupsMembers = groupsMembers;\n }\n }\n\n public void setGroupsMembers(String groupsMembers) {\n if (groupsMembers != null) {\n String[] groupsMembersToken = groupsMembers.split(\",\");\n this.groupsMembers = new ArrayList<String>(groupsMembersToken.length);\n for (String token : groupsMembersToken) {\n this.groupsMembers.add(token);\n }\n }\n }\n\n public String toJSON() throws JSONException {\n JSONObject jsonResult = new JSONObject();\n jsonResult.put(\"siteId\", siteId);\n jsonResult.put(\"sitesId\", sitesId);\n jsonResult.put(\"appName\", appName);\n jsonResult.put(\"appNames\", appNames);\n jsonResult.put(\"actionName\", actionName);\n jsonResult.put(\"actionNames\", actionNames);\n jsonResult.put(\"object\", object);\n jsonResult.put(\"userId\", userId);\n jsonResult.put(\"userIds\", userIds);\n jsonResult.put(\"dateFrom\", Long.toString(dateFrom));\n jsonResult.put(\"dateTo\", Long.toString(dateTo));\n jsonResult.put(\"slicedDates\", slicedDates);\n jsonResult.put(\"limit\", Integer.toString(limit));\n jsonResult.put(\"nodeType\", nodeType);\n jsonResult.put(\"nodeTypes\", nodeTypes);\n jsonResult.put(\"groupsMembers\", groupsMembers);\n\n return jsonResult.toString();\n }\n}", "public class InsertAuditPost extends DeclarativeWebScript implements InitializingBean {\n public static final String INSERT_ENTRY = \"alfresco.atolcd.audit.insert.insertEntry\";\n public static final String INSERT_VOLUMETRY = \"alfresco.atolcd.audit.insert.insertVolumetry\";\n public static final String INSERT_VOLUMETRY_MULTI = \"alfresco.atolcd.audit.insert.insertVolumetryMulti\";\n\n private static final String SITE_TO_FIND = \"/service\";\n public static final String SITE_REPOSITORY = \"_repository\";\n private static final String MODEL_SUCCESS = \"success\";\n\n // SqlMapClientTemplate for MyBatis calls\n private SqlSessionTemplate sqlSessionTemplate;\n private SiteService siteService;\n private NodeService nodeService;\n private NamespaceService namespaceService;\n\n private static final Log logger = LogFactory.getLog(InsertAuditPost.class);\n\n public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {\n this.sqlSessionTemplate = sqlSessionTemplate;\n }\n\n public void setSiteService(SiteService siteService) {\n this.siteService = siteService;\n }\n\n public void setNodeService(NodeService nodeService) {\n this.nodeService = nodeService;\n }\n\n public void setNamespaceService(NamespaceService namespaceService) {\n this.namespaceService = namespaceService;\n }\n\n @Override\n public void afterPropertiesSet() throws Exception {\n Assert.notNull(this.sqlSessionTemplate);\n Assert.notNull(this.nodeService);\n Assert.notNull(this.siteService);\n Assert.notNull(this.namespaceService);\n }\n\n @Override\n protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {\n // Map that will be passed to the template\n Map<String, Object> model = new HashMap<String, Object>();\n model.put(MODEL_SUCCESS, false);\n try {\n // Check for the sqlMapClientTemplate Bean\n if (this.sqlSessionTemplate != null) {\n // Get the input content given into the request.\n String jsonArg = req.getContent().getContent();\n\n if (!jsonArg.isEmpty()) {\n // Fill an auditSample from the request content and insert\n // it\n AuditEntry auditSample = new AuditEntry(jsonArg);\n getSiteFromObject(auditSample);\n String myAuditNodeType = auditSample.getAuditNodeType();\n\n // Retrieving the node type when it does not already exists\n if (myAuditNodeType == null || myAuditNodeType.isEmpty()) {\n auditSample.setAuditNodeType(getTypeFromObject(auditSample));\n }\n\n if (logger.isInfoEnabled()) {\n logger.info(auditSample.toJSON());\n }\n\n insert(auditSample);\n model.put(MODEL_SUCCESS, true);\n }\n }\n } catch (InvalidNodeRefException invalidNodeRefException) {\n if (logger.isWarnEnabled()) {\n logger.warn(invalidNodeRefException);\n }\n } catch (Exception e) {\n if (logger.isDebugEnabled()) {\n logger.debug(e.getMessage(), e);\n }\n throw new WebScriptException(\"[ShareStats-DbInsert] Error in executeImpl function\");\n }\n return model;\n }\n\n public void insert(AuditEntry auditSample) throws SQLException, JSONException {\n if (!auditSample.getAuditSite().isEmpty()) {\n sqlSessionTemplate.insert(INSERT_ENTRY, auditSample);\n logger.info(\"Entry successfully inserted: \" + auditSample.toJSON());\n }\n }\n\n public String getTypeFromObject(AuditEntry auditSample) {\n try {\n String myAuditObject = auditSample.getAuditObject();\n if (myAuditObject != null && !myAuditObject.isEmpty()) {\n NodeRef nodeRef = new NodeRef(myAuditObject);\n if (this.nodeService.exists(nodeRef)) {\n return this.nodeService.getType(nodeRef).toPrefixString(this.namespaceService);\n }\n }\n } catch (MalformedNodeRefException e) {\n if (logger.isTraceEnabled()) {\n logger.trace(e);\n }\n }\n\n // Default value: cm:content\n return ContentModel.TYPE_CONTENT.toPrefixString(this.namespaceService);\n }\n\n public void getSiteFromObject(AuditEntry auditSample) {\n // Even if we are into the repository, we try to find the site of the\n // document\n if (auditSample.getAuditSite().equals(SITE_TO_FIND)) {\n SiteInfo siteInfo = null;\n try {\n NodeRef nodeRef = new NodeRef(auditSample.getAuditObject());\n siteInfo = siteService.getSite(nodeRef);\n } catch (Exception e) {\n if (logger.isDebugEnabled()) {\n logger.debug(e.getMessage(), e);\n }\n }\n\n if (siteInfo != null) {\n auditSample.setAuditSite(siteInfo.getShortName());\n } else {\n auditSample.setAuditSite(SITE_REPOSITORY);\n }\n }\n }\n\n public void insertVolumetry(AtolVolumetryEntry atolVolumetryEntry) {\n sqlSessionTemplate.insert(INSERT_VOLUMETRY, atolVolumetryEntry);\n logger.info(\"Volumetry entry successfully inserted.\");\n }\n\n public void insertVolumetryMulti(List<AtolVolumetryEntry> atolVolumetryEntry) {\n sqlSessionTemplate.insert(INSERT_VOLUMETRY_MULTI, atolVolumetryEntry);\n logger.info(\"Volumetry entry successfully inserted.\");\n }\n}", "public class SelectAuditsGet extends DeclarativeWebScript implements InitializingBean {\n // Logger\n private static final Log logger = LogFactory.getLog(SelectAuditsGet.class);\n\n // SqlMapClientTemplate for MyBatis calls\n private SqlSessionTemplate sqlSessionTemplate;\n private NodeService nodeService;\n private SiteService siteService;\n private int limitMostReadOrUpdate;\n\n public static final String SELECT_BY_VIEW = \"alfresco.atolcd.audit.selectByRead\";\n public static final String SELECT_BY_CREATED = \"alfresco.atolcd.audit.selectByCreated\";\n public static final String SELECT_BY_UPDATED = \"alfresco.atolcd.audit.selectByUpdated\";\n public static final String SELECT_BY_DELETED = \"alfresco.atolcd.audit.selectByDeleted\";\n public static final String SELECT_BY_MOSTREAD = \"alfresco.atolcd.audit.special-queries.selectByMostRead\";\n public static final String SELECT_BY_MOSTUPDATED = \"alfresco.atolcd.audit.special-queries.selectByMostUpdated\";\n public static final String SELECT_TO_UPDATE = \"alfresco.atolcd.audit.selectEntriesToUpdate\";\n\n static final QName TYPE_DATALIST = QName.createQName(\"http://www.alfresco.org/model/datalist/1.0\", \"dataList\");\n static final QName TYPE_CALENDAR_EVENT = QName.createQName(\"http://www.alfresco.org/model/calendar\", \"calendarEvent\");\n static final QName PROP_CALENDAR_EVENT_WHAT = QName.createQName(\"http://www.alfresco.org/model/calendar\", \"whatEvent\");\n static final QName TYPE_LINK = QName.createQName(\"http://www.alfresco.org/model/linksmodel/1.0\", \"link\");\n static final QName PROP_LINK_TITLE = QName.createQName(\"http://www.alfresco.org/model/linksmodel/1.0\", \"title\");\n\n static final String MODEL_DATES_VARIABLE = \"dates\";\n static final String MODEL_POPULARITY_VARIABLE = \"popularity\";\n\n public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {\n this.sqlSessionTemplate = sqlSessionTemplate;\n }\n\n public void setNodeService(NodeService nodeService) {\n this.nodeService = nodeService;\n }\n\n public void setSiteService(SiteService siteService) {\n this.siteService = siteService;\n }\n\n public int getLimitMostReadOrUpdate() {\n return limitMostReadOrUpdate;\n }\n\n public void setLimitMostReadOrUpdate(int limitMostReadOrUpdate) {\n this.limitMostReadOrUpdate = limitMostReadOrUpdate;\n }\n\n @Override\n public void afterPropertiesSet() throws Exception {\n Assert.notNull(this.sqlSessionTemplate);\n Assert.notNull(this.nodeService);\n }\n\n @Override\n protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {\n try {\n Map<String, Object> model = new HashMap<String, Object>();\n if (PermissionsHelper.isAuthorized(req)) {\n // Check for the sqlMapClientTemplate Bean\n if (this.sqlSessionTemplate != null) {\n // Get the input content given into the request.\n AuditQueryParameters params = buildParametersFromRequest(req);\n String type = req.getParameter(\"type\");\n String stringLimit = req.getParameter(\"limit\");\n\n //Check if limit exist\n if (stringLimit != null && !stringLimit.isEmpty()) {\n this.limitMostReadOrUpdate = Integer.parseInt(stringLimit);\n }\n\n params.setLimit(limitMostReadOrUpdate);\n\n if (logger.isInfoEnabled()) {\n logger.info(params.toJSON());\n }\n\n checkForQuery(model, params, type);\n }\n } else {\n status.setCode(Status.STATUS_UNAUTHORIZED);\n }\n\n return model;\n } catch (Exception e) {\n if (logger.isDebugEnabled()) {\n logger.debug(e.getMessage(), e);\n }\n throw new WebScriptException(\"[ShareStats - SelectAudits] Error in executeImpl function\");\n }\n }\n\n public void checkForQuery(Map<String, Object> model, AuditQueryParameters params, String type) throws SQLException,\n JSONException {\n switch (queryType.valueOf(type)) {\n case read:\n model.put(MODEL_DATES_VARIABLE, selectByDate(params, SELECT_BY_VIEW));\n break;\n case created:\n model.put(MODEL_DATES_VARIABLE, selectByDate(params, SELECT_BY_CREATED));\n break;\n case deleted:\n model.put(MODEL_DATES_VARIABLE, selectByDate(params, SELECT_BY_DELETED));\n break;\n case updated:\n model.put(MODEL_DATES_VARIABLE, selectByDate(params, SELECT_BY_UPDATED));\n break;\n case mostread:\n model.put(MODEL_POPULARITY_VARIABLE, selectByPopularity(params, SELECT_BY_MOSTREAD));\n break;\n case mostupdated:\n default:\n model.put(MODEL_POPULARITY_VARIABLE, selectByPopularity(params, SELECT_BY_MOSTUPDATED));\n break;\n }\n }\n\n public List<AuditObjectPopularity> selectByPopularity(AuditQueryParameters params, String query) {\n List<AuditObjectPopularity> auditObjectPopularityList = sqlSessionTemplate.selectList(query, params);\n logger.info(\"Performing \" + query + \" ... \");\n\n Iterator<AuditObjectPopularity> iterator = auditObjectPopularityList.iterator();\n // Verify if the returned items always exist\n while (iterator.hasNext()) {\n AuditObjectPopularity auditObjectPopularity = iterator.next();\n try {\n NodeRef nodeRef = new NodeRef(auditObjectPopularity.getAuditObject());\n if (!nodeService.exists(nodeRef)) {\n iterator.remove();\n } else {\n auditObjectPopularity.setObjectName((String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME));\n auditObjectPopularity.setObjectDisplayName(getPrettyDisplayname(nodeRef));\n\n SiteInfo si = siteService.getSite(nodeRef);\n if (si != null) {\n // Find in which site component is this node\n Path nodePath = nodeService.getPath(nodeRef);\n if (nodePath.size() > 4) {\n String siteContainerQName = nodeService.getPath(nodeRef).get(4).getElementString();\n auditObjectPopularity.setSiteComponent(QName.createQName(siteContainerQName).getLocalName());\n }\n }\n\n }\n } catch (AlfrescoRuntimeException e) {\n iterator.remove();\n logger.warn(e.getMessage(), e);\n }\n }\n\n return auditObjectPopularityList;\n }\n\n public List<List<AuditCount>> selectByDate(AuditQueryParameters params, String query) {\n String[] dates = params.getSlicedDates().split(\",\");\n List<List<AuditCount>> auditCount = new ArrayList<List<AuditCount>>();\n for (int i = 0; i < dates.length - 1; i++) {\n params.setDateFrom(dates[i]);\n params.setDateTo(dates[i + 1]);\n List<AuditCount> auditSample = sqlSessionTemplate.selectList(query, params);\n auditCount.add(auditSample);\n }\n logger.info(\"Performing \" + query + \" ... \");\n return auditCount;\n }\n\n public List<AuditEntry> selectEntriesToUpdate() {\n return sqlSessionTemplate.selectList(SELECT_TO_UPDATE);\n }\n\n public AuditQueryParameters buildParametersFromRequest(WebScriptRequest req) {\n try {\n String dateFrom = req.getParameter(\"from\");\n String dateTo = req.getParameter(\"to\");\n\n AuditQueryParameters params = new AuditQueryParameters();\n params.setSiteId(req.getParameter(\"site\"));\n\n String sites = req.getParameter(\"sites\");\n if (\"*\".equals(sites)) {\n params.setSitesId(PermissionsHelper.getUserSites());\n } else {\n params.setSitesId(sites);\n }\n\n params.setActionName(req.getParameter(\"action\"));\n params.setAppName(req.getParameter(\"module\"));\n params.setAppNames(req.getParameter(\"modules\"));\n params.setDateFrom(dateFrom);\n params.setDateTo(dateTo);\n params.setSlicedDates(req.getParameter(\"dates\"));\n params.setNodeType(req.getParameter(\"nodeType\"));\n params.setNodeTypes(req.getParameter(\"nodeTypes\"));\n return params;\n } catch (Exception e) {\n logger.error(\"Error building parameters\", e);\n return null;\n }\n }\n\n private String getPrettyDisplayname(NodeRef nodeRef) {\n String nodeName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);\n\n QName nodeType = nodeService.getType(nodeRef);\n if (nodeType.equals(TYPE_DATALIST)) {\n // DataList: use title\n return (String) nodeService.getProperty(nodeRef, ContentModel.PROP_TITLE);\n } else if (nodeType.equals(ForumModel.TYPE_TOPIC)) {\n // Discussion: find first child that have the same name\n NodeRef firstTopic = nodeService.getChildByName(nodeRef, ContentModel.ASSOC_CONTAINS, nodeName);\n if (firstTopic != null) {\n return (String) nodeService.getProperty(firstTopic, ContentModel.PROP_TITLE);\n }\n } else if (nodeType.equals(TYPE_LINK)) {\n // Link: use link title\n return (String) nodeService.getProperty(nodeRef, PROP_LINK_TITLE);\n } else if (nodeType.equals(TYPE_CALENDAR_EVENT)) {\n // Event: use 'what' metadata\n return (String) nodeService.getProperty(nodeRef, PROP_CALENDAR_EVENT_WHAT);\n } else {\n // Others: content, wiki, blog\n NodeRef parentRef = nodeService.getPrimaryParent(nodeRef).getParentRef();\n if (parentRef != null) {\n if (nodeService.hasAspect(parentRef, SiteModel.ASPECT_SITE_CONTAINER)) {\n String parentName = (String) nodeService.getProperty(parentRef, ContentModel.PROP_NAME);\n if (\"blog\".equals(parentName) || \"wiki\".equals(parentName)) {\n // For Blog or Wiki pages, we use the title\n return (String) nodeService.getProperty(nodeRef, ContentModel.PROP_TITLE);\n }\n }\n }\n }\n\n return nodeName;\n }\n}", "public interface AuditShareReferentielService {\n\n public static String auditShareReferentielNodeUUID = \"auditshare-user-connections-groups\";\n\n public List<Group> parseReferentielGroups(InputStream file);\n\n public List<Group> parseRefentielForNodeUUID(String id);\n}", "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\", propOrder = { \"id\", \"libelle\" })\n@XmlRootElement(name = \"group\")\npublic class Group implements Serializable {\n\n private static final long serialVersionUID = 3626364911766188408L;\n @XmlElement(required = true)\n protected String id;\n @XmlElement(required = true)\n protected String libelle;\n\n /**\n * Gets the value of the id property.\n *\n * @return possible object is {@link String }\n *\n */\n public String getId() {\n return id;\n }\n\n /**\n * Sets the value of the id property.\n *\n * @param value allowed object is {@link String }\n *\n */\n public void setId(String value) {\n this.id = value;\n }\n\n /**\n * Gets the value of the libelle property.\n *\n * @return possible object is {@link String }\n *\n */\n public String getLibelle() {\n return libelle;\n }\n\n /**\n * Sets the value of the libelle property.\n *\n * @param value allowed object is {@link String }\n *\n */\n public void setLibelle(String value) {\n this.libelle = value;\n }\n\n}" ]
import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.alfresco.model.ContentModel; import org.alfresco.repo.domain.node.ContentDataWithId; import org.alfresco.repo.jscript.BaseScopableProcessorExtension; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.search.LimitBy; import org.alfresco.service.cmr.search.ResultSet; import org.alfresco.service.cmr.search.ResultSetRow; import org.alfresco.service.cmr.search.SearchParameters; import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.cmr.site.SiteInfo; import org.alfresco.service.cmr.site.SiteService; import org.alfresco.util.ISO9075; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; import com.atolcd.alfresco.AtolVolumetryEntry; import com.atolcd.alfresco.AuditCount; import com.atolcd.alfresco.AuditEntry; import com.atolcd.alfresco.AuditQueryParameters; import com.atolcd.alfresco.web.scripts.shareStats.InsertAuditPost; import com.atolcd.alfresco.web.scripts.shareStats.SelectAuditsGet; import com.atolcd.auditshare.repo.service.AuditShareReferentielService; import com.atolcd.auditshare.repo.xml.Group;
/* * Copyright (C) 2018 Atol Conseils et Développements. * http://www.atolcd.com/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.atolcd.alfresco.repo.jscript; public class ShareStats extends BaseScopableProcessorExtension implements InitializingBean { // Logger private static final Log logger = LogFactory.getLog(ShareStats.class); private InsertAuditPost wsInsertAudits; private SiteService siteService; private SearchService searchService; private int batchSize; // SqlMapClientTemplate for MyBatis calls private SqlSessionTemplate sqlSessionTemplate; // For the user groups referentiel services private AuditShareReferentielService auditShareReferentielService; public SiteService getSiteService() { return siteService; } public void setSiteService(SiteService siteService) { this.siteService = siteService; } public SearchService getSearchService() { return searchService; } public void setSearchService(SearchService searchService) { this.searchService = searchService; } public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public void setWsInsertAudits(InsertAuditPost wsInsertAudits) { this.wsInsertAudits = wsInsertAudits; } public AuditShareReferentielService getAuditShareReferentielService() { return auditShareReferentielService; } public void setAuditShareReferentielService(AuditShareReferentielService auditShareReferentielService) { this.auditShareReferentielService = auditShareReferentielService; } public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } @Override public void afterPropertiesSet() throws Exception { Assert.notNull(siteService); Assert.notNull(searchService); Assert.notNull(wsInsertAudits); Assert.notNull(auditShareReferentielService); Assert.notNull(sqlSessionTemplate); } public List<Group> getReferentiel(String refGroup) { // Referentiel return auditShareReferentielService.parseRefentielForNodeUUID(refGroup); } public void insertAuditEntry(long id, String auditUserId, String auditSite, String auditAppName, String auditActionName, String auditObject, long auditTime, String auditNodeType) throws SQLException, JSONException { AuditEntry auditSample = new AuditEntry(); auditSample.setId(id); auditSample.setAuditUserId(auditUserId); auditSample.setAuditAppName(auditAppName); auditSample.setAuditActionName(auditActionName); auditSample.setAuditObject(auditObject); auditSample.setAuditTime(auditTime); auditSample.setAuditSite(StringUtils.isNotBlank(auditSite) ? auditSite : InsertAuditPost.SITE_REPOSITORY); if (StringUtils.isNotBlank(auditNodeType)) { auditSample.setAuditNodeType(auditNodeType); } sqlSessionTemplate.insert(InsertAuditPost.INSERT_ENTRY, auditSample); logger.info("Entry successfully inserted: " + auditSample.toJSON()); } public List<AuditCount> selectByRead(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites, String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException { return this.selectAuditCount(SelectAuditsGet.SELECT_BY_VIEW, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject, dateFrom, dateTo, auditNodeTypes); } public List<AuditCount> selectByCreated(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites, String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException { return this.selectAuditCount(SelectAuditsGet.SELECT_BY_CREATED, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject, dateFrom, dateTo, auditNodeTypes); } public List<AuditCount> selectByUpdated(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites, String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException { return this.selectAuditCount(SelectAuditsGet.SELECT_BY_UPDATED, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject, dateFrom, dateTo, auditNodeTypes); } public List<AuditCount> selectByDeleted(String auditAppNames, String auditActionNames, String auditUserIds, String auditSites, String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException { return this.selectAuditCount(SelectAuditsGet.SELECT_BY_DELETED, auditAppNames, auditActionNames, auditUserIds, auditSites, auditObject, dateFrom, dateTo, auditNodeTypes); } private List<AuditCount> selectAuditCount(String queryType, String auditAppNames, String auditActionNames, String auditUserIds, String auditSites, String auditObject, Long dateFrom, Long dateTo, String auditNodeTypes) throws SQLException, JSONException {
AuditQueryParameters params = new AuditQueryParameters();
1
googleapis/google-oauth-java-client
samples/dailymotion-cmdline-sample/src/main/java/com/google/api/services/samples/dailymotion/cmdline/DailyMotionSample.java
[ "public class AuthorizationCodeFlow {\n\n /**\n * Method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod}).\n */\n private final AccessMethod method;\n\n /** HTTP transport. */\n private final HttpTransport transport;\n\n /** JSON factory. */\n private final JsonFactory jsonFactory;\n\n /** Token server encoded URL. */\n private final String tokenServerEncodedUrl;\n\n /**\n * Client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n */\n private final HttpExecuteInterceptor clientAuthentication;\n\n /** Client identifier. */\n private final String clientId;\n\n /** Authorization server encoded URL. */\n private final String authorizationServerEncodedUrl;\n\n /** The Proof Key for Code Exchange (PKCE) or {@code null} if this flow should not use PKCE. */\n private final PKCE pkce;\n\n /** Credential persistence store or {@code null} for none. */\n @Beta @Deprecated private final CredentialStore credentialStore;\n\n /** Stored credential data store or {@code null} for none. */\n @Beta private final DataStore<StoredCredential> credentialDataStore;\n\n /** HTTP request initializer or {@code null} for none. */\n private final HttpRequestInitializer requestInitializer;\n\n /** Clock passed along to Credential. */\n private final Clock clock;\n\n /** Collection of scopes. */\n private final Collection<String> scopes;\n\n /** Credential created listener or {@code null} for none. */\n private final CredentialCreatedListener credentialCreatedListener;\n\n /** Refresh listeners provided by the client. */\n private final Collection<CredentialRefreshListener> refreshListeners;\n\n /**\n * @param method method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod})\n * @param transport HTTP transport\n * @param jsonFactory JSON factory\n * @param tokenServerUrl token server URL\n * @param clientAuthentication client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})\n * @param clientId client identifier\n * @param authorizationServerEncodedUrl authorization server encoded URL\n * @since 1.14\n */\n public AuthorizationCodeFlow(\n AccessMethod method,\n HttpTransport transport,\n JsonFactory jsonFactory,\n GenericUrl tokenServerUrl,\n HttpExecuteInterceptor clientAuthentication,\n String clientId,\n String authorizationServerEncodedUrl) {\n this(\n new Builder(\n method,\n transport,\n jsonFactory,\n tokenServerUrl,\n clientAuthentication,\n clientId,\n authorizationServerEncodedUrl));\n }\n\n /**\n * @param builder authorization code flow builder\n * @since 1.14\n */\n protected AuthorizationCodeFlow(Builder builder) {\n method = Preconditions.checkNotNull(builder.method);\n transport = Preconditions.checkNotNull(builder.transport);\n jsonFactory = Preconditions.checkNotNull(builder.jsonFactory);\n tokenServerEncodedUrl = Preconditions.checkNotNull(builder.tokenServerUrl).build();\n clientAuthentication = builder.clientAuthentication;\n clientId = Preconditions.checkNotNull(builder.clientId);\n authorizationServerEncodedUrl =\n Preconditions.checkNotNull(builder.authorizationServerEncodedUrl);\n requestInitializer = builder.requestInitializer;\n credentialStore = builder.credentialStore;\n credentialDataStore = builder.credentialDataStore;\n scopes = Collections.unmodifiableCollection(builder.scopes);\n clock = Preconditions.checkNotNull(builder.clock);\n credentialCreatedListener = builder.credentialCreatedListener;\n refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners);\n pkce = builder.pkce;\n }\n\n /**\n * Returns a new instance of an authorization code request URL.\n *\n * <p>This is a builder for an authorization web page to allow the end user to authorize the\n * application to access their protected resources and that returns an authorization code. It uses\n * the {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and {@link\n * #getScopes()}. Sample usage:\n *\n * <pre>\n * private AuthorizationCodeFlow flow;\n *\n * public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n * String url = flow.newAuthorizationUrl().setState(\"xyz\")\n * .setRedirectUri(\"https://client.example.com/rd\").build();\n * response.sendRedirect(url);\n * }\n * </pre>\n */\n public AuthorizationCodeRequestUrl newAuthorizationUrl() {\n AuthorizationCodeRequestUrl url =\n new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId);\n url.setScopes(scopes);\n if (pkce != null) {\n url.setCodeChallenge(pkce.getChallenge());\n url.setCodeChallengeMethod(pkce.getChallengeMethod());\n }\n return url;\n }\n\n /**\n * Returns a new instance of an authorization code token request based on the given authorization\n * code.\n *\n * <p>This is used to make a request for an access token using the authorization code. It uses\n * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getTokenServerEncodedUrl()}, {@link\n * #getClientAuthentication()}, {@link #getRequestInitializer()}, and {@link #getScopes()}.\n *\n * <pre>\n * static TokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code)\n * throws IOException, TokenResponseException {\n * return flow.newTokenRequest(code).setRedirectUri(\"https://client.example.com/rd\").execute();\n * }\n * </pre>\n *\n * @param authorizationCode authorization code.\n */\n public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {\n HttpExecuteInterceptor pkceClientAuthenticationWrapper =\n new HttpExecuteInterceptor() {\n @Override\n public void intercept(HttpRequest request) throws IOException {\n clientAuthentication.intercept(request);\n if (pkce != null) {\n Map<String, Object> data =\n Data.mapOf(UrlEncodedContent.getContent(request).getData());\n data.put(\"code_verifier\", pkce.getVerifier());\n }\n }\n };\n\n return new AuthorizationCodeTokenRequest(\n transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), authorizationCode)\n .setClientAuthentication(pkceClientAuthenticationWrapper)\n .setRequestInitializer(requestInitializer)\n .setScopes(scopes);\n }\n\n /**\n * Creates a new credential for the given user ID based on the given token response and stores it\n * in the credential store.\n *\n * @param response token response\n * @param userId user ID or {@code null} if not using a persisted credential store\n * @return newly created credential\n */\n @SuppressWarnings(\"deprecation\")\n public Credential createAndStoreCredential(TokenResponse response, String userId)\n throws IOException {\n Credential credential = newCredential(userId).setFromTokenResponse(response);\n if (credentialStore != null) {\n credentialStore.store(userId, credential);\n }\n if (credentialDataStore != null) {\n credentialDataStore.set(userId, new StoredCredential(credential));\n }\n if (credentialCreatedListener != null) {\n credentialCreatedListener.onCredentialCreated(credential, response);\n }\n return credential;\n }\n\n /**\n * Loads the credential of the given user ID from the credential store.\n *\n * @param userId user ID or {@code null} if not using a persisted credential store\n * @return credential found in the credential store of the given user ID or {@code null} for none\n * found\n */\n @SuppressWarnings(\"deprecation\")\n public Credential loadCredential(String userId) throws IOException {\n\n // No requests need to be performed when userId is not specified.\n if (isNullOrEmpty(userId)) {\n return null;\n }\n\n if (credentialDataStore == null && credentialStore == null) {\n return null;\n }\n Credential credential = newCredential(userId);\n if (credentialDataStore != null) {\n StoredCredential stored = credentialDataStore.get(userId);\n if (stored == null) {\n return null;\n }\n credential.setAccessToken(stored.getAccessToken());\n credential.setRefreshToken(stored.getRefreshToken());\n credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds());\n } else if (!credentialStore.load(userId, credential)) {\n return null;\n }\n return credential;\n }\n\n /**\n * Returns a new credential instance based on the given user ID.\n *\n * @param userId user ID or {@code null} if not using a persisted credential store\n */\n @SuppressWarnings(\"deprecation\")\n private Credential newCredential(String userId) {\n Credential.Builder builder =\n new Credential.Builder(method)\n .setTransport(transport)\n .setJsonFactory(jsonFactory)\n .setTokenServerEncodedUrl(tokenServerEncodedUrl)\n .setClientAuthentication(clientAuthentication)\n .setRequestInitializer(requestInitializer)\n .setClock(clock);\n if (credentialDataStore != null) {\n builder.addRefreshListener(\n new DataStoreCredentialRefreshListener(userId, credentialDataStore));\n } else if (credentialStore != null) {\n builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore));\n }\n builder.getRefreshListeners().addAll(refreshListeners);\n return builder.build();\n }\n\n /**\n * Returns the method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod}).\n */\n public final AccessMethod getMethod() {\n return method;\n }\n\n /** Returns the HTTP transport. */\n public final HttpTransport getTransport() {\n return transport;\n }\n\n /** Returns the JSON factory. */\n public final JsonFactory getJsonFactory() {\n return jsonFactory;\n }\n\n /** Returns the token server encoded URL. */\n public final String getTokenServerEncodedUrl() {\n return tokenServerEncodedUrl;\n }\n\n /**\n * Returns the client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n */\n public final HttpExecuteInterceptor getClientAuthentication() {\n return clientAuthentication;\n }\n\n /** Returns the client identifier. */\n public final String getClientId() {\n return clientId;\n }\n\n /** Returns the authorization server encoded URL. */\n public final String getAuthorizationServerEncodedUrl() {\n return authorizationServerEncodedUrl;\n }\n\n /**\n * {@link Beta} <br>\n * Returns the credential persistence store or {@code null} for none.\n *\n * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead.\n */\n @Beta\n @Deprecated\n public final CredentialStore getCredentialStore() {\n return credentialStore;\n }\n\n /**\n * {@link Beta} <br>\n * Returns the stored credential data store or {@code null} for none.\n *\n * @since 1.16\n */\n @Beta\n public final DataStore<StoredCredential> getCredentialDataStore() {\n return credentialDataStore;\n }\n\n /** Returns the HTTP request initializer or {@code null} for none. */\n public final HttpRequestInitializer getRequestInitializer() {\n return requestInitializer;\n }\n\n /**\n * Returns the space-separated list of scopes.\n *\n * @since 1.15\n */\n public final String getScopesAsString() {\n return Joiner.on(' ').join(scopes);\n }\n\n /** Returns the a collection of scopes. */\n public final Collection<String> getScopes() {\n return scopes;\n }\n\n /**\n * Returns the clock which will be passed along to the Credential.\n *\n * @since 1.9\n */\n public final Clock getClock() {\n return clock;\n }\n\n /**\n * Returns the unmodifiable list of listeners for refresh token results.\n *\n * @since 1.15\n */\n public final Collection<CredentialRefreshListener> getRefreshListeners() {\n return refreshListeners;\n }\n\n /**\n * Listener for a created credential after a successful token response in {@link\n * #createAndStoreCredential}.\n *\n * @since 1.14\n */\n public interface CredentialCreatedListener {\n\n /**\n * Notifies of a created credential after a successful token response in {@link\n * #createAndStoreCredential}.\n *\n * <p>Typical use is to parse additional fields from the credential created, such as an ID\n * token.\n *\n * @param credential created credential\n * @param tokenResponse successful token response\n */\n void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException;\n }\n\n /**\n * An implementation of <a href=\"https://tools.ietf.org/html/rfc7636\">Proof Key for Code\n * Exchange</a> which, according to the <a\n * href=\"https://tools.ietf.org/html/rfc8252#section-6\">OAuth 2.0 for Native Apps RFC</a>, is\n * mandatory for public native apps.\n */\n private static class PKCE {\n private final String verifier;\n private String challenge;\n private String challengeMethod;\n\n public PKCE() {\n verifier = generateVerifier();\n generateChallenge(verifier);\n }\n\n private static String generateVerifier() {\n SecureRandom sr = new SecureRandom();\n byte[] code = new byte[32];\n sr.nextBytes(code);\n return Base64.encodeBase64URLSafeString(code);\n }\n\n /**\n * Create the PKCE code verifier. It uses the S256 method but falls back to using the 'plain'\n * method in the unlikely case that the SHA-256 MessageDigest algorithm implementation can't be\n * loaded.\n */\n private void generateChallenge(String verifier) {\n try {\n byte[] bytes = verifier.getBytes();\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n md.update(bytes, 0, bytes.length);\n byte[] digest = md.digest();\n challenge = Base64.encodeBase64URLSafeString(digest);\n challengeMethod = \"S256\";\n } catch (NoSuchAlgorithmException e) {\n challenge = verifier;\n challengeMethod = \"plain\";\n }\n }\n\n public String getVerifier() {\n return verifier;\n }\n\n public String getChallenge() {\n return challenge;\n }\n\n public String getChallengeMethod() {\n return challengeMethod;\n }\n }\n\n /**\n * Authorization code flow builder.\n *\n * <p>Implementation is not thread-safe.\n */\n public static class Builder {\n\n /**\n * Method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod}).\n */\n AccessMethod method;\n\n /** HTTP transport. */\n HttpTransport transport;\n\n /** JSON factory. */\n JsonFactory jsonFactory;\n\n /** Token server URL. */\n GenericUrl tokenServerUrl;\n\n /**\n * Client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n */\n HttpExecuteInterceptor clientAuthentication;\n\n /** Client identifier. */\n String clientId;\n\n /** Authorization server encoded URL. */\n String authorizationServerEncodedUrl;\n\n PKCE pkce;\n\n /** Credential persistence store or {@code null} for none. */\n @Deprecated @Beta CredentialStore credentialStore;\n\n /** Stored credential data store or {@code null} for none. */\n @Beta DataStore<StoredCredential> credentialDataStore;\n\n /** HTTP request initializer or {@code null} for none. */\n HttpRequestInitializer requestInitializer;\n\n /** Collection of scopes. */\n Collection<String> scopes = Lists.newArrayList();\n\n /** Clock passed along to the Credential. */\n Clock clock = Clock.SYSTEM;\n\n /** Credential created listener or {@code null} for none. */\n CredentialCreatedListener credentialCreatedListener;\n\n /** Refresh listeners provided by the client. */\n Collection<CredentialRefreshListener> refreshListeners = Lists.newArrayList();\n\n /**\n * @param method method of presenting the access token to the resource server (for example\n * {@link BearerToken#authorizationHeaderAccessMethod})\n * @param transport HTTP transport\n * @param jsonFactory JSON factory\n * @param tokenServerUrl token server URL\n * @param clientAuthentication client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)})\n * @param clientId client identifier\n * @param authorizationServerEncodedUrl authorization server encoded URL\n */\n public Builder(\n AccessMethod method,\n HttpTransport transport,\n JsonFactory jsonFactory,\n GenericUrl tokenServerUrl,\n HttpExecuteInterceptor clientAuthentication,\n String clientId,\n String authorizationServerEncodedUrl) {\n setMethod(method);\n setTransport(transport);\n setJsonFactory(jsonFactory);\n setTokenServerUrl(tokenServerUrl);\n setClientAuthentication(clientAuthentication);\n setClientId(clientId);\n setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl);\n }\n\n /** Returns a new instance of an authorization code flow based on this builder. */\n public AuthorizationCodeFlow build() {\n return new AuthorizationCodeFlow(this);\n }\n\n /**\n * Returns the method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod}).\n */\n public final AccessMethod getMethod() {\n return method;\n }\n\n /**\n * Sets the method of presenting the access token to the resource server (for example {@link\n * BearerToken#authorizationHeaderAccessMethod}).\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setMethod(AccessMethod method) {\n this.method = Preconditions.checkNotNull(method);\n return this;\n }\n\n /** Returns the HTTP transport. */\n public final HttpTransport getTransport() {\n return transport;\n }\n\n /**\n * Sets the HTTP transport.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setTransport(HttpTransport transport) {\n this.transport = Preconditions.checkNotNull(transport);\n return this;\n }\n\n /** Returns the JSON factory. */\n public final JsonFactory getJsonFactory() {\n return jsonFactory;\n }\n\n /**\n * Sets the JSON factory.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setJsonFactory(JsonFactory jsonFactory) {\n this.jsonFactory = Preconditions.checkNotNull(jsonFactory);\n return this;\n }\n\n /** Returns the token server URL. */\n public final GenericUrl getTokenServerUrl() {\n return tokenServerUrl;\n }\n\n /**\n * Sets the token server URL.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setTokenServerUrl(GenericUrl tokenServerUrl) {\n this.tokenServerUrl = Preconditions.checkNotNull(tokenServerUrl);\n return this;\n }\n\n /**\n * Returns the client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n */\n public final HttpExecuteInterceptor getClientAuthentication() {\n return clientAuthentication;\n }\n\n /**\n * Sets the client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {\n this.clientAuthentication = clientAuthentication;\n return this;\n }\n\n /** Returns the client identifier. */\n public final String getClientId() {\n return clientId;\n }\n\n /**\n * Sets the client identifier.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setClientId(String clientId) {\n this.clientId = Preconditions.checkNotNull(clientId);\n return this;\n }\n\n /** Returns the authorization server encoded URL. */\n public final String getAuthorizationServerEncodedUrl() {\n return authorizationServerEncodedUrl;\n }\n\n /**\n * Sets the authorization server encoded URL.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.11\n */\n public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) {\n this.authorizationServerEncodedUrl =\n Preconditions.checkNotNull(authorizationServerEncodedUrl);\n return this;\n }\n\n /**\n * {@link Beta} <br>\n * Returns the credential persistence store or {@code null} for none.\n *\n * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead.\n */\n @Beta\n @Deprecated\n public final CredentialStore getCredentialStore() {\n return credentialStore;\n }\n\n /**\n * {@link Beta} <br>\n * Returns the stored credential data store or {@code null} for none.\n *\n * @since 1.16\n */\n @Beta\n public final DataStore<StoredCredential> getCredentialDataStore() {\n return credentialDataStore;\n }\n\n /**\n * Returns the clock passed along to the Credential or {@link Clock#SYSTEM} when system default\n * is used.\n *\n * @since 1.9\n */\n public final Clock getClock() {\n return clock;\n }\n\n /**\n * Sets the clock to pass to the Credential.\n *\n * <p>The default value for this parameter is {@link Clock#SYSTEM}\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.9\n */\n public Builder setClock(Clock clock) {\n this.clock = Preconditions.checkNotNull(clock);\n return this;\n }\n\n /**\n * {@link Beta} <br>\n * Sets the credential persistence store or {@code null} for none.\n *\n * <p>Warning: not compatible with {@link #setDataStoreFactory} or {@link\n * #setCredentialDataStore}, and if either of those is called before this method is called, this\n * method will throw an {@link IllegalArgumentException}.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @deprecated (to be removed in the future) Use {@link #setDataStoreFactory(DataStoreFactory)}\n * or {@link #setCredentialDataStore(DataStore)} instead.\n */\n @Beta\n @Deprecated\n public Builder setCredentialStore(CredentialStore credentialStore) {\n Preconditions.checkArgument(credentialDataStore == null);\n this.credentialStore = credentialStore;\n return this;\n }\n\n /**\n * {@link Beta} <br>\n * Sets the data store factory or {@code null} for none.\n *\n * <p>Warning: not compatible with {@link #setCredentialStore}, and if it is called before this\n * method is called, this method will throw an {@link IllegalArgumentException}.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.16\n */\n @Beta\n public Builder setDataStoreFactory(DataStoreFactory dataStoreFactory) throws IOException {\n return setCredentialDataStore(StoredCredential.getDefaultDataStore(dataStoreFactory));\n }\n\n /**\n * {@link Beta} <br>\n * Sets the stored credential data store or {@code null} for none.\n *\n * <p>Warning: not compatible with {@link #setCredentialStore}, and if it is called before this\n * method is called, this method will throw an {@link IllegalArgumentException}.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.16\n */\n @Beta\n public Builder setCredentialDataStore(DataStore<StoredCredential> credentialDataStore) {\n Preconditions.checkArgument(credentialStore == null);\n this.credentialDataStore = credentialDataStore;\n return this;\n }\n\n /** Returns the HTTP request initializer or {@code null} for none. */\n public final HttpRequestInitializer getRequestInitializer() {\n return requestInitializer;\n }\n\n /**\n * Sets the HTTP request initializer or {@code null} for none.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) {\n this.requestInitializer = requestInitializer;\n return this;\n }\n\n /**\n * Enables Proof Key for Code Exchange (PKCE) for this Athorization Code Flow.\n *\n * @since 1.31\n */\n @Beta\n public Builder enablePKCE() {\n this.pkce = new PKCE();\n return this;\n }\n\n /**\n * Sets the collection of scopes.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param scopes collection of scopes\n * @since 1.15\n */\n public Builder setScopes(Collection<String> scopes) {\n this.scopes = Preconditions.checkNotNull(scopes);\n return this;\n }\n\n /** Returns a collection of scopes. */\n public final Collection<String> getScopes() {\n return scopes;\n }\n\n /**\n * Sets the credential created listener or {@code null} for none.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.14\n */\n public Builder setCredentialCreatedListener(\n CredentialCreatedListener credentialCreatedListener) {\n this.credentialCreatedListener = credentialCreatedListener;\n return this;\n }\n\n /**\n * Adds a listener for refresh token results.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param refreshListener refresh listener\n * @since 1.15\n */\n public Builder addRefreshListener(CredentialRefreshListener refreshListener) {\n refreshListeners.add(Preconditions.checkNotNull(refreshListener));\n return this;\n }\n\n /**\n * Returns the listeners for refresh token results.\n *\n * @since 1.15\n */\n public final Collection<CredentialRefreshListener> getRefreshListeners() {\n return refreshListeners;\n }\n\n /**\n * Sets the listeners for refresh token results.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @since 1.15\n */\n public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) {\n this.refreshListeners = Preconditions.checkNotNull(refreshListeners);\n return this;\n }\n\n /**\n * Returns the credential created listener or {@code null} for none.\n *\n * @since 1.14\n */\n public final CredentialCreatedListener getCredentialCreatedListener() {\n return credentialCreatedListener;\n }\n }\n}", "public class BearerToken {\n\n /** Query and form-encoded parameter name. */\n static final String PARAM_NAME = \"access_token\";\n\n /**\n * In case an abnormal HTTP response is received with {@code WWW-Authenticate} header, and its\n * value contains this error pattern, we will try to refresh the token.\n */\n static final Pattern INVALID_TOKEN_ERROR =\n Pattern.compile(\"\\\\s*error\\\\s*=\\\\s*\\\"?invalid_token\\\"?\");\n\n /**\n * Immutable and thread-safe OAuth 2.0 method for accessing protected resources using the <a\n * href=\"http://tools.ietf.org/html/rfc6750#section-2.1\">Authorization Request Header Field</a>.\n *\n * <p>According to the specification, this method MUST be supported by resource servers.\n */\n static final class AuthorizationHeaderAccessMethod implements Credential.AccessMethod {\n\n /** Authorization header prefix. */\n static final String HEADER_PREFIX = \"Bearer \";\n\n AuthorizationHeaderAccessMethod() {}\n\n public void intercept(HttpRequest request, String accessToken) throws IOException {\n request.getHeaders().setAuthorization(HEADER_PREFIX + accessToken);\n }\n\n public String getAccessTokenFromRequest(HttpRequest request) {\n List<String> authorizationAsList = request.getHeaders().getAuthorizationAsList();\n if (authorizationAsList != null) {\n for (String header : authorizationAsList) {\n if (header.startsWith(HEADER_PREFIX)) {\n return header.substring(HEADER_PREFIX.length());\n }\n }\n }\n return null;\n }\n }\n\n /**\n * Immutable and thread-safe OAuth 2.0 method for accessing protected resources using the <a\n * href=\"http://tools.ietf.org/html/rfc6750#section-2.2\">Form-Encoded Body Parameter</a>.\n */\n static final class FormEncodedBodyAccessMethod implements Credential.AccessMethod {\n\n FormEncodedBodyAccessMethod() {}\n\n public void intercept(HttpRequest request, String accessToken) throws IOException {\n Preconditions.checkArgument(\n !HttpMethods.GET.equals(request.getRequestMethod()), \"HTTP GET method is not supported\");\n getData(request).put(PARAM_NAME, accessToken);\n }\n\n public String getAccessTokenFromRequest(HttpRequest request) {\n Object bodyParam = getData(request).get(PARAM_NAME);\n return bodyParam == null ? null : bodyParam.toString();\n }\n\n private static Map<String, Object> getData(HttpRequest request) {\n return Data.mapOf(UrlEncodedContent.getContent(request).getData());\n }\n }\n\n /**\n * Immutable and thread-safe OAuth 2.0 method for accessing protected resources using the <a\n * href=\"http://tools.ietf.org/html/rfc6750#section-2.3\">URI Query Parameter</a>.\n */\n static final class QueryParameterAccessMethod implements Credential.AccessMethod {\n\n QueryParameterAccessMethod() {}\n\n public void intercept(HttpRequest request, String accessToken) throws IOException {\n request.getUrl().set(PARAM_NAME, accessToken);\n }\n\n public String getAccessTokenFromRequest(HttpRequest request) {\n Object param = request.getUrl().get(PARAM_NAME);\n return param == null ? null : param.toString();\n }\n }\n\n /**\n * Returns a new instance of an immutable and thread-safe OAuth 2.0 method for accessing protected\n * resources using the <a href=\"http://tools.ietf.org/html/rfc6750#section-2.1\">Authorization\n * Request Header Field</a>.\n *\n * <p>According to the specification, this method MUST be supported by resource servers.\n */\n public static Credential.AccessMethod authorizationHeaderAccessMethod() {\n return new AuthorizationHeaderAccessMethod();\n }\n\n /**\n * Returns a new instance of an immutable and thread-safe OAuth 2.0 method for accessing protected\n * resources using the <a href=\"http://tools.ietf.org/html/rfc6750#section-2.2\">Form-Encoded Body\n * Parameter</a>.\n */\n public static Credential.AccessMethod formEncodedBodyAccessMethod() {\n return new FormEncodedBodyAccessMethod();\n }\n\n /**\n * Returns a new instance of an immutable and thread-safe OAuth 2.0 method for accessing protected\n * resources using the <a href=\"http://tools.ietf.org/html/rfc6750#section-2.3\">URI Query\n * Parameter</a>.\n */\n public static Credential.AccessMethod queryParameterAccessMethod() {\n return new QueryParameterAccessMethod();\n }\n}", "public class ClientParametersAuthentication\n implements HttpRequestInitializer, HttpExecuteInterceptor {\n\n /** Client identifier issued to the client during the registration process. */\n private final String clientId;\n\n /** Client secret or {@code null} for none. */\n private final String clientSecret;\n\n /**\n * @param clientId client identifier issued to the client during the registration process\n * @param clientSecret client secret or {@code null} for none\n */\n public ClientParametersAuthentication(String clientId, String clientSecret) {\n this.clientId = Preconditions.checkNotNull(clientId);\n this.clientSecret = clientSecret;\n }\n\n public void initialize(HttpRequest request) throws IOException {\n request.setInterceptor(this);\n }\n\n public void intercept(HttpRequest request) throws IOException {\n Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());\n data.put(\"client_id\", clientId);\n if (clientSecret != null) {\n data.put(\"client_secret\", clientSecret);\n }\n }\n\n /** Returns the client identifier issued to the client during the registration process. */\n public final String getClientId() {\n return clientId;\n }\n\n /** Returns the client secret or {@code null} for none. */\n public final String getClientSecret() {\n return clientSecret;\n }\n}", "public class Credential\n implements HttpExecuteInterceptor, HttpRequestInitializer, HttpUnsuccessfulResponseHandler {\n\n static final Logger LOGGER = Logger.getLogger(Credential.class.getName());\n\n /**\n * Method of presenting the access token to the resource server as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-7\">Accessing Protected Resources</a>.\n */\n public interface AccessMethod {\n\n /**\n * Intercept the HTTP request during {@link Credential#intercept(HttpRequest)} right before the\n * HTTP request executes by providing the access token.\n *\n * @param request HTTP request\n * @param accessToken access token\n */\n void intercept(HttpRequest request, String accessToken) throws IOException;\n\n /**\n * Retrieve the original access token in the HTTP request, as provided in {@link\n * #intercept(HttpRequest, String)}.\n *\n * @param request HTTP request\n * @return original access token or {@code null} for none\n */\n String getAccessTokenFromRequest(HttpRequest request);\n }\n\n /** Lock on the token response information. */\n private final Lock lock = new ReentrantLock();\n\n /**\n * Method of presenting the access token to the resource server (for example {@link\n * BearerToken.AuthorizationHeaderAccessMethod}).\n */\n private final AccessMethod method;\n\n /** Clock used to provide the currentMillis. */\n private final Clock clock;\n\n /** Access token issued by the authorization server. */\n private String accessToken;\n\n /**\n * Expected expiration time in milliseconds based on {@link #setExpiresInSeconds} or {@code null}\n * for none.\n */\n private Long expirationTimeMilliseconds;\n\n /**\n * Refresh token which can be used to obtain new access tokens using the same authorization grant\n * or {@code null} for none.\n */\n private String refreshToken;\n\n /** HTTP transport for executing refresh token request or {@code null} for none. */\n private final HttpTransport transport;\n\n /** Client authentication or {@code null} for none. */\n private final HttpExecuteInterceptor clientAuthentication;\n\n /**\n * JSON factory to use for parsing response for refresh token request or {@code null} for none.\n */\n private final JsonFactory jsonFactory;\n\n /** Encoded token server URL or {@code null} for none. */\n private final String tokenServerEncodedUrl;\n\n /** Unmodifiable collection of listeners for refresh token results. */\n private final Collection<CredentialRefreshListener> refreshListeners;\n\n /**\n * HTTP request initializer for refresh token requests to the token server or {@code null} for\n * none.\n */\n private final HttpRequestInitializer requestInitializer;\n\n /**\n * Constructor with the ability to access protected resources, but not refresh tokens.\n *\n * <p>To use with the ability to refresh tokens, use {@link Builder}.\n *\n * @param method method of presenting the access token to the resource server (for example {@link\n * BearerToken.AuthorizationHeaderAccessMethod})\n */\n public Credential(AccessMethod method) {\n this(new Builder(method));\n }\n\n /**\n * @param builder credential builder\n * @since 1.14\n */\n protected Credential(Builder builder) {\n method = Preconditions.checkNotNull(builder.method);\n transport = builder.transport;\n jsonFactory = builder.jsonFactory;\n tokenServerEncodedUrl = builder.tokenServerUrl == null ? null : builder.tokenServerUrl.build();\n clientAuthentication = builder.clientAuthentication;\n requestInitializer = builder.requestInitializer;\n refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners);\n clock = Preconditions.checkNotNull(builder.clock);\n }\n\n /**\n * {@inheritDoc}\n *\n * <p>Default implementation is to try to refresh the access token if there is no access token or\n * if we are 1 minute away from expiration. If token server is unavailable, it will try to use the\n * access token even if has expired. If a 4xx error is encountered while refreshing the token,\n * {@link TokenResponseException} is thrown. If successful, it will call {@link #getMethod()} and\n * {@link AccessMethod#intercept}.\n *\n * <p>Subclasses may override.\n */\n public void intercept(HttpRequest request) throws IOException {\n lock.lock();\n try {\n Long expiresIn = getExpiresInSeconds();\n // check if token will expire in a minute\n if (accessToken == null || expiresIn != null && expiresIn <= 60) {\n refreshToken();\n if (accessToken == null) {\n // nothing we can do without an access token\n return;\n }\n }\n method.intercept(request, accessToken);\n } finally {\n lock.unlock();\n }\n }\n\n /**\n * {@inheritDoc}\n *\n * <p>Default implementation checks if {@code WWW-Authenticate} exists and contains a \"Bearer\"\n * value (see <a href=\"http://tools.ietf.org/html/rfc6750#section-3.1\">rfc6750 section 3.1</a> for\n * more details). If so, it calls {@link #refreshToken} in case the error code contains {@code\n * invalid_token}. If there is no \"Bearer\" in {@code WWW-Authenticate} and the status code is\n * {@link HttpStatusCodes#STATUS_CODE_UNAUTHORIZED} it calls {@link #refreshToken}. If {@link\n * #executeRefreshToken()} throws an I/O exception, this implementation will log the exception and\n * return {@code false}. Subclasses may override.\n */\n public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) {\n boolean refreshToken = false;\n boolean bearer = false;\n\n List<String> authenticateList = response.getHeaders().getAuthenticateAsList();\n\n // TODO(peleyal): this logic should be implemented as a pluggable interface, in the same way we\n // implement different AccessMethods\n\n // if authenticate list is not null we will check if one of the entries contains \"Bearer\"\n if (authenticateList != null) {\n for (String authenticate : authenticateList) {\n if (authenticate.startsWith(BearerToken.AuthorizationHeaderAccessMethod.HEADER_PREFIX)) {\n // mark that we found a \"Bearer\" value, and check if there is a invalid_token error\n bearer = true;\n refreshToken = BearerToken.INVALID_TOKEN_ERROR.matcher(authenticate).find();\n break;\n }\n }\n }\n\n // if \"Bearer\" wasn't found, we will refresh the token, if we got 401\n if (!bearer) {\n refreshToken = response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED;\n }\n\n if (refreshToken) {\n try {\n lock.lock();\n try {\n // need to check if another thread has already refreshed the token\n return !Objects.equal(accessToken, method.getAccessTokenFromRequest(request))\n || refreshToken();\n } finally {\n lock.unlock();\n }\n } catch (IOException exception) {\n LOGGER.log(Level.SEVERE, \"unable to refresh token\", exception);\n }\n }\n return false;\n }\n\n public void initialize(HttpRequest request) throws IOException {\n request.setInterceptor(this);\n request.setUnsuccessfulResponseHandler(this);\n }\n\n /**\n * Returns the access token or {@code null} for none. If {@code null} the token needs to be\n * refreshed using refreshToken().\n */\n public final String getAccessToken() {\n lock.lock();\n try {\n return accessToken;\n } finally {\n lock.unlock();\n }\n }\n\n /**\n * Sets the access token.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param accessToken access token or {@code null} for none\n */\n public Credential setAccessToken(String accessToken) {\n lock.lock();\n try {\n this.accessToken = accessToken;\n } finally {\n lock.unlock();\n }\n return this;\n }\n\n /**\n * Return the method of presenting the access token to the resource server (for example {@link\n * BearerToken.AuthorizationHeaderAccessMethod}).\n */\n public final AccessMethod getMethod() {\n return method;\n }\n\n /**\n * Returns the clock used for expiration checks by this Credential. Mostly used for unit-testing.\n *\n * @since 1.9\n */\n public final Clock getClock() {\n return clock;\n }\n\n /** Return the HTTP transport for executing refresh token request or {@code null} for none. */\n public final HttpTransport getTransport() {\n return transport;\n }\n\n /**\n * Returns the JSON factory to use for parsing response for refresh token request or {@code null}\n * for none.\n */\n public final JsonFactory getJsonFactory() {\n return jsonFactory;\n }\n\n /** Returns the encoded authorization server URL or {@code null} for none. */\n public final String getTokenServerEncodedUrl() {\n return tokenServerEncodedUrl;\n }\n\n /**\n * Returns the refresh token associated with the access token to be refreshed or {@code null} for\n * none.\n */\n public final String getRefreshToken() {\n lock.lock();\n try {\n return refreshToken;\n } finally {\n lock.unlock();\n }\n }\n\n /**\n * Sets the refresh token.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param refreshToken refresh token or {@code null} for none\n */\n public Credential setRefreshToken(String refreshToken) {\n lock.lock();\n try {\n if (refreshToken != null) {\n Preconditions.checkArgument(\n jsonFactory != null\n && transport != null\n && clientAuthentication != null\n && tokenServerEncodedUrl != null,\n \"Please use the Builder and call setJsonFactory, setTransport, setClientAuthentication\"\n + \" and setTokenServerUrl/setTokenServerEncodedUrl\");\n }\n this.refreshToken = refreshToken;\n } finally {\n lock.unlock();\n }\n return this;\n }\n\n /**\n * Expected expiration time in milliseconds relative to the {@link System#currentTimeMillis() Java\n * epoch}, or {@code null} for none.\n */\n public final Long getExpirationTimeMilliseconds() {\n lock.lock();\n try {\n return expirationTimeMilliseconds;\n } finally {\n lock.unlock();\n }\n }\n\n /**\n * Sets the expected expiration time in milliseconds relative to the {@link\n * System#currentTimeMillis() Java epoch}, or {@code null} for none.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Credential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) {\n lock.lock();\n try {\n this.expirationTimeMilliseconds = expirationTimeMilliseconds;\n } finally {\n lock.unlock();\n }\n return this;\n }\n\n /**\n * Returns the remaining lifetime in seconds of the access token (for example 3600 for an hour\n * from now, or -3600 if expired an hour ago) or {@code null} if unknown.\n */\n public final Long getExpiresInSeconds() {\n lock.lock();\n try {\n if (expirationTimeMilliseconds == null) {\n return null;\n }\n return (expirationTimeMilliseconds - clock.currentTimeMillis()) / 1000;\n } finally {\n lock.unlock();\n }\n }\n\n /**\n * Sets the lifetime in seconds of the access token (for example 3600 for an hour from now) or\n * {@code null} for none.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param expiresIn lifetime in seconds of the access token (for example 3600 for an hour from\n * now) or {@code null} for none\n */\n public Credential setExpiresInSeconds(Long expiresIn) {\n return setExpirationTimeMilliseconds(\n expiresIn == null ? null : clock.currentTimeMillis() + expiresIn * 1000);\n }\n\n /** Returns the client authentication or {@code null} for none. */\n public final HttpExecuteInterceptor getClientAuthentication() {\n return clientAuthentication;\n }\n\n /**\n * Returns the HTTP request initializer for refresh token requests to the token server or {@code\n * null} for none.\n */\n public final HttpRequestInitializer getRequestInitializer() {\n return requestInitializer;\n }\n\n /**\n * Request a new access token from the authorization endpoint.\n *\n * <p>On success, it will call {@link #setFromTokenResponse(TokenResponse)}, call {@link\n * CredentialRefreshListener#onTokenResponse} with the token response, and return {@code true}. On\n * error, it will call {@link #setAccessToken(String)} and {@link #setExpiresInSeconds(Long)} with\n * {@code null}, call {@link CredentialRefreshListener#onTokenErrorResponse} with the token error\n * response, and return {@code false}. If a 4xx error is encountered while refreshing the token,\n * {@link TokenResponseException} is thrown.\n *\n * <p>If there is no refresh token, it will quietly return {@code false}.\n *\n * @return whether a new access token was successfully retrieved\n */\n public final boolean refreshToken() throws IOException {\n lock.lock();\n try {\n try {\n TokenResponse tokenResponse = executeRefreshToken();\n if (tokenResponse != null) {\n setFromTokenResponse(tokenResponse);\n for (CredentialRefreshListener refreshListener : refreshListeners) {\n refreshListener.onTokenResponse(this, tokenResponse);\n }\n return true;\n }\n } catch (TokenResponseException e) {\n boolean statusCode4xx = 400 <= e.getStatusCode() && e.getStatusCode() < 500;\n // check if it is a normal error response\n if (e.getDetails() != null && statusCode4xx) {\n // We were unable to get a new access token (e.g. it may have been revoked), we must now\n // indicate that our current token is invalid.\n setAccessToken(null);\n setExpiresInSeconds(null);\n }\n for (CredentialRefreshListener refreshListener : refreshListeners) {\n refreshListener.onTokenErrorResponse(this, e.getDetails());\n }\n if (statusCode4xx) {\n throw e;\n }\n }\n return false;\n } finally {\n lock.unlock();\n }\n }\n\n /**\n * Sets the {@link #setAccessToken access token}, {@link #setRefreshToken refresh token} (if\n * available), and {@link #setExpiresInSeconds expires-in time} based on the values from the token\n * response.\n *\n * <p>It does not call the refresh listeners.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param tokenResponse successful token response\n */\n public Credential setFromTokenResponse(TokenResponse tokenResponse) {\n setAccessToken(tokenResponse.getAccessToken());\n // handle case of having a refresh token previous, but no refresh token in current\n // response\n if (tokenResponse.getRefreshToken() != null) {\n setRefreshToken(tokenResponse.getRefreshToken());\n }\n setExpiresInSeconds(tokenResponse.getExpiresInSeconds());\n return this;\n }\n\n /**\n * Executes a request for new credentials from the token server.\n *\n * <p>The default implementation calls {@link RefreshTokenRequest#execute()} using the {@link\n * #getTransport()}, {@link #getJsonFactory()}, {@link #getRequestInitializer()}, {@link\n * #getTokenServerEncodedUrl()}, {@link #getRefreshToken()}, and the {@link\n * #getClientAuthentication()}. If {@link #getRefreshToken()} is {@code null}, it instead returns\n * {@code null}.\n *\n * <p>Subclasses may override for a different implementation. Implementations can assume proper\n * thread synchronization is already taken care of inside {@link #refreshToken()}.\n *\n * @return successful response from the token server or {@code null} if it is not possible to\n * refresh the access token\n * @throws TokenResponseException if an error response was received from the token server\n */\n protected TokenResponse executeRefreshToken() throws IOException {\n if (refreshToken == null) {\n return null;\n }\n return new RefreshTokenRequest(\n transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), refreshToken)\n .setClientAuthentication(clientAuthentication)\n .setRequestInitializer(requestInitializer)\n .execute();\n }\n\n /** Returns the unmodifiable collection of listeners for refresh token results. */\n public final Collection<CredentialRefreshListener> getRefreshListeners() {\n return refreshListeners;\n }\n\n /**\n * Credential builder.\n *\n * <p>Implementation is not thread-safe.\n */\n public static class Builder {\n\n /**\n * Method of presenting the access token to the resource server (for example {@link\n * BearerToken.AuthorizationHeaderAccessMethod}).\n */\n final AccessMethod method;\n\n /**\n * HTTP transport for executing refresh token request or {@code null} if not refreshing tokens.\n */\n HttpTransport transport;\n\n /**\n * JSON factory to use for parsing response for refresh token request or {@code null} if not\n * refreshing tokens.\n */\n JsonFactory jsonFactory;\n\n /** Token server URL or {@code null} if not refreshing tokens. */\n GenericUrl tokenServerUrl;\n\n /** Clock used for expiration checks. */\n Clock clock = Clock.SYSTEM;\n\n /**\n * Client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n */\n HttpExecuteInterceptor clientAuthentication;\n\n /**\n * HTTP request initializer for refresh token requests to the token server or {@code null} for\n * none.\n */\n HttpRequestInitializer requestInitializer;\n\n /** Listeners for refresh token results. */\n Collection<CredentialRefreshListener> refreshListeners = Lists.newArrayList();\n\n /**\n * @param method method of presenting the access token to the resource server (for example\n * {@link BearerToken.AuthorizationHeaderAccessMethod})\n */\n public Builder(AccessMethod method) {\n this.method = Preconditions.checkNotNull(method);\n }\n\n /** Returns a new credential instance. */\n public Credential build() {\n return new Credential(this);\n }\n\n /**\n * Returns the method of presenting the access token to the resource server (for example {@link\n * BearerToken.AuthorizationHeaderAccessMethod}).\n */\n public final AccessMethod getMethod() {\n return method;\n }\n\n /**\n * Returns the HTTP transport for executing refresh token request or {@code null} if not\n * refreshing tokens.\n */\n public final HttpTransport getTransport() {\n return transport;\n }\n\n /**\n * Sets the HTTP transport for executing refresh token request or {@code null} if not refreshing\n * tokens.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setTransport(HttpTransport transport) {\n this.transport = transport;\n return this;\n }\n\n /**\n * Returns the clock to use for expiration checks or {@link Clock#SYSTEM} as default.\n *\n * @since 1.9\n */\n public final Clock getClock() {\n return clock;\n }\n\n /**\n * Sets the clock to use for expiration checks.\n *\n * <p>The default value is Clock.SYSTEM.\n *\n * @since 1.9\n */\n public Builder setClock(Clock clock) {\n this.clock = Preconditions.checkNotNull(clock);\n return this;\n }\n\n /**\n * Returns the JSON factory to use for parsing response for refresh token request or {@code\n * null} if not refreshing tokens.\n */\n public final JsonFactory getJsonFactory() {\n return jsonFactory;\n }\n\n /**\n * Sets the JSON factory to use for parsing response for refresh token request or {@code null}\n * if not refreshing tokens.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setJsonFactory(JsonFactory jsonFactory) {\n this.jsonFactory = jsonFactory;\n return this;\n }\n\n /** Returns the token server URL or {@code null} if not refreshing tokens. */\n public final GenericUrl getTokenServerUrl() {\n return tokenServerUrl;\n }\n\n /**\n * Sets the token server URL or {@code null} if not refreshing tokens.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setTokenServerUrl(GenericUrl tokenServerUrl) {\n this.tokenServerUrl = tokenServerUrl;\n return this;\n }\n\n /**\n * Sets the encoded token server URL or {@code null} if not refreshing tokens.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) {\n this.tokenServerUrl =\n tokenServerEncodedUrl == null ? null : new GenericUrl(tokenServerEncodedUrl);\n return this;\n }\n\n /**\n * Returns the client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n */\n public final HttpExecuteInterceptor getClientAuthentication() {\n return clientAuthentication;\n }\n\n /**\n * Sets the client authentication or {@code null} for none (see {@link\n * TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}).\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {\n this.clientAuthentication = clientAuthentication;\n return this;\n }\n\n /**\n * Returns the HTTP request initializer for refresh token requests to the token server or {@code\n * null} for none.\n */\n public final HttpRequestInitializer getRequestInitializer() {\n return requestInitializer;\n }\n\n /**\n * Sets the HTTP request initializer for refresh token requests to the token server or {@code\n * null} for none.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) {\n this.requestInitializer = requestInitializer;\n return this;\n }\n\n /**\n * Adds a listener for refresh token results.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n *\n * @param refreshListener refresh listener\n */\n public Builder addRefreshListener(CredentialRefreshListener refreshListener) {\n refreshListeners.add(Preconditions.checkNotNull(refreshListener));\n return this;\n }\n\n /** Returns the listeners for refresh token results. */\n public final Collection<CredentialRefreshListener> getRefreshListeners() {\n return refreshListeners;\n }\n\n /**\n * Sets the listeners for refresh token results.\n *\n * <p>Overriding is only supported for the purpose of calling the super implementation and\n * changing the return type, but nothing else.\n */\n public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) {\n this.refreshListeners = Preconditions.checkNotNull(refreshListeners);\n return this;\n }\n }\n}", "public class AuthorizationCodeInstalledApp {\n\n /** Helper interface to allow caller to browse. */\n public static interface Browser {\n /**\n * @param url url to browse\n * @throws IOException\n */\n public void browse(String url) throws IOException;\n }\n\n /**\n * Default browser that just delegates to {@link AuthorizationCodeInstalledApp#browse(String)}.\n */\n public static class DefaultBrowser implements Browser {\n\n @Override\n public void browse(String url) throws IOException {\n AuthorizationCodeInstalledApp.browse(url);\n }\n }\n\n /** Authorization code flow. */\n private final AuthorizationCodeFlow flow;\n\n /** Verification code receiver. */\n private final VerificationCodeReceiver receiver;\n\n private static final Logger LOGGER =\n Logger.getLogger(AuthorizationCodeInstalledApp.class.getName());\n\n private final Browser browser;\n\n /**\n * @param flow authorization code flow\n * @param receiver verification code receiver\n */\n public AuthorizationCodeInstalledApp(\n AuthorizationCodeFlow flow, VerificationCodeReceiver receiver) {\n this(flow, receiver, new DefaultBrowser());\n }\n\n /**\n * @param flow authorization code flow\n * @param receiver verification code receiver\n */\n public AuthorizationCodeInstalledApp(\n AuthorizationCodeFlow flow, VerificationCodeReceiver receiver, Browser browser) {\n this.flow = Preconditions.checkNotNull(flow);\n this.receiver = Preconditions.checkNotNull(receiver);\n this.browser = browser;\n }\n\n /**\n * Authorizes the installed application to access user's protected data.\n *\n * @param userId user ID or {@code null} if not using a persisted credential store\n * @return credential\n * @throws IOException\n */\n public Credential authorize(String userId) throws IOException {\n try {\n Credential credential = flow.loadCredential(userId);\n if (credential != null\n && (credential.getRefreshToken() != null\n || credential.getExpiresInSeconds() == null\n || credential.getExpiresInSeconds() > 60)) {\n return credential;\n }\n // open in browser\n String redirectUri = receiver.getRedirectUri();\n AuthorizationCodeRequestUrl authorizationUrl =\n flow.newAuthorizationUrl().setRedirectUri(redirectUri);\n onAuthorization(authorizationUrl);\n // receive authorization code and exchange it for an access token\n String code = receiver.waitForCode();\n TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();\n // store credential and return it\n return flow.createAndStoreCredential(response, userId);\n } finally {\n receiver.stop();\n }\n }\n\n /**\n * Handles user authorization by redirecting to the OAuth 2.0 authorization server.\n *\n * <p>Default implementation is to call {@code browse(authorizationUrl.build())}. Subclasses may\n * override to provide optional parameters such as the recommended state parameter. Sample\n * implementation:\n *\n * <pre>\n * &#64;Override\n * protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {\n * authorizationUrl.setState(\"xyz\");\n * super.onAuthorization(authorizationUrl);\n * }\n * </pre>\n *\n * @param authorizationUrl authorization URL\n * @throws IOException I/O exception\n */\n protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {\n String url = authorizationUrl.build();\n Preconditions.checkNotNull(url);\n browser.browse(url);\n }\n\n /**\n * Open a browser at the given URL using {@link Desktop} if available, or alternatively output the\n * URL to {@link System#out} for command-line applications.\n *\n * @param url URL to browse\n */\n public static void browse(String url) {\n Preconditions.checkNotNull(url);\n // Ask user to open in their browser using copy-paste\n System.out.println(\"Please open the following address in your browser:\");\n System.out.println(\" \" + url);\n // Attempt to open it in the browser\n try {\n if (Desktop.isDesktopSupported()) {\n Desktop desktop = Desktop.getDesktop();\n if (desktop.isSupported(Action.BROWSE)) {\n System.out.println(\"Attempting to open that address in the default browser now...\");\n desktop.browse(URI.create(url));\n }\n }\n } catch (IOException e) {\n LOGGER.log(Level.WARNING, \"Unable to open browser\", e);\n } catch (InternalError e) {\n // A bug in a JRE can cause Desktop.isDesktopSupported() to throw an\n // InternalError rather than returning false. The error reads,\n // \"Can't connect to X11 window server using ':0.0' as the value of the\n // DISPLAY variable.\" The exact error message may vary slightly.\n LOGGER.log(Level.WARNING, \"Unable to open browser\", e);\n }\n }\n\n /** Returns the authorization code flow. */\n public final AuthorizationCodeFlow getFlow() {\n return flow;\n }\n\n /** Returns the verification code receiver. */\n public final VerificationCodeReceiver getReceiver() {\n return receiver;\n }\n}", "public final class LocalServerReceiver implements VerificationCodeReceiver {\n\n private static final String LOCALHOST = \"localhost\";\n\n private static final String CALLBACK_PATH = \"/Callback\";\n\n /** Server or {@code null} before {@link #getRedirectUri()}. */\n private HttpServer server;\n\n /** Verification code or {@code null} for none. */\n String code;\n\n /** Error code or {@code null} for none. */\n String error;\n\n /** To block until receiving an authorization response or stop() is called. */\n final Semaphore waitUnlessSignaled = new Semaphore(0 /* initially zero permit */);\n\n /** Port to use or {@code -1} to select an unused port in {@link #getRedirectUri()}. */\n private int port;\n\n /** Host name to use. */\n private final String host;\n\n /** Callback path of redirect_uri. */\n private final String callbackPath;\n\n /**\n * URL to an HTML page to be shown (via redirect) after successful login. If null, a canned\n * default landing page will be shown (via direct response).\n */\n private String successLandingPageUrl;\n\n /**\n * URL to an HTML page to be shown (via redirect) after failed login. If null, a canned default\n * landing page will be shown (via direct response).\n */\n private String failureLandingPageUrl;\n\n /**\n * Constructor that starts the server on {@link #LOCALHOST} and an unused port.\n *\n * <p>Use {@link Builder} if you need to specify any of the optional parameters.\n */\n public LocalServerReceiver() {\n this(LOCALHOST, -1, CALLBACK_PATH, null, null);\n }\n\n /**\n * Constructor.\n *\n * @param host Host name to use\n * @param port Port to use or {@code -1} to select an unused port\n */\n LocalServerReceiver(\n String host, int port, String successLandingPageUrl, String failureLandingPageUrl) {\n this(host, port, CALLBACK_PATH, successLandingPageUrl, failureLandingPageUrl);\n }\n\n /**\n * Constructor.\n *\n * @param host Host name to use\n * @param port Port to use or {@code -1} to select an unused port\n */\n LocalServerReceiver(\n String host,\n int port,\n String callbackPath,\n String successLandingPageUrl,\n String failureLandingPageUrl) {\n this.host = host;\n this.port = port;\n this.callbackPath = callbackPath;\n this.successLandingPageUrl = successLandingPageUrl;\n this.failureLandingPageUrl = failureLandingPageUrl;\n }\n\n @Override\n public String getRedirectUri() throws IOException {\n\n server = HttpServer.create(new InetSocketAddress(port != -1 ? port : findOpenPort()), 0);\n HttpContext context = server.createContext(callbackPath, new CallbackHandler());\n server.setExecutor(null);\n\n try {\n server.start();\n port = server.getAddress().getPort();\n } catch (Exception e) {\n Throwables.propagateIfPossible(e);\n throw new IOException(e);\n }\n return \"http://\" + this.getHost() + \":\" + port + callbackPath;\n }\n\n /*\n * Copied from Jetty findFreePort() as referenced by: https://gist.github.com/vorburger/3429822\n */\n private int findOpenPort() {\n try (ServerSocket socket = new ServerSocket(0)) {\n socket.setReuseAddress(true);\n return socket.getLocalPort();\n } catch (IOException e) {\n throw new IllegalStateException(\"No free TCP/IP port to start embedded HTTP Server on\");\n }\n }\n\n /**\n * Blocks until the server receives a login result, or the server is stopped by {@link #stop()},\n * to return an authorization code.\n *\n * @return authorization code if login succeeds; may return {@code null} if the server is stopped\n * by {@link #stop()}\n * @throws IOException if the server receives an error code (through an HTTP request parameter\n * {@code error})\n */\n @Override\n public String waitForCode() throws IOException {\n waitUnlessSignaled.acquireUninterruptibly();\n if (error != null) {\n throw new IOException(\"User authorization failed (\" + error + \")\");\n }\n return code;\n }\n\n @Override\n public void stop() throws IOException {\n waitUnlessSignaled.release();\n if (server != null) {\n try {\n server.stop(0);\n } catch (Exception e) {\n Throwables.propagateIfPossible(e);\n throw new IOException(e);\n }\n server = null;\n }\n }\n\n /** Returns the host name to use. */\n public String getHost() {\n return host;\n }\n\n /**\n * Returns the port to use or {@code -1} to select an unused port in {@link #getRedirectUri()}.\n */\n public int getPort() {\n return port;\n }\n\n /** Returns callback path used in redirect_uri. */\n public String getCallbackPath() {\n return callbackPath;\n }\n\n /**\n * Builder.\n *\n * <p>Implementation is not thread-safe.\n */\n public static final class Builder {\n\n /** Host name to use. */\n private String host = LOCALHOST;\n\n /** Port to use or {@code -1} to select an unused port. */\n private int port = -1;\n\n private String successLandingPageUrl;\n private String failureLandingPageUrl;\n\n private String callbackPath = CALLBACK_PATH;\n\n /** Builds the {@link LocalServerReceiver}. */\n public LocalServerReceiver build() {\n return new LocalServerReceiver(\n host, port, callbackPath, successLandingPageUrl, failureLandingPageUrl);\n }\n\n /** Returns the host name to use. */\n public String getHost() {\n return host;\n }\n\n /** Sets the host name to use. */\n public Builder setHost(String host) {\n this.host = host;\n return this;\n }\n\n /** Returns the port to use or {@code -1} to select an unused port. */\n public int getPort() {\n return port;\n }\n\n /** Sets the port to use or {@code -1} to select an unused port. */\n public Builder setPort(int port) {\n this.port = port;\n return this;\n }\n\n /** Returns the callback path of redirect_uri. */\n public String getCallbackPath() {\n return callbackPath;\n }\n\n /** Set the callback path of redirect_uri. */\n public Builder setCallbackPath(String callbackPath) {\n this.callbackPath = callbackPath;\n return this;\n }\n\n public Builder setLandingPages(String successLandingPageUrl, String failureLandingPageUrl) {\n this.successLandingPageUrl = successLandingPageUrl;\n this.failureLandingPageUrl = failureLandingPageUrl;\n return this;\n }\n }\n\n /**\n * HttpServer handler that takes the verifier token passed over from the OAuth provider and\n * stashes it where {@link #waitForCode} will find it.\n */\n class CallbackHandler implements HttpHandler {\n\n @Override\n public void handle(HttpExchange httpExchange) throws IOException {\n\n if (!callbackPath.equals(httpExchange.getRequestURI().getPath())) {\n return;\n }\n\n StringBuilder body = new StringBuilder();\n\n try {\n Map<String, String> parms = this.queryToMap(httpExchange.getRequestURI().getQuery());\n error = parms.get(\"error\");\n code = parms.get(\"code\");\n\n Headers respHeaders = httpExchange.getResponseHeaders();\n if (error == null && successLandingPageUrl != null) {\n respHeaders.add(\"Location\", successLandingPageUrl);\n httpExchange.sendResponseHeaders(HTTP_MOVED_TEMP, -1);\n } else if (error != null && failureLandingPageUrl != null) {\n respHeaders.add(\"Location\", failureLandingPageUrl);\n httpExchange.sendResponseHeaders(HTTP_MOVED_TEMP, -1);\n } else {\n writeLandingHtml(httpExchange, respHeaders);\n }\n httpExchange.close();\n } finally {\n waitUnlessSignaled.release();\n }\n }\n\n private Map<String, String> queryToMap(String query) {\n Map<String, String> result = new HashMap<String, String>();\n if (query != null) {\n for (String param : query.split(\"&\")) {\n String pair[] = param.split(\"=\");\n if (pair.length > 1) {\n result.put(pair[0], pair[1]);\n } else {\n result.put(pair[0], \"\");\n }\n }\n }\n return result;\n }\n\n private void writeLandingHtml(HttpExchange exchange, Headers headers) throws IOException {\n try (OutputStream os = exchange.getResponseBody()) {\n exchange.sendResponseHeaders(HTTP_OK, 0);\n headers.add(\"ContentType\", \"text/html\");\n\n OutputStreamWriter doc = new OutputStreamWriter(os, StandardCharsets.UTF_8);\n doc.write(\"<html>\");\n doc.write(\"<head><title>OAuth 2.0 Authentication Token Received</title></head>\");\n doc.write(\"<body>\");\n doc.write(\"Received verification code. You may now close this window.\");\n doc.write(\"</body>\");\n doc.write(\"</html>\\n\");\n doc.flush();\n }\n }\n }\n}" ]
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.FileDataStoreFactory; import java.io.File; import java.io.IOException; import java.util.Arrays;
/* * Copyright (c) 2011 Google Inc. * * 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 com.google.api.services.samples.dailymotion.cmdline; /** * A sample application that demonstrates how the Google OAuth2 library can be used to authenticate * against Daily Motion. * * @author Ravi Mistry */ public class DailyMotionSample { /** Directory to store user credentials. */ private static final File DATA_STORE_DIR = new File(System.getProperty("user.home"), ".store/dailymotion_sample"); /** * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single * globally shared instance across your application. */ private static FileDataStoreFactory DATA_STORE_FACTORY; /** OAuth 2 scope. */ private static final String SCOPE = "read"; /** Global instance of the HTTP transport. */ private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); /** Global instance of the JSON factory. */ static final JsonFactory JSON_FACTORY = new GsonFactory(); private static final String TOKEN_SERVER_URL = "https://api.dailymotion.com/oauth/token"; private static final String AUTHORIZATION_SERVER_URL = "https://api.dailymotion.com/oauth/authorize"; /** Authorizes the installed application to access user's protected data. */ private static Credential authorize() throws Exception { OAuth2ClientCredentials.errorIfNotSpecified(); // set up authorization code flow AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(TOKEN_SERVER_URL), new ClientParametersAuthentication( OAuth2ClientCredentials.API_KEY, OAuth2ClientCredentials.API_SECRET), OAuth2ClientCredentials.API_KEY, AUTHORIZATION_SERVER_URL) .setScopes(Arrays.asList(SCOPE)) .setDataStoreFactory(DATA_STORE_FACTORY) .build(); // authorize
LocalServerReceiver receiver =
5
ResearchStack/ResearchStack
backbone/src/main/java/org/researchstack/backbone/ui/step/layout/SurveyStepLayout.java
[ "public abstract class ResourcePathManager {\n private static Gson gson = new GsonBuilder().setDateFormat(\"MMM yyyy\").create();\n\n private static ResourcePathManager instance;\n\n /**\n * Initializes the ResourcePathManager singleton. It is best to call this method inside your\n * {@link Application#onCreate()} method.\n *\n * @param manager an implementation of ResourcePathManager\n */\n public static void init(ResourcePathManager manager) {\n ResourcePathManager.instance = manager;\n }\n\n /**\n * Returns the singleton instance of this class.\n *\n * @return the singleton instance of this class\n */\n public static ResourcePathManager getInstance() {\n if (instance == null) {\n throw new RuntimeException(\n \"ResourceManager instance is null. Make sure to init a concrete implementation of ResearchStack in Application.onCreate()\");\n }\n\n return instance;\n }\n\n /**\n * Load resource from a file-path and turns contents to a String for consumption\n *\n * @param context android context\n * @param filePath relative file path\n * @return String representation of the file\n */\n public static String getResourceAsString(Context context, String filePath) {\n return new String(getResourceAsBytes(context, filePath), Charset.forName(\"UTF-8\"));\n }\n\n /**\n * Load resource from a file-path and turns contents to a byte[] for consumption\n *\n * @param context android context\n * @param filePath relative file path\n * @return byte [] representation of the asset\n */\n public static byte[] getResourceAsBytes(Context context, String filePath) {\n InputStream is = getResouceAsInputStream(context, filePath);\n ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();\n\n byte[] readBuffer = new byte[4 * 1024];\n\n try {\n int read;\n do {\n read = is.read(readBuffer, 0, readBuffer.length);\n if (read == -1) {\n break;\n }\n byteOutput.write(readBuffer, 0, read);\n }\n while (true);\n\n return byteOutput.toByteArray();\n } catch (IOException e) {\n LogExt.e(ResourcePathManager.class, e);\n } finally {\n try {\n is.close();\n } catch (IOException e) {\n LogExt.e(ResourcePathManager.class, e);\n }\n }\n return null;\n }\n\n /**\n * Load resource from a file-path and turns contents to a InputStream for consumption\n *\n * @param context android context\n * @param filePath relative file path\n * @return InputStream representation of the asset\n */\n public static InputStream getResouceAsInputStream(Context context, String filePath) {\n AssetManager assetManager = context.getAssets();\n InputStream inputStream = null;\n try {\n return assetManager.open(filePath);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Load resource from a file-path and turns contents to a objects, of type T, for consumption\n *\n * @param context android context\n * @param clazz the class of T\n * @param filePath relative file path\n * @return Class representation of the asset\n */\n public static <T> T getResourceAsClass(Context context, Class<T> clazz, String filePath) {\n InputStream stream = getResouceAsInputStream(context, filePath);\n Reader reader = null;\n try {\n reader = new InputStreamReader(stream, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n\n return gson.fromJson(reader, clazz);\n }\n\n /**\n * The genereatePath method is abstract as the Framework does not know what the parent\n * directory of a file is. While it is possible to open a file using only the fileName, there are\n * many instances where we need the path of a file instead (like for WebView). This method is\n * used for that purpose and is used to get the path of a resource when the framework only knows\n * the name of the file and what type of file it is.\n *\n * @param type the type of file. This will be used for appending the file extension.\n * @param name the name of the file\n * @return a path relative to the asset folder\n */\n public abstract String generatePath(int type, String name);\n\n /**\n * Generates an absolute string file path\n *\n * @param type the type of file. This will be used for appending the file extension.\n * @param name the name of the file\n * @return an absolute path for a file\n */\n public String generateAbsolutePath(int type, String name) {\n return new StringBuilder(\"file:///android_asset/\").append(generatePath(type, name))\n .toString();\n }\n\n /**\n * @param type the type of file. Supported file types are defined within the {@link Resource}\n * class. You may override this method in your implementation and implement your own\n * cases\n * @return file extension of a file type\n */\n public String getFileExtension(int type) {\n switch (type) {\n case Resource.TYPE_HTML:\n return \"html\";\n case Resource.TYPE_JSON:\n return \"json\";\n case Resource.TYPE_PDF:\n return \"pdf\";\n case Resource.TYPE_MP4:\n return \"mp4\";\n default:\n throw new IllegalArgumentException(\"Unknown type \" + type);\n }\n }\n\n /**\n * Class represents one asset within the assets folder.\n */\n public static class Resource {\n public static final int TYPE_HTML = 0;\n public static final int TYPE_JSON = 1;\n public static final int TYPE_PDF = 2;\n public static final int TYPE_MP4 = 3;\n\n private final int type;\n private final String dir;\n private final String name;\n private Class clazz;\n\n /**\n * Initializes this Resource object\n *\n * @param type the type of file of the resource\n * @param dir the sub directory of the fiel\n * @param name the name of the file (excluding extension)\n */\n public Resource(int type, String dir, String name) {\n this(type, dir, name, null);\n }\n\n /**\n * Initializes this Resource object\n *\n * @param type the type of file of the resource\n * @param dir the dir path of the file\n * @param name the name of the file (excluding extension)\n * @param clazz the class file that this file is represented as\n */\n public Resource(int type, String dir, String name, Class clazz) {\n this.type = type;\n this.dir = dir;\n this.name = name;\n this.clazz = clazz;\n }\n\n /**\n * Returns the directroy path of this Resource\n *\n * @return The dir path of the file\n */\n public String getDir() {\n return dir;\n }\n\n /**\n * Returns the name of this Resource\n *\n * @return the name, excluding extension, of the file\n */\n public String getName() {\n return name;\n }\n\n /**\n * Returns the file type of this Resource\n *\n * @return The dir path of the file\n */\n public int getType() {\n return type;\n }\n\n /**\n * Create this Resource into an Object of type T. This method will only work for Json\n * files.\n *\n * @param context android context\n * @return object of type T\n */\n public <T> T create(Context context) {\n String path = getRelativePath();\n return ResourcePathManager.getResourceAsClass(context, (Class<T>) clazz, path);\n }\n\n /**\n * Returns an inputstream for this Resource\n *\n * @param context android context\n * @return InputStream of the resource\n */\n public InputStream open(Context context) {\n String path = getRelativePath();\n return getResouceAsInputStream(context, path);\n }\n\n /**\n * Returns the absolute path of this Resource\n *\n * @return the absolute path of this Resource\n */\n public String getAbsolutePath() {\n return new StringBuilder(\"file:///android_asset/\").append(getRelativePath()).toString();\n }\n\n /**\n * Returns the relative path of this Resource\n *\n * @return the relative path of this Resource\n */\n public String getRelativePath() {\n StringBuilder path = new StringBuilder();\n if (!TextUtils.isEmpty(dir)) {\n path.append(dir).append(\"/\");\n }\n\n return path.append(name).append(\".\").append(getFileExtension()).toString();\n }\n\n /**\n * Returns the file extension of this Resource\n *\n * @return the file extension of this Resource\n */\n public String getFileExtension() {\n return ResourcePathManager.getInstance().getFileExtension(type);\n }\n }\n\n}", "public class StepResult<T> extends Result {\n /**\n * When StepResult only has a single value, pair that value with the following key\n */\n public static final String DEFAULT_KEY = \"answer\";\n\n private Map<String, T> results;\n\n private AnswerFormat answerFormat;\n\n /**\n * Creates a StepResult from a {@link Step}.\n * <p>\n * Using this constructor ensures that the StepResult has the correct identifier and answer\n * format for the corresponding step.\n *\n * @param step the step from which to create the StepResult\n */\n public StepResult(Step step) {\n super(step.getIdentifier());\n this.results = new HashMap<>();\n\n if (step instanceof QuestionStep) {\n answerFormat = ((QuestionStep) step).getAnswerFormat();\n }\n setStartDate(new Date());\n // this will be updated when the result is set\n setEndDate(new Date());\n }\n\n public Map<String, T> getResults() {\n return results;\n }\n\n public void setResults(Map<String, T> results) {\n this.results = results;\n }\n\n /**\n * Returns the result stored using {@link #setResult}.\n *\n * @return the result with the default identifier\n */\n public T getResult() {\n return getResultForIdentifier(DEFAULT_KEY);\n }\n\n /**\n * Sets the result using the default key, useful when there is only a single result.\n *\n * @param result the result to save with the default key\n */\n public void setResult(T result) {\n setResultForIdentifier(DEFAULT_KEY, result);\n setEndDate(new Date());\n }\n\n /**\n * Returns the result for the given identifier, use this when there are multiple results for the\n * step.\n *\n * @param identifier the identifier used as the key for storing this result\n * @return the result for the given identifier\n */\n public T getResultForIdentifier(String identifier) {\n return results.get(identifier);\n }\n\n /**\n * Sets the result for the given identifier, use when there are multiple results for the step.\n * <p>\n * If there is only one result, use the {@link #setResult} convenience method instead.\n *\n * @param identifier the identifier for the result\n * @param result the result to save\n */\n public void setResultForIdentifier(String identifier, T result) {\n results.put(identifier, result);\n }\n\n /**\n * Gets the {@link AnswerFormat} for this step result. May be useful when processing the\n * result.\n *\n * @return the answer format associated with the step\n */\n public AnswerFormat getAnswerFormat() {\n return answerFormat;\n }\n}", "public class QuestionStep extends Step {\n private AnswerFormat answerFormat;\n\n private String placeholder;\n\n /**\n * Returns a new question step that includes the specified identifier.\n *\n * @param identifier The identifier of the step (a step identifier should be unique within the\n * task).\n */\n public QuestionStep(String identifier) {\n super(identifier);\n }\n\n /**\n * Returns a new question step that includes the specified identifier, and title.\n *\n * @param identifier The identifier of the step (a step identifier should be unique within the\n * task).\n * @param title A localized string that represents the primary text of the question.\n */\n public QuestionStep(String identifier, String title) {\n super(identifier, title);\n }\n\n /**\n * Returns a new question step that includes the specified identifier, title, and answer\n * format.\n *\n * @param identifier The identifier of the step (a step identifier should be unique within the\n * task).\n * @param title A localized string that represents the primary text of the question.\n * @param format The format in which the answer is expected.\n */\n public QuestionStep(String identifier, String title, AnswerFormat format) {\n super(identifier, title);\n this.answerFormat = format;\n }\n\n /**\n * Returns a special {@link org.researchstack.backbone.ui.step.layout.StepLayout} that is used\n * for all question steps.\n * <p>\n * This step layout uses the {@link #getStepBodyClass()} to fill in the user interaction portion\n * of the layout's UI.\n *\n * @return the StepLayout to be used for general QuestionSteps\n */\n @Override\n public Class getStepLayoutClass() {\n return SurveyStepLayout.class;\n }\n\n /**\n * Returns a subclass of {@link org.researchstack.backbone.ui.step.body.StepBody} responsible\n * for creating the ui for answering the question, base on the AnswerFormat.\n * <p>\n * This class is used by {@link SurveyStepLayout} to create the part of the layout where the\n * user answers the question. For example, a StepBody for a simple text question would be\n * responsible for creating an EditText for the SurveyStepLayout to place inside of its layout.\n * <p>\n * Override this method with your own StepBody implementation if you create a custom\n * QuestionStep.\n *\n * @return the StepBody implementation for this question step.\n */\n public Class<?> getStepBodyClass() {\n return answerFormat.getQuestionType().getStepBodyClass();\n }\n\n /**\n * Returns the format of the answer.\n * <p>\n * For example, the answer format might include the type of data to collect, the constraints to\n * place on the answer, or a list of available choices (in the case of single or multiple select\n * questions). It also provides the default {@link org.researchstack.backbone.ui.step.body.StepBody}\n * for questions of its type.\n *\n * @return the answer format for this question step\n */\n public AnswerFormat getAnswerFormat() {\n return answerFormat;\n }\n\n /**\n * Sets the answer format for this question step.\n *\n * @param answerFormat the answer format for this question step\n * @see #getAnswerFormat()\n */\n public void setAnswerFormat(AnswerFormat answerFormat) {\n this.answerFormat = answerFormat;\n }\n\n /**\n * Returns a localized string that represents the placeholder text displayed before an answer\n * has been entered.\n * <p>\n * For numeric and text-based answers, the placeholder content is displayed in the text field or\n * text area when an answer has not yet been entered.\n *\n * @return the placeholder string\n */\n public String getPlaceholder() {\n return placeholder;\n }\n\n /**\n * Sets a localized string that represents the placeholder text displayed before an answer has\n * been entered.\n * <p>\n * For numeric and text-based answers, the placeholder content is displayed in the text field or\n * text area when an answer has not yet been entered.\n *\n * @param placeholder the placeholder string\n */\n public void setPlaceholder(String placeholder) {\n this.placeholder = placeholder;\n }\n}", "public class Step implements Serializable {\n private String identifier;\n\n private Class stepLayoutClass;\n\n private int stepTitle;\n\n private boolean optional = true;\n\n private String title;\n\n private String text;\n\n // The following fields are in RK but not implemented in ResearchStack\n // These options can be developed as needed or removed if we find they are not necessary\n private boolean restorable;\n private Task task;\n private boolean shouldTintImages;\n private boolean showsProgress;\n private boolean allowsBackNavigation;\n private boolean useSurveyMode;\n\n /**\n * Returns a new step initialized with the specified identifier.\n *\n * @param identifier The unique identifier of the step.\n */\n public Step(String identifier) {\n this.identifier = identifier;\n }\n\n /**\n * Returns a new step initialized with the specified identifier and title.\n *\n * @param identifier The unique identifier of the step.\n * @param title The primary text to display for this step.\n */\n public Step(String identifier, String title) {\n this.identifier = identifier;\n this.title = title;\n }\n\n /**\n * A short string that uniquely identifies the step within the task.\n * <p>\n * The identifier is reproduced in the results of a step. In fact, the only way to link a result\n * (a {@link org.researchstack.backbone.result.StepResult} object) to the step that generated it\n * is to look at the value of <code>identifier</code>. To accurately identify step results, you\n * need to ensure that step identifiers are unique within each task.\n * <p>\n * In some cases, it can be useful to link the step identifier to a unique identifier in a\n * database; in other cases, it can make sense to make the identifier human readable.\n */\n public String getIdentifier() {\n return identifier;\n }\n\n /**\n * A boolean value indicating whether the user can skip the step without providing an answer.\n * <p>\n * The default value of this property is <code>true</code>. When the value is\n * <code>false</code>, the Skip button does not appear on this step.\n * <p>\n * This property may not be meaningful for all steps; for example, an active step might not\n * provide a way to skip, because it requires a timer to finish.\n *\n * @return a boolean indicating whether the step is skippable\n */\n public boolean isOptional() {\n return optional;\n }\n\n /**\n * Sets whether the step is skippable\n *\n * @param optional\n * @see #isOptional()\n */\n public void setOptional(boolean optional) {\n this.optional = optional;\n }\n\n /**\n * The primary text to display for the step in a localized string.\n * <p>\n * This text is also used as the label when a step is shown in the more compact version in a\n * {@link FormStep}.\n *\n * @return the primary text for the question\n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Sets the primary text to display for the step in a localized string.\n *\n * @param title the primary text for the question.\n * @see #getTitle()\n */\n public void setTitle(String title) {\n this.title = title;\n }\n\n /**\n * Additional text to display for the step in a localized string.\n * <p>\n * The additional text is displayed in a smaller font below <code>title</code>. If you need to\n * display a long question, it can work well to keep the title short and put the additional\n * content in the <code>text</code> property.\n *\n * @return\n */\n public String getText() {\n return text;\n }\n\n /**\n * Sets the additional text for the step.\n *\n * @param text the detail text for the step\n * @see #getText()\n */\n public void setText(String text) {\n this.text = text;\n }\n\n /**\n * Gets the int id for the title to display in the action bar (optional).\n *\n * @return the id for the title to display in the action bar\n */\n public int getStepTitle() {\n return stepTitle;\n }\n\n /**\n * Gets the int id for the title to display in the action bar (optional).\n *\n * @param stepTitle the Android resource id for the title\n */\n public void setStepTitle(int stepTitle) {\n this.stepTitle = stepTitle;\n }\n\n /**\n * Returns the class that the {@link org.researchstack.backbone.ui.ViewTaskActivity} should\n * instantiate to display this step.\n * <p>\n * This method is used within the framework so that steps can define their step view controller\n * pairing.\n * <p>\n * Outside the framework, developers should instantiate the required view controller in their\n * ViewTaskActivity delegate to override the ViewTaskActivity's default.\n *\n * @return the class of the {@link org.researchstack.backbone.ui.step.layout.StepLayout} for\n * this step\n */\n public Class getStepLayoutClass() {\n return stepLayoutClass;\n }\n\n /**\n * Sets the class that should be used to display this step\n *\n * @param stepLayoutClass the {@link org.researchstack.backbone.ui.step.layout.StepLayout} class\n * to be used to display this step\n */\n public void setStepLayoutClass(Class stepLayoutClass) {\n this.stepLayoutClass = stepLayoutClass;\n }\n}", "public class BodyAnswer {\n public static final BodyAnswer VALID = new BodyAnswer(true, 0);\n public static final BodyAnswer INVALID = new BodyAnswer(false,\n R.string.rsb_invalid_answer_default);\n\n private boolean isValid;\n private int reason;\n private String[] params;\n\n public BodyAnswer(boolean isValid, @StringRes int reason, String... params) {\n this.isValid = isValid;\n this.reason = reason;\n this.params = params;\n }\n\n public boolean isValid() {\n return isValid;\n }\n\n @StringRes\n public int getReason() {\n return reason;\n }\n\n public String[] getParams() {\n return params;\n }\n\n public String getString(Context context) {\n if (getParams().length == 0) {\n return context.getString(getReason());\n } else {\n return context.getString(getReason(), getParams());\n }\n }\n}", "public class TextUtils {\n public static final Pattern EMAIL_ADDRESS = Pattern.compile(\n \"[a-zA-Z0-9\\\\+\\\\.\\\\_\\\\%\\\\-\\\\+]{1,256}\" +\n \"\\\\@\" +\n \"[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,64}\" +\n \"(\" +\n \"\\\\.\" +\n \"[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,25}\" +\n \")+\");\n\n private TextUtils() {\n }\n\n /**\n * Returns true if the string is null or 0-length.\n *\n * @param str the string to be examined\n * @return true if str is null or zero length\n */\n public static boolean isEmpty(CharSequence str) {\n if (str == null || str.length() == 0) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Returns true if the char sequence is a valid email address\n *\n * @param text the email address to be validated\n * @return a boolean indicating whether the email is valid\n */\n public static boolean isValidEmail(CharSequence text) {\n return !isEmpty(text) && EMAIL_ADDRESS.matcher(text).matches();\n }\n\n\n public static class AlphabeticFilter implements InputFilter {\n @Override\n public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {\n for (int i = start; i < end; i++) {\n if (!Character.isLetter(source.charAt(i))) {\n return \"\";\n }\n }\n return null;\n }\n }\n\n public static class NumericFilter implements InputFilter {\n @Override\n public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {\n for (int i = start; i < end; i++) {\n if (!Character.isDigit(source.charAt(i))) {\n return \"\";\n }\n }\n return null;\n }\n }\n\n public static class AlphanumericFilter implements InputFilter {\n @Override\n public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {\n for (int i = start; i < end; i++) {\n if (!Character.isLetterOrDigit(source.charAt(i))) {\n return \"\";\n }\n }\n return null;\n }\n }\n}" ]
import android.content.Context; import android.content.Intent; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.text.Html; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.researchstack.backbone.R; import org.researchstack.backbone.ResourcePathManager; import org.researchstack.backbone.result.StepResult; import org.researchstack.backbone.step.QuestionStep; import org.researchstack.backbone.step.Step; import org.researchstack.backbone.ui.ViewWebDocumentActivity; import org.researchstack.backbone.ui.callbacks.StepCallbacks; import org.researchstack.backbone.ui.step.body.BodyAnswer; import org.researchstack.backbone.ui.step.body.StepBody; import org.researchstack.backbone.ui.views.FixedSubmitBarLayout; import org.researchstack.backbone.ui.views.SubmitBar; import org.researchstack.backbone.utils.LogExt; import org.researchstack.backbone.utils.TextUtils; import java.lang.reflect.Constructor;
package org.researchstack.backbone.ui.step.layout; public class SurveyStepLayout extends FixedSubmitBarLayout implements StepLayout { public static final String TAG = SurveyStepLayout.class.getSimpleName(); //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Data used to initializeLayout and return //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= private QuestionStep questionStep; private StepResult stepResult; //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Communicate w/ host //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= private StepCallbacks callbacks; //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Child Views //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= private LinearLayout container; private StepBody stepBody; public SurveyStepLayout(Context context) { super(context); } public SurveyStepLayout(Context context, AttributeSet attrs) { super(context, attrs); } public SurveyStepLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void initialize(Step step) { initialize(step, null); } @Override public void initialize(Step step, StepResult result) { if (!(step instanceof QuestionStep)) { throw new RuntimeException("Step being used in SurveyStep is not a QuestionStep"); } this.questionStep = (QuestionStep) step; this.stepResult = result; initializeStep(); } @Override public View getLayout() { return this; } /** * Method allowing a step to consume a back event. * * @return */ @Override public boolean isBackEventConsumed() { callbacks.onSaveStep(StepCallbacks.ACTION_PREV, getStep(), stepBody.getStepResult(false)); return false; } @Override public void setCallbacks(StepCallbacks callbacks) { this.callbacks = callbacks; } @Override public int getContentResourceId() { return R.layout.rsb_step_layout; } public void initializeStep() { initStepLayout(); initStepBody(); } public void initStepLayout() { LogExt.i(getClass(), "initStepLayout()"); container = (LinearLayout) findViewById(R.id.rsb_survey_content_container); TextView title = (TextView) findViewById(R.id.rsb_survey_title); TextView summary = (TextView) findViewById(R.id.rsb_survey_text); SubmitBar submitBar = (SubmitBar) findViewById(R.id.rsb_submit_bar); submitBar.setPositiveAction(v -> onNextClicked()); if (questionStep != null) { if (!TextUtils.isEmpty(questionStep.getTitle())) { title.setVisibility(View.VISIBLE); title.setText(questionStep.getTitle()); } if (!TextUtils.isEmpty(questionStep.getText())) { summary.setVisibility(View.VISIBLE); summary.setText(Html.fromHtml(questionStep.getText())); summary.setMovementMethod(new TextViewLinkHandler() { @Override public void onLinkClick(String url) { String path = ResourcePathManager.getInstance(). generateAbsolutePath(ResourcePathManager.Resource.TYPE_HTML, url); Intent intent = ViewWebDocumentActivity.newIntentForPath(getContext(), questionStep.getTitle(), path); getContext().startActivity(intent); } }); } if (questionStep.isOptional()) { submitBar.setNegativeTitle(R.string.rsb_step_skip); submitBar.setNegativeAction(v -> onSkipClicked()); } else { submitBar.getNegativeActionView().setVisibility(View.GONE); } } } public void initStepBody() { LogExt.i(getClass(), "initStepBody()"); LayoutInflater inflater = LayoutInflater.from(getContext()); stepBody = createStepBody(questionStep, stepResult); View body = stepBody.getBodyView(StepBody.VIEW_TYPE_DEFAULT, inflater, this); if (body != null) { View oldView = container.findViewById(R.id.rsb_survey_step_body); int bodyIndex = container.indexOfChild(oldView); container.removeView(oldView); container.addView(body, bodyIndex); body.setId(R.id.rsb_survey_step_body); } } @NonNull private StepBody createStepBody(QuestionStep questionStep, StepResult result) { try { Class cls = questionStep.getStepBodyClass(); Constructor constructor = cls.getConstructor(Step.class, StepResult.class); return (StepBody) constructor.newInstance(questionStep, result); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Parcelable onSaveInstanceState() { callbacks.onSaveStep(StepCallbacks.ACTION_NONE, getStep(), stepBody.getStepResult(false)); return super.onSaveInstanceState(); } protected void onNextClicked() {
BodyAnswer bodyAnswer = stepBody.getBodyAnswerState();
4
inouire/baggle
baggle-client/src/inouire/baggle/client/gui/ConnectionPanel.java
[ "public class Language {\n\n static String[] tooltip_fr = new String[]{\n \"Lister les serveurs sur le réseau officiel\",//0\n \"Lister les serveurs en réseau local\",//1\n };\n static String[] tooltip_en = new String[]{\n \"List servers of the official network\",//0\n \"List servers on the local network\",//1\n };\n \n static String[] fr = new String[] {\n \"Protégé par un mot de passe\",//0\n \"Serveur:\",\"Port:\",\"Connecter\",//1\n \"Vous devez choisir un pseudo:\",//4\n \"Le port doit être un entier.\",//5\n \"Erreur\",//6\n \"Connexion au serveur...\",//7\n \"B@ggle, connecté sur \",//8\n \"J'ai lancé un serveur\",//9\n \"Avatar:\",\"Pseudo:\",\"Scan du réseau local...\",//10\n \"Récupération de la liste des salons...\",//13\n \"Tous les mots trouvés comptent\",//14\n \"Rejoindre une partie\",\"Connexion manuelle\",//15\n \"Mode barre intelligente\",\"Mode jeu uniquement\",\"Mode discussion uniquement\",//17\n \"Temps restant à jouer pour cette partie\",//20\n \"Joueurs\",\"Chat\",//21\n \"Saisir un mot\",//23\n \"(click ou Shift-Enter pour changer de mode)\",//24\n \"Mots trouvés\",//25\n \"Rechercher une définition\",//26\n \"Impossible de lancer un navigateur internet.\",//27\n \"À propos de b@ggle\",//28\n \"Se déconnecter de ce salon\",//29\n \"Impossible d'envoyer un mot, pas de partie en cours.\",//30\n \"Je suis prêt\",\"Signaler au serveur que vous êtes prêt à jouer (SHIFT-Enter)\",//31\n \"Faire une petite pause.\",\"Revenir dans le jeu.\",\"Changer de grille\",//33\n \"Signaler au serveur que vous voulez changer de grille (SHIFT-Backspace)\",//36\n \"Nombre de mots que \",\" a trouvé par rapport au nombre total de mots trouvés\",//37\n \" joueurs\",\"Entrez le mot de passe pour ce salon:\",//39\n \"Résultats\",//41\n \"Impossible de se connecter à internet.\",\"Connexion bloquée par un proxy ou un firewall\",//42\n \"Choisir un salon depuis la liste\",//44\n \"Nom d'hôte inconnu.\",//45\n \"Serveur injoignable sur ce port.\\n\\nÊtes vous bien connectés au reseau ?\\nLe serveur est il bien lancé sur le port \",//46\n \" ?\\nLe port est il ouvert sur le firewall de la machine serveur ?\",//47\n \"Numéro de port invalide.\",//48\n \"La partie va commencer...\",\"Nouvelle grille !\",//49\n \"Impossible de se connecter à ce salon.\",//51\n \"La connexion avec le serveur a été perdue\",//52\n \"Password incorrect !\",//53\n \"Mot à chercher:\",//54\n \"Aller voir le tableau des scores\",\"Impossible de lancer un navigateur internet, rendez-vous manuellement sur \"+Main.OFFICIAL_WEBSITE+\"/scores.php\",//55\n \"Tourner la grille dans le sens horaire (SHIFT-DROITE)\",\"Tourner la grille dans le sens anti-horaire (SHIFT-GAUCHE)\",//57\n \"Modifier la taille de la grille\",//59\n \"Pas de réponse de la part du server principal\",//60\n \"inconnue\",//61\n \"Ajouter un robot\",\"Deconnecter le robot\",//62\n \"Finalement, non !\",\"Annuler la demande de changement de grille (SHIFT-Backspace)\",//64\n \"Mot valide\",\"Le mot est trop court\",\"Le mot n'est pas dans la grille\",\"Le mot n'est pas dans le dictionnaire\",\"Le mot a été filtré par le controle parental\",//66\n \"Me voilà !\",\"à bientôt\",//71\n \"Signaler au serveur que vous n'êtes pas prêt à jouer\",//73\n \"Seuls les mots que je suis seul à trouver comptent\",//74\n \"est disponible\",\"Aller à la page de téléchargement\",//75\n \"La nouvelle version peut être téléchargée sur\",//77\n \"Pas de partie en cours\",\"Cliquer sur 'Je suis prêt' pour jouer\",//78\n \"Obtenir plus d'informations sur les règles dans ce salon\",\"Règles\",//80\n \"Réseau officiel\",\"Réseau local\",//82\n \"Il n'y a plus de place dans ce salon.\",//84\n \"Palmarès\"//85,\n \n };\n\n static String[] en = new String[] {\n \"Protected by a password\",\n \"Server:\",\n \"Port:\",\n \"Connect\",\n \"You must choose a nick:\",\n \"The port number must be an integer\",\n \"Error\",\n \"Connecting to server...\",\n \"B@ggle, connected on \",\n \"I started a server\",\n \"Avatar:\",\n \"Nick:\",\n \"Local network auto scan...\",\n \"Collecting rooms list...\",\n \"Each word found earn points\",\n \"Join a game\",\n \"Manual connection\",\n \"Smart field mode\",\n \"Game Only Mode \",\n \"Chat Only Mode\",\n \"Time left for this game\",\n \"Players\",\n \"Chat\",\n \"Enter a word\",\n \"(click or shift-enter to change mode)\",\n \"Found words\",\n \"Look for a definition\",\n \"Error while starting an internet browser\",\n \"About b@ggle...\",\n \"Disconnect from this room\",\n \"Unable to send word, no game running now\",\n \"I'm ready\",\n \"Notify server you're ready to play (SHIFT-Enter)\",\n \"Have a break\",\n \"Resume game\",\n \"Change grid\",\n \"Tell the server that you want to play with a new grid (SHIFT-Backspace)\",\n \"Number of words \",\n \"has found compared to the total number of words found by all the players.\",\n \"players\",\n \"Enter a password for this room: \",\n \"Results\",\n \"Impossible to connect to the internet\",\n \"Connection may be locked by a proxy or a firewall\",\n \"Pick a room from the list\",//44\n \"Unknown host name\",\n \"Server unreachable on this port.\\n\\nAre you connected to the network ?\\nIs the server listenning on port \",\n \"?\\nIs the port opened on the firewall of the server machine ?\",\n \"Invalid port number\",\n \"The game is about to start...\",\n \"New grid !\",\n \"Impossible to connect to this room\",\n \"Lost server connection\",\n \"Wrong password !\",\n \"Word to find:\",//54,\n \"Go to the hall of fame\",\"Error while starting an internet browser, go to \"+Main.OFFICIAL_WEBSITE+\"/scores.php\",//55\n \"Turn the grid clockwise (SHIFT-RIGHT)\",\"Turn the grid counter-clockwise (SHIFT-LEFT)\",//57\n \"Modify grid size\",//59\n \"No response from master server\",//60\n \"unknown\",//61\n \"Connect a robot\",\"Disconnect bot\",//62\n \"Well... finally, no !\",\"Cancel grid change request (SHIFT-Backspace)\",//63\n \"Word accepted\",\"This word is too short\",\"This word is not in the grid\",\"This word is not in the dictionnary\",\"This word has been filtered\",//66\n \"Here I am !\",\"Good bye\",//71\n \"Tell the server that you're not so ready to play\",//73\n \"Words that I'm the only one to find earn points\",//74\n \"is out\",\"Go to download page\",//75\n \"The new version can be downloaded at\",//77\n \"No game in progress\",\"Click on 'I'm ready' to play\",//78\n \"Know more about the rules in this room\",\"Rules\",//80\n \"Official network\",\"Local network\",//82\n \"Maximum number of players has been reached, try another room\",//84\n \"Ranking\"//85\n \n };\n\n public static String getString(int id){\n String a=\"###\";\n try{\n if(Main.LOCALE.equals(\"fr\")){\n a=fr[id];\n }else if(Main.LOCALE.equals(\"en\")){\n a=en[id];\n }\n }catch(Exception ex){\n ex.printStackTrace();\n }finally{\n return a;\n }\n }\n\n public static String getToolTip(int id){\n String a=\"###\";\n try{\n if(Main.LOCALE.equals(\"fr\")){\n a=tooltip_fr[id];\n }else if(Main.LOCALE.equals(\"en\")){\n a=tooltip_en[id];\n }\n }catch(Exception ex){\n ex.printStackTrace();\n }finally{\n return a;\n }\n }\n \n public static String getAboutMessage(){\n String s;\n if(Main.LOCALE.equals(\"fr\")){\n s=\"B@ggle version \"+ Main.VERSION + \"\\n\\n\"+\n \"B@ggle est un logiciel libre (license GPLv3) principalement écrit par Edouard de Labareyre.\\n\"+\n \"- Le dictionnaire français est régulièrement mis à jour par Bernard Javerliat\\n\"+ \n \"- La liste des mots du filtre parental a été constituée par Ersatz.\\n\"+\n \"- L'excellente structure de stockage du dictionnaire (DAWG) est de JohnPaul Adamovsky.\\n\"+\n \" http://pathcom.com/~vadco/dawg.html\\n\\n\"+\n \"Si vous ne connaissez pas les règles du jeu de boggle, il est possible de les afficher\\n\"+\n \"une fois que vous êtes connectés à un salon de jeu.\\n\\n\"+\n \"Pour plus d'informations, visitez le site \"+Main.OFFICIAL_WEBSITE;\n }else{\n s=\"B@ggle version \"+ Main.VERSION + \"\\n\\n\"+\n \"B@ggle is a free software (GPLv3 license) mainly developed by Edouard de Labareyre.\\n\"+\n \"- The french dictionnary is continuously updated by Bernard Javerliat\\n\"+ \n \"- The list of french words for parental filter has been made by Ersatz.\\n\"+ \n \"- The awesome storage structure for dictionnary (DAWG) is from JohnPaul Adamovsky.\\n\"+\n \" http://pathcom.com/~vadco/dawg.html\\n\\n\"+\n \"If you don't know boggle rules, you can display them when you are connected to a room.\\n\\n\"+\n \"For more information you can visit the website at \"+Main.OFFICIAL_WEBSITE;\n }\n return s;\n }\n \n public static String[] getRules(){\n \n String[] rules = new String[11];\n \n if(Main.LOCALE.equals(\"fr\")){\n rules[0]= \"Règles génériques\";\n rules[1]=\"Le but du boggle est de former des mots à partir des lettres \"+\n \"de la grille, sachant que les lettres doivent se toucher (sur le coté ou en diagonale).\\n\"+\n \"Les mots doivent être dans le dictionnaire, mais peuvent être mis au pluriel, \"+\n \"conjugués, accordés en genre et en nombre...\";\n rules[2]=\"Exemple: on peut trouver le mot TRIA dans cette grille (du verbe trier).\";\n rules[3]=\"Attention, un même dé ne peut pas être utilisé pour un mot donné.\";\n rules[4]=\"Exemple: on peut former le mot SERRA (du verbe serrer), mais pas PAVA !\";\n rules[5]=\"Règles spécifiques à ce salon\";\n rules[6]=\"Dans ce salon c'est la règle officielle qui s'applique. Ainsi ne rapportent \"+\n \"des points que les mots qu'un joueur est le seul à trouver. \";\n rules[7]=\"Dans ce salon, la règle qui s'applique est un dérivé de la règle officielle. Tous \"+\n \"les mots comptent, sachant que plus ils sont longs plus ils rapportent de points. \";\n rules[8]=\"Les mots doivent comporter au minimum \";\n rules[9]=\" lettres pour être acceptés. \";\n rules[10]=\"En cas de problème n'hésitez pas à demander de l'aide via le chat !\";\n }else{\n rules[0]= \"Generic rules\";\n rules[1]=\"The purpose of boggle is to form words from the letters of the grid,\\n\"+\n \"knowing that the letters must touch (on the side or diagonally).\"+\n \"Words must be in the dictionary, but may be plural, conjugated\\n\"+\n \"granted in gender and number...\";\n rules[2]=\"Example: you can find the word CORE in this grid.\";\n rules[3]=\"Note that a dice cannot be used twice in the same word.\";\n rules[4]=\"Example: you cannot find the word CANCEL in this grid because C cannot be used twice !\";\n rules[5]=\"Specific rules for this room\";\n rules[6]=\"In this room the official boggle rule is used. It means that you have to be the only\"+\n \"player who finds a word in order to earn points with this word.\";\n rules[7]=\"In this room, the rule is a derivate from the official rule. All the words \"+\n \"count, and the longer they are, the more points you win. \";\n rules[8]=\"Words shall contain at least \";\n rules[9]=\" letters to be valid. \";\n rules[10]=\"If you have troubles to play, feel free to ask fro help in the chat !\";\n }\n \n return rules;\n }\n \n}", "public class Main {\n\n //global variables\n public static String LOCALE=System.getProperty(\"user.language\");\n \n public final static String VERSION = \"3.7\";\n public final static int BUILD=3700;\n \n public static final String OFFICIAL_WEBSITE=\"http://baggle.org\";\n public static String MASTER_SERVER_HOST=\"masterserver.baggle.org\";\n public static int MASTER_SERVER_PORT=80;\n \n public static String STATIC_SERVER_IP=\"localhost\";\n public static int STATIC_SERVER_PORT=42705;\n\n public static boolean STORE_CONFIG_LOCALLY=false;\n public static String CONNECT_ONLY_TO=null;\n public static File CONFIG_FOLDER;\n\n public static MainFrame mainFrame;\n\n public static ServerConnection connection;\n public static BotServerConnection bot;\n \n public static CachedServersList cachedServers;\n public static CachedServersList cachedLANServers;\n \n public static AvatarFactory avatarFactory;\n public static UserConfiguration configuration;\n \n public static void printUsage(){\n System.out.println(\"B@ggle client version \"+Main.VERSION);\n System.out.println(\"Usage: \\n\\t-M [master server host]\"+\n \"\\n\\t-P [master server port]\"+\n \"\\n\\t-l (store config file in current directory)\");\n System.out.println(\"All parameters are optionnal.\");\n }\n \n /**\n * Main function for baggle-client.\n * Schedules all the others\n * @param Args the command line Arguments\n */\n public static void main(String[] args) throws InterruptedException {\n\n Utils.setBestLookAndFeelAvailable();\n\n printUsage();\n \n SimpleLog.initConsoleConfig();\n SimpleLog.logger.setLevel(Level.INFO);\n \n MASTER_SERVER_HOST = Args.getStringOption(\"-M\",args,MASTER_SERVER_HOST);\n MASTER_SERVER_PORT = Args.getIntegerOption(\"-P\", args, MASTER_SERVER_PORT);\n STORE_CONFIG_LOCALLY = Args.getOption(\"-l\",args);\n CONNECT_ONLY_TO = Args.getStringOption(\"--only\",args,CONNECT_ONLY_TO);\n \n //set path of config folder\n if(Main.STORE_CONFIG_LOCALLY){\n CONFIG_FOLDER=new File(\".baggle\"+File.separator);\n }else{\n CONFIG_FOLDER=new File(System.getProperty(\"user.home\")+File.separator+\".baggle\"+File.separator);\n }\n \n //init graphical elements\n avatarFactory=new AvatarFactory();\n \n //init main frame with connect panel only (for faster startup)\n mainFrame = new MainFrame();\n mainFrame.initConnectionPanel();\n mainFrame.setVisible(true);\n \n //load configuration\n configuration = new UserConfiguration();\n configuration.loadFromFile();\n \n //load cached servers list\n cachedServers = new CachedServersList(Main.MASTER_SERVER_HOST);\n cachedServers.loadList(7);\n \n //set auto refresh for server detection\n Timer T = new Timer();\n T.schedule(new AutoRefresh(), 0, 120000);//every 2 minutes\n \n //now init the game part of the main frame\n mainFrame.initGamePanel();\n \n //check for new version in the background\n mainFrame.connectionPane.sideConnectionPane.newVersionPane.checkForNewVersion();\n }\n}", "public class LANDiscoverPanel extends JPanel{\n\n \n private ServerListPanel serverListPanel;\n private ListStatusPanel listStatusPanel;\n \n private int refresh_id=1;\n \n public LANDiscoverPanel(){\n super();\n \n //status panel\n listStatusPanel=new ListStatusPanel(this);\n \n //server list\n serverListPanel = new ServerListPanel();\n \n this.setLayout(new BorderLayout());\n this.add(listStatusPanel,BorderLayout.NORTH);\n this.add(serverListPanel,BorderLayout.CENTER);\n\n }\n \n public void setStartOfPingProcess(){\n listStatusPanel.setStartOfPingProcess();\n }\n \n public int newRefreshId(){\n refresh_id++;\n serverListPanel.resetList();\n return refresh_id;\n }\n \n public void addValidServer(int id,String ip, int port,PINGDatagram pingD){\n if(refresh_id==id){\n serverListPanel.addServer(ip,port,pingD);\n this.listStatusPanel.setOkMessage();\n serverListPanel.notifyResize();\n Main.mainFrame.connectionPane.lanDiscoverPane.listStatusPanel.setEndOfPingProcess();\n }//else ignore\n }\n\n}", "public class OfficialServersPanel extends JPanel{\n\n \n private ServerListPanel serverListPanel;\n private ServerListStatusPanel serverListStatusPanel;\n \n private int nb_servers=0;\n private int server_ok_counter=0;\n private int server_total_counter=0;\n private int refresh_id=1;\n \n public OfficialServersPanel(){\n super();\n \n //status panel\n serverListStatusPanel=new ServerListStatusPanel(this);\n \n //server list\n serverListPanel = new ServerListPanel();\n \n this.setLayout(new BorderLayout());\n this.add(serverListStatusPanel,BorderLayout.NORTH);\n this.add(serverListPanel,BorderLayout.CENTER);\n \n }\n \n public void setStartOfPingProcess(){\n serverListStatusPanel.setStartOfPingProcess();\n }\n \n public int newRefreshId(int nb){\n nb_servers=nb;\n serverListStatusPanel.setTotalNbServers(nb);\n serverListPanel.resetList();\n server_total_counter=0;\n server_ok_counter=0;\n refresh_id++;\n return refresh_id;\n }\n \n public synchronized void addValidServer(int id,String ip, int port,PINGDatagram pingD){\n if(refresh_id==id){\n serverListPanel.addServer(ip, port, pingD);\n server_total_counter++;\n server_ok_counter++;\n updateNbAnswers();\n }//else ignore\n }\n \n public void addFailedServer(int id){\n if(refresh_id==id){\n server_total_counter++;\n updateNbAnswers();\n }\n }\n \n private synchronized void updateNbAnswers(){\n serverListStatusPanel.setNbServersPinged(server_total_counter);\n if(server_total_counter==nb_servers){\n SimpleLog.logger.debug(\"All server ping threads ended\");\n serverListStatusPanel.setOkMessage();\n if(server_ok_counter==0){\n Main.mainFrame.connectionPane.officialServersPane.serverListStatusPanel.setErrorMessage();\n }else{\n \n }\n Main.mainFrame.connectionPane.officialServersPane.serverListStatusPanel.setEndOfPingProcess();\n }\n serverListPanel.notifyResize();\n }\n\n \n}", "public class SideConnectionPanel extends JPanel{\n \n private JComboBox player_avatar_combo;\n private JTextField player_name_field;\n\n public NewVersionPanel newVersionPane;\n \n public ScoresPanel scoresPane;\n \n public SideConnectionPanel(){\n \n newVersionPane = new NewVersionPanel();\n \n player_avatar_combo = new JComboBox(Main.avatarFactory.getPlayerAvatarList());\n Dimension d = new Dimension(100,50);\n player_avatar_combo.setMaximumSize(d);\n player_avatar_combo.setMinimumSize(d);\n player_avatar_combo.setPreferredSize(d);\n \n\n player_name_field = new JTextField(8);\n player_name_field.setMaximumSize(new Dimension(500,50));\n player_name_field.setFont(new Font(\"Serial\", Font.BOLD, 20));\n player_name_field.addKeyListener(new KeyListener() {\n public void keyTyped(KeyEvent ke) {\n new Thread(){\n @Override\n public void run(){\n try {sleep(200);\n } catch (InterruptedException ex) {}\n scoresPane.updateScores();\n }\n }.start();\n }\n public void keyPressed(KeyEvent ke) {\n }\n public void keyReleased(KeyEvent ke) {\n }\n });\n\n JLabel avatar_label = new JLabel(Language.getString(10));\n JLabel pseudo_label = new JLabel(Language.getString(11));\n \n JPanel p1 = new JPanel();\n GroupLayout layout = new GroupLayout(p1);\n p1.setBorder(BorderFactory.createTitledBorder(\"\"));\n p1.setLayout(layout);\n layout.setAutoCreateGaps(true);\n layout.setAutoCreateContainerGaps(true);\n layout.setHorizontalGroup(\n layout.createSequentialGroup()\n .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)\n .addComponent(avatar_label)\n .addComponent(player_avatar_combo))\n .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)\n .addComponent(pseudo_label)\n .addComponent(player_name_field))\n );\n layout.setVerticalGroup(\n layout.createSequentialGroup()\n .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)\n .addComponent(avatar_label)\n .addComponent(pseudo_label))\n .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)\n .addComponent(player_avatar_combo)\n .addComponent(player_name_field))\n );\n \n scoresPane = new ScoresPanel();\n \n //this.setPreferredSize(d);\n this.setLayout(new BorderLayout());\n this.add(newVersionPane,BorderLayout.NORTH);\n this.add(p1,BorderLayout.CENTER);\n this.add(scoresPane,BorderLayout.SOUTH);\n }\n \n public String getPlayerName(){\n return player_name_field.getText().trim();\n }\n \n public void setPlayerName(String name){\n player_name_field.setText(name.trim());\n }\n \n public void setPlayerAvatar(String avatar){\n player_avatar_combo.setSelectedIndex(Main.avatarFactory.getAvatarIdByName(avatar));\n }\n \n public String getPlayerAvatar(){\n return Main.avatarFactory.getAvatarByIdInAvatarList(player_avatar_combo.getSelectedIndex());\n }\n}", "public class LANDiscoverThread extends Thread{\n \n protected DatagramSocket socket =null;\n \n public Integer lanListeningPort=42710;\n public Integer returnPort = 42711;\n \n private LANDiscoverPanel listener;\n \n public LANDiscoverThread(LANDiscoverPanel listener) {\n this.setName(\"lanDiscoverThread\");\n this.listener=listener;\n do{\n try {\n socket= new DatagramSocket(returnPort);\n } catch (SocketException se) {\n SimpleLog.logger.debug(\"Impossible to create socket on port \"+returnPort);\n //TODO améliorer ça, trop bourrin\n returnPort++;\n }\n }while(socket==null);\n \n }\n\n @Override\n public void run(){\n \n //prepare HMI\n listener.setStartOfPingProcess();\n \n SimpleLog.logger.info(\"Starting LAN discovey\");\n \n int refreshId = listener.newRefreshId();\n \n try {\n // build broadcast message\n String dString=\"PING|returnPort=\"+returnPort;\n byte[] bufS = dString.getBytes();\n\n //broadcast this message\n InetAddress group = InetAddress.getByName(\"230.0.0.1\");\n DatagramPacket packetS = new DatagramPacket(bufS, bufS.length, group, lanListeningPort);\n socket.send(packetS);\n\n //receive answers\n byte[] bufR = new byte[512];\n DatagramPacket packetR;\n String received;\n while(true){\n packetR = new DatagramPacket(bufR, bufR.length);\n socket.receive(packetR);\n InetAddress host = packetR.getAddress();\n received = new String(packetR.getData(), 0, packetR.getLength());\n SimpleLog.logger.debug(\"[<LANRCV] \"+received);\n try {\n PINGDatagram pingD = new PINGDatagram(received.split(\"\\\\|\"));\n if(pingD.port==null){\n throw new IllegalDatagramException();\n }\n listener.addValidServer(refreshId, host.getHostAddress(),pingD.port,pingD);\n } catch (IllegalDatagramException ex) {\n SimpleLog.logger.warn(\"error while parsing \"+received);\n }\n \n }\n } catch (IOException e) {\n SimpleLog.logger.error(\"error during lan discover\",e);\n }\n\tsocket.close();\n \n }\n \n}" ]
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import inouire.baggle.client.Language; import inouire.baggle.client.Main; import inouire.baggle.client.gui.modules.LANDiscoverPanel; import inouire.baggle.client.gui.modules.OfficialServersPanel; import inouire.baggle.client.gui.modules.SideConnectionPanel; import inouire.baggle.client.threads.LANDiscoverThread;
package inouire.baggle.client.gui; /** * * @author Edouard de Labareyre */ public class ConnectionPanel extends JPanel{ public SideConnectionPanel sideConnectionPane; public OfficialServersPanel officialServersPane; public LANDiscoverPanel lanDiscoverPane; private NetworkTypeSelectionPanel networkTypePane; private JButton about_button; private JPanel networksPane; private CardLayout networksLayout; public static GridBagConstraints CENTERED = new GridBagConstraints (0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.CENTER, new Insets (0,0,0,0), 0, 0); private boolean local_showed=false; public ConnectionPanel(){ super(); //selection buttons networkTypePane = new NetworkTypeSelectionPanel(); JPanel network_type_wrapper = new JPanel(new GridBagLayout ()); network_type_wrapper.add(networkTypePane,CENTERED); network_type_wrapper.setOpaque(false); //top banner JLabel brand_label = new JLabel(); brand_label.setIcon(new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/banner.png"))); brand_label.setText(Main.VERSION); brand_label.setFont(new Font("Serial", Font.BOLD, 16)); brand_label.setForeground(Color.WHITE); about_button = new JButton(); about_button.setIcon(new ImageIcon(getClass().getResource("/inouire/baggle/client/icons/info.png"))); about_button.setToolTipText(Language.getString(28)); about_button.setPreferredSize(new Dimension(42,42)); about_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { aboutPressed(); } }); JPanel about_button_wrapper = new JPanel(new GridBagLayout ()); about_button_wrapper.add (about_button,CENTERED); about_button_wrapper.setOpaque(false); about_button_wrapper.setPreferredSize(new Dimension(58,50)); JPanel top_panel = new JPanel(new BorderLayout()); top_panel.add(brand_label,BorderLayout.WEST); top_panel.add(about_button_wrapper,BorderLayout.EAST); top_panel.add(network_type_wrapper,BorderLayout.CENTER); top_panel.setBackground(ColorFactory.GREEN_BOARD); JLabel non_dispo = new JLabel("Non disponible pour le moment"); non_dispo.setHorizontalAlignment(SwingConstants.CENTER); sideConnectionPane = new SideConnectionPanel(); officialServersPane = new OfficialServersPanel(); lanDiscoverPane = new LANDiscoverPanel(); networksPane=new JPanel(); networksLayout=new CardLayout(); networksPane.setLayout(networksLayout); networksPane.add(officialServersPane,"official"); networksPane.add(lanDiscoverPane,"local"); networksLayout.show(networksPane, "official"); this.setLayout(new BorderLayout()); this.add(top_panel,BorderLayout.NORTH); this.add(sideConnectionPane,BorderLayout.WEST); this.add(networksPane,BorderLayout.CENTER); } public void showOfficial(){ networksLayout.show(networksPane, "official"); local_showed = false; } public void showLocal(){ networksLayout.show(networksPane, "local"); local_showed = true;
new LANDiscoverThread(lanDiscoverPane).start();
5
moxious/neoprofiler
src/main/java/org/mitre/neoprofiler/html/HTMLMaker.java
[ "public class MarkdownMaker {\n\tpublic MarkdownMaker() {\n\t\t\n\t}\n\t\n\tpublic String link(String text, String url) { return \"[\" + text + \"](\" + url + \")\"; } \n\tpublic String h1(String content) { return \"\\n# \" + content + \"\\n\"; }\n\tpublic String h2(String content) { return \"\\n## \" + content + \"\\n\"; }\n\tpublic String h3(String content) { return \"\\n### \" + content + \"\\n\"; }\n\tpublic String h4(String content) { return \"\\n#### \" + content + \"\\n\"; }\n\t\n\tprotected String observations(Map<String,Object>observations) {\n\t\tif(observations.isEmpty()) return \"\";\n\t\t\n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\t\n\t\tb.append(h3(\"Observations\"));\n\t\t\t\t\n\t\tArrayList<String>keys = new ArrayList<String>(observations.keySet());\n\t\tCollections.sort(keys);\n\t\t\n\t\tfor(String key : keys) { \n\t\t\tb.append(\"* \" + key + \": \" + observation(observations.get(key)));\n\t\t\t\n\t\t\tif(b.charAt(b.length() - 1) != '\\n') b.append(\"\\n\");\n\t\t}\n\t\t\n\t\treturn b.toString();\n\t}\n\n\tprotected String observation(Object ob) {\n\t\tif(ob == null) return \"N/A\";\n\t\tif(ob instanceof String || ob instanceof Number) return \"\"+ob;\n\t\tif(ob instanceof Collection) {\n\t\t\tStringBuffer b = new StringBuffer(\"\\n\");\n\t\t\t\n\t\t\tfor(Object o : ((Collection)ob)) {\n\t\t\t\tb.append(\" * \" + o + \"\\n\");\n\t\t\t}\n\t\t\t\n\t\t\treturn b.toString();\n\t\t}\n\t\t\n\t\treturn \"\"+ob;\n\t} // End observation\n\t\n\tpublic String constraints(String title, List<NeoConstraint> constraints) {\n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\tb.append(h3(title));\n\t\t\n\t\tif(constraints.isEmpty()) b.append(\"**None found**\");\n\t\telse {\n\t\t\tfor(NeoConstraint con : constraints) {\n\t\t\t\tb.append(\"* \" + (con.isIndex() ? \"Index\" : \"Constraint\") + \" \" + con.getDescription() + \"\\n\");\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\treturn b.toString();\n\t}\n\t\n\tpublic String parameters(Map<String,Object>parameters) {\n\t\tif(parameters.isEmpty()) return \"\";\n\t\t\n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\t\n\t\tb.append(h3(\"Parameters\"));\n\t\t\t\t\n\t\tArrayList<String>keys = new ArrayList<String>(parameters.keySet());\n\t\tCollections.sort(keys);\n\t\t\n\t\tfor(String key : keys) { \n\t\t\tb.append(\"* \" + key + \": \" + observation(parameters.get(key)) + \"\\n\");\n\t\t}\n\t\t\n\t\tb.append(\"\\n\");\n\t\t\n\t\treturn b.toString();\n\t}\n\t\t\n\tpublic void markdownComponentProfile(NeoProfile profile, Writer writer) throws IOException {\n\t\twriter.write(h2(profile.getName()) + \"*\" + profile.getDescription() + \"*\\n\");\n\t\t\n\t\t//if(profile instanceof ParameterizedNeoProfile) { \n\t\t//\twriter.write(parameters(((ParameterizedNeoProfile)profile).getParameters()));\n\t\t//}\n\t\t\n\t\tif(profile instanceof SchemaProfile) {\n\t\t\tSchemaProfile sp = (SchemaProfile)profile;\n\t\t\twriter.write(constraints(\"Indexes\", sp.getIndexes()));\n\t\t\twriter.write(constraints(\"Non-Index Constraints\", sp.getNonIndexes()));\n\t\t}\n\t\t\n\t\twriter.write(observations(profile.getObservations()));\n\t\twriter.write(\"\\n\");\n\t}\n\t\n\tpublic void markdown(DBProfile profile, Writer writer) throws IOException {\n\t\twriter.write(h1(profile.getName()) + \t\t\t\t \n\t\t\t\t profile.getDescription() + \"\\n\\n\");\n\t\t\n\t\twriter.write(\"Generated by [NeoProfiler](https://github.com/moxious/neoprofiler)\\n\\n\");\n\t\t\n\t\twriter.write(observations(profile.getObservations()));\n\t\t\n\t\tfor(NeoProfile p : profile.getProfiles()) {\n\t\t\tmarkdownComponentProfile(p, writer); \n\t\t}\t\t\n\t}\n}", "public class DBProfile extends NeoProfile {\n\tprotected List<NeoProfile> profiles = new ArrayList<NeoProfile>();\n\t\t\n\tpublic DBProfile(String storageLoc) {\t\t\n\t\tDateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n\t\tDate date = new Date();\n\t\t\n\t\tname = \"Profile of \" + storageLoc + \" generated \" + dateFormat.format(date);\n\t\tdescription = storageLoc;\n\t}\n\t\n\tpublic List<NeoProfile> getProfiles() { return profiles; } \n\t\n\tpublic List<LabelProfile> getLabels() { \n\t\tArrayList<LabelProfile> arr = new ArrayList<LabelProfile>();\n\t\t\n\t\tfor(NeoProfile p : getProfiles())\n\t\t\tif(p instanceof LabelProfile)\n\t\t\t\tarr.add((LabelProfile)p);\n\t\t\n\t\treturn arr;\n\t}\n\t\n\tpublic List<RelationshipTypeProfile> getRelationshipTypes() { \n\t\tArrayList<RelationshipTypeProfile> arr = new ArrayList<RelationshipTypeProfile>();\n\t\t\n\t\tfor(NeoProfile p : getProfiles())\n\t\t\tif(p instanceof RelationshipTypeProfile)\n\t\t\t\tarr.add((RelationshipTypeProfile)p);\n\t\t\n\t\treturn arr;\n\t}\n\t\n\tpublic RelationshipTypeProfile getRelationshipTypeProfile(String type) { \n\t\tfor(NeoProfile p : getProfiles()) { \n\t\t\tif(!(p instanceof RelationshipTypeProfile)) continue;\n\t\t\t\n\t\t\tif(type.equals(((RelationshipTypeProfile)p).getParameter(\"type\"))) \n\t\t\t\treturn ((RelationshipTypeProfile)p);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic LabelProfile getLabelProfile(String label) { \n\t\tfor(NeoProfile p : getProfiles()) { \n\t\t\tif(!(p instanceof LabelProfile)) continue;\n\t\t\t\n\t\t\tif(label.equals(((LabelProfile)p).getParameter(\"label\"))) \n\t\t\t\treturn ((LabelProfile)p);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\t\n\tpublic void addProfile(NeoProfile profile) { \n\t\tprofiles.add(profile);\n\t}\n\t\n\tpublic String toString() { \n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\t\n\t\tb.append(\"DBProfile \" + name + \"\\n\");\n\t\tb.append(\"DBProfile \" + description + \"\\n\\n\");\n\t\t\n\t\tfor(NeoProfile profile : profiles) { \n\t\t\tb.append(profile.toString() + \"\\n\"); \n\t\t}\n\t\t\n\t\treturn b.toString();\n\t}\n} // End DBProfile", "public class LabelProfile extends ParameterizedNeoProfile {\n\tpublic static String OB_OUTBOUND_RELATIONSHIP_TYPES = \"Outbound relationship types\";\n\tpublic static String OB_INBOUND_RELATIONSHIP_TYPES = \"Outbound relationship types\";\n\t\n\tpublic LabelProfile(String label) { \n\t\tname=\"Label '\" + label + \"'\"; \n\t\tdescription=\"Profile of nodes labeled '\" + label + \"'\";\n\t\tsetParameter(\"label\", label);\n\t\tsetParameter(\"sampleSize\", new Integer(100));\n\t}\n}", "public abstract class NeoProfile {\n\tpublic static final String OB_COUNT = \"Total\";\n\tpublic static final String OB_SAMPLE_PROPERTIES = \"Sample properties\";\n\tpublic static final String OB_VALUE_NA = \"N/A\";\n\t\n\tprotected String name;\n\tprotected String description;\n\tprotected HashMap<String,Object> observations = new HashMap<String,Object>();\n\t\n\tpublic String getName() { return name; } \n\tpublic String getDescription() { return description; } \n\tpublic Map<String,Object> getObservations() { return observations; } \n\tpublic void addObservation(String name, Object observation) { observations.put(name, observation); } \n\t\n\tpublic boolean has(String observationName) { \n\t\treturn observations.containsKey(observationName);\n\t}\n\t\n\tpublic String toString() { \n\t\tStringBuffer b = new StringBuffer(\"\");\n\t\tb.append(name + \": \" + description + \"\\n\");\n\t\t\n\t\tArrayList<String> keys = new ArrayList<String>(getObservations().keySet());\n\t\tCollections.sort(keys);\n\t\t\n\t\tfor(String key : keys) {\n\t\t\tb.append(key + \": \" + observations.get(key) + \"\\n\"); \n\t\t}\n\t\t\n\t\treturn b.toString();\n\t} // End toString\n}", "public class RelationshipTypeProfile extends ParameterizedNeoProfile {\n\tpublic static final String OB_DOMAIN = \"domain\";\n\tpublic static final String OB_RANGE = \"range\";\n\t\n\tpublic RelationshipTypeProfile(String type) { \n\t\tname=\"Relationships Typed '\" + type + \"'\"; \n\t\tdescription=\"Profile of relationships of type '\" + type + \"'\";\n\t\tsetParameter(\"type\", type);\t\t\t\n\t\tsetParameter(\"sampleSize\", new Integer(100));\n\t}\n}" ]
import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.mitre.neoprofiler.markdown.MarkdownMaker; import org.mitre.neoprofiler.profile.DBProfile; import org.mitre.neoprofiler.profile.LabelProfile; import org.mitre.neoprofiler.profile.NeoProfile; import org.mitre.neoprofiler.profile.RelationshipTypeProfile;
package org.mitre.neoprofiler.html; /** * Class that renders a DBProfile as HTML. * The general approach is to write a graph structure in JSON rendered via D3.js, and to populate the rest * of the page with regular markdown from the MarkdownGenerator, rendered to HTML by strapdown.js. * @author moxious */ public class HTMLMaker { public HTMLMaker() { ; } public String generateGraph(DBProfile profile) { StringBuffer b = new StringBuffer("var links = [\n");
for(NeoProfile p : profile.getProfiles()) {
3
NanYoMy/mybatis-generator
src/main/java/org/mybatis/generator/config/Context.java
[ "public class GeneratedXmlFile extends GeneratedFile {\n private Document document;\n\n private String fileName;\n\n private String targetPackage;\n\n private boolean isMergeable;\n \n private XmlFormatter xmlFormatter;\n\n /**\n * \n * @param document\n * @param fileName\n * @param targetPackage\n * @param targetProject\n * @param isMergeable\n * true if the file can be merged by the built in XML file\n * merger.\n */\n public GeneratedXmlFile(Document document, String fileName,\n String targetPackage, String targetProject, boolean isMergeable,\n XmlFormatter xmlFormatter) {\n super(targetProject);\n this.document = document;\n this.fileName = fileName;\n this.targetPackage = targetPackage;\n this.isMergeable = isMergeable;\n this.xmlFormatter = xmlFormatter;\n }\n\n @Override\n public String getFormattedContent() {\n return xmlFormatter.getFormattedContent(document);\n }\n\n /**\n * @return Returns the fileName.\n */\n @Override\n public String getFileName() {\n return fileName;\n }\n\n /**\n * @return Returns the targetPackage.\n */\n @Override\n public String getTargetPackage() {\n return targetPackage;\n }\n\n @Override\n public boolean isMergeable() {\n return isMergeable;\n }\n}", "public interface JavaFormatter {\n void setContext(Context context);\n String getFormattedContent(CompilationUnit compilationUnit);\n}", "public interface Plugin {\n public enum ModelClassType {\n PRIMARY_KEY, BASE_RECORD, RECORD_WITH_BLOBS\n }\n\n /**\n * Set the context under which this plugin is running\n * \n * @param context\n */\n void setContext(Context context);\n\n /**\n * Set properties from the plugin configuration\n * \n * @param properties\n */\n void setProperties(Properties properties);\n\n /**\n * This method is called just before the getGeneratedXXXFiles methods are\n * called on the introspected table. Plugins can implement this method to\n * override any of the default attributes, or change the results of database\n * introspection, before any code generation activities occur. Attributes\n * are listed as static Strings with the prefix ATTR_ in IntrospectedTable.\n * <p>\n * A good example of overriding an attribute would be the case where a user\n * wanted to change the name of one of the generated classes, change the\n * target package, or change the name of the generated SQL map file.\n * <p>\n * <b>Warning:</b> Anything that is listed as an attribute should not be\n * changed by one of the other plugin methods. For example, if you want to\n * change the name of a generated example class, you should not simply\n * change the Type in the <code>modelExampleClassGenerated()</code> method.\n * If you do, the change will not be reflected in other generated artifacts.\n * \n * @param introspectedTable\n */\n void initialized(IntrospectedTable introspectedTable);\n\n /**\n * This method is called after all the setXXX methods are called, but before\n * any other method is called. This allows the plugin to determine whether\n * it can run or not. For example, if the plugin requires certain properties\n * to be set, and the properties are not set, then the plugin is invalid and\n * will not run.\n * \n * @param warnings\n * add strings to this list to specify warnings. For example, if\n * the plugin is invalid, you should specify why. Warnings are\n * reported to users after the completion of the run.\n * @return true if the plugin is in a valid state. Invalid plugins will not\n * be called\n */\n boolean validate(List<String> warnings);\n\n /**\n * This method can be used to generate any additional Java file needed by\n * your implementation. This method is called once, after all other Java\n * files have been generated.\n * \n * @return a List of GeneratedJavaFiles - these files will be saved\n * with the other files from this run.\n */\n List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles();\n\n /**\n * This method can be used to generate additional Java files needed by your\n * implementation that might be related to a specific table. This method is\n * called once for every table in the configuration.\n * \n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return a List of GeneratedJavaFiles - these files will be saved\n * with the other files from this run.\n */\n List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(\n IntrospectedTable introspectedTable);\n\n /**\n * This method can be used to generate any additional XML file needed by\n * your implementation. This method is called once, after all other XML\n * files have been generated.\n * \n * @return a List of GeneratedXmlFiles - these files will be saved\n * with the other files from this run.\n */\n List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles();\n\n /**\n * This method can be used to generate additional XML files needed by your\n * implementation that might be related to a specific table. This method is\n * called once for every table in the configuration.\n * \n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return a List of GeneratedXmlFiles - these files will be saved\n * with the other files from this run.\n */\n List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles(\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the entire client has been generated.\n * Implement this method to add additional methods or fields to a generated\n * client interface or implementation.\n * \n * @param interfaze\n * the generated interface if any, may be null\n * @param topLevelClass\n * the generated implementation class if any, may be null\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the interface should be generated, false if the generated\n * interface should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the countByExample method has been generated\n * in the client implementation class.\n * \n * @param method\n * the generated countByExample method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientCountByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByExample method has been generated\n * in the client implementation class.\n * \n * @param method\n * the generated deleteByExample method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientDeleteByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByPrimaryKey method has been\n * generated in the client implementation class.\n * \n * @param method\n * the generated deleteByPrimaryKey method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientDeleteByPrimaryKeyMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insert method has been generated in the\n * client implementation class.\n * \n * @param method\n * the generated insert method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientInsertMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insert selective method has been generated\n * in the client implementation class.\n * \n * @param method\n * the generated insert method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientInsertSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExampleWithBLOBs method has been\n * generated in the client implementation class.\n * \n * @param method\n * the generated selectByExampleWithBLOBs method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExampleWithoutBLOBs method has\n * been generated in the client implementation class.\n * \n * @param method\n * the generated selectByExampleWithoutBLOBs method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByPrimaryKey method has been\n * generated in the client implementation class.\n * \n * @param method\n * the generated selectByPrimaryKey method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectByPrimaryKeyMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleSelective method has been\n * generated in the client implementation class.\n * \n * @param method\n * the generated updateByExampleSelective method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByExampleSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithBLOBs method has been\n * generated in the client implementation class.\n * \n * @param method\n * the generated updateByExampleWithBLOBs method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithoutBLOBs method has\n * been generated in the client implementation class.\n * \n * @param method\n * the generated updateByExampleWithoutBLOBs method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeySelective method has\n * been generated in the client implementation class.\n * \n * @param method\n * the generated updateByPrimaryKeySelective method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeyWithBLOBs method has\n * been generated in the client implementation class.\n * \n * @param method\n * the generated updateByPrimaryKeyWithBLOBs method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeyWithoutBLOBs method has\n * been generated in the client implementation class.\n * \n * @param method\n * the generated updateByPrimaryKeyWithBLOBs method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the countByExample method has been generated\n * in the client interface.\n * \n * @param method\n * the generated countByExample method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientCountByExampleMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByExample method has been generated\n * in the client interface.\n * \n * @param method\n * the generated deleteByExample method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientDeleteByExampleMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByPrimaryKey method has been\n * generated in the client interface.\n * \n * @param method\n * the generated deleteByPrimaryKey method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientDeleteByPrimaryKeyMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insert method has been generated in the\n * client interface.\n * \n * @param method\n * the generated insert method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientInsertMethodGenerated(Method method, Interface interfaze,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insert selective method has been generated\n * in the client interface.\n * \n * @param method\n * the generated insert method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientInsertSelectiveMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectAll method has been\n * generated in the client interface. This method is only generated by\n * the simple runtime.\n * \n * @param method\n * the generated selectAll method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectAllMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectAll method has been\n * generated in the client implementation class.\n * \n * @param method\n * the generated selectAll method\n * @param topLevelClass\n * the partially implemented client implementation class. You can\n * add additional imported classes to the implementation class if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectAllMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n \n /**\n * This method is called when the selectByExampleWithBLOBs method has been\n * generated in the client interface.\n * \n * @param method\n * the generated selectByExampleWithBLOBs method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExampleWithoutBLOBs method has\n * been generated in the client interface.\n * \n * @param method\n * the generated selectByExampleWithoutBLOBs method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByPrimaryKey method has been\n * generated in the client interface.\n * \n * @param method\n * the generated selectByPrimaryKey method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientSelectByPrimaryKeyMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleSelective method has been\n * generated in the client interface.\n * \n * @param method\n * the generated updateByExampleSelective method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByExampleSelectiveMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithBLOBs method has been\n * generated in the client interface.\n * \n * @param method\n * the generated updateByExampleWithBLOBs method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithoutBLOBs method has\n * been generated in the client interface.\n * \n * @param method\n * the generated updateByExampleWithoutBLOBs method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeySelective method has\n * been generated in the client interface.\n * \n * @param method\n * the generated updateByPrimaryKeySelective method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeyWithBLOBs method has\n * been generated in the client interface.\n * \n * @param method\n * the generated updateByPrimaryKeyWithBLOBs method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeyWithoutBLOBs method has\n * been generated in the client interface.\n * \n * @param method\n * the generated updateByPrimaryKeyWithoutBLOBs method\n * @param interfaze\n * the partially implemented client interface. You can add\n * additional imported classes to the interface if\n * necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable);\n\n /**\n * This method is called after the field is generated for a specific column\n * in a table.\n * \n * @param field\n * the field generated for the specified column\n * @param topLevelClass\n * the partially implemented model class. You can add additional\n * imported classes to the implementation class if necessary.\n * @param introspectedColumn\n * The class containing information about the column related\n * to this field as introspected from the database\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @param modelClassType\n * the type of class that the field is generated for\n * @return true if the field should be generated, false if the generated\n * field should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass,\n IntrospectedColumn introspectedColumn,\n IntrospectedTable introspectedTable, ModelClassType modelClassType);\n\n /**\n * This method is called after the getter, or accessor, method is generated\n * for a specific column in a table.\n * \n * @param method\n * the getter, or accessor, method generated for the specified\n * column\n * @param topLevelClass\n * the partially implemented model class. You can add additional\n * imported classes to the implementation class if necessary.\n * @param introspectedColumn\n * The class containing information about the column related\n * to this field as introspected from the database\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @param modelClassType\n * the type of class that the field is generated for\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelGetterMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,\n IntrospectedTable introspectedTable, ModelClassType modelClassType);\n\n /**\n * This method is called after the setter, or mutator, method is generated\n * for a specific column in a table.\n * \n * @param method\n * the setter, or mutator, method generated for the specified\n * column\n * @param topLevelClass\n * the partially implemented model class. You can add additional\n * imported classes to the implementation class if necessary.\n * @param introspectedColumn\n * The class containing information about the column related\n * to this field as introspected from the database\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @param modelClassType\n * the type of class that the field is generated for\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelSetterMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,\n IntrospectedTable introspectedTable, ModelClassType modelClassType);\n\n /**\n * This method is called after the primary key class is generated by the\n * JavaModelGenerator. This method will only be called if\n * the table rules call for generation of a primary key class.\n * <p/>\n * This method is only guaranteed to be called by the Java\n * model generators. Other user supplied generators may, or may not, call\n * this method.\n * \n * @param topLevelClass\n * the generated primary key class\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the class should be generated, false if the generated\n * class should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called after the base record class is generated by the\n * JavaModelGenerator. This method will only be called if\n * the table rules call for generation of a base record class.\n * <p/>\n * This method is only guaranteed to be called by the default Java\n * model generators. Other user supplied generators may, or may not, call\n * this method.\n * \n * @param topLevelClass\n * the generated base record class\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the class should be generated, false if the generated\n * class should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called after the record with BLOBs class is generated by\n * the JavaModelGenerator. This method will only be called\n * if the table rules call for generation of a record with BLOBs class.\n * <p/>\n * This method is only guaranteed to be called by the default Java\n * model generators. Other user supplied generators may, or may not, call\n * this method.\n * \n * @param topLevelClass\n * the generated record with BLOBs class\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the class should be generated, false if the generated\n * class should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called after the example class is generated by the \n * JavaModelGenerator. This method will only be called if the table\n * rules call for generation of an example class.\n * <p/>\n * This method is only guaranteed to be called by the default Java\n * model generators. Other user supplied generators may, or may not, call\n * this method.\n * \n * @param topLevelClass\n * the generated example class\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the class should be generated, false if the generated\n * class should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean modelExampleClassGenerated(TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the SqlMap file has been generated.\n * \n * @param sqlMap\n * the generated file (containing the file name, package name,\n * and project name)\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the sqlMap should be generated, false if the generated\n * sqlMap should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapGenerated(GeneratedXmlFile sqlMap,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the SqlMap document has been generated. This\n * method can be used to add additional XML elements the the generated\n * document.\n * \n * @param document\n * the generated document (note that this is the MyBatis generator's internal\n * Document class - not the w3c XML Document class)\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the document should be generated, false if the generated\n * document should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins. Also, if any plugin returns false, then the\n * <tt>sqlMapGenerated</tt> method will not be called.\n */\n boolean sqlMapDocumentGenerated(Document document,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the base resultMap is generated.\n * \n * @param element\n * the generated &lt;resultMap&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapResultMapWithoutBLOBsElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the countByExample element is generated.\n * \n * @param element\n * the generated &lt;select&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapCountByExampleElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByExample element is generated.\n * \n * @param element\n * the generated &lt;delete&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapDeleteByExampleElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByPrimaryKey element is generated.\n * \n * @param element\n * the generated &lt;delete&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapDeleteByPrimaryKeyElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the exampleWhereClause element is generated.\n * \n * @param element\n * the generated &lt;sql&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapExampleWhereClauseElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the baseColumnList element is generated.\n * \n * @param element\n * the generated &lt;sql&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapBaseColumnListElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the blobColumnList element is generated.\n * \n * @param element\n * the generated &lt;sql&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapBlobColumnListElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insert element is generated.\n * \n * @param element\n * the generated &lt;insert&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapInsertElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insert selective element is generated.\n * \n * @param element\n * the generated &lt;insert&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapInsertSelectiveElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the resultMap with BLOBs element is generated\n * - this resultMap will extend the base resultMap.\n * \n * @param element\n * the generated &lt;resultMap&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapResultMapWithBLOBsElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectAll element is generated.\n * \n * @param element\n * the generated &lt;select&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapSelectAllElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByPrimaryKey element is generated.\n * \n * @param element\n * the generated &lt;select&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExample element is generated.\n * \n * @param element\n * the generated &lt;select&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExampleWithBLOBs element is\n * generated.\n * \n * @param element\n * the generated &lt;select&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleSelective element is\n * generated.\n * \n * @param element\n * the generated &lt;update&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithBLOBs element is\n * generated.\n * \n * @param element\n * the generated &lt;update&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapUpdateByExampleWithBLOBsElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithourBLOBs element is\n * generated.\n * \n * @param element\n * the generated &lt;update&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapUpdateByExampleWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeySelective element is\n * generated.\n * \n * @param element\n * the generated &lt;update&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeyWithBLOBs element is\n * generated.\n * \n * @param element\n * the generated &lt;update&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapUpdateByPrimaryKeyWithBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeyWithoutBLOBs element is\n * generated.\n * \n * @param element\n * the generated &lt;update&gt; element\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the element should be generated, false if the generated\n * element should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the SQL provider has been generated.\n * Implement this method to add additional methods or fields to a generated\n * SQL provider.\n * \n * @param topLevelClass\n * the generated provider\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the provider should be generated, false if the generated\n * provider should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerGenerated(TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the applyWhere method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated applyWhere method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerApplyWhereMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the countByExample method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated countByExample method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerCountByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the deleteByExample method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated deleteByExample method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerDeleteByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the insertSelective method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated insertSelective method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerInsertSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExampleWithBLOBs method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated selectByExampleWithBLOBs method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerSelectByExampleWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the selectByExampleWithoutBLOBs method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated selectByExampleWithoutBLOBs method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerSelectByExampleWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleSelective method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated updateByExampleSelective method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerUpdateByExampleSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithBLOBs method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated updateByExampleWithBLOBs method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerUpdateByExampleWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByExampleWithoutBLOBs method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated updateByExampleWithoutBLOBs method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerUpdateByExampleWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n\n /**\n * This method is called when the updateByPrimaryKeySelective method has\n * been generated in the SQL provider.\n * \n * @param method\n * the generated updateByPrimaryKeySelective method\n * @param topLevelClass\n * the partially generated provider class\n * You can add additional imported classes to the class\n * if necessary.\n * @param introspectedTable\n * The class containing information about the table as\n * introspected from the database\n * @return true if the method should be generated, false if the generated\n * method should be ignored. In the case of multiple plugins, the\n * first plugin returning false will disable the calling of further\n * plugins.\n */\n boolean providerUpdateByPrimaryKeySelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable);\n}", "public abstract class IntrospectedTable {\n public enum TargetRuntime {\n IBATIS2, MYBATIS3\n }\n\n protected enum InternalAttribute {\n ATTR_DAO_IMPLEMENTATION_TYPE,\n ATTR_DAO_INTERFACE_TYPE,\n ATTR_PRIMARY_KEY_TYPE,\n ATTR_BASE_RECORD_TYPE,\n ATTR_RECORD_WITH_BLOBS_TYPE,\n ATTR_EXAMPLE_TYPE,\n ATTR_IBATIS2_SQL_MAP_PACKAGE,\n ATTR_IBATIS2_SQL_MAP_FILE_NAME,\n ATTR_IBATIS2_SQL_MAP_NAMESPACE,\n ATTR_MYBATIS3_XML_MAPPER_PACKAGE,\n ATTR_MYBATIS3_XML_MAPPER_FILE_NAME,\n /** also used as XML Mapper namespace if a Java mapper is generated */\n ATTR_MYBATIS3_JAVA_MAPPER_TYPE,\n /** used as XML Mapper namespace if no client is generated */\n ATTR_MYBATIS3_FALLBACK_SQL_MAP_NAMESPACE,\n ATTR_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME,\n ATTR_ALIASED_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME,\n ATTR_COUNT_BY_EXAMPLE_STATEMENT_ID,\n ATTR_DELETE_BY_EXAMPLE_STATEMENT_ID,\n ATTR_DELETE_BY_PRIMARY_KEY_STATEMENT_ID,\n ATTR_INSERT_STATEMENT_ID,\n ATTR_INSERT_SELECTIVE_STATEMENT_ID,\n ATTR_SELECT_ALL_STATEMENT_ID,\n ATTR_SELECT_BY_EXAMPLE_STATEMENT_ID,\n ATTR_SELECT_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID,\n ATTR_SELECT_BY_PRIMARY_KEY_STATEMENT_ID,\n ATTR_UPDATE_BY_EXAMPLE_STATEMENT_ID,\n ATTR_UPDATE_BY_EXAMPLE_SELECTIVE_STATEMENT_ID,\n ATTR_UPDATE_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID,\n ATTR_UPDATE_BY_PRIMARY_KEY_STATEMENT_ID,\n ATTR_UPDATE_BY_PRIMARY_KEY_SELECTIVE_STATEMENT_ID,\n ATTR_UPDATE_BY_PRIMARY_KEY_WITH_BLOBS_STATEMENT_ID,\n ATTR_BASE_RESULT_MAP_ID,\n ATTR_RESULT_MAP_WITH_BLOBS_ID,\n ATTR_EXAMPLE_WHERE_CLAUSE_ID,\n ATTR_BASE_COLUMN_LIST_ID,\n ATTR_BLOB_COLUMN_LIST_ID,\n ATTR_MYBATIS3_UPDATE_BY_EXAMPLE_WHERE_CLAUSE_ID,\n ATTR_MYBATIS3_SQL_PROVIDER_TYPE\n }\n\n protected TableConfiguration tableConfiguration;\n protected FullyQualifiedTable fullyQualifiedTable;\n protected Context context;\n protected Rules rules;\n protected List<IntrospectedColumn> primaryKeyColumns;\n protected List<IntrospectedColumn> baseColumns;\n protected List<IntrospectedColumn> blobColumns;\n protected TargetRuntime targetRuntime;\n\n /**\n * Attributes may be used by plugins to capture table related state between\n * the different plugin calls.\n */\n protected Map<String, Object> attributes;\n\n /**\n * Internal attributes are used to store commonly accessed items by all code\n * generators\n */\n protected Map<IntrospectedTable.InternalAttribute, String> internalAttributes;\n\n public IntrospectedTable(TargetRuntime targetRuntime) {\n super();\n this.targetRuntime = targetRuntime;\n primaryKeyColumns = new ArrayList<IntrospectedColumn>();\n baseColumns = new ArrayList<IntrospectedColumn>();\n blobColumns = new ArrayList<IntrospectedColumn>();\n attributes = new HashMap<String, Object>();\n internalAttributes = new HashMap<IntrospectedTable.InternalAttribute, String>();\n }\n\n public FullyQualifiedTable getFullyQualifiedTable() {\n return fullyQualifiedTable;\n }\n\n public String getSelectByExampleQueryId() {\n return tableConfiguration.getSelectByExampleQueryId();\n }\n\n public String getSelectByPrimaryKeyQueryId() {\n return tableConfiguration.getSelectByPrimaryKeyQueryId();\n }\n\n public GeneratedKey getGeneratedKey() {\n return tableConfiguration.getGeneratedKey();\n }\n\n public IntrospectedColumn getColumn(String columnName) {\n if (columnName == null) {\n return null;\n } else {\n // search primary key columns\n for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {\n if (introspectedColumn.isColumnNameDelimited()) {\n if (introspectedColumn.getActualColumnName().equals(\n columnName)) {\n return introspectedColumn;\n }\n } else {\n if (introspectedColumn.getActualColumnName()\n .equalsIgnoreCase(columnName)) {\n return introspectedColumn;\n }\n }\n }\n\n // search base columns\n for (IntrospectedColumn introspectedColumn : baseColumns) {\n if (introspectedColumn.isColumnNameDelimited()) {\n if (introspectedColumn.getActualColumnName().equals(\n columnName)) {\n return introspectedColumn;\n }\n } else {\n if (introspectedColumn.getActualColumnName()\n .equalsIgnoreCase(columnName)) {\n return introspectedColumn;\n }\n }\n }\n\n // search blob columns\n for (IntrospectedColumn introspectedColumn : blobColumns) {\n if (introspectedColumn.isColumnNameDelimited()) {\n if (introspectedColumn.getActualColumnName().equals(\n columnName)) {\n return introspectedColumn;\n }\n } else {\n if (introspectedColumn.getActualColumnName()\n .equalsIgnoreCase(columnName)) {\n return introspectedColumn;\n }\n }\n }\n\n return null;\n }\n }\n\n /**\n * Returns true if any of the columns in the table are JDBC Dates (as\n * opposed to timestamps).\n * \n * @return true if the table contains DATE columns\n */\n public boolean hasJDBCDateColumns() {\n boolean rc = false;\n\n for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {\n if (introspectedColumn.isJDBCDateColumn()) {\n rc = true;\n break;\n }\n }\n\n if (!rc) {\n for (IntrospectedColumn introspectedColumn : baseColumns) {\n if (introspectedColumn.isJDBCDateColumn()) {\n rc = true;\n break;\n }\n }\n }\n\n return rc;\n }\n\n /**\n * Returns true if any of the columns in the table are JDBC Times (as\n * opposed to timestamps).\n * \n * @return true if the table contains TIME columns\n */\n public boolean hasJDBCTimeColumns() {\n boolean rc = false;\n\n for (IntrospectedColumn introspectedColumn : primaryKeyColumns) {\n if (introspectedColumn.isJDBCTimeColumn()) {\n rc = true;\n break;\n }\n }\n\n if (!rc) {\n for (IntrospectedColumn introspectedColumn : baseColumns) {\n if (introspectedColumn.isJDBCTimeColumn()) {\n rc = true;\n break;\n }\n }\n }\n\n return rc;\n }\n\n /**\n * Returns the columns in the primary key. If the generatePrimaryKeyClass()\n * method returns false, then these columns will be iterated as the\n * parameters of the selectByPrimaryKay and deleteByPrimaryKey methods\n * \n * @return a List of ColumnDefinition objects for columns in the primary key\n */\n public List<IntrospectedColumn> getPrimaryKeyColumns() {\n return primaryKeyColumns;\n }\n\n public boolean hasPrimaryKeyColumns() {\n return primaryKeyColumns.size() > 0;\n }\n\n public List<IntrospectedColumn> getBaseColumns() {\n return baseColumns;\n }\n\n /**\n * Returns all columns in the table (for use by the select by primary key\n * and select by example with BLOBs methods)\n * \n * @return a List of ColumnDefinition objects for all columns in the table\n */\n public List<IntrospectedColumn> getAllColumns() {\n List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();\n answer.addAll(primaryKeyColumns);\n answer.addAll(baseColumns);\n answer.addAll(blobColumns);\n\n return answer;\n }\n\n /**\n * Returns all columns except BLOBs (for use by the select by example\n * without BLOBs method)\n * \n * @return a List of ColumnDefinition objects for columns in the table that\n * are non BLOBs\n */\n public List<IntrospectedColumn> getNonBLOBColumns() {\n List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();\n answer.addAll(primaryKeyColumns);\n answer.addAll(baseColumns);\n\n return answer;\n }\n\n public int getNonBLOBColumnCount() {\n return primaryKeyColumns.size() + baseColumns.size();\n }\n\n public List<IntrospectedColumn> getNonPrimaryKeyColumns() {\n List<IntrospectedColumn> answer = new ArrayList<IntrospectedColumn>();\n answer.addAll(baseColumns);\n answer.addAll(blobColumns);\n\n return answer;\n }\n\n public List<IntrospectedColumn> getBLOBColumns() {\n return blobColumns;\n }\n\n public boolean hasBLOBColumns() {\n return blobColumns.size() > 0;\n }\n\n public boolean hasBaseColumns() {\n return baseColumns.size() > 0;\n }\n\n public Rules getRules() {\n return rules;\n }\n\n public String getTableConfigurationProperty(String property) {\n return tableConfiguration.getProperty(property);\n }\n\n public String getPrimaryKeyType() {\n return internalAttributes.get(InternalAttribute.ATTR_PRIMARY_KEY_TYPE);\n }\n\n /**\n * \n * @return the type for the record (the class that holds non-primary key and\n * non-BLOB fields). Note that the value will be calculated\n * regardless of whether the table has these columns or not.\n */\n public String getBaseRecordType() {\n return internalAttributes.get(InternalAttribute.ATTR_BASE_RECORD_TYPE);\n }\n\n /**\n * \n * @return the type for the example class.\n */\n public String getExampleType() {\n return internalAttributes.get(InternalAttribute.ATTR_EXAMPLE_TYPE);\n }\n\n /**\n * \n * @return the type for the record with BLOBs class. Note that the value\n * will be calculated regardless of whether the table has BLOB\n * columns or not.\n */\n public String getRecordWithBLOBsType() {\n return internalAttributes\n .get(InternalAttribute.ATTR_RECORD_WITH_BLOBS_TYPE);\n }\n\n /**\n * Calculates an SQL Map file name for the table. Typically the name is\n * \"XXXX_SqlMap.xml\" where XXXX is the fully qualified table name (delimited\n * with underscores).\n * \n * @return the name of the SqlMap file\n */\n public String getIbatis2SqlMapFileName() {\n return internalAttributes\n .get(InternalAttribute.ATTR_IBATIS2_SQL_MAP_FILE_NAME);\n }\n\n public String getIbatis2SqlMapNamespace() {\n return internalAttributes\n .get(InternalAttribute.ATTR_IBATIS2_SQL_MAP_NAMESPACE);\n }\n\n public String getMyBatis3SqlMapNamespace() {\n String namespace = getMyBatis3JavaMapperType();\n if (namespace == null) {\n namespace = getMyBatis3FallbackSqlMapNamespace();\n }\n \n return namespace;\n }\n \n public String getMyBatis3FallbackSqlMapNamespace() {\n return internalAttributes\n .get(InternalAttribute.ATTR_MYBATIS3_FALLBACK_SQL_MAP_NAMESPACE);\n }\n \n /**\n * Calculates the package for the current table.\n * \n * @return the package for the SqlMap for the current table\n */\n public String getIbatis2SqlMapPackage() {\n return internalAttributes\n .get(InternalAttribute.ATTR_IBATIS2_SQL_MAP_PACKAGE);\n }\n\n public String getDAOImplementationType() {\n return internalAttributes\n .get(InternalAttribute.ATTR_DAO_IMPLEMENTATION_TYPE);\n }\n\n public String getDAOInterfaceType() {\n return internalAttributes\n .get(InternalAttribute.ATTR_DAO_INTERFACE_TYPE);\n }\n\n public boolean hasAnyColumns() {\n return primaryKeyColumns.size() > 0 || baseColumns.size() > 0\n || blobColumns.size() > 0;\n }\n\n public void setTableConfiguration(TableConfiguration tableConfiguration) {\n this.tableConfiguration = tableConfiguration;\n }\n\n public void setFullyQualifiedTable(FullyQualifiedTable fullyQualifiedTable) {\n this.fullyQualifiedTable = fullyQualifiedTable;\n }\n\n public void setContext(Context context) {\n this.context = context;\n }\n\n public void addColumn(IntrospectedColumn introspectedColumn) {\n if (introspectedColumn.isBLOBColumn()) {\n blobColumns.add(introspectedColumn);\n } else {\n baseColumns.add(introspectedColumn);\n }\n\n introspectedColumn.setIntrospectedTable(this);\n }\n\n public void addPrimaryKeyColumn(String columnName) {\n boolean found = false;\n // first search base columns\n Iterator<IntrospectedColumn> iter = baseColumns.iterator();\n while (iter.hasNext()) {\n IntrospectedColumn introspectedColumn = iter.next();\n if (introspectedColumn.getActualColumnName().equals(columnName)) {\n primaryKeyColumns.add(introspectedColumn);\n iter.remove();\n found = true;\n break;\n }\n }\n\n // search blob columns in the weird event that a blob is the primary key\n if (!found) {\n iter = blobColumns.iterator();\n while (iter.hasNext()) {\n IntrospectedColumn introspectedColumn = iter.next();\n if (introspectedColumn.getActualColumnName().equals(columnName)) {\n primaryKeyColumns.add(introspectedColumn);\n iter.remove();\n found = true;\n break;\n }\n }\n }\n }\n\n public Object getAttribute(String name) {\n return attributes.get(name);\n }\n\n public void removeAttribute(String name) {\n attributes.remove(name);\n }\n\n public void setAttribute(String name, Object value) {\n attributes.put(name, value);\n }\n\n public void initialize() {\n calculateJavaClientAttributes();\n calculateModelAttributes();\n calculateXmlAttributes();\n\n if (tableConfiguration.getModelType() == ModelType.HIERARCHICAL) {\n rules = new HierarchicalModelRules(this);\n } else if (tableConfiguration.getModelType() == ModelType.FLAT) {\n rules = new FlatModelRules(this);\n } else {\n rules = new ConditionalModelRules(this);\n }\n\n context.getPlugins().initialized(this);\n }\n\n /**\n * \n */\n protected void calculateXmlAttributes() {\n setIbatis2SqlMapPackage(calculateSqlMapPackage());\n setIbatis2SqlMapFileName(calculateIbatis2SqlMapFileName());\n setMyBatis3XmlMapperFileName(calculateMyBatis3XmlMapperFileName());\n setMyBatis3XmlMapperPackage(calculateSqlMapPackage());\n\n setIbatis2SqlMapNamespace(calculateIbatis2SqlMapNamespace());\n setMyBatis3FallbackSqlMapNamespace(calculateMyBatis3FallbackSqlMapNamespace());\n \n setSqlMapFullyQualifiedRuntimeTableName(calculateSqlMapFullyQualifiedRuntimeTableName());\n setSqlMapAliasedFullyQualifiedRuntimeTableName(calculateSqlMapAliasedFullyQualifiedRuntimeTableName());\n\n setCountByExampleStatementId(\"countByExample\"); //$NON-NLS-1$\n setDeleteByExampleStatementId(\"deleteByExample\"); //$NON-NLS-1$\n setDeleteByPrimaryKeyStatementId(\"deleteByPrimaryKey\"); //$NON-NLS-1$\n setInsertStatementId(\"insert\"); //$NON-NLS-1$\n setInsertSelectiveStatementId(\"insertSelective\"); //$NON-NLS-1$\n setSelectAllStatementId(\"selectAll\"); //$NON-NLS-1$\n setSelectByExampleStatementId(\"selectByExample\"); //$NON-NLS-1$\n setSelectByExampleWithBLOBsStatementId(\"selectByExampleWithBLOBs\"); //$NON-NLS-1$\n setSelectByPrimaryKeyStatementId(\"selectByPrimaryKey\"); //$NON-NLS-1$\n setUpdateByExampleStatementId(\"updateByExample\"); //$NON-NLS-1$\n setUpdateByExampleSelectiveStatementId(\"updateByExampleSelective\"); //$NON-NLS-1$\n setUpdateByExampleWithBLOBsStatementId(\"updateByExampleWithBLOBs\"); //$NON-NLS-1$\n setUpdateByPrimaryKeyStatementId(\"updateByPrimaryKey\"); //$NON-NLS-1$\n setUpdateByPrimaryKeySelectiveStatementId(\"updateByPrimaryKeySelective\"); //$NON-NLS-1$\n setUpdateByPrimaryKeyWithBLOBsStatementId(\"updateByPrimaryKeyWithBLOBs\"); //$NON-NLS-1$\n setBaseResultMapId(\"BaseResultMap\"); //$NON-NLS-1$\n setResultMapWithBLOBsId(\"ResultMapWithBLOBs\"); //$NON-NLS-1$\n setExampleWhereClauseId(\"Example_Where_Clause\"); //$NON-NLS-1$\n setBaseColumnListId(\"Base_Column_List\"); //$NON-NLS-1$\n setBlobColumnListId(\"Blob_Column_List\"); //$NON-NLS-1$\n setMyBatis3UpdateByExampleWhereClauseId(\"Update_By_Example_Where_Clause\"); //$NON-NLS-1$\n }\n\n public void setBlobColumnListId(String s) {\n internalAttributes.put(InternalAttribute.ATTR_BLOB_COLUMN_LIST_ID, s);\n }\n\n public void setBaseColumnListId(String s) {\n internalAttributes.put(InternalAttribute.ATTR_BASE_COLUMN_LIST_ID, s);\n }\n\n public void setExampleWhereClauseId(String s) {\n internalAttributes.put(InternalAttribute.ATTR_EXAMPLE_WHERE_CLAUSE_ID,\n s);\n }\n\n public void setMyBatis3UpdateByExampleWhereClauseId(String s) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_MYBATIS3_UPDATE_BY_EXAMPLE_WHERE_CLAUSE_ID,\n s);\n }\n\n public void setResultMapWithBLOBsId(String s) {\n internalAttributes.put(InternalAttribute.ATTR_RESULT_MAP_WITH_BLOBS_ID,\n s);\n }\n\n public void setBaseResultMapId(String s) {\n internalAttributes.put(InternalAttribute.ATTR_BASE_RESULT_MAP_ID, s);\n }\n\n public void setUpdateByPrimaryKeyWithBLOBsStatementId(String s) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_UPDATE_BY_PRIMARY_KEY_WITH_BLOBS_STATEMENT_ID,\n s);\n }\n\n public void setUpdateByPrimaryKeySelectiveStatementId(String s) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_UPDATE_BY_PRIMARY_KEY_SELECTIVE_STATEMENT_ID,\n s);\n }\n\n public void setUpdateByPrimaryKeyStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_UPDATE_BY_PRIMARY_KEY_STATEMENT_ID, s);\n }\n\n public void setUpdateByExampleWithBLOBsStatementId(String s) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_UPDATE_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID,\n s);\n }\n\n public void setUpdateByExampleSelectiveStatementId(String s) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_UPDATE_BY_EXAMPLE_SELECTIVE_STATEMENT_ID,\n s);\n }\n\n public void setUpdateByExampleStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_UPDATE_BY_EXAMPLE_STATEMENT_ID, s);\n }\n\n public void setSelectByPrimaryKeyStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_SELECT_BY_PRIMARY_KEY_STATEMENT_ID, s);\n }\n\n public void setSelectByExampleWithBLOBsStatementId(String s) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_SELECT_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID,\n s);\n }\n\n public void setSelectAllStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_SELECT_ALL_STATEMENT_ID, s);\n }\n\n public void setSelectByExampleStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_SELECT_BY_EXAMPLE_STATEMENT_ID, s);\n }\n\n public void setInsertSelectiveStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_INSERT_SELECTIVE_STATEMENT_ID, s);\n }\n\n public void setInsertStatementId(String s) {\n internalAttributes.put(InternalAttribute.ATTR_INSERT_STATEMENT_ID, s);\n }\n\n public void setDeleteByPrimaryKeyStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_DELETE_BY_PRIMARY_KEY_STATEMENT_ID, s);\n }\n\n public void setDeleteByExampleStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_DELETE_BY_EXAMPLE_STATEMENT_ID, s);\n }\n\n public void setCountByExampleStatementId(String s) {\n internalAttributes.put(\n InternalAttribute.ATTR_COUNT_BY_EXAMPLE_STATEMENT_ID, s);\n }\n\n public String getBlobColumnListId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_BLOB_COLUMN_LIST_ID);\n }\n\n public String getBaseColumnListId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_BASE_COLUMN_LIST_ID);\n }\n\n public String getExampleWhereClauseId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_EXAMPLE_WHERE_CLAUSE_ID);\n }\n\n public String getMyBatis3UpdateByExampleWhereClauseId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_MYBATIS3_UPDATE_BY_EXAMPLE_WHERE_CLAUSE_ID);\n }\n\n public String getResultMapWithBLOBsId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_RESULT_MAP_WITH_BLOBS_ID);\n }\n\n public String getBaseResultMapId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_BASE_RESULT_MAP_ID);\n }\n\n public String getUpdateByPrimaryKeyWithBLOBsStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_UPDATE_BY_PRIMARY_KEY_WITH_BLOBS_STATEMENT_ID);\n }\n\n public String getUpdateByPrimaryKeySelectiveStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_UPDATE_BY_PRIMARY_KEY_SELECTIVE_STATEMENT_ID);\n }\n\n public String getUpdateByPrimaryKeyStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_UPDATE_BY_PRIMARY_KEY_STATEMENT_ID);\n }\n\n public String getUpdateByExampleWithBLOBsStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_UPDATE_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID);\n }\n\n public String getUpdateByExampleSelectiveStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_UPDATE_BY_EXAMPLE_SELECTIVE_STATEMENT_ID);\n }\n\n public String getUpdateByExampleStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_UPDATE_BY_EXAMPLE_STATEMENT_ID);\n }\n\n public String getSelectByPrimaryKeyStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_SELECT_BY_PRIMARY_KEY_STATEMENT_ID);\n }\n\n public String getSelectByExampleWithBLOBsStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_SELECT_BY_EXAMPLE_WITH_BLOBS_STATEMENT_ID);\n }\n\n public String getSelectAllStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_SELECT_ALL_STATEMENT_ID);\n }\n\n public String getSelectByExampleStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_SELECT_BY_EXAMPLE_STATEMENT_ID);\n }\n\n public String getInsertSelectiveStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_INSERT_SELECTIVE_STATEMENT_ID);\n }\n\n public String getInsertStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_INSERT_STATEMENT_ID);\n }\n\n public String getDeleteByPrimaryKeyStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_DELETE_BY_PRIMARY_KEY_STATEMENT_ID);\n }\n\n public String getDeleteByExampleStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_DELETE_BY_EXAMPLE_STATEMENT_ID);\n }\n\n public String getCountByExampleStatementId() {\n return internalAttributes\n .get(InternalAttribute.ATTR_COUNT_BY_EXAMPLE_STATEMENT_ID);\n }\n\n protected String calculateJavaClientImplementationPackage() {\n JavaClientGeneratorConfiguration config = context\n .getJavaClientGeneratorConfiguration();\n if (config == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n if (stringHasValue(config.getImplementationPackage())) {\n sb.append(config.getImplementationPackage());\n } else {\n sb.append(config.getTargetPackage());\n }\n\n sb.append(fullyQualifiedTable.getSubPackage(isSubPackagesEnabled(config)));\n\n return sb.toString();\n }\n \n private boolean isSubPackagesEnabled(PropertyHolder propertyHolder) {\n return isTrue(propertyHolder.getProperty(PropertyRegistry.ANY_ENABLE_SUB_PACKAGES));\n }\n\n protected String calculateJavaClientInterfacePackage() {\n JavaClientGeneratorConfiguration config = context\n .getJavaClientGeneratorConfiguration();\n if (config == null) {\n return null;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(config.getTargetPackage());\n\n sb.append(fullyQualifiedTable.getSubPackage(isSubPackagesEnabled(config)));\n\n return sb.toString();\n }\n\n protected void calculateJavaClientAttributes() {\n if (context.getJavaClientGeneratorConfiguration() == null) {\n return;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(calculateJavaClientImplementationPackage());\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"DAOImpl\"); //$NON-NLS-1$\n setDAOImplementationType(sb.toString());\n\n sb.setLength(0);\n sb.append(calculateJavaClientInterfacePackage());\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"DAO\"); //$NON-NLS-1$\n setDAOInterfaceType(sb.toString());\n\n sb.setLength(0);\n sb.append(calculateJavaClientInterfacePackage());\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"Mapper\"); //$NON-NLS-1$\n setMyBatis3JavaMapperType(sb.toString());\n\n sb.setLength(0);\n sb.append(calculateJavaClientInterfacePackage());\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"SqlProvider\"); //$NON-NLS-1$\n setMyBatis3SqlProviderType(sb.toString());\n }\n\n protected String calculateJavaModelPackage() {\n JavaModelGeneratorConfiguration config = context\n .getJavaModelGeneratorConfiguration();\n\n StringBuilder sb = new StringBuilder();\n sb.append(config.getTargetPackage());\n sb.append(fullyQualifiedTable.getSubPackage(isSubPackagesEnabled(config)));\n\n return sb.toString();\n }\n\n protected void calculateModelAttributes() {\n String pakkage = calculateJavaModelPackage();\n\n StringBuilder sb = new StringBuilder();\n sb.append(pakkage);\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"Key\"); //$NON-NLS-1$\n setPrimaryKeyType(sb.toString());\n\n sb.setLength(0);\n sb.append(pakkage);\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n setBaseRecordType(sb.toString());\n\n sb.setLength(0);\n sb.append(pakkage);\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"WithBLOBs\"); //$NON-NLS-1$\n setRecordWithBLOBsType(sb.toString());\n\n sb.setLength(0);\n sb.append(pakkage);\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"Example\"); //$NON-NLS-1$\n setExampleType(sb.toString());\n }\n\n protected String calculateSqlMapPackage() {\n StringBuilder sb = new StringBuilder();\n SqlMapGeneratorConfiguration config = context\n .getSqlMapGeneratorConfiguration();\n \n // config can be null if the Java client does not require XML\n if (config != null) {\n sb.append(config.getTargetPackage());\n sb.append(fullyQualifiedTable.getSubPackage(isSubPackagesEnabled(config)));\n }\n\n return sb.toString();\n }\n\n protected String calculateIbatis2SqlMapFileName() {\n StringBuilder sb = new StringBuilder();\n sb.append(fullyQualifiedTable.getIbatis2SqlMapNamespace());\n sb.append(\"_SqlMap.xml\"); //$NON-NLS-1$\n return sb.toString();\n }\n\n protected String calculateMyBatis3XmlMapperFileName() {\n StringBuilder sb = new StringBuilder();\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"Mapper.xml\"); //$NON-NLS-1$\n return sb.toString();\n }\n\n protected String calculateIbatis2SqlMapNamespace() {\n return fullyQualifiedTable.getIbatis2SqlMapNamespace();\n }\n \n protected String calculateMyBatis3FallbackSqlMapNamespace() {\n StringBuilder sb = new StringBuilder();\n sb.append(calculateSqlMapPackage());\n sb.append('.');\n sb.append(fullyQualifiedTable.getDomainObjectName());\n sb.append(\"Mapper\"); //$NON-NLS-1$\n return sb.toString();\n }\n\n protected String calculateSqlMapFullyQualifiedRuntimeTableName() {\n return fullyQualifiedTable.getFullyQualifiedTableNameAtRuntime();\n }\n\n protected String calculateSqlMapAliasedFullyQualifiedRuntimeTableName() {\n return fullyQualifiedTable.getAliasedFullyQualifiedTableNameAtRuntime();\n }\n\n public String getFullyQualifiedTableNameAtRuntime() {\n return internalAttributes\n .get(InternalAttribute.ATTR_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME);\n }\n\n public String getAliasedFullyQualifiedTableNameAtRuntime() {\n return internalAttributes\n .get(InternalAttribute.ATTR_ALIASED_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME);\n }\n\n /**\n * This method can be used to initialize the generators before they will be\n * called.\n * \n * This method is called after all the setX methods, but before\n * getNumberOfSubtasks(), getGeneratedJavaFiles, and getGeneratedXmlFiles.\n * \n * @param warnings\n * @param progressCallback\n */\n public abstract void calculateGenerators(List<String> warnings,\n ProgressCallback progressCallback);\n\n /**\n * This method should return a list of generated Java files related to this\n * table. This list could include various types of model classes, as well as\n * DAO classes.\n * \n * @return the list of generated Java files for this table\n */\n public abstract List<GeneratedJavaFile> getGeneratedJavaFiles();\n\n /**\n * This method should return a list of generated XML files related to this\n * table. Most implementations will only return one file - the generated\n * SqlMap file.\n * \n * @return the list of generated XML files for this table\n */\n public abstract List<GeneratedXmlFile> getGeneratedXmlFiles();\n\n /**\n * Denotes whether generated code is targeted for Java version 5.0 or\n * higher.\n * \n * @return true if the generated code makes use of Java5 features\n */\n public abstract boolean isJava5Targeted();\n\n /**\n * This method should return the number of progress messages that will be\n * send during the generation phase.\n * \n * @return the number of progress messages\n */\n public abstract int getGenerationSteps();\n\n /**\n * This method exists to give plugins the opportunity to replace the\n * calculated rules if necessary.\n * \n * @param rules\n */\n public void setRules(Rules rules) {\n this.rules = rules;\n }\n\n public TableConfiguration getTableConfiguration() {\n return tableConfiguration;\n }\n\n public void setDAOImplementationType(String DAOImplementationType) {\n internalAttributes.put(InternalAttribute.ATTR_DAO_IMPLEMENTATION_TYPE,\n DAOImplementationType);\n }\n\n public void setDAOInterfaceType(String DAOInterfaceType) {\n internalAttributes.put(InternalAttribute.ATTR_DAO_INTERFACE_TYPE,\n DAOInterfaceType);\n }\n\n public void setPrimaryKeyType(String primaryKeyType) {\n internalAttributes.put(InternalAttribute.ATTR_PRIMARY_KEY_TYPE,\n primaryKeyType);\n }\n\n public void setBaseRecordType(String baseRecordType) {\n internalAttributes.put(InternalAttribute.ATTR_BASE_RECORD_TYPE,\n baseRecordType);\n }\n\n public void setRecordWithBLOBsType(String recordWithBLOBsType) {\n internalAttributes.put(InternalAttribute.ATTR_RECORD_WITH_BLOBS_TYPE,\n recordWithBLOBsType);\n }\n\n public void setExampleType(String exampleType) {\n internalAttributes\n .put(InternalAttribute.ATTR_EXAMPLE_TYPE, exampleType);\n }\n\n public void setIbatis2SqlMapPackage(String sqlMapPackage) {\n internalAttributes.put(InternalAttribute.ATTR_IBATIS2_SQL_MAP_PACKAGE,\n sqlMapPackage);\n }\n\n public void setIbatis2SqlMapFileName(String sqlMapFileName) {\n internalAttributes.put(\n InternalAttribute.ATTR_IBATIS2_SQL_MAP_FILE_NAME,\n sqlMapFileName);\n }\n\n public void setIbatis2SqlMapNamespace(String sqlMapNamespace) {\n internalAttributes.put(\n InternalAttribute.ATTR_IBATIS2_SQL_MAP_NAMESPACE,\n sqlMapNamespace);\n }\n \n public void setMyBatis3FallbackSqlMapNamespace(String sqlMapNamespace) {\n internalAttributes.put(\n InternalAttribute.ATTR_MYBATIS3_FALLBACK_SQL_MAP_NAMESPACE,\n sqlMapNamespace);\n }\n\n public void setSqlMapFullyQualifiedRuntimeTableName(\n String fullyQualifiedRuntimeTableName) {\n internalAttributes.put(\n InternalAttribute.ATTR_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME,\n fullyQualifiedRuntimeTableName);\n }\n\n public void setSqlMapAliasedFullyQualifiedRuntimeTableName(\n String aliasedFullyQualifiedRuntimeTableName) {\n internalAttributes\n .put(\n InternalAttribute.ATTR_ALIASED_FULLY_QUALIFIED_TABLE_NAME_AT_RUNTIME,\n aliasedFullyQualifiedRuntimeTableName);\n }\n\n public String getMyBatis3XmlMapperPackage() {\n return internalAttributes\n .get(InternalAttribute.ATTR_MYBATIS3_XML_MAPPER_PACKAGE);\n }\n\n public void setMyBatis3XmlMapperPackage(String mybatis3XmlMapperPackage) {\n internalAttributes.put(\n InternalAttribute.ATTR_MYBATIS3_XML_MAPPER_PACKAGE,\n mybatis3XmlMapperPackage);\n }\n\n public String getMyBatis3XmlMapperFileName() {\n return internalAttributes\n .get(InternalAttribute.ATTR_MYBATIS3_XML_MAPPER_FILE_NAME);\n }\n\n public void setMyBatis3XmlMapperFileName(String mybatis3XmlMapperFileName) {\n internalAttributes.put(\n InternalAttribute.ATTR_MYBATIS3_XML_MAPPER_FILE_NAME,\n mybatis3XmlMapperFileName);\n }\n\n public String getMyBatis3JavaMapperType() {\n return internalAttributes\n .get(InternalAttribute.ATTR_MYBATIS3_JAVA_MAPPER_TYPE);\n }\n\n public void setMyBatis3JavaMapperType(String mybatis3JavaMapperType) {\n internalAttributes.put(\n InternalAttribute.ATTR_MYBATIS3_JAVA_MAPPER_TYPE,\n mybatis3JavaMapperType);\n }\n\n public String getMyBatis3SqlProviderType() {\n return internalAttributes\n .get(InternalAttribute.ATTR_MYBATIS3_SQL_PROVIDER_TYPE);\n }\n\n public void setMyBatis3SqlProviderType(String mybatis3SqlProviderType) {\n internalAttributes.put(\n InternalAttribute.ATTR_MYBATIS3_SQL_PROVIDER_TYPE,\n mybatis3SqlProviderType);\n }\n \n public TargetRuntime getTargetRuntime() {\n return targetRuntime;\n }\n \n public boolean isImmutable() {\n Properties properties;\n \n if (tableConfiguration.getProperties().containsKey(PropertyRegistry.ANY_IMMUTABLE)) {\n properties = tableConfiguration.getProperties();\n } else {\n properties = context.getJavaModelGeneratorConfiguration().getProperties();\n }\n \n return isTrue(properties.getProperty(PropertyRegistry.ANY_IMMUTABLE));\n }\n \n public boolean isConstructorBased() {\n if (isImmutable()) {\n return true;\n }\n \n Properties properties;\n \n if (tableConfiguration.getProperties().containsKey(PropertyRegistry.ANY_CONSTRUCTOR_BASED)) {\n properties = tableConfiguration.getProperties();\n } else {\n properties = context.getJavaModelGeneratorConfiguration().getProperties();\n }\n \n return isTrue(properties.getProperty(PropertyRegistry.ANY_CONSTRUCTOR_BASED));\n }\n\n /**\n * Should return true if an XML generator is required for this table.\n * This method will be called during validation of the configuration,\n * so it should not rely on database introspection. This method\n * simply tells the validator if an XML configuration is normally\n * required for this implementation.\n * @return\n */\n public abstract boolean requiresXMLGenerator();\n\n public Context getContext() {\n return context;\n }\n}", "public interface ProgressCallback {\n /**\n * Called to note the start of the introspection phase, and to note the\n * maximum number of startTask messages that will be sent for the\n * introspection phase.\n * \n * @param totalTasks\n * the maximum number of times startTask will be called for the\n * introspection phase.\n */\n void introspectionStarted(int totalTasks);\n\n /**\n * Called to note the start of the generation phase, and to note the maximum\n * number of startTask messages that will be sent for the generation phase.\n * \n * @param totalTasks\n * the maximum number of times startTask will be called for the\n * generation phase.\n */\n void generationStarted(int totalTasks);\n\n /**\n * Called to note the start of the file saving phase, and to note the\n * maximum number of startTask messages that will be sent for the file\n * saving phase phase.\n * \n * @param totalTasks\n * the maximum number of times startTask will be called for the\n * file saving phase.\n */\n void saveStarted(int totalTasks);\n\n /**\n * Called to denote the beginning of a save task\n * \n * @param taskName\n * a descriptive name of the current work step\n */\n void startTask(String taskName);\n\n /**\n * This method is called when all generated files have been saved\n */\n void done();\n\n /**\n * The method is called periodically during a long running method.\n * If the the implementation throws <code>InterruptedException</code> then\n * the method will be canceled. Any files that have already been saved will\n * remain on the file system.\n * \n * @throws InterruptedException\n * if the operation should be halted\n */\n void checkCancel() throws InterruptedException;\n}", "public class ObjectFactory {\n private static List<ClassLoader> externalClassLoaders;\n private static List<ClassLoader> resourceClassLoaders;\n \n static {\n \texternalClassLoaders = new ArrayList<ClassLoader>();\n resourceClassLoaders = new ArrayList<ClassLoader>();\n }\n\n /**\n * Utility class. No instances allowed\n */\n private ObjectFactory() {\n super();\n }\n\n /**\n * Adds a custom classloader to the collection of classloaders\n * searched for resources. Currently, this is only used\n * when searching for properties files that may be\n * referenced in the configuration file. \n * \n * @param classLoader\n */\n public static synchronized void addResourceClassLoader(\n ClassLoader classLoader) {\n ObjectFactory.resourceClassLoaders.add(classLoader);\n }\n\n /**\n * Adds a custom classloader to the collection of classloaders\n * searched for \"external\" classes. These are classes that\n * do not depend on any of the generator's classes or\n * interfaces. Examples are JDBC drivers, root classes, root\n * interfaces, etc.\n * \n * @param classLoader\n */\n public static synchronized void addExternalClassLoader(\n ClassLoader classLoader) {\n ObjectFactory.externalClassLoaders.add(classLoader);\n }\n \n /**\n * This method returns a class loaded from the context classloader, or the\n * classloader supplied by a client. This is appropriate for JDBC drivers,\n * model root classes, etc. It is not appropriate for any class that extends\n * one of the supplied classes or interfaces.\n * \n * @param type\n * @return the Class loaded from the external classloader\n * @throws ClassNotFoundException\n */\n public static Class<?> externalClassForName(String type)\n throws ClassNotFoundException {\n\n Class<?> clazz;\n\n for (ClassLoader classLoader : externalClassLoaders) {\n try {\n clazz = Class.forName(type, true, classLoader);\n return clazz;\n } catch (Throwable e) {\n // ignore - fail safe below\n ;\n }\n }\n \n return internalClassForName(type);\n }\n\n public static Object createExternalObject(String type) {\n Object answer;\n\n try {\n Class<?> clazz = externalClassForName(type);\n answer = clazz.newInstance();\n } catch (Exception e) {\n throw new RuntimeException(getString(\n \"RuntimeError.6\", type), e); //$NON-NLS-1$\n }\n\n return answer;\n }\n\n public static Class<?> internalClassForName(String type)\n throws ClassNotFoundException {\n Class<?> clazz = null;\n\n try {\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n clazz = Class.forName(type, true, cl);\n } catch (Exception e) {\n // ignore - failsafe below\n }\n\n if (clazz == null) {\n clazz = Class.forName(type, true, ObjectFactory.class.getClassLoader());\n }\n\n return clazz;\n }\n\n public static URL getResource(String resource) {\n URL url;\n\n for (ClassLoader classLoader : resourceClassLoaders) {\n url = classLoader.getResource(resource);\n if (url != null) {\n return url;\n }\n }\n \n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n url = cl.getResource(resource);\n\n if (url == null) {\n url = ObjectFactory.class.getClassLoader().getResource(resource);\n }\n\n return url;\n }\n\n public static Object createInternalObject(String type) {\n Object answer;\n\n try {\n Class<?> clazz = internalClassForName(type);\n\n answer = clazz.newInstance();\n } catch (Exception e) {\n throw new RuntimeException(getString(\n \"RuntimeError.6\", type), e); //$NON-NLS-1$\n\n }\n\n return answer;\n }\n\n public static JavaTypeResolver createJavaTypeResolver(Context context,\n List<String> warnings) {\n JavaTypeResolverConfiguration config = context\n .getJavaTypeResolverConfiguration();\n String type;\n\n if (config != null && config.getConfigurationType() != null) {\n type = config.getConfigurationType();\n if (\"DEFAULT\".equalsIgnoreCase(type)) { //$NON-NLS-1$\n type = JavaTypeResolverDefaultImpl.class.getName();\n }\n } else {\n type = JavaTypeResolverDefaultImpl.class.getName();\n }\n\n JavaTypeResolver answer = (JavaTypeResolver) createInternalObject(type);\n answer.setWarnings(warnings);\n\n if (config != null) {\n answer.addConfigurationProperties(config.getProperties());\n }\n\n answer.setContext(context);\n\n return answer;\n }\n\n public static Plugin createPlugin(Context context,\n PluginConfiguration pluginConfiguration) {\n Plugin plugin = (Plugin) createInternalObject(pluginConfiguration\n .getConfigurationType());\n plugin.setContext(context);\n plugin.setProperties(pluginConfiguration.getProperties());\n return plugin;\n }\n\n public static CommentGenerator createCommentGenerator(Context context) {\n\n CommentGeneratorConfiguration config = context\n .getCommentGeneratorConfiguration();\n CommentGenerator answer;\n\n String type;\n if (config == null || config.getConfigurationType() == null) {\n type = DefaultCommentGenerator.class.getName();\n } else {\n type = config.getConfigurationType();\n }\n\n answer = (CommentGenerator) createInternalObject(type);\n\n if (config != null) {\n answer.addConfigurationProperties(config.getProperties());\n }\n\n return answer;\n }\n\n public static JavaFormatter createJavaFormatter(Context context) {\n String type = context.getProperty(PropertyRegistry.CONTEXT_JAVA_FORMATTER);\n if (!StringUtility.stringHasValue(type)) {\n type = DefaultJavaFormatter.class.getName();\n }\n\n JavaFormatter answer = (JavaFormatter) createInternalObject(type);\n\n answer.setContext(context);\n\n return answer;\n }\n \n public static XmlFormatter createXmlFormatter(Context context) {\n String type = context.getProperty(PropertyRegistry.CONTEXT_XML_FORMATTER);\n if (!StringUtility.stringHasValue(type)) {\n type = DefaultXmlFormatter.class.getName();\n }\n\n XmlFormatter answer = (XmlFormatter) createInternalObject(type);\n\n answer.setContext(context);\n\n return answer;\n }\n \n public static IntrospectedTable createIntrospectedTable(\n TableConfiguration tableConfiguration, FullyQualifiedTable table,\n Context context) {\n\n IntrospectedTable answer = createIntrospectedTableForValidation(context);\n answer.setFullyQualifiedTable(table);\n answer.setTableConfiguration(tableConfiguration);\n\n return answer;\n }\n\n /**\n * This method creates an introspected table implementation that is\n * only usable for validation (i.e. for a context to determine\n * if the target is ibatis2 or mybatis3).\n * \n * @param context\n * @return\n */\n public static IntrospectedTable createIntrospectedTableForValidation(Context context) {\n String type = context.getTargetRuntime();\n if (!stringHasValue(type)) {\n type = IntrospectedTableMyBatis3Impl.class.getName();\n } else if (\"Ibatis2Java2\".equalsIgnoreCase(type)) { //$NON-NLS-1$\n type = IntrospectedTableIbatis2Java2Impl.class.getName();\n } else if (\"Ibatis2Java5\".equalsIgnoreCase(type)) { //$NON-NLS-1$\n type = IntrospectedTableIbatis2Java5Impl.class.getName();\n } else if (\"Ibatis3\".equalsIgnoreCase(type)) { //$NON-NLS-1$\n type = IntrospectedTableMyBatis3Impl.class.getName();\n } else if (\"MyBatis3\".equalsIgnoreCase(type)) { //$NON-NLS-1$\n type = IntrospectedTableMyBatis3Impl.class.getName();\n } else if (\"MyBatis3Simple\".equalsIgnoreCase(type)) { //$NON-NLS-1$\n type = IntrospectedTableMyBatis3SimpleImpl.class.getName();\n }\n\n IntrospectedTable answer = (IntrospectedTable) createInternalObject(type);\n answer.setContext(context);\n\n return answer;\n }\n \n public static IntrospectedColumn createIntrospectedColumn(Context context) {\n String type = context.getIntrospectedColumnImpl();\n if (!stringHasValue(type)) {\n type = IntrospectedColumn.class.getName();\n }\n\n IntrospectedColumn answer = (IntrospectedColumn) createInternalObject(type);\n answer.setContext(context);\n\n return answer;\n }\n}", "public final class PluginAggregator implements Plugin {\n private List<Plugin> plugins;\n\n public PluginAggregator() {\n plugins = new ArrayList<Plugin>();\n }\n\n public void addPlugin(Plugin plugin) {\n plugins.add(plugin);\n }\n\n public void setContext(Context context) {\n throw new UnsupportedOperationException();\n }\n\n public void setProperties(Properties properties) {\n throw new UnsupportedOperationException();\n }\n\n public boolean validate(List<String> warnings) {\n throw new UnsupportedOperationException();\n }\n\n public boolean modelBaseRecordClassGenerated(TopLevelClass tlc,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelBaseRecordClassGenerated(tlc, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass tlc,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelRecordWithBLOBsClassGenerated(tlc,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapCountByExampleElementGenerated(XmlElement element,\n IntrospectedTable table) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapCountByExampleElementGenerated(element, table)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapDeleteByExampleElementGenerated(XmlElement element,\n IntrospectedTable table) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapDeleteByExampleElementGenerated(element, table)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapDeleteByPrimaryKeyElementGenerated(XmlElement element,\n IntrospectedTable table) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin\n .sqlMapDeleteByPrimaryKeyElementGenerated(element, table)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean modelExampleClassGenerated(TopLevelClass tlc,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelExampleClassGenerated(tlc, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(\n IntrospectedTable introspectedTable) {\n List<GeneratedJavaFile> answer = new ArrayList<GeneratedJavaFile>();\n for (Plugin plugin : plugins) {\n List<GeneratedJavaFile> temp = plugin\n .contextGenerateAdditionalJavaFiles(introspectedTable);\n if (temp != null) {\n answer.addAll(temp);\n }\n }\n return answer;\n }\n\n public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles(\n IntrospectedTable introspectedTable) {\n List<GeneratedXmlFile> answer = new ArrayList<GeneratedXmlFile>();\n for (Plugin plugin : plugins) {\n List<GeneratedXmlFile> temp = plugin\n .contextGenerateAdditionalXmlFiles(introspectedTable);\n if (temp != null) {\n answer.addAll(temp);\n }\n }\n return answer;\n }\n\n public boolean modelPrimaryKeyClassGenerated(TopLevelClass tlc,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelPrimaryKeyClassGenerated(tlc, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapResultMapWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapResultMapWithoutBLOBsElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapExampleWhereClauseElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapExampleWhereClauseElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapInsertElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin\n .sqlMapInsertElementGenerated(element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapResultMapWithBLOBsElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapResultMapWithBLOBsElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapSelectByExampleWithoutBLOBsElementGenerated(\n element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapSelectByExampleWithBLOBsElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapSelectByPrimaryKeyElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapSelectByPrimaryKeyElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapGenerated(GeneratedXmlFile sqlMap,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapGenerated(sqlMap, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapUpdateByExampleSelectiveElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapUpdateByExampleSelectiveElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapUpdateByExampleWithBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapUpdateByExampleWithBLOBsElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapUpdateByExampleWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(\n element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapUpdateByPrimaryKeySelectiveElementGenerated(\n element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapUpdateByPrimaryKeyWithBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapUpdateByPrimaryKeyWithBLOBsElementGenerated(\n element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(\n XmlElement element, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapUpdateByPrimaryKeyWithoutBLOBsElementGenerated(\n element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientCountByExampleMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientCountByExampleMethodGenerated(method, interfaze,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientCountByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientCountByExampleMethodGenerated(method, topLevelClass,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientDeleteByExampleMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientDeleteByExampleMethodGenerated(method, interfaze,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientDeleteByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientDeleteByExampleMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientDeleteByPrimaryKeyMethodGenerated(method, interfaze,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientDeleteByPrimaryKeyMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientInsertMethodGenerated(Method method, Interface interfaze,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientInsertMethodGenerated(method, interfaze,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientInsertMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientInsertMethodGenerated(method, topLevelClass,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientGenerated(Interface interfaze,\n TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientGenerated(interfaze, topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectAllMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectAllMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectAllMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectAllMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectByExampleWithBLOBsMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectByExampleWithBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectByExampleWithoutBLOBsMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectByExampleWithoutBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectByPrimaryKeyMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectByPrimaryKeyMethodGenerated(method, interfaze,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientSelectByPrimaryKeyMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientSelectByPrimaryKeyMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByExampleSelectiveMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByExampleSelectiveMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByExampleWithBLOBsMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByExampleWithBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByExampleWithoutBLOBsMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByExampleWithoutBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByPrimaryKeySelectiveMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByPrimaryKeySelectiveMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(method,\n interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(\n Method method, Interface interfaze,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(\n method, interfaze, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(\n method, topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles() {\n List<GeneratedJavaFile> answer = new ArrayList<GeneratedJavaFile>();\n for (Plugin plugin : plugins) {\n List<GeneratedJavaFile> temp = plugin\n .contextGenerateAdditionalJavaFiles();\n if (temp != null) {\n answer.addAll(temp);\n }\n }\n return answer;\n }\n\n public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles() {\n List<GeneratedXmlFile> answer = new ArrayList<GeneratedXmlFile>();\n for (Plugin plugin : plugins) {\n List<GeneratedXmlFile> temp = plugin\n .contextGenerateAdditionalXmlFiles();\n if (temp != null) {\n answer.addAll(temp);\n }\n }\n return answer;\n }\n\n public boolean sqlMapDocumentGenerated(Document document,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapDocumentGenerated(document, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean modelFieldGenerated(Field field,\n TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,\n IntrospectedTable introspectedTable,\n Plugin.ModelClassType modelClassType) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelFieldGenerated(field, topLevelClass,\n introspectedColumn, introspectedTable, modelClassType)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean modelGetterMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,\n IntrospectedTable introspectedTable,\n Plugin.ModelClassType modelClassType) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelGetterMethodGenerated(method, topLevelClass,\n introspectedColumn, introspectedTable, modelClassType)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean modelSetterMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,\n IntrospectedTable introspectedTable,\n Plugin.ModelClassType modelClassType) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.modelSetterMethodGenerated(method, topLevelClass,\n introspectedColumn, introspectedTable, modelClassType)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapInsertSelectiveElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientInsertSelectiveMethodGenerated(Method method,\n Interface interfaze, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientInsertSelectiveMethodGenerated(method, interfaze,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean clientInsertSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.clientInsertSelectiveMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public void initialized(IntrospectedTable introspectedTable) {\n for (Plugin plugin : plugins) {\n plugin.initialized(introspectedTable);\n }\n }\n\n public boolean sqlMapBaseColumnListElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapBaseColumnListElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapBlobColumnListElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapBlobColumnListElementGenerated(element,\n introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerGenerated(TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerGenerated(topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerApplyWhereMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerApplyWhereMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerCountByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerCountByExampleMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerDeleteByExampleMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerDeleteByExampleMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerInsertSelectiveMethodGenerated(Method method,\n TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerInsertSelectiveMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerSelectByExampleWithBLOBsMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerSelectByExampleWithBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerSelectByExampleWithoutBLOBsMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerSelectByExampleWithoutBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerUpdateByExampleSelectiveMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerUpdateByExampleSelectiveMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerUpdateByExampleWithBLOBsMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerUpdateByExampleWithBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerUpdateByExampleWithoutBLOBsMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerUpdateByExampleWithoutBLOBsMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean providerUpdateByPrimaryKeySelectiveMethodGenerated(\n Method method, TopLevelClass topLevelClass,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.providerUpdateByPrimaryKeySelectiveMethodGenerated(method,\n topLevelClass, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n\n public boolean sqlMapSelectAllElementGenerated(XmlElement element,\n IntrospectedTable introspectedTable) {\n boolean rc = true;\n\n for (Plugin plugin : plugins) {\n if (!plugin.sqlMapSelectAllElementGenerated(element, introspectedTable)) {\n rc = false;\n break;\n }\n }\n\n return rc;\n }\n}" ]
import static org.mybatis.generator.internal.util.StringUtility.composeFullyQualifiedTableName; import static org.mybatis.generator.internal.util.StringUtility.isTrue; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; import static org.mybatis.generator.internal.util.messages.Messages.getString; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.GeneratedJavaFile; import org.mybatis.generator.api.GeneratedXmlFile; import org.mybatis.generator.api.JavaFormatter; import org.mybatis.generator.api.Plugin; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.JavaTypeResolver; import org.mybatis.generator.api.ProgressCallback; import org.mybatis.generator.api.XmlFormatter; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.XmlElement; import org.mybatis.generator.internal.ObjectFactory; import org.mybatis.generator.internal.PluginAggregator; import org.mybatis.generator.internal.db.ConnectionFactory; import org.mybatis.generator.internal.db.DatabaseIntrospector;
/* * Copyright 2005 The Apache Software Foundation * * 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.mybatis.generator.config; /** * @author Jeff Butler */ public class Context extends PropertyHolder { private String id; private JDBCConnectionConfiguration jdbcConnectionConfiguration; private SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration; private JavaTypeResolverConfiguration javaTypeResolverConfiguration; private JavaModelGeneratorConfiguration javaModelGeneratorConfiguration; private JavaClientGeneratorConfiguration javaClientGeneratorConfiguration; private ArrayList<TableConfiguration> tableConfigurations; private ModelType defaultModelType; private String beginningDelimiter = "\""; //$NON-NLS-1$ private String endingDelimiter = "\""; //$NON-NLS-1$ private CommentGeneratorConfiguration commentGeneratorConfiguration; private CommentGenerator commentGenerator; private PluginAggregator pluginAggregator; private List<PluginConfiguration> pluginConfigurations; private String targetRuntime; private String introspectedColumnImpl; private Boolean autoDelimitKeywords; private JavaFormatter javaFormatter; private XmlFormatter xmlFormatter; /** * Constructs a Context object. * * @param defaultModelType * - may be null */ public Context(ModelType defaultModelType) { super(); if (defaultModelType == null) { this.defaultModelType = ModelType.CONDITIONAL; } else { this.defaultModelType = defaultModelType; } tableConfigurations = new ArrayList<TableConfiguration>(); pluginConfigurations = new ArrayList<PluginConfiguration>(); } public void addTableConfiguration(TableConfiguration tc) { tableConfigurations.add(tc); } public JDBCConnectionConfiguration getJdbcConnectionConfiguration() { return jdbcConnectionConfiguration; } public JavaClientGeneratorConfiguration getJavaClientGeneratorConfiguration() { return javaClientGeneratorConfiguration; } public JavaModelGeneratorConfiguration getJavaModelGeneratorConfiguration() { return javaModelGeneratorConfiguration; } public JavaTypeResolverConfiguration getJavaTypeResolverConfiguration() { return javaTypeResolverConfiguration; } public SqlMapGeneratorConfiguration getSqlMapGeneratorConfiguration() { return sqlMapGeneratorConfiguration; } public void addPluginConfiguration( PluginConfiguration pluginConfiguration) { pluginConfigurations.add(pluginConfiguration); } /** * This method does a simple validate, it makes sure that all required * fields have been filled in. It does not do any more complex operations * such as validating that database tables exist or validating that named * columns exist */ public void validate(List<String> errors) { if (!stringHasValue(id)) { errors.add(getString("ValidationError.16")); //$NON-NLS-1$ } if (jdbcConnectionConfiguration == null) { errors.add(getString("ValidationError.10", id)); //$NON-NLS-1$ } else { jdbcConnectionConfiguration.validate(errors); } if (javaModelGeneratorConfiguration == null) { errors.add(getString("ValidationError.8", id)); //$NON-NLS-1$ } else { javaModelGeneratorConfiguration.validate(errors, id); } if (javaClientGeneratorConfiguration != null) { javaClientGeneratorConfiguration.validate(errors, id); }
IntrospectedTable it = null;
3
immopoly/android
src/org/immopoly/android/app/UserLoginActivity.java
[ "public class C2DMessaging {\n\tpublic static final String EXTRA_SENDER = \"sender\";\n\tpublic static final String EXTRA_APPLICATION_PENDING_INTENT = \"app\";\n\tpublic static final String REQUEST_UNREGISTRATION_INTENT = \"com.google.android.c2dm.intent.UNREGISTER\";\n\tpublic static final String REQUEST_REGISTRATION_INTENT = \"com.google.android.c2dm.intent.REGISTER\";\n\tpublic static final String LAST_REGISTRATION_CHANGE = \"last_registration_change\";\n\tpublic static final String BACKOFF = \"backoff\";\n\tpublic static final String GSF_PACKAGE = \"com.google.android.gsf\";\n\n\t// package\n\tstatic final String PREFERENCE = \"com.google.android.c2dm\";\n\n\tprivate static final long DEFAULT_BACKOFF = 30000;\n\n\t/**\n\t * Initiate c2d messaging registration for the current application\n\t */\n\tpublic static void register(Context context, String senderId) {\n\t\t// only if wanted\n\t\tSharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n\t\tboolean notification = sharedPreferences.getBoolean(\"notification\", true);\n\t\tif (!notification)\n\t\t\treturn;\n\t\tIntent registrationIntent = new Intent(REQUEST_REGISTRATION_INTENT);\n\t\tregistrationIntent.setPackage(GSF_PACKAGE);\n\t\tregistrationIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT,\n\t\t\t\tPendingIntent.getBroadcast(context, 0, new Intent(), 0));\n\t\tregistrationIntent.putExtra(EXTRA_SENDER, Const.IMMOPOLY_EMAIL);\n\t\tcontext.startService(registrationIntent);\n\t}\n\n\t/**\n\t * Unregister the application. New messages will be blocked by server.\n\t */\n\tpublic static void unregister(Context context) {\n\t\tIntent regIntent = new Intent(REQUEST_UNREGISTRATION_INTENT);\n\t\tregIntent.setPackage(GSF_PACKAGE);\n\t\tregIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT,\n\t\t\t\tPendingIntent.getBroadcast(context, 0, new Intent(), 0));\n\t\tcontext.startService(regIntent);\n\t}\n\n\t/**\n\t * Return the current registration id.\n\t * \n\t * If result is empty, the registration has failed.\n\t * \n\t * @return registration id, or empty string if the registration is not\n\t * complete.\n\t */\n\tpublic static String getRegistrationId(Context context) {\n\t\tfinal SharedPreferences prefs = context.getSharedPreferences(\n\t\t\t\tPREFERENCE, Context.MODE_PRIVATE);\n\t\tString registrationId = prefs.getString(\"dm_registration\", \"\");\n\t\treturn registrationId;\n\t}\n\n\tpublic static long getLastRegistrationChange(Context context) {\n\t\tfinal SharedPreferences prefs = context.getSharedPreferences(\n\t\t\t\tPREFERENCE, Context.MODE_PRIVATE);\n\t\treturn prefs.getLong(LAST_REGISTRATION_CHANGE, 0);\n\t}\n\n\tstatic long getBackoff(Context context) {\n\t\tfinal SharedPreferences prefs = context.getSharedPreferences(\n\t\t\t\tPREFERENCE, Context.MODE_PRIVATE);\n\t\treturn prefs.getLong(BACKOFF, DEFAULT_BACKOFF);\n\t}\n\n\tstatic void setBackoff(Context context, long backoff) {\n\t\tfinal SharedPreferences prefs = context.getSharedPreferences(\n\t\t\t\tPREFERENCE, Context.MODE_PRIVATE);\n\t\tEditor editor = prefs.edit();\n\t\teditor.putLong(BACKOFF, backoff);\n\t\teditor.commit();\n\n\t}\n\n\t// package\n\tstatic void clearRegistrationId(Context context) {\n\t\tfinal SharedPreferences prefs = context.getSharedPreferences(\n\t\t\t\tPREFERENCE, Context.MODE_PRIVATE);\n\t\tEditor editor = prefs.edit();\n\t\teditor.putString(\"dm_registration\", \"\");\n\t\teditor.putLong(LAST_REGISTRATION_CHANGE, System.currentTimeMillis());\n\t\teditor.commit();\n\n\t}\n\n\t// package\n\tstatic void setRegistrationId(Context context, String registrationId) {\n\t\tfinal SharedPreferences prefs = context.getSharedPreferences(\n\t\t\t\tPREFERENCE, Context.MODE_PRIVATE);\n\t\tEditor editor = prefs.edit();\n\t\teditor.putString(\"dm_registration\", registrationId);\n\t\teditor.commit();\n\n\t}\n}", "public class Const {\n\n\tpublic static final String LOG_TAG = \"IMPO\";\n\n\t// Intents\n\n\t// Intent open webview\n\tpublic static final String EXPOSE_ID = \"exposeID\";\n\tpublic static final String EXPOSE_NAME = \"exposeName\";\n\tpublic static final String EXPOSE_DESC = \"exposeDescription\";\n\tpublic static final String EXPOSE_URL = \"exposeURL\";\n\tpublic static final String EXPOSE_IN_PORTOFOLIO = \"exposeInPortfolio\";\n\t\n//\tpublic static final String EXPOSE_OWNED = \"exposeOwned\";\n\n\t// Intent add portofolio\n\tpublic static final String EXPOSE_ADD_PORTIFOLIO = \"addToPortifolio\";\n\tpublic static final String EXPOSE_RELEASE_PORTIFOLIO = \"releaseFromPortifolio\";\n\n\tpublic static final String SOURCE = \"source\";\n\n\t// immopoly\n\tpublic static final String EXPOSE_PICTURE_SMALL = \"exposeDescription\";\n\n\tpublic static final String SHARED_PREF_EXPOSE_WEBVIEW = \"exposeWebView\";\n\tpublic static final String KEY_VISITED = \"visited\";\n\n\tpublic static final String AUTH_URL = \"oauth_url\";\n\tpublic static final long EXPOSE_THRESHOLD_OLD = 1000L * 60L * 60L * 24L\n\t\t\t* 30L;\n\tpublic static final long EXPOSE_THRESHOLD_NEW = 1000L * 60L * 60L * 24L\n\t\t\t* 7L;\n\n\tpublic static final String MESSAGE_IMMOPOLY_EXCEPTION = \"org.immopoly.common.ImmopolyException\";\n\n\tpublic static final String IMMOPOLY_EMAIL = \"[email protected]\";\n\tpublic static final int ANALYTICS_INTERVAL = 20;\n\n\tpublic static final int USER_SIGNUP = 110;\n\n\t// IS24 search control - search different radii until at least SEARCH_MIN_RESULTS flats are found \n\tpublic static final float[] SEARCH_RADII \t = { 1, 3, 10 }; // in km\n\tpublic static final int SEARCH_MIN_RESULTS = 50;\t\t // ignored for last search radius\n\tpublic static final int SEARCH_MAX_RESULTS = 80;\t\t // forced result limit. fernglas me, baby!\n}", "public class Settings {\n\n\tprivate static ImageListDownloader exposeImageDownloader;\n\tprivate static float screenDesity;\n\t\n\tpublic static void shareMessage(Context context, String title,\n\t\t\tString message, String link) {\n\t\tfinal String tag = \"@immopoly\";\n\t\t/*\n\t\t * This code can limit the size of the messages which will be shared, \n\t\t * not needed at the moment\n\t\tfinal int maxMessage = 140;\n\t\tint overhead = maxMessage - message.length() - link.length() - 1\n\t\t\t\t- tag.length() - 1 - title.length() - 1;\n\t\tif (overhead < 0) {\n\t\t\tmessage = message.substring((-1)*overhead, message.length() - 1);\n\t\t}\n\t\tmessage = title + message;\n\t\t*/\n\t\tmessage += \" \" + link + \" \" + tag;\n\t\tfinal Intent intent = new Intent(Intent.ACTION_SEND);\n\t\tintent.setType(\"text/plain\");\n\t\tintent.putExtra(Intent.EXTRA_SUBJECT, title);\n\t\tintent.putExtra(Intent.EXTRA_TEXT, message);\n\t\tcontext.startActivity(Intent.createChooser(intent, \"Share\"));\n\t}\n\n\tpublic static boolean isOnline(Context context) {\n\t\tConnectivityManager cm = (ConnectivityManager) context\n\t\t\t\t.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tif (cm.getActiveNetworkInfo() == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn cm.getActiveNetworkInfo().isConnectedOrConnecting();\n\n\t}\n\n\tpublic static String getFlatLink(String exposeID, boolean mobile) {\n\t\tif(mobile)\n\t\t\treturn OAuthData.sExposeUrl + exposeID;\n\t\telse\n\t\t\treturn OAuthData.sExposeUrlWeb + exposeID;\n\t}\n\t\n\tpublic static ImageListDownloader getExposeImageDownloader( Context ctx ) {\n\t\tif ( exposeImageDownloader == null ) {\n\t\t\tBitmap loadingBmp = ((BitmapDrawable) ctx.getResources().getDrawable( R.drawable.loading )).getBitmap();\n\t\t\tBitmap fallbackBmp = ((BitmapDrawable) ctx.getResources().getDrawable( R.drawable.portfolio_fallback )).getBitmap();\n\t\t\tAnimation loadingAni = AnimationUtils.loadAnimation( ctx,R.anim.loading_animation );\n\t\t\texposeImageDownloader = new ImageListDownloader( loadingBmp, loadingAni, fallbackBmp );\n\t\t}\n\t\treturn exposeImageDownloader;\n\t}\n\n\n\t\n\tpublic static float getScreenDensity( Activity activity) {\n\t\tif ( screenDesity == 0.0f ) {\n\t\t\tDisplayMetrics metrics = new DisplayMetrics();\n\t\t\tactivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);\n\t\t\tscreenDesity = metrics.density;\n\t\t}\n\t\treturn screenDesity;\n\t}\n\t\n\tpublic static float dp2px( Activity activity, float dp ) {\n\t\tif ( screenDesity == 0.0f ) \n\t\t\tgetScreenDensity(activity);\n\t\treturn screenDesity*dp;\n\t}\n\t\n}", "public class TrackingManager {\n\n\tpublic static final String UA_ACCOUNT = \"UA-25341313-1\";\n\n\t// Page views, basicly Activities where you can do events\n\tpublic static final String VIEW_SIGNUP = \"signup\";\n\tpublic static final String VIEW_REGISTER = \"register\";\n\tpublic static final String VIEW_LOGIN = \"login\";\n\tpublic static final String VIEW_MAP = \"map\";\n\tpublic static final String VIEW_EXPOSE = \"expose\";\n\tpublic static final String VIEW_HISTORY = \"history\";\n\tpublic static final String VIEW_SHARE = \"share\";\n\tpublic static final String VIEW_ITEMS = \"actionItems\";\n\tpublic static final String VIEW_PORTFOLIO_LIST = \"portfolioList\";\n\tpublic static final String VIEW_PORTFOLIO_MAP = \"portfolioMap\";\n\tpublic static final String VIEW_PROFILE = \"profile\";\n\tpublic static final String VIEW_SETTINGS = \"settings\";\n\tpublic static final String VIEW_HELP = \"help\";\n\tpublic static final String VIEW_HIGHSCORE_OVERALL = \"highscoreOverall\";\n\tpublic static final String VIEW_HIGHSCORE_MONTH = \"highscoreMonth\";\n\tpublic static final String VIEW_HIGHSCORE_RELEAS_TESTER = \"highscoreReleaseTester\";\n\tpublic static final String VIEW_WEB_VIEW_DIALOG = \"webviewDialog\";\n\tpublic static final String VIEW_FIRST_AID = \"firstAid\";\n\tpublic static final String VIEW_ACTION_ITEM_SPY = \"actionItemSpye\";\n\t\n\n\tpublic static final String CATEGORY_CLICKS = \"clicks\";\n\tpublic static final String CATEGORY_SCROLL = \"scroll\";\n\tpublic static final String CATEGORY_ALERT_EXPOSE_TAKEN = \"alert\";\n\tpublic static final String CATEGORY_CLICKS_IN_WEBSITE = \"click_in_website\";\n\tpublic static final String CATEGORY_SHAREBUTTON = \"click_on_share_button\";\n\n\tpublic static final String ACTION_SHARE = \"share\";\n\tpublic static final String ACTION_VIEW = \"view\";\n\tpublic static final String ACTION_ERROR = \"error\";\n\tpublic static final String ACTION_EXPOSE = \"tookExpose\";\n\tpublic static final String ACTION_TOOK_EXPOSE = \"tookExpose\";\n\tpublic static final String ACTION_RELEASED_EXPOSE = \"releasedExpose\";\n\tpublic static final String ACTION_CONTACT = \"clickWebviewContact\";\n\tpublic static final String ACTION_FIRST_AID = \"firstAid\";\n\tpublic static final String ACTION_SEARCH = \"search\";\n\tpublic static final String ACTION_BADGE = \"badge\";\n\n\tpublic static final String LABEL_TRY = \"try\";\n\tpublic static final String LABEL_RELEASE = \"release\";\n\tpublic static final String LABEL_POSITIVE = \"positive\";\n\tpublic static final String LABEL_NEGATIVE = \"negative\";\n\tpublic static final String LABEL_IMAGES = \"image\";\n\tpublic static final String LABEL_IMAGES_DETAILS = \"imagesDetails\";\n\tpublic static final String LABEL_CHANGE_TO_REGISTER_FROM_LOGIN = \"changeFromRegisterToLogin\";\n\tpublic static final String LABEL_CHANGE_TO_LOGIN_FROM_REGISTER = \"changeFromLoginToRegister\";\n\tpublic static final String LABEL_BACK_INSIDE_IMMOSCOUT_WEBSITE = \"clickBackInsideImmoscoutWebsite\";\n\tpublic static final String LABEL_HUD_POPUP = \"showHudPopup\";\n\tpublic static final String LABEL_EXPOSE_PORTFOLIO = \"openExposeFromPortfolio\";\n\tpublic static final String LABEL_EXPOSE_MAP = \"openExposeFromMap\";\n\tpublic static final String LABEL_DISABLED = \"disabled\";\n\tpublic static final String LABEL_ENABLED = \"enabled\";\n\tpublic static final String LABEL_REFRESH = \"refresh\";\n\tpublic static final String LABEL_VIEW = \"view\";\n\n\n}", "public class WebHelper {\n\n// appengine on immopoly.appspot.com\n\tpublic static final String SERVER_URL_PREFIX = \"http://immopoly.appspot.com\";\n\tpublic static final String SERVER_HTTPS_URL_PREFIX = \"https://immopoly.appspot.com\";\n// appengine on emulator host (http only)\n//\tpublic static final String SERVER_URL_PREFIX = \"http://10.0.2.2:8888\";\n//\tpublic static final String SERVER_HTTPS_URL_PREFIX = \"http://10.0.2.2:8888\";\n\t\n\tpublic static final int SOCKET_TIMEOUT = 30000;\n\n\t\t\n\t\n\n\t\n\tpublic static JSONObject getHttpsData(URL url, boolean signed,\n\t\t\tContext context) throws ImmopolyException {\n\t\tJSONObject obj = null;\n\t\tif (Settings.isOnline(context)) {\n\t\t\tHttpURLConnection request;\n\t\t\ttry {\n\t\t\t\trequest = (HttpURLConnection) url.openConnection();\n\t\t\t\trequest.addRequestProperty(\"User-Agent\", \"immopoly android client \"+ImmopolyActivity.getStaticVersionInfo());\n\n\t\t\t\tif (signed)\n\t\t\t\t\tOAuthData.getInstance(context).consumer.sign(request);\n\n\t\t\t\trequest.setConnectTimeout(SOCKET_TIMEOUT);\n\t\t\t\trequest.connect();\n\n\t\t\t\tInputStream in = new BufferedInputStream(request\n\t\t\t\t\t\t.getInputStream());\n\t\t\t\tString s = readInputStream(in);\n\t\t\t\tJSONTokener tokener = new JSONTokener(s);\n\t\t\t\treturn new JSONObject(tokener);\n\t\t\t} catch (JSONException e) {\n\t\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem (beim lesen der Antwort)\",e);\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem (fehlerhafte URL)\",e);\n\t\t\t} catch (OAuthMessageSignerException e) {\n\t\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem (Signierung)\",e);\n\t\t\t} catch (OAuthExpectationFailedException e) {\n\t\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem (Sicherherit)\",e);\n\t\t\t} catch (OAuthCommunicationException e) {\n\t\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem (Sicherherit)\",e);\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem\",e);\n\t\t\t}\n\t\t}else\n\t\t\tthrow new ImmopolyException(\"Kommunikationsproblem (Offline)\");\n\t}\n\n\tpublic static JSONObject getHttpData(URL url, boolean signed,\n\t\t\tContext context) throws JSONException {\n\t\tJSONObject obj = null;\n\t\tif (Settings.isOnline(context)) {\n\t\t\tHttpURLConnection request;\n\t\t\ttry {\n\n\t\t\t\trequest = (HttpURLConnection) url.openConnection();\n\t\t\t\t\n\t\t\t\trequest.addRequestProperty(\"User-Agent\", \"immopoly android client \"+ImmopolyActivity.getStaticVersionInfo());\n\t\t\t\trequest.addRequestProperty(\"Accept-Encoding\", \"gzip\");\n\t\t\t\tif (signed)\n\t\t\t\t\tOAuthData.getInstance(context).consumer.sign(request);\n\t\t\t\trequest.setConnectTimeout(SOCKET_TIMEOUT);\n\n\t\t\t\trequest.connect();\n\t\t\t\tString encoding = request.getContentEncoding();\n\n\t\t\t\tInputStream in;\n\t\t\t\tif (encoding != null && encoding.equalsIgnoreCase(\"gzip\")) {\n\t\t\t\t\tin = new GZIPInputStream(request.getInputStream());\n\t\t\t\t} else {\n\t\t\t\t\tin = new BufferedInputStream(request.getInputStream());\n\t\t\t\t}\n\t\t\t\tString s = readInputStream(in);\n\t\t\t\tJSONTokener tokener = new JSONTokener(s);\n\t\t\t\tobj = new JSONObject(tokener);\n\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (OAuthMessageSignerException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (OAuthExpectationFailedException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (OAuthCommunicationException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn obj;\n\t}\n\t\n\tprivate static HttpResponse postHttp(String url, JSONObject jsonObject)\n\t\t\tthrows ClientProtocolException, IOException {\n\t\tHttpClient httpclient = new DefaultHttpClient();\n\t\tHttpPost httppost = new HttpPost(url);\n\n\t\thttppost.setHeader(\"User-Agent\", \"immopoly android client \"+ImmopolyActivity.getStaticVersionInfo());\n\t\thttppost.setHeader(\"Accept-Encoding\", \"gzip\");\n\t\t\n\t\tHttpEntity entity;\n\t\tentity = new StringEntity(jsonObject.toString());\n\t\t// sets the post request as the resulting string\n\t\thttppost.setEntity(entity);\n\t\t// Pass local context as a parameter\n\t\treturn httpclient.execute(httppost);\n\t}\n\t\n\tpublic static JSONArray postFlatIdsHttpData(String url, JSONObject jsonObject) throws JSONException {\n\t\ttry {\n\t\t\tInputStream in;\n\t\t\tHttpResponse response = postHttp(url, jsonObject);\n\t\t\tHeader contentEncoding = response.getFirstHeader(\"Content-Encoding\");\n\t\t\tif (response != null && contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase(\"gzip\")) {\n\t\t\t\tin = new GZIPInputStream(response.getEntity().getContent());\n\t\t\t} else {\n\t\t\t\tin = new BufferedInputStream(response.getEntity().getContent());\n\t\t\t}\n\t\t\tString s = readInputStream(in);\n\t\t\treturn new JSONArray(s);\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\tpublic static String readInputStream(InputStream in) throws IOException {\n\t\tStringBuffer stream = new StringBuffer();\n\t\tbyte[] b = new byte[4096];\n\t\tfor (int n; (n = in.read(b)) != -1;) {\n\t\t\tstream.append(new String(b, 0, n));\n\t\t}\n\t\treturn stream.toString();\n\t}\n}", "public class ImmopolyException extends org.immopoly.common.ImmopolyException {\n\n\tpublic ImmopolyException(Exception t) {\n\t\tsuper(t);\n\t}\n\n\tpublic ImmopolyException(String msg,Exception t) {\n\t\tsuper(t);\n\t\tmessage=msg;\n\t}\n\n\tpublic ImmopolyException(String msg) {\n\t\tsuper();\n\t\tmessage=msg;\n\t}\n\t\n\t\n\tpublic ImmopolyException(Context context, JSONObject jsonObject) {\n\t\tsuper(jsonObject);\n\t\tswitch (errorCode) {\n\t\tcase USERNAME_NOT_FOUND:\n\t\t\tmessage = context.getString(R.string.account_not_found);\n\t\t\tbreak;\n\t\tcase 201:\n\t\t\tmessage = context.getString(R.string.flat_already_in_portifolio);\n\t\t\tbreak;\n\t\tcase 301:\n\t\t\tmessage = context.getString(R.string.flat_does_not_exist_anymore);\n\t\t\tbreak;\n\t\tcase 302:\n\t\t\tmessage = context.getString(R.string.flat_has_no_raw_rent);\n\t\t\tbreak;\n\t\tcase 441:\n\t\t\tmessage = context.getString(R.string.expose_location_spoofing);\n\t\t\tbreak;\n\t\tcase USER_SEND_PASSWORDMAIL_NOEMAIL:\n\t\t\tmessage = context.getString(R.string.account_has_no_email);;\n\t\t\tbreak;\n\t\tcase USER_SEND_PASSWORDMAIL_EMAIL_NOMATCH:\n\t\t\tmessage = context.getString(R.string.account_has_different_email);;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tLog.i( Const.LOG_TAG, \"not yet translated ImmopolyException errorCode: \" + errorCode );\n\t\t}\n\t}\n}", "public class ImmopolyUser extends User {\n\n\tpublic static final String sPREF_USER = \"user\";\n\tpublic static final String sPREF_TOKEN = \"user_token\";\n\n\tprivate String mUserToken;\n\tprivate String mUserName;\n\tprivate String mEmail;\n\tprivate String mTwitter;\n\tprivate double mBalance;\n\tprivate List<ImmopolyHistory> mUserHistory;\n\tprivate Flats flats;\n\tprivate double sLastProvision;\n\tprivate double sLastRent;\n\tprivate static ImmopolyUser sInstance = null;\n\n\tprivate List<ImmopolyBadge> badges;\n\n\tprivate List<ImmopolyActionItem> actionItems;\n\n\tprivate int maxExposes;\n\n\t\n// private static long mTimeUpdated = -1;\n\n\tprivate ImmopolyUser() {\n\t\tmUserHistory = new ArrayList<ImmopolyHistory>();\n\t\tbadges = new ArrayList<ImmopolyBadge>();\n\t\tactionItems = new ArrayList<ImmopolyActionItem>();\n\t\tflats = new Flats();\n\t}\n\n\t@Override\n\tpublic double getBalance() {\n\t\treturn mBalance;\n\t}\n\n\t/**\n\t * \n\t * @param context\n\t * @return\n\t * @deprecated was soll der schmarn hier? fragt den USerDataManager nach dem status\n\t */\n\tpublic String readToken(Context context) {\n\t\tif (mUserToken == null || mUserToken.length() == 0) {\n\t\t\tSharedPreferences shared = context.getSharedPreferences(sPREF_USER,\n\t\t\t\t\t0);\n\t\t\tString userToken = shared.getString(sPREF_TOKEN, \"\");\n\t\t\tmUserToken = userToken;\n\t\t}\n\t\treturn mUserToken;\n\t}\n\n\t@Override\n\tpublic String getToken() {\n\t\treturn mUserToken;\n\t}\n\n\t@Override\n\tpublic String getUserName() {\n\t\treturn mUserName;\n\t}\n\n\t@Override\n\tpublic void setBalance(double balance) {\n\t\tmBalance = balance;\n\t}\n\n\t@Override\n\tpublic void setToken(String token) {\n\t\tmUserToken = token;\n\t}\n\n\t@Override\n\tpublic void setUsername(String username) {\n\t\tmUserName = username;\n\t}\n\n\t@Override\n\tpublic JSONObject toJSON() {\n\t\treturn null;\n\t}\n\n\tpublic static ImmopolyUser getInstance() {\n\t\tif (sInstance == null) {\n\t\t\tsInstance = new ImmopolyUser();\n\t\t}\n\t\treturn sInstance;\n\t}\n\t\n\tpublic static void resetInstance(){\n\t\tsInstance=null;\n\t}\n\n\t@Override\n\tpublic void setPortfolio(JSONObject portfolio) {\n\t\tif (portfolio != null) {\n\t\t\t// this.mTimeUpdated = Calendar.getInstance().getTimeInMillis();\n\t\t\tJSONArray results;\n\t\t\tJSONArray resultEntries;\n\t\t\ttry {\n\t\t\t\tFlat item;\n\t\t\t\tresults = portfolio.getJSONArray(\"resultlistEntries\");\n\t\t\t\tresultEntries = results.getJSONArray(0);\n\n\t\t\t\tJSONObject expose;\n\t\t\t\tJSONObject realEstate;\n\t\t\t\tflats = new Flats();\n\t\t\t\tfor (int i = 0; i < resultEntries.length(); i++) {\n\t\t\t\t\titem = new Flat();\n\t\t\t\t\texpose = resultEntries.getJSONObject(i).getJSONObject(\n\t\t\t\t\t\t\t\"expose.expose\");\n\t\t\t\t\trealEstate = expose.getJSONObject(\"realEstate\");\n\t\t\t\t\titem.priceValue = realEstate.optString(\"baseRent\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tdouble price = Double.parseDouble(item.priceValue);\n\t\t\t\t\t\titem.priceValue = Integer.toString( (int) Math.round(price) );\n\t\t\t\t\t} catch (Exception e) {} \n\t\t\t\t\titem.name = realEstate.optString(\"title\");\n\t\t\t\t\titem.uid = realEstate.optInt(\"@id\");\n\t\t\t\t\titem.lat = realEstate.getJSONObject(\"address\")\n\t\t\t\t\t\t\t.getJSONObject(\"wgs84Coordinate\")\n\t\t\t\t\t\t\t.optDouble(\"latitude\");\n\t\t\t\t\titem.lng = realEstate.getJSONObject(\"address\")\n\t\t\t\t\t\t\t.getJSONObject(\"wgs84Coordinate\")\n\t\t\t\t\t\t\t.optDouble(\"longitude\");\n\t\t\t\t\titem.takeoverDate = realEstate.optLong(\"overtakeDate\");\n\t\t\t\t\titem.takeoverTries = realEstate.optInt(\"overtakeTries\");\n\t\t\t\t\titem.numRooms = realEstate.optInt(\"numberOfRooms\");\n\t\t\t\t\titem.livingSpace = realEstate.optInt(\"livingSpace\");\n\t\t\t\t\t\n\t\t\t\t\tif (realEstate.has(\"titlePicture\")) {\n\t\t\t\t\t\tJSONObject objPicture = realEstate.getJSONObject(\"titlePicture\");\n\t\t\t\t\t\tif (objPicture.has(\"urls\") && objPicture.getJSONArray(\"urls\").length() > 0) {\n\t\t\t\t\t\t\tJSONObject urls = objPicture.getJSONArray(\"urls\").getJSONObject(0).getJSONObject(\"url\");\n\t\t\t\t\t\t\tif ( urls != null )\n\t\t\t\t\t\t\titem.titlePictureSmall = urls.optString(\"@href\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\titem.owned = true;\n\t\t\t\t\tflats.add(item);\n\t\t\t\t}\n\t\t\t} catch (JSONException e) {\n\t\t\t\tLog.e( Const.LOG_TAG, \"Exception while parsing portfolio: \", e );\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic Flats getPortfolio() {\n\t\treturn flats;\n\t}\n\t\n\n\t@Override\n\tpublic History instantiateHistory(JSONObject o) {\n\t\treturn new ImmopolyHistory(o);\n\t}\n\n\t@Override\n\tpublic void setHistory(List<History> history) {\n\t\tmUserHistory.clear();\n\t\tfor (History history2 : history) {\n\t\t\tmUserHistory.add((ImmopolyHistory) history2);\n\t\t}\n\n\t}\n\n\tpublic List<ImmopolyHistory> getHistory() {\n\t\treturn mUserHistory;\n\t}\n\n\t@Override\n\tpublic void setLastProvision(double lastProvision) {\n\t\tsLastProvision = lastProvision;\n\t}\n\n\t@Override\n\tpublic void setLastRent(double lastRent) {\n\t\tsLastRent = lastRent;\n\t}\n\n\tpublic double getLastProvision() {\n\t\treturn sLastProvision;\n\t}\n\n\tpublic double getLastRent() {\n\t\treturn sLastRent;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn mEmail;\n\t}\n\n\tpublic String getTwitter() {\n\t\treturn mTwitter;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tmEmail = email;\n\t}\n\n\tpublic void setTwitter(String twitter) {\n\t\tmTwitter = twitter;\n\t}\n\n\tpublic List<ImmopolyBadge> getBadges() {\n\t\treturn badges;\n\t}\n\n\t@Override\n\tpublic Badge instantiateBadge(JSONObject o) {\n\t\treturn new ImmopolyBadge(o);\n\t}\n\n\t@Override\n\tpublic void setBadges(List<Badge> badges) {\n\t\tthis.badges.clear();\n\t\tfor (Badge badge: badges) {\n\t\t\tthis.badges.add((ImmopolyBadge) badge);\n\t\t}\n\n\t}\n\n\tpublic List<ImmopolyActionItem> getActionItems() {\n\t\treturn actionItems;\n\t}\n\n\tpublic boolean hasActionItemWithAmount() {\n\t\tif (null == actionItems)\n\t\t\treturn false;\n\t\tfor (ImmopolyActionItem actionItem : actionItems) {\n\t\t\tif (actionItem.getAmount() > 0)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic ActionItem instantiateActionItem(JSONObject o) {\n\t\treturn new ImmopolyActionItem(o);\n\t}\n\n\t@Override\n\tpublic void setActionItems(List<ActionItem> actionItems) {\n\t\tthis.actionItems.clear();\n\t\tfor (ActionItem actionItem : actionItems) {\n\t\t\tthis.actionItems.add((ImmopolyActionItem) actionItem);\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void setMaxExposes(int maxExposes) {\n\t\tthis.maxExposes = maxExposes;\n\t}\n\n\tpublic int getMaxExposes() {\n\t\treturn maxExposes;\n\t}\n\t\n\t@Override\n\tpublic void setNumExposes(int numExposes) {\n\t\t// numExposes == flats.size() !\n\t}\n\t\n\tpublic void removeActionItem(int type) {\n\t\tfor (ImmopolyActionItem item : actionItems) {\n\t\t\tif (item.getType() == type) {\n\t\t\t\titem.removeAmount(1);\n\t\t\t}\n\t\t}\n\t\tUserDataManager.instance.fireUsedDataChanged();\n\t}\n}", "public class Result {\n\tpublic boolean success = false;\n\tpublic ImmopolyHistory history = null;\n\tpublic ImmopolyException exception = null;\n}" ]
import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import org.immopoly.android.R; import org.immopoly.android.c2dm.C2DMessaging; import org.immopoly.android.constants.Const; import org.immopoly.android.helper.Settings; import org.immopoly.android.helper.TrackingManager; import org.immopoly.android.helper.WebHelper; import org.immopoly.android.model.ImmopolyException; import org.immopoly.android.model.ImmopolyUser; import org.immopoly.android.tasks.Result; import org.json.JSONException; import org.json.JSONObject; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.EditText; import android.widget.Toast;
package org.immopoly.android.app; public class UserLoginActivity extends Activity { public static final int RESULT_REGISTER = 4321; private GoogleAnalyticsTracker tracker; private Handler toggleProgressHandler; public static final int MIN_PASSWORTH_LENGTH = 4; private static final int MIN_USERNAME_LENGTH = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tracker = GoogleAnalyticsTracker.getInstance(); // Start the tracker in manual dispatch mode...
tracker.startNewSession(TrackingManager.UA_ACCOUNT,
3
3pillarlabs/socialauth
socialauth/src/main/java/org/brickred/socialauth/provider/SalesForceImpl.java
[ "public abstract class AbstractProvider implements AuthProvider, Serializable {\n\n\tprivate static final long serialVersionUID = -7827145708317886744L;\n\n\tprivate Map<Class<? extends Plugin>, Class<? extends Plugin>> pluginsMap;\n\n\tprivate final Log LOG = LogFactory.getLog(this.getClass());\n\n\tpublic AbstractProvider() throws Exception {\n\t\tpluginsMap = new HashMap<Class<? extends Plugin>, Class<? extends Plugin>>();\n\t}\n\n\t@Override\n\tpublic <T> T getPlugin(final Class<T> clazz) throws Exception {\n\t\tClass<? extends Plugin> plugin = pluginsMap.get(clazz);\n\t\tConstructor<? extends Plugin> cons = plugin\n\t\t\t\t.getConstructor(ProviderSupport.class);\n\t\tProviderSupport support = new ProviderSupport(getOauthStrategy());\n\t\tPlugin obj = cons.newInstance(support);\n\t\treturn (T) obj;\n\t}\n\n\t@Override\n\tpublic boolean isSupportedPlugin(final Class<? extends Plugin> clazz) {\n\t\tif (pluginsMap.containsKey(clazz)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic final void registerPlugins() throws Exception {\n\t\tLOG.info(\"Loading plugins\");\n\t\tList<String> pluginsList = getPluginsList();\n\t\tif (pluginsList != null && !pluginsList.isEmpty()) {\n\t\t\tfor (String s : pluginsList) {\n\t\t\t\tLOG.info(\"Loading plugin :: \" + s);\n\t\t\t\tClass<? extends Plugin> clazz = Class.forName(s).asSubclass(\n\t\t\t\t\t\tPlugin.class);\n\t\t\t\t// getting constructor only for checking\n\t\t\t\tConstructor<? extends Plugin> cons = clazz\n\t\t\t\t\t\t.getConstructor(ProviderSupport.class);\n\t\t\t\tClass<?> interfaces[] = clazz.getInterfaces();\n\t\t\t\tfor (Class<?> c : interfaces) {\n\t\t\t\t\tif (Plugin.class.isAssignableFrom(c)) {\n\t\t\t\t\t\tpluginsMap.put(c.asSubclass(Plugin.class), clazz);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void refreshToken(AccessGrant accessGrant)\n\t\t\tthrows SocialAuthException {\n\t\tthrow new SocialAuthException(\"Not implemented for given provider\");\n\n\t}\n\n\t/**\n\t * Returns the scopes of custom plugins of a provider those are configured\n\t * in properties file\n\t * \n\t * @param oauthConfig\n\t * OAuthConfig object of that provider\n\t * @return String of comma separated scopes of all register plugins of a\n\t * provider those are configured in properties file\n\t */\n\tpublic String getPluginsScope(final OAuthConfig oauthConfig) {\n\t\tList<String> scopes = oauthConfig.getPluginsScopes();\n\t\tif (scopes != null && !scopes.isEmpty()) {\n\t\t\tString scopesStr = scopes.get(0);\n\t\t\tfor (int i = 1; i < scopes.size(); i++) {\n\t\t\t\tscopesStr += \",\" + scopes.get(i);\n\t\t\t}\n\t\t\treturn scopesStr;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Returns the list of plugins of a provider.\n\t * \n\t * @return List of plugins of a provider\n\t */\n\tprotected abstract List<String> getPluginsList();\n\n\t/**\n\t * Returns the OAuthStrategyBase of a provider.\n\t * \n\t * @return OAuthStrategyBase of a provider.\n\t */\n\tprotected abstract OAuthStrategyBase getOauthStrategy();\n}", "public class Contact implements Serializable {\n\tprivate static final long serialVersionUID = 7983770896851139223L;\n\n\t/**\n\t * Email\n\t */\n\tString email;\n\n\t/**\n\t * First Name\n\t */\n\tString firstName;\n\n\t/**\n\t * Last Name\n\t */\n\tString lastName;\n\n\t/**\n\t * Display Name\n\t */\n\tString displayName;\n\n\t/**\n\t * Other emails array.\n\t */\n\tString otherEmails[];\n\n\t/**\n\t * Profile URL\n\t */\n\tString profileUrl;\n\n\t/**\n\t * Id of person\n\t */\n\tString id;\n\n\t/**\n\t * Email hash\n\t */\n\tString emailHash;\n\n\t/**\n\t * profile image URL\n\t */\n\tprivate String profileImageURL;\n\n\t/**\n\t * raw response xml/json as string\n\t */\n\tprivate String rawResponse;\n\n\t/**\n\t * Retrieves the first name\n\t * \n\t * @return String the first name\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\t/**\n\t * Updates the first name\n\t * \n\t * @param firstName\n\t * the first name of user\n\t */\n\tpublic void setFirstName(final String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\t/**\n\t * Retrieves the last name\n\t * \n\t * @return String the last name\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\t/**\n\t * Updates the last name\n\t * \n\t * @param lastName\n\t * the last name of user\n\t */\n\tpublic void setLastName(final String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\t/**\n\t * Returns the email address.\n\t * \n\t * @return email address of the user\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Updates the email\n\t * \n\t * @param email\n\t * the email of user\n\t */\n\tpublic void setEmail(final String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Retrieves the display name\n\t * \n\t * @return String the display name\n\t */\n\tpublic String getDisplayName() {\n\t\treturn displayName;\n\t}\n\n\t/**\n\t * Updates the display name\n\t * \n\t * @param displayName\n\t * the display name of user\n\t */\n\tpublic void setDisplayName(final String displayName) {\n\t\tthis.displayName = displayName;\n\t}\n\n\t/**\n\t * Retrieves the contact person emails\n\t * \n\t * @return String Array of emails\n\t */\n\tpublic String[] getOtherEmails() {\n\t\treturn otherEmails;\n\t}\n\n\t/**\n\t * \n\t * @param otherEmails\n\t * array of emails, if contact person has more than one email\n\t * then it contains rest of the emails except first one\n\t */\n\tpublic void setOtherEmails(final String[] otherEmails) {\n\t\tthis.otherEmails = otherEmails;\n\t}\n\n\t/**\n\t * Retrieves the contact person Public profile URL\n\t * \n\t * @return String contact person Public profile URL\n\t */\n\tpublic String getProfileUrl() {\n\t\treturn profileUrl;\n\t}\n\n\t/**\n\t * Updates the contact person Public profile URL\n\t * \n\t * @param profileUrl\n\t * contact person Public profile URL\n\t */\n\tpublic void setProfileUrl(final String profileUrl) {\n\t\tthis.profileUrl = profileUrl;\n\t}\n\n\t/**\n\t * Retrieves the contact person id\n\t * \n\t * @return String contact person id\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Updates the contact person id\n\t * \n\t * @param id\n\t * contact person id\n\t */\n\tpublic void setId(final String id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Retrieves the email hash\n\t * \n\t * @return String contact person email hash\n\t */\n\tpublic String getEmailHash() {\n\t\treturn emailHash;\n\t}\n\n\t/**\n\t * Updates the contact person email hash\n\t * \n\t * @param emailHash\n\t * contact person email hash\n\t */\n\tpublic void setEmailHash(final String emailHash) {\n\t\tthis.emailHash = emailHash;\n\t}\n\n\t/**\n\t * Retrieves the profile image URL\n\t * \n\t * @return String the profileImageURL\n\t */\n\tpublic String getProfileImageURL() {\n\t\treturn profileImageURL;\n\t}\n\n\t/**\n\t * Updates the profile image URL\n\t * \n\t * @param profileImageURL\n\t * profile image URL of user\n\t */\n\tpublic void setProfileImageURL(final String profileImageURL) {\n\t\tthis.profileImageURL = profileImageURL;\n\t}\n\n\t/**\n\t * Retrieves the raw response xml/json in string which is returned by the\n\t * provider for this object call. Set\n\t * {@link SocialAuthConfig#setRawResponse(boolean)} to true to save the\n\t * response in object.\n\t * \n\t * @return raw response xml/json in string\n\t */\n\tpublic String getRawResponse() {\n\t\treturn rawResponse;\n\t}\n\n\t/**\n\t * Updates raw response xml/json returned by the provider for this object\n\t * call. Set {@link SocialAuthConfig#setRawResponse(boolean)} to true to\n\t * save the response in object.\n\t * \n\t * @param rawResponse\n\t * raw response xml/json in string\n\t */\n\tpublic void setRawResponse(String rawResponse) {\n\t\tthis.rawResponse = rawResponse;\n\t}\n\n\t/**\n\t * Retrieves the profile info as a string\n\t * \n\t * @return String\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString NEW_LINE = System.getProperty(\"line.separator\");\n\t\tresult.append(this.getClass().getName() + \" Object {\" + NEW_LINE);\n\t\tresult.append(\" email: \" + email + NEW_LINE);\n\t\tresult.append(\" firstName: \" + firstName + NEW_LINE);\n\t\tresult.append(\" lastName: \" + lastName + NEW_LINE);\n\t\tresult.append(\" displayName: \" + displayName + NEW_LINE);\n\t\tresult.append(\" id: \" + id + NEW_LINE);\n\t\tresult.append(\" profileUrl: \" + profileUrl + NEW_LINE);\n\t\tresult.append(\" profileImageURL: \" + profileImageURL + NEW_LINE);\n\t\tresult.append(\"emailHash: \" + emailHash + NEW_LINE);\n\t\tresult.append(\" otherEmails: \");\n\t\tif (otherEmails != null) {\n\t\t\tStringBuilder estr = new StringBuilder();\n\t\t\tfor (String str : otherEmails) {\n\t\t\t\tif (estr.length() > 0) {\n\t\t\t\t\testr.append(\" , \");\n\t\t\t\t}\n\t\t\t\testr.append(str);\n\t\t\t}\n\t\t\tresult.append(estr.toString());\n\t\t}\n\t\tresult.append(NEW_LINE);\n\t\tresult.append(\"}\");\n\t\treturn result.toString();\n\t}\n\n}", "public class Profile implements Serializable {\n\n\tprivate static final long serialVersionUID = 6082073969740796991L;\n\n\t/**\n\t * Email\n\t */\n\tprivate String email;\n\n\t/**\n\t * First Name\n\t */\n\tprivate String firstName;\n\n\t/**\n\t * Last Name\n\t */\n\tprivate String lastName;\n\n\t/**\n\t * Country\n\t */\n\tprivate String country;\n\n\t/**\n\t * Language\n\t */\n\tprivate String language;\n\n\t/**\n\t * Full Name\n\t */\n\tprivate String fullName;\n\n\t/**\n\t * Display Name\n\t */\n\tprivate String displayName;\n\n\t/**\n\t * Date of Birth\n\t */\n\tprivate BirthDate dob;\n\n\t/**\n\t * Gender\n\t */\n\tprivate String gender;\n\n\t/**\n\t * Location\n\t */\n\tprivate String location;\n\n\t/**\n\t * Validated Id\n\t */\n\tprivate String validatedId;\n\n\t/**\n\t * profile image URL\n\t */\n\tprivate String profileImageURL;\n\n\t/**\n\t * provider id with this profile associates\n\t */\n\tprivate String providerId;\n\n\t/**\n\t * contact info\n\t */\n\tprivate Map<String, String> contactInfo;\n\n\t/**\n\t * raw response xml/json as string\n\t */\n\tprivate String rawResponse;\n\n\t/**\n\t * Retrieves the first name\n\t * \n\t * @return String the first name\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\t/**\n\t * Updates the first name\n\t * \n\t * @param firstName\n\t * the first name of user\n\t */\n\tpublic void setFirstName(final String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\t/**\n\t * Retrieves the last name\n\t * \n\t * @return String the last name\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\t/**\n\t * Updates the last name\n\t * \n\t * @param lastName\n\t * the last name of user\n\t */\n\tpublic void setLastName(final String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\t/**\n\t * Returns the email address.\n\t * \n\t * @return email address of the user\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Updates the email\n\t * \n\t * @param email\n\t * the email of user\n\t */\n\tpublic void setEmail(final String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Retrieves the validated id\n\t * \n\t * @return String the validated id\n\t */\n\tpublic String getValidatedId() {\n\t\treturn validatedId;\n\t}\n\n\t/**\n\t * Updates the validated id\n\t * \n\t * @param validatedId\n\t * the validated id of user\n\t */\n\tpublic void setValidatedId(final String validatedId) {\n\t\tthis.validatedId = validatedId;\n\t}\n\n\t/**\n\t * Retrieves the display name\n\t * \n\t * @return String the display name\n\t */\n\tpublic String getDisplayName() {\n\t\treturn displayName;\n\t}\n\n\t/**\n\t * Updates the display name\n\t * \n\t * @param displayName\n\t * the display name of user\n\t */\n\tpublic void setDisplayName(final String displayName) {\n\t\tthis.displayName = displayName;\n\t}\n\n\t/**\n\t * Retrieves the country\n\t * \n\t * @return String the country\n\t */\n\tpublic String getCountry() {\n\t\treturn country;\n\t}\n\n\t/**\n\t * Updates the country\n\t * \n\t * @param country\n\t * the country of user\n\t */\n\tpublic void setCountry(final String country) {\n\t\tthis.country = country;\n\t}\n\n\t/**\n\t * Retrieves the language\n\t * \n\t * @return String the language\n\t */\n\tpublic String getLanguage() {\n\t\treturn language;\n\t}\n\n\t/**\n\t * Updates the language\n\t * \n\t * @param language\n\t * the language of user\n\t */\n\tpublic void setLanguage(final String language) {\n\t\tthis.language = language;\n\t}\n\n\t/**\n\t * Retrieves the full name\n\t * \n\t * @return String the full name\n\t */\n\tpublic String getFullName() {\n\t\treturn fullName;\n\t}\n\n\t/**\n\t * Updates the full name\n\t * \n\t * @param fullName\n\t * the full name of user\n\t */\n\tpublic void setFullName(final String fullName) {\n\t\tthis.fullName = fullName;\n\t}\n\n\t/**\n\t * Retrieves the date of birth\n\t * \n\t * @return the date of birth different providers may use different formats\n\t */\n\tpublic BirthDate getDob() {\n\t\treturn dob;\n\t}\n\n\t/**\n\t * Updates the date of birth\n\t * \n\t * @param dob\n\t * the date of birth of user\n\t */\n\tpublic void setDob(final BirthDate dob) {\n\t\tthis.dob = dob;\n\t}\n\n\t/**\n\t * Retrieves the gender\n\t * \n\t * @return String the gender - could be \"Male\", \"M\" or \"male\"\n\t */\n\tpublic String getGender() {\n\t\treturn gender;\n\t}\n\n\t/**\n\t * Updates the gender\n\t * \n\t * @param gender\n\t * the gender of user\n\t */\n\tpublic void setGender(final String gender) {\n\t\tthis.gender = gender;\n\t}\n\n\t/**\n\t * Retrieves the location\n\t * \n\t * @return String the location\n\t */\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\t/**\n\t * Updates the location\n\t * \n\t * @param location\n\t * the location of user\n\t */\n\tpublic void setLocation(final String location) {\n\t\tthis.location = location;\n\t}\n\n\t/**\n\t * Retrieves the profile image URL\n\t * \n\t * @return String the profileImageURL\n\t */\n\tpublic String getProfileImageURL() {\n\t\treturn profileImageURL;\n\t}\n\n\t/**\n\t * Updates the profile image URL\n\t * \n\t * @param profileImageURL\n\t * profile image URL of user\n\t */\n\tpublic void setProfileImageURL(final String profileImageURL) {\n\t\tthis.profileImageURL = profileImageURL;\n\t}\n\n\t/**\n\t * Retrieves the provider id with this profile associates\n\t * \n\t * @return the provider id\n\t */\n\tpublic String getProviderId() {\n\t\treturn providerId;\n\t}\n\n\t/**\n\t * Updates the provider id\n\t * \n\t * @param providerId\n\t * the provider id\n\t */\n\tpublic void setProviderId(final String providerId) {\n\t\tthis.providerId = providerId;\n\t}\n\n\t/**\n\t * Retrieves the contact information. It contains address and phone numbers.\n\t * Key may contain values like mainAddress, home, work where home and work\n\t * value will be phone numbers.\n\t * \n\t * @return contact information.\n\t */\n\tpublic Map<String, String> getContactInfo() {\n\t\treturn contactInfo;\n\t}\n\n\t/**\n\t * Updates the contact info.\n\t * \n\t * @param contactInfo\n\t * the map which contains the contact information\n\t */\n\tpublic void setContactInfo(final Map<String, String> contactInfo) {\n\t\tthis.contactInfo = contactInfo;\n\t}\n\n\t/**\n\t * Retrieves the raw response xml/json in string which is returned by the\n\t * provider for this object. Set\n\t * {@link SocialAuthConfig#setRawResponse(boolean)} to true to save this\n\t * response in object.\n\t * \n\t * @return raw response xml/json in string\n\t */\n\tpublic String getRawResponse() {\n\t\treturn rawResponse;\n\t}\n\n\t/**\n\t * Updates raw response xml/json return by the provider for this object\n\t * call. Set {@link SocialAuthConfig#setRawResponse(boolean)} to true to\n\t * save this response in object.\n\t * \n\t * @param rawResponse\n\t */\n\tpublic void setRawResponse(String rawResponse) {\n\t\tthis.rawResponse = rawResponse;\n\t}\n\n\t/**\n\t * Retrieves the profile info as a string\n\t * \n\t * @return String\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString NEW_LINE = System.getProperty(\"line.separator\");\n\t\tresult.append(this.getClass().getName() + \" Object {\" + NEW_LINE);\n\t\tresult.append(\" email: \" + email + NEW_LINE);\n\t\tresult.append(\" firstName: \" + firstName + NEW_LINE);\n\t\tresult.append(\" lastName: \" + lastName + NEW_LINE);\n\t\tresult.append(\" country: \" + country + NEW_LINE);\n\t\tresult.append(\" language: \" + language + NEW_LINE);\n\t\tresult.append(\" fullName: \" + fullName + NEW_LINE);\n\t\tresult.append(\" displayName: \" + displayName + NEW_LINE);\n\t\tresult.append(\" dob: \" + dob + NEW_LINE);\n\t\tresult.append(\" gender: \" + gender + NEW_LINE);\n\t\tresult.append(\" location: \" + location + NEW_LINE);\n\t\tresult.append(\" validatedId: \" + validatedId + NEW_LINE);\n\t\tresult.append(\" profileImageURL: \" + profileImageURL + NEW_LINE);\n\t\tresult.append(\" providerId: \" + providerId + NEW_LINE);\n\t\tresult.append(\" contactInfo { \" + NEW_LINE);\n\t\tif (contactInfo != null && !contactInfo.isEmpty()) {\n\t\t\tfor (Map.Entry<String, String> entry : contactInfo.entrySet()) {\n\t\t\t\tresult.append(entry.getKey() + \" = \" + entry.getValue()\n\t\t\t\t\t\t+ NEW_LINE);\n\t\t\t}\n\t\t}\n\t\tresult.append(\" } \" + NEW_LINE);\n\t\tresult.append(\"}\");\n\n\t\treturn result.toString();\n\n\t}\n\n}", "public class OAuth2 implements OAuthStrategyBase {\n\n\tprivate static final long serialVersionUID = -8431902665718727947L;\n\tprivate final Log LOG = LogFactory.getLog(OAuth2.class);\n\tprivate AccessGrant accessGrant;\n\tprivate OAuthConsumer oauth;\n\tprivate boolean providerState;\n\tprivate Map<String, String> endpoints;\n\tprivate String scope;\n\tprivate Permission permission;\n\tprivate String providerId;\n\tprivate String successUrl;\n\tprivate String accessTokenParameterName;\n\tprivate Map<String,String> customProperties;\n\n\tpublic OAuth2(final OAuthConfig config, final Map<String, String> endpoints) {\n\t\toauth = new OAuthConsumer(config);\n\t\tthis.endpoints = endpoints;\n\t\tpermission = Permission.DEFAULT;\n\t\tproviderId = config.getId();\n\t\taccessTokenParameterName = Constants.ACCESS_TOKEN_PARAMETER_NAME;\n\t\tcustomProperties = config.getCustomProperties();\n\t}\n\n\t@Override\n\tpublic String getLoginRedirectURL(final String successUrl) throws Exception {\n\t\treturn getLoginRedirectURL(successUrl, null);\n\t}\n\n\t@Override\n\tpublic String getLoginRedirectURL(String successUrl,\n\t\t\tMap<String, String> requestParams) throws Exception {\n\t\tLOG.info(\"Determining URL for redirection\");\n\t\tproviderState = true;\n\t\ttry {\n\t\t\tthis.successUrl = URLEncoder.encode(successUrl, Constants.ENCODING);\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthis.successUrl = successUrl;\n\t\t}\n\t\tStringBuffer sb = new StringBuffer();\n\t\tsb.append(endpoints.get(Constants.OAUTH_AUTHORIZATION_URL));\n\t\tchar separator = endpoints.get(Constants.OAUTH_AUTHORIZATION_URL)\n\t\t\t\t.indexOf('?') == -1 ? '?' : '&';\n\t\tsb.append(separator);\n\t\tsb.append(\"client_id=\").append(oauth.getConfig().get_consumerKey());\n\t\tsb.append(\"&response_type=code\");\n\t\tsb.append(\"&redirect_uri=\").append(this.successUrl);\n\t\tif (scope != null) {\n\t\t\tsb.append(\"&scope=\").append(scope);\n\t\t}\n\t\tif (requestParams != null && !requestParams.isEmpty()) {\n\t\t\tfor (String key : requestParams.keySet()) {\n\t\t\t\tsb.append(\"&\");\n\t\t\t\tsb.append(key).append(\"=\").append(requestParams.get(key));\n\t\t\t}\n\t\t}\n\t\tString url = sb.toString();\n\n\t\tLOG.info(\"Redirection to following URL should happen : \" + url);\n\t\treturn url;\n\t}\n\n\t@Override\n\tpublic AccessGrant verifyResponse(final Map<String, String> requestParams)\n\t\t\tthrows Exception {\n\t\treturn verifyResponse(requestParams, MethodType.GET.toString());\n\t}\n\n\t@Override\n\tpublic AccessGrant verifyResponse(final Map<String, String> requestParams,\n\t\t\tfinal String methodType) throws Exception {\n\t\tLOG.info(\"Verifying the authentication response from provider\");\n\n\t\tif (requestParams.get(\"access_token\") != null) {\n\t\t\tLOG.debug(\"Creating Access Grant\");\n\t\t\tString accessToken = requestParams.get(\"access_token\");\n\t\t\tInteger expires = null;\n\t\t\tif (requestParams.get(Constants.EXPIRES) != null) {\n\t\t\t\texpires = new Integer(requestParams.get(Constants.EXPIRES));\n\t\t\t}\n\t\t\taccessGrant = new AccessGrant();\n\t\t\taccessGrant.setKey(accessToken);\n\t\t\taccessGrant.setAttribute(Constants.EXPIRES, expires);\n\t\t\tif (permission != null) {\n\t\t\t\taccessGrant.setPermission(permission);\n\t\t\t} else {\n\t\t\t\taccessGrant.setPermission(Permission.ALL);\n\t\t\t}\n\t\t\taccessGrant.setProviderId(providerId);\n\t\t\tLOG.debug(accessGrant);\n\t\t\treturn accessGrant;\n\t\t}\n\n\t\tif (!providerState) {\n\t\t\tthrow new ProviderStateException();\n\t\t}\n\n\t\tString code = requestParams.get(\"code\");\n\t\tif (code == null || code.length() == 0) {\n\t\t\tthrow new SocialAuthException(\"Verification code is null\");\n\t\t}\n\t\tLOG.debug(\"Verification Code : \" + code);\n\t\tString acode;\n\t\tString accessToken = null;\n\t\ttry {\n\t\t\tacode = URLEncoder.encode(code, \"UTF-8\");\n\t\t} catch (Exception e) {\n\t\t\tacode = code;\n\t\t}\n\t\tStringBuffer sb = new StringBuffer();\n\t\tif (MethodType.GET.toString().equals(methodType)) {\n\t\t\tsb.append(endpoints.get(Constants.OAUTH_ACCESS_TOKEN_URL));\n\t\t\tchar separator = endpoints.get(Constants.OAUTH_ACCESS_TOKEN_URL)\n\t\t\t\t\t.indexOf('?') == -1 ? '?' : '&';\n\t\t\tsb.append(separator);\n\t\t}\n\t\tsb.append(\"client_id=\").append(oauth.getConfig().get_consumerKey());\n\t\tsb.append(\"&redirect_uri=\").append(this.successUrl);\n\t\tsb.append(\"&client_secret=\").append(\n\t\t\t\toauth.getConfig().get_consumerSecret());\n\t\tsb.append(\"&code=\").append(acode);\n\t\tsb.append(\"&grant_type=authorization_code\");\n\t\tif(customProperties != null){\n\t\t\tfor(String key: customProperties.keySet()){\n\t\t\t\tsb.append(\"&\");\n\t\t\t\tsb.append(key);\n\t\t\t\tsb.append(\"=\");\n\t\t\t\tsb.append(customProperties.get(key));\n\t\t\t}\n\t\t}\n\t\tLOG.debug(\"Access token request url:\"+ sb.toString());\n\t\tResponse response;\n\t\tString authURL = null;\n\t\ttry {\n\t\t\tif (MethodType.GET.toString().equals(methodType)) {\n\t\t\t\tauthURL = sb.toString();\n\t\t\t\tLOG.debug(\"URL for Access Token request : \" + authURL);\n\t\t\t\tresponse = HttpUtil.doHttpRequest(authURL, methodType, null,\n\t\t\t\t\t\tnull);\n\t\t\t} else {\n\t\t\t\tauthURL = endpoints.get(Constants.OAUTH_ACCESS_TOKEN_URL);\n\t\t\t\tLOG.debug(\"URL for Access Token request : \" + authURL);\n\t\t\t\tresponse = HttpUtil.doHttpRequest(authURL, methodType,\n\t\t\t\t\t\tsb.toString(), null);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new SocialAuthException(\"Error in url : \" + authURL, e);\n\t\t}\n\t\tString result;\n\t\ttry {\n\t\t\tresult = response.getResponseBodyAsString(Constants.ENCODING);\n\t\t} catch (IOException io) {\n\t\t\tthrow new SocialAuthException(io);\n\t\t}\n\t\tMap<String, Object> attributes = new HashMap<String, Object>();\n\t\tInteger expires = null;\n\t\tif (result.indexOf(\"{\") < 0) {\n\t\t\tString[] pairs = result.split(\"&\");\n\t\t\tfor (String pair : pairs) {\n\t\t\t\tString[] kv = pair.split(\"=\");\n\t\t\t\tif (kv.length != 2) {\n\t\t\t\t\tthrow new SocialAuthException(\n\t\t\t\t\t\t\t\"Unexpected auth response from \" + authURL);\n\t\t\t\t} else {\n\t\t\t\t\tif (kv[0].equals(\"access_token\")) {\n\t\t\t\t\t\taccessToken = kv[1];\n\t\t\t\t\t} else if (kv[0].equals(\"expires\")) {\n\t\t\t\t\t\texpires = Integer.valueOf(kv[1]);\n\t\t\t\t\t} else if (kv[0].equals(\"expires_in\")) {\n\t\t\t\t\t\texpires = Integer.valueOf(kv[1]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tattributes.put(kv[0], kv[1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tJSONObject jObj = new JSONObject(result);\n\t\t\t\tif (jObj.has(\"access_token\")) {\n\t\t\t\t\taccessToken = jObj.getString(\"access_token\");\n\t\t\t\t}\n\n\t\t\t\t// expires_in can come in several different types, and newer\n\t\t\t\t// org.json versions complain if you try to do getString over an\n\t\t\t\t// integer...\n\t\t\t\tif (jObj.has(\"expires_in\") && jObj.opt(\"expires_in\") != null) {\n\t\t\t\t\tString str = jObj.get(\"expires_in\").toString();\n\t\t\t\t\tif (str != null && str.length() > 0) {\n\t\t\t\t\t\texpires = Integer.valueOf(str);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (accessToken != null) {\n\t\t\t\t\tIterator<String> keyItr = jObj.keys();\n\t\t\t\t\twhile (keyItr.hasNext()) {\n\t\t\t\t\t\tString key = keyItr.next();\n\t\t\t\t\t\tif (!\"access_token\".equals(key)\n\t\t\t\t\t\t\t\t&& !\"expires_in\".equals(key)\n\t\t\t\t\t\t\t\t&& jObj.opt(key) != null) {\n\t\t\t\t\t\t\tattributes.put(key, jObj.opt(key).toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (JSONException je) {\n\t\t\t\tthrow new SocialAuthException(\"Unexpected auth response from \"\n\t\t\t\t\t\t+ authURL);\n\t\t\t}\n\t\t}\n\t\tLOG.debug(\"Access Token : \" + accessToken);\n\t\tLOG.debug(\"Expires : \" + expires);\n\t\tif (accessToken != null) {\n\t\t\taccessGrant = new AccessGrant();\n\t\t\taccessGrant.setKey(accessToken);\n\t\t\taccessGrant.setAttribute(Constants.EXPIRES, expires);\n\t\t\tif (attributes.size() > 0) {\n\t\t\t\taccessGrant.setAttributes(attributes);\n\t\t\t}\n\t\t\tif (permission != null) {\n\t\t\t\taccessGrant.setPermission(permission);\n\t\t\t} else {\n\t\t\t\taccessGrant.setPermission(Permission.ALL);\n\t\t\t}\n\t\t\taccessGrant.setProviderId(providerId);\n\t\t} else {\n\t\t\tthrow new SocialAuthException(\n\t\t\t\t\t\"Access token and expires not found from \" + authURL);\n\t\t}\n\t\treturn accessGrant;\n\t}\n\n\t@Override\n\tpublic void setScope(final String scope) {\n\t\tthis.scope = scope;\n\t}\n\n\t@Override\n\tpublic void setPermission(final Permission permission) {\n\t\tthis.permission = permission;\n\t}\n\n\t@Override\n\tpublic Response executeFeed(final String url) throws Exception {\n\t\tif (accessGrant == null) {\n\t\t\tthrow new SocialAuthException(\n\t\t\t\t\t\"Please call verifyResponse function first to get Access Token\");\n\t\t}\n\t\tchar separator = url.indexOf('?') == -1 ? '?' : '&';\n\t\tString urlStr = url + separator + accessTokenParameterName + \"=\"\n\t\t\t\t+ accessGrant.getKey();\n\t\tLOG.debug(\"Calling URL : \" + urlStr);\n\t\treturn HttpUtil.doHttpRequest(urlStr, MethodType.GET.toString(), null,\n\t\t\t\tnull);\n\t}\n\n\t@Override\n\tpublic Response executeFeed(final String url, final String methodType,\n\t\t\tfinal Map<String, String> params,\n\t\t\tfinal Map<String, String> headerParams, final String body)\n\t\t\tthrows Exception {\n\t\tif (accessGrant == null) {\n\t\t\tthrow new SocialAuthException(\n\t\t\t\t\t\"Please call verifyResponse function first to get Access Token\");\n\t\t}\n\t\tString reqURL = url;\n\t\tString bodyStr = body;\n\t\tStringBuffer sb = new StringBuffer();\n\t\tsb.append(accessTokenParameterName).append(\"=\")\n\t\t\t\t.append(accessGrant.getKey());\n\t\tif (params != null && params.size() > 0) {\n\t\t\tfor (String key : params.keySet()) {\n\t\t\t\tif (sb.length() > 0) {\n\t\t\t\t\tsb.append(\"&\");\n\t\t\t\t}\n\t\t\t\tsb.append(key).append(\"=\").append(params.get(key));\n\t\t\t}\n\t\t}\n\t\tif (MethodType.GET.toString().equals(methodType)) {\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tint idx = url.indexOf('?');\n\t\t\t\tif (idx == -1) {\n\t\t\t\t\treqURL += \"?\";\n\t\t\t\t} else {\n\t\t\t\t\treqURL += \"&\";\n\t\t\t\t}\n\t\t\t\treqURL += sb.toString();\n\t\t\t}\n\t\t} else if (MethodType.POST.toString().equals(methodType)\n\t\t\t\t|| MethodType.PUT.toString().equals(methodType)) {\n\t\t\tif (sb.length() > 0) {\n\t\t\t\tif (bodyStr != null) {\n\t\t\t\t\tif (headerParams != null\n\t\t\t\t\t\t\t&& headerParams.containsKey(\"Content-Type\")) {\n\t\t\t\t\t\tString val = headerParams.get(\"Content-Type\");\n\t\t\t\t\t\tif (!\"application/json\".equals(val)\n\t\t\t\t\t\t\t\t&& val.indexOf(\"text/xml\") == -1) {\n\t\t\t\t\t\t\tbodyStr += \"&\";\n\t\t\t\t\t\t\tbodyStr += sb.toString();\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbodyStr += \"&\";\n\t\t\t\t\t\tbodyStr += sb.toString();\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tbodyStr = sb.toString();\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tLOG.debug(\"Calling URL\t:\t\" + reqURL);\n\t\tLOG.debug(\"Body\t\t:\t\" + bodyStr);\n\t\tLOG.debug(\"Header Params\t:\t\" + headerParams);\n\t\treturn HttpUtil\n\t\t\t\t.doHttpRequest(reqURL, methodType, bodyStr, headerParams);\n\t}\n\n\t@Override\n\tpublic void setAccessGrant(final AccessGrant accessGrant) {\n\t\tthis.accessGrant = accessGrant;\n\t}\n\n\t@Override\n\tpublic void setAccessTokenParameterName(\n\t\t\tfinal String accessTokenParameterName) {\n\t\tthis.accessTokenParameterName = accessTokenParameterName;\n\t}\n\n\t@Override\n\tpublic void logout() {\n\t\taccessGrant = null;\n\t\tproviderState = false;\n\t}\n\n\t@Override\n\tpublic Response uploadImage(final String url, final String methodType,\n\t\t\tfinal Map<String, String> params,\n\t\t\tfinal Map<String, String> headerParams, final String fileName,\n\t\t\tfinal InputStream inputStream, final String fileParamName)\n\t\t\tthrows Exception {\n\t\tMap<String, String> map = new HashMap<String, String>();\n\t\tmap.put(accessTokenParameterName, accessGrant.getKey());\n\t\tif (params != null && params.size() > 0) {\n\t\t\tmap.putAll(params);\n\t\t}\n\t\treturn HttpUtil.doHttpRequest(url, methodType, map, headerParams,\n\t\t\t\tinputStream, fileName, null);\n\t}\n\n\t@Override\n\tpublic AccessGrant getAccessGrant() {\n\t\treturn accessGrant;\n\t}\n\n}", "public interface OAuthStrategyBase extends Serializable {\n\n\t/**\n\t * It provides the URL which will be used for authentication with the\n\t * provider\n\t * \n\t * @param successUrl\n\t * the call back url on which user will be redirected after\n\t * authentication\n\t * @return the authentication url\n\t * @throws Exception\n\t */\n\tpublic String getLoginRedirectURL(String successUrl) throws Exception;\n\t\n\t/**\n\t * It provides the URL which will be used for authentication with the\n\t * provider\n\t * \n\t * @param successUrl\n\t * the call back url on which user will be redirected after\n\t * authentication\n\t * @param requestParams \n\t * \t\t\t parameters need to pass in request \n\t * @return the authentication url\n\t * @throws Exception\n\t */\n\tpublic String getLoginRedirectURL(String successUrl,Map<String, String> requestParams) throws Exception;\n\n\t/**\n\t * Verifies the user and get access token\n\t * \n\t * @param requestParams\n\t * request parameters, received from the provider\n\t * @return AccessGrant which contains access token and other information\n\t * @throws Exception\n\t */\n\tpublic AccessGrant verifyResponse(Map<String, String> requestParams)\n\t\t\tthrows Exception;\n\n\t/**\n\t * Verifies the user and get access token\n\t * \n\t * @param requestParams\n\t * @param methodType\n\t * @return AccessGrant which contains access token and other attributes\n\t * @throws Exception\n\t */\n\tpublic AccessGrant verifyResponse(Map<String, String> requestParams,\n\t\t\tString methodType) throws Exception;\n\n\t/**\n\t * Makes HTTP GET request to a given URL.It attaches access token in URL if\n\t * required.\n\t * \n\t * @param url\n\t * URL to make HTTP request.\n\t * @return Response object\n\t * @throws Exception\n\t */\n\tpublic Response executeFeed(String url) throws Exception;\n\n\t/**\n\t * Makes HTTP request to a given URL.It attaches access token in URL if\n\t * required.\n\t * \n\t * @param url\n\t * URL to make HTTP request.\n\t * @param methodType\n\t * Method type can be GET, POST or PUT\n\t * @param params\n\t * Not using this parameter in Google API function\n\t * @param headerParams\n\t * Parameters need to pass as Header Parameters\n\t * @param body\n\t * Request Body\n\t * @throws Exception\n\t */\n\tpublic Response executeFeed(String url, String methodType,\n\t\t\tMap<String, String> params, Map<String, String> headerParams,\n\t\t\tString body) throws Exception;\n\n\t/**\n\t * Sets the permission\n\t * \n\t * @param permission\n\t * Permission object which can be Permission.AUHTHENTICATE_ONLY,\n\t * Permission.ALL, Permission.DEFAULT\n\t */\n\tpublic void setPermission(final Permission permission);\n\n\t/**\n\t * Sets the scope string\n\t * \n\t * @param scope\n\t * scope string\n\t */\n\tpublic void setScope(final String scope);\n\n\t/**\n\t * Stores access grant for the provider\n\t * \n\t * @param accessGrant\n\t * It contains the access token and other information\n\t * @throws Exception\n\t */\n\tpublic void setAccessGrant(AccessGrant accessGrant);\n\n\t/**\n\t * Sets the name of access token parameter which will returns by the\n\t * provider. By default it is \"access_token\"\n\t * \n\t * @param accessTokenParameterName\n\t */\n\tpublic void setAccessTokenParameterName(String accessTokenParameterName);\n\n\t/**\n\t * Logout\n\t */\n\tpublic void logout();\n\n\t/**\n\t * Makes HTTP request to upload image and status.\n\t * \n\t * @param url\n\t * URL to make HTTP request.\n\t * @param methodType\n\t * Method type can be GET, POST or PUT\n\t * @param params\n\t * Parameters need to pass in request\n\t * @param headerParams\n\t * Parameters need to pass as Header Parameters\n\t * @param fileName\n\t * Image file name\n\t * @param inputStream\n\t * Input stream of image\n\t * @param fileParamName\n\t * Image Filename parameter. It requires in some provider.\n\t * @return Response object\n\t * @throws Exception\n\t */\n\tpublic Response uploadImage(final String url, final String methodType,\n\t\t\tfinal Map<String, String> params,\n\t\t\tfinal Map<String, String> headerParams, final String fileName,\n\t\t\tfinal InputStream inputStream, final String fileParamName)\n\t\t\tthrows Exception;\n\n\t/**\n\t * Retrieves the AccessGrant object.\n\t * \n\t * @return AccessGrant object.\n\t */\n\tpublic AccessGrant getAccessGrant();\n}", "public interface Constants {\n\n\t/**\n\t * UTF-8\n\t */\n\tpublic static final String ENCODING = \"UTF-8\";\n\n\t/**\n\t * oauth_consumer_key\n\t */\n\tpublic static final String OAUTH_CONSUMER_KEY = \"oauth_consumer_key\";\n\n\t/**\n\t * oauth_signature_method\n\t */\n\tpublic static final String OAUTH_SIGNATURE_METHOD = \"oauth_signature_method\";\n\n\t/**\n\t * oauth_signature\n\t */\n\tpublic static final String OAUTH_SIGNATURE = \"oauth_signature\";\n\n\t/**\n\t * \"oauth_timestamp\"\n\t */\n\tpublic static final String OAUTH_TIMESTAMP = \"oauth_timestamp\";\n\n\t/**\n\t * \"oauth_nonce\"\n\t */\n\tpublic static final String OAUTH_NONCE = \"oauth_nonce\";\n\n\t/**\n\t * \"oauth_version\"\n\t */\n\tpublic static final String OAUTH_VERSION = \"oauth_version\";\n\n\t/**\n\t * \"oauth_token\"\n\t */\n\tpublic static final String OAUTH_TOKEN = \"oauth_token\";\n\n\t/**\n\t * \"oauth_token_secret\"\n\t */\n\tpublic static final String OAUTH_TOKEN_SECRET = \"oauth_token_secret\";\n\n\t/**\n\t * \"oauth_callback\"\n\t */\n\tpublic static final String OAUTH_CALLBACK = \"oauth_callback\";\n\n\t/**\n\t * \"oauth_callback_confirmed\"\n\t */\n\tpublic static final String OAUTH_CALLBACK_CONFIRMED = \"oauth_callback_confirmed\";\n\n\t/**\n\t * \"oauth_problem\"\n\t */\n\tpublic static final String OAUTH_PROBLEM = \"oauth_problem\";\n\n\t/**\n\t * \"oauth_verifier\"\n\t */\n\tpublic static final String OAUTH_VERIFIER = \"oauth_verifier\";\n\n\t/**\n\t * \"oauth_\"\n\t */\n\tpublic static final String PREFIX = \"oauth_\";\n\n\t/**\n\t * \"1.0\"\n\t */\n\tpublic static final String CURRENT_VERSION = \"1.0\";\n\n\t/**\n\t * \"oob\"\n\t */\n\tpublic static final String OOB = \"oob\";\n\n\t/**\n\t * HMAC-SHA1\n\t */\n\tpublic static final String HMACSHA1_SIGNATURE = \"HMAC-SHA1\";\n\n\t/**\n\t * request token url\n\t */\n\tpublic static final String OAUTH_REQUEST_TOKEN_URL = \"reqTokenURL\";\n\n\t/**\n\t * authorization url\n\t */\n\tpublic static final String OAUTH_AUTHORIZATION_URL = \"authorizationURL\";\n\n\t/**\n\t * access token url\n\t */\n\tpublic static final String OAUTH_ACCESS_TOKEN_URL = \"accessTokenURL\";\n\n\t/**\n\t * refresh token url\n\t */\n\tpublic static final String REFRESH_TOKEN_URL = \"refreshTokenURL\";\n\n\t/**\n\t * API URl (used for GitHub enterprise connection)\n\t */\n\tpublic static final String API_URL = \"apiURL\";\n\n\t/**\n\t * token expires string\n\t */\n\tpublic static final String EXPIRES = \"expires\";\n\n\t/**\n\t * openid\n\t */\n\tpublic static final String OPENID = \"openid\";\n\n\t/**\n\t * facebook\n\t */\n\tpublic static final String FACEBOOK = \"facebook\";\n\n\t/**\n\t * foursquare\n\t */\n\tpublic static final String FOURSQUARE = \"foursquare\";\n\n\t/**\n\t * google\n\t */\n\tpublic static final String GOOGLE = \"google\";\n\n\t/**\n\t * hotmail\n\t */\n\tpublic static final String HOTMAIL = \"hotmail\";\n\n\t/**\n\t * linkedin\n\t */\n\tpublic static final String LINKEDIN = \"linkedin\";\n\n\t/**\n\t * myspace\n\t */\n\tpublic static final String MYSPACE = \"myspace\";\n\n\t/**\n\t * twitter\n\t */\n\tpublic static final String TWITTER = \"twitter\";\n\n\t/**\n\t * yahoo\n\t */\n\tpublic static final String YAHOO = \"yahoo\";\n\n\t/**\n\t * salesforce\n\t */\n\tpublic static final String SALESFORCE = \"salesforce\";\n\n\t/**\n\t * yammer\n\t */\n\tpublic static final String YAMMER = \"yammer\";\n\n\t/**\n\t * mendeley\n\t */\n\tpublic static final String MENDELEY = \"mendeley\";\n\n\t/**\n\t * runkeeper\n\t */\n\tpublic static final String RUNKEEPER = \"runkeeper\";\n\n\t/**\n\t * instagram\n\t */\n\tpublic static final String INSTAGRAM = \"instagram\";\n\n\t/**\n\t * googlePlus\n\t */\n\tpublic static final String GOOGLE_PLUS = \"googleplus\";\n\n\t/**\n\t * github\n\t */\n\tpublic static final String GITHUB = \"github\";\n\n\t/**\n\t * flickr\n\t */\n\tpublic static final String FLICKR = \"flickr\";\n\n\t/**\n\t * nimble\n\t */\n\tpublic static final String NIMBLE = \"nimble\";\n\n\t/**\n\t * linkedin OAuth2 provider\n\t */\n\tpublic static final String LINKEDINOAUTH2 = \"linkedin2\";\n\n\t/**\n\t * amazon\n\t */\n\tpublic static final String AMAZON = \"amazon\";\n\n\t/**\n\t * stackexchange\n\t */\n\tpublic static final String STACK_EXCHANGE = \"stackexchange\";\n\n\t/**\n\t * access token parameter name\n\t */\n\tpublic static final String ACCESS_TOKEN_PARAMETER_NAME = \"access_token\";\n\n\t/**\n\t * Proxy host property name\n\t */\n\tpublic static final String PROXY_HOST = \"proxy.host\";\n\n\t/**\n\t * Proxy port property name\n\t * \n\t */\n\tpublic static final String PROXY_PORT = \"proxy.port\";\n\n\t/**\n\t * HTTP connection timeout property\n\t */\n\tpublic static final String HTTP_CONNECTION_TIMEOUT = \"http.connectionTimeOut\";\n\n\t/**\n\t * Content Encoding Header\n\t */\n\tpublic static final String CONTENT_ENCODING_HEADER = \"Content-Encoding\";\n\n\t/**\n\t * GZip Content Encoding\n\t */\n\tpublic static final String GZIP_CONTENT_ENCODING = \"gzip\";\n\n\t/**\n\t * Constant for state paramter\n\t */\n\tpublic static final String STATE = \"state\";\n}", "public class OAuthConfig implements Serializable {\n\n\tprivate static final long serialVersionUID = 7574560869168900919L;\n\tprivate final String _consumerKey;\n\tprivate final String _consumerSecret;\n\tprivate final String _signatureMethod;\n\tprivate final String _transportName;\n\tprivate String id;\n\tprivate Class<?> providerImplClass;\n\tprivate String customPermissions;\n\tprivate String requestTokenUrl;\n\tprivate String authenticationUrl;\n\tprivate String accessTokenUrl;\n\tprivate String[] registeredPlugins;\n\tprivate List<String> pluginsScopes;\n\tprivate boolean saveRawResponse;\n\tprivate Map<String, String> customProperties;\n\n\t/**\n\t * \n\t * @param consumerKey\n\t * Application consumer key\n\t * @param consumerSecret\n\t * Application consumer secret\n\t * @param signatureMethod\n\t * Signature Method type\n\t * @param transportName\n\t * Transport name\n\t */\n\tpublic OAuthConfig(final String consumerKey, final String consumerSecret,\n\t\t\tfinal String signatureMethod, final String transportName) {\n\t\t_consumerKey = consumerKey;\n\t\t_consumerSecret = consumerSecret;\n\t\tif (signatureMethod == null || signatureMethod.length() == 0) {\n\t\t\t_signatureMethod = Constants.HMACSHA1_SIGNATURE;\n\t\t} else {\n\t\t\t_signatureMethod = signatureMethod;\n\t\t}\n\t\tif (transportName == null || transportName.length() == 0) {\n\t\t\t_transportName = MethodType.GET.toString();\n\t\t} else {\n\t\t\t_transportName = transportName;\n\t\t}\n\t}\n\n\tpublic OAuthConfig(final String consumerKey, final String consumerSecret) {\n\t\t_consumerKey = consumerKey;\n\t\t_consumerSecret = consumerSecret;\n\t\t_transportName = MethodType.GET.toString();\n\t\t_signatureMethod = Constants.HMACSHA1_SIGNATURE;\n\t}\n\n\t/**\n\t * Retrieves the consumer key\n\t * \n\t * @return the consumer key\n\t */\n\tpublic String get_consumerKey() {\n\t\treturn _consumerKey;\n\t}\n\n\t/**\n\t * Retrieves the consumer secret\n\t * \n\t * @return the consumer secret\n\t */\n\tpublic String get_consumerSecret() {\n\t\treturn _consumerSecret;\n\t}\n\n\t/**\n\t * Retrieves the signature method\n\t * \n\t * @return the signature method\n\t */\n\tpublic String get_signatureMethod() {\n\t\treturn _signatureMethod;\n\t}\n\n\t/**\n\t * Retrieves the transport name\n\t * \n\t * @return the transport name\n\t */\n\tpublic String get_transportName() {\n\t\treturn _transportName;\n\t}\n\n\t/**\n\t * Retrieves the provider id\n\t * \n\t * @return the provider id\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Updates the provider id\n\t * \n\t * @param id\n\t * the provider id\n\t */\n\tpublic void setId(final String id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Retrieves the provider implementation class\n\t * \n\t * @return the provider implementation class\n\t */\n\tpublic Class<?> getProviderImplClass() {\n\t\treturn providerImplClass;\n\t}\n\n\t/**\n\t * Updates the provider implementation class\n\t * \n\t * @param providerImplClass\n\t * the provider implementation class\n\t */\n\tpublic void setProviderImplClass(final Class<?> providerImplClass) {\n\t\tthis.providerImplClass = providerImplClass;\n\t}\n\n\t/**\n\t * Retrieves custom permissions configured in properties file\n\t * \n\t * @return String of custom permissions\n\t */\n\tpublic String getCustomPermissions() {\n\t\treturn customPermissions;\n\t}\n\n\t/**\n\t * Updates custom permissions configured in properties file\n\t * \n\t * @param customPermissions\n\t * String of comma seperated custom permissions\n\t */\n\tpublic void setCustomPermissions(final String customPermissions) {\n\t\tthis.customPermissions = customPermissions;\n\t}\n\n\t/**\n\t * Retrieves the authentication url\n\t * \n\t * @return the authentication url string\n\t */\n\tpublic String getAuthenticationUrl() {\n\t\treturn authenticationUrl;\n\t}\n\n\t/**\n\t * Updates the authentication url\n\t * \n\t * @param authenticationUrl\n\t * the authentication url string\n\t */\n\tpublic void setAuthenticationUrl(final String authenticationUrl) {\n\t\tthis.authenticationUrl = authenticationUrl;\n\t}\n\n\t/**\n\t * Retrieves the access token url\n\t * \n\t * @return the access token url string\n\t */\n\tpublic String getAccessTokenUrl() {\n\t\treturn accessTokenUrl;\n\t}\n\n\t/**\n\t * Updates the access token url\n\t * \n\t * @param accessTokenUrl\n\t * the access token url string\n\t */\n\tpublic void setAccessTokenUrl(final String accessTokenUrl) {\n\t\tthis.accessTokenUrl = accessTokenUrl;\n\t}\n\n\t/**\n\t * Retrieves the request token url\n\t * \n\t * @return the request token url string\n\t */\n\tpublic String getRequestTokenUrl() {\n\t\treturn requestTokenUrl;\n\t}\n\n\t/**\n\t * Updates the request token url\n\t * \n\t * @param requestTokenUrl\n\t * the request token url string\n\t */\n\tpublic void setRequestTokenUrl(final String requestTokenUrl) {\n\t\tthis.requestTokenUrl = requestTokenUrl;\n\t}\n\n\t/**\n\t * Retrieves the registered plugins of a provider configured in properties\n\t * file. String contains the fully qualified plugin class name\n\t * \n\t * @return String array of registered plugins\n\t */\n\tpublic String[] getRegisteredPlugins() {\n\t\treturn registeredPlugins;\n\t}\n\n\t/**\n\t * Updates the registered plugins configured in properties file\n\t * \n\t * @param registeredPlugins\n\t * String array of plugins. String should contain fully qualified\n\t * plugin class name\n\t */\n\tpublic void setRegisteredPlugins(final String[] registeredPlugins) {\n\t\tthis.registeredPlugins = registeredPlugins;\n\t}\n\n\t/**\n\t * Retrieves the list of plugins scopes\n\t * \n\t * @return list of plugins scope\n\t */\n\tpublic List<String> getPluginsScopes() {\n\t\treturn pluginsScopes;\n\t}\n\n\t/**\n\t * Updates the plugins scopes\n\t * \n\t * @param pluginsScopes\n\t * list of plugins scopes\n\t */\n\tpublic void setPluginsScopes(final List<String> pluginsScopes) {\n\t\tthis.pluginsScopes = pluginsScopes;\n\t}\n\n\t/**\n\t * Returns status to save the raw response for profile and contacts. Default\n\t * value is False.\n\t * \n\t * @return True/False to check whether raw response should save or not.\n\t */\n\tpublic boolean isSaveRawResponse() {\n\t\treturn saveRawResponse;\n\t}\n\n\t/**\n\t * Set this flag to True if raw response should be save for profile and\n\t * contacts. Default it is False.\n\t * \n\t * @param saveRawResponse\n\t * flag to config whether raw response should be saved or not.\n\t */\n\tpublic void setSaveRawResponse(boolean saveRawResponse) {\n\t\tthis.saveRawResponse = saveRawResponse;\n\t}\n\n\t/**\n\t * Returns custom properties for the provider\n\t * \n\t * @return map which contains custom properties\n\t */\n\tpublic Map<String, String> getCustomProperties() {\n\t\treturn customProperties;\n\t}\n\n\t/**\n\t * Updates the custom properties\n\t * \n\t * @param customProperties\n\t * map which store the custom properties required for the\n\t * provider except conumer key, secret and scopes\n\t */\n\tpublic void setCustomProperties(Map<String, String> customProperties) {\n\t\tthis.customProperties = customProperties;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString NEW_LINE = System.getProperty(\"line.separator\");\n\t\tresult.append(this.getClass().getName() + \" Object {\" + NEW_LINE);\n\t\tresult.append(\" consumerKey: \" + _consumerKey + NEW_LINE);\n\t\tresult.append(\" consumerSecret: \" + _consumerSecret + NEW_LINE);\n\t\tresult.append(\" signatureMethod: \" + _signatureMethod + NEW_LINE);\n\t\tresult.append(\" transportName: \" + _transportName + NEW_LINE);\n\t\tresult.append(\" id: \" + id + NEW_LINE);\n\t\tresult.append(\" providerImplClass: \" + providerImplClass + NEW_LINE);\n\t\tresult.append(\" customPermissions: \" + customPermissions + NEW_LINE);\n\t\tresult.append(\" requestTokenUrl: \" + requestTokenUrl + NEW_LINE);\n\t\tresult.append(\" authenticationUrl: \" + authenticationUrl + NEW_LINE);\n\t\tresult.append(\" accessTokenUrl: \" + accessTokenUrl + NEW_LINE);\n\t\tresult.append(\" registeredPlugins: \" + registeredPlugins + NEW_LINE);\n\t\tresult.append(\" pluginsScopes: \" + pluginsScopes + NEW_LINE);\n\t\tresult.append(\" saveRawResponse: \" + saveRawResponse + NEW_LINE);\n\t\tif (customProperties != null) {\n\t\t\tresult.append(\" customProperties: \" + customProperties.toString()\n\t\t\t\t\t+ NEW_LINE);\n\t\t} else {\n\t\t\tresult.append(\" customProperties: null\" + NEW_LINE);\n\t\t}\n\t\tresult.append(\"}\");\n\t\treturn result.toString();\n\t}\n}" ]
import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.brickred.socialauth.AbstractProvider; import org.brickred.socialauth.AuthProvider; import org.brickred.socialauth.Contact; import org.brickred.socialauth.Permission; import org.brickred.socialauth.Profile; import org.brickred.socialauth.exception.AccessTokenExpireException; import org.brickred.socialauth.exception.SocialAuthException; import org.brickred.socialauth.exception.UserDeniedPermissionException; import org.brickred.socialauth.oauthstrategy.OAuth2; import org.brickred.socialauth.oauthstrategy.OAuthStrategyBase; import org.brickred.socialauth.util.AccessGrant; import org.brickred.socialauth.util.Constants; import org.brickred.socialauth.util.MethodType; import org.brickred.socialauth.util.OAuthConfig; import org.brickred.socialauth.util.Response; import org.json.JSONObject;
/* =========================================================================== Copyright (c) 2010 BrickRed Technologies Limited 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, sub-license, 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 org.brickred.socialauth.provider; /** * Provider implementation for SalesForce * * */ public class SalesForceImpl extends AbstractProvider implements AuthProvider, Serializable { private static final long serialVersionUID = 6929330230703360670L; private static final Map<String, String> ENDPOINTS; private final Log LOG = LogFactory.getLog(SalesForceImpl.class);
private OAuthConfig config;
6
chanjarster/artemis-disruptor-miaosha
jms-server/src/main/java/me/chanjar/jms/server/config/OrderInsertProcessorConfiguration.java
[ "public class DisruptorLifeCycleContainer implements SmartLifecycle {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorLifeCycleContainer.class);\n\n private volatile boolean running = false;\n\n private final String disruptorName;\n private final Disruptor disruptor;\n private final int phase;\n\n public DisruptorLifeCycleContainer(String disruptorName, Disruptor disruptor, int phase) {\n this.disruptorName = disruptorName;\n this.disruptor = disruptor;\n this.phase = phase;\n }\n\n @Override\n public boolean isAutoStartup() {\n return true;\n }\n\n @Override\n public void stop(Runnable callback) {\n this.stop();\n callback.run();\n }\n\n @Override\n public void start() {\n LOGGER.info(\"Starting disruptor [{}]\", this.disruptorName);\n disruptor.start();\n this.running = true;\n }\n\n @Override\n public void stop() {\n LOGGER.info(\"Shutdown disruptor [{}]\", this.disruptorName);\n disruptor.shutdown();\n this.running = false;\n }\n\n @Override\n public boolean isRunning() {\n return this.running;\n }\n\n @Override\n public int getPhase() {\n return this.phase;\n }\n}", "public abstract class StartupOrderConstants {\n\n public static final int DISRUPTOR_REQUEST_DTO = 1;\n public static final int DISRUPTOR_ORDER_INSERT = 2;\n public static final int DISRUPTOR_ITEM_UPDATE = 3;\n\n private StartupOrderConstants() {\n // singleton\n }\n\n}", "public interface CommandDispatcher {\n\n void dispatch(Command command);\n\n void registerCommandProcessor(CommandProcessor commandProcessor);\n\n}", "public class OrderInsertCommand extends Command {\n\n private static final long serialVersionUID = -1844388054958673686L;\n private final Long itemId;\n\n private final String userId;\n\n /**\n * @param requestId Command来源的requestId\n * @param itemId 商品ID\n * @param userId 用户ID\n */\n public OrderInsertCommand(String requestId, Long itemId, String userId) {\n super(requestId);\n this.itemId = itemId;\n this.userId = userId;\n }\n\n public Long getItemId() {\n return itemId;\n }\n\n public String getUserId() {\n return userId;\n }\n\n}", "public class OrderInsertCommandBuffer implements CommandBuffer<OrderInsertCommand> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(OrderInsertCommandBuffer.class);\n\n private final List<OrderInsertCommand> commandList;\n\n private final int capacity;\n\n public OrderInsertCommandBuffer(int capacity) {\n this.capacity = capacity;\n this.commandList = new ArrayList<>(capacity);\n }\n\n @Override\n public boolean hasRemaining() {\n return commandList.size() < this.capacity;\n }\n\n /**\n * @param command\n * @throws CommandBufferOverflowException\n */\n @Override\n public void put(OrderInsertCommand command) {\n\n if (!hasRemaining()) {\n throw new CommandBufferOverflowException();\n }\n\n this.commandList.add(command);\n LOGGER.info(\"Put\", command);\n\n }\n\n @Override\n public void clear() {\n commandList.clear();\n }\n\n @Override\n public List<OrderInsertCommand> get() {\n return new ArrayList<>(commandList);\n }\n\n}", "public class OrderInsertCommandExecutor implements CommandExecutor<OrderInsertCommandBuffer> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(OrderInsertCommandExecutor.class);\n\n private static final String SQL = \"INSERT INTO ITEM_ORDER(ID, ITEM_ID, USER_ID)\\n\"\n + \"VALUES (SEQ_ITEM_ORDER.nextval, ?, ?)\";\n\n private JdbcTemplate jdbcTemplate;\n\n public OrderInsertCommandExecutor(JdbcTemplate jdbcTemplate) {\n this.jdbcTemplate = jdbcTemplate;\n }\n\n @Override\n public void execute(OrderInsertCommandBuffer commandBuffer) {\n\n List<OrderInsertCommand> commands = commandBuffer.get();\n if (CollectionUtils.isEmpty(commands)) {\n return;\n }\n\n List<Object[]> args = commands.stream().map(cmd -> new Object[] { cmd.getItemId(), cmd.getUserId() })\n .collect(toList());\n\n try {\n\n jdbcTemplate.batchUpdate(SQL, args);\n commands.forEach(command -> LOGGER.info(\"Executed\", command));\n\n } catch (Exception e) {\n\n commands.forEach(command -> LOGGER.error(\"Failed\", command));\n LOGGER.error(ExceptionUtils.getStackTrace(e));\n\n }\n\n }\n\n}", "public class OrderInsertCommandProcessor implements CommandProcessor<OrderInsertCommand> {\n\n private final CommandEventProducer<OrderInsertCommand>[] commandEventProducerList;\n\n private final int producerCount;\n\n public OrderInsertCommandProcessor(\n CommandEventProducer<OrderInsertCommand>[] commandEventProducerList) {\n this.commandEventProducerList = commandEventProducerList;\n this.producerCount = commandEventProducerList.length;\n }\n\n @Override\n public Class<OrderInsertCommand> getMatchClass() {\n return OrderInsertCommand.class;\n }\n\n @Override\n public void process(OrderInsertCommand command) {\n\n // 根据商品ID去模\n int index = (int) (command.getItemId() % (long) this.producerCount);\n commandEventProducerList[index].onData(command);\n\n }\n\n}", "public abstract class BeanRegisterUtils {\n\n private BeanRegisterUtils() {\n }\n\n public static void registerSingleton(ApplicationContext applicationContext, String beanName, Object singletonObject) {\n\n AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();\n if (!SingletonBeanRegistry.class.isAssignableFrom(beanFactory.getClass())) {\n throw new IllegalArgumentException(\n \"ApplicationContext: \" + applicationContext.getClass().toString()\n + \" doesn't implements SingletonBeanRegistry, cannot register JMS connection at runtime\");\n }\n\n SingletonBeanRegistry beanDefinitionRegistry = (SingletonBeanRegistry) beanFactory;\n beanDefinitionRegistry.registerSingleton(beanName, singletonObject);\n\n }\n\n public static void registerSingleton(BeanDefinitionRegistry registry, String beanName, Object singletonObject) {\n\n if (!SingletonBeanRegistry.class.isAssignableFrom(registry.getClass())) {\n throw new IllegalArgumentException(\n \"BeanDefinitionRegistry: \" + registry.getClass().toString()\n + \" doesn't implements SingletonBeanRegistry, cannot register JMS connection at runtime\");\n }\n\n SingletonBeanRegistry beanDefinitionRegistry = (SingletonBeanRegistry) registry;\n beanDefinitionRegistry.registerSingleton(beanName, singletonObject);\n\n }\n\n}" ]
import com.lmax.disruptor.dsl.Disruptor; import me.chanjar.jms.base.lifecycle.DisruptorLifeCycleContainer; import me.chanjar.jms.server.StartupOrderConstants; import me.chanjar.jms.server.command.infras.CommandDispatcher; import me.chanjar.jms.server.command.infras.disruptor.*; import me.chanjar.jms.server.command.order.OrderInsertCommand; import me.chanjar.jms.server.command.order.OrderInsertCommandBuffer; import me.chanjar.jms.server.command.order.OrderInsertCommandExecutor; import me.chanjar.jms.server.command.order.OrderInsertCommandProcessor; import me.chanjar.jms.base.utils.BeanRegisterUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import java.util.concurrent.Executors;
package me.chanjar.jms.server.config; @Configuration @EnableConfigurationProperties(OrderInsertProcessorConfiguration.Conf.class) public class OrderInsertProcessorConfiguration implements ApplicationContextAware { private static final Logger LOGGER = LoggerFactory.getLogger(OrderInsertProcessorConfiguration.class); @Autowired private Conf conf; @Autowired private CommandDispatcher commandDispatcher; @Autowired private JdbcTemplate jdbcTemplate; private ApplicationContext applicationContext; @Bean public OrderInsertCommandProcessor courseTakeInsertCmdProcessor() { LOGGER.info("Configure OrderInsertCommandProcessor"); CommandEventProducer<OrderInsertCommand>[] commandEventProducerList = new CommandEventProducer[conf.getNum()]; for (int i = 0; i < conf.getNum(); i++) { OrderInsertCommandBuffer cmdBuffer = new OrderInsertCommandBuffer(conf.getSqlBufferSize()); OrderInsertCommandExecutor cmdExecutor = new OrderInsertCommandExecutor(jdbcTemplate); Disruptor<CommandEvent<OrderInsertCommand>> disruptor = new Disruptor<>( new CommandEventFactory(), conf.getQueueSize(), Executors.defaultThreadFactory()); disruptor .handleEventsWith(new CommandEventDbHandler(cmdBuffer, cmdExecutor)) .then(new CommandEventGcHandler()) ; // disruptor 的异常处理是这样的, // 不论这种形式 A->B, 还是这种形式 A,B->C,D, 只有抛出异常的那个handler会中断执行 disruptor.setDefaultExceptionHandler(new CommandEventExceptionHandler()); commandEventProducerList[i] = new CommandEventProducer<>(disruptor.getRingBuffer());
BeanRegisterUtils.registerSingleton(
7
aeshell/aesh-extensions
aesh/src/test/java/org/aesh/extensions/rm/RmTest.java
[ "@CommandDefinition(name = \"cat\", description = \"concatenate files and print on the standard output\")\npublic class Cat implements Command<CommandInvocation> {\n\n @Option(shortName = 'A', name = \"show-all\", hasValue = false, description = \"equivalent to -vET\")\n private boolean showAll;\n\n @Option(shortName = 'b', name = \"number-nonblank\", hasValue = false, description = \"number nonempty output lines, overrides -n\")\n private boolean numberNonBlank;\n\n @Option(shortName = 'E', name = \"show-ends\", hasValue = false, description = \"display $ at end of each line\")\n private boolean showEnds;\n\n @Option(shortName = 'n', name = \"number\", hasValue = false, description = \"number all output lines\")\n private boolean number;\n\n @Option(shortName = 's', name = \"squeeze-blank\", hasValue = false, description = \"suppress repeated empty output lines\")\n private boolean squeezeBlank;\n\n @Option(shortName = 'T', name = \"show-tabs\", hasValue = false, description = \"display TAB characters as ^I\")\n private boolean showTabs;\n\n @Option(shortName = 'h', name = \"help\", hasValue = false, description = \"display this help and exit\")\n private boolean help;\n\n @Arguments\n private List<Resource> files;\n\n private boolean prevBlank = false;\n private boolean currentBlank = false;\n private int counter;\n\n @Override\n public CommandResult execute(CommandInvocation commandInvocation) {\n\n if(help) {\n commandInvocation.println(\n commandInvocation.getHelpInfo(\"cat\") );\n return CommandResult.SUCCESS;\n }\n\n try {\n counter = 1;\n if(showAll) {\n showEnds = true;\n showTabs = true;\n }\n //do we have data from a pipe/redirect?\n /*\n if(commandInvocation.getShell().in().getStdIn().available() > 0) {\n java.util.Scanner s = new java.util.Scanner(commandInvocation.getShell().in().getStdIn()).useDelimiter(\"\\\\A\");\n String input = s.hasNext() ? s.next() : \"\";\n commandInvocation.getShell().out().println();\n for(String i : input.split(Config.getLineSeparator()))\n displayLine(i, commandInvocation.getShell());\n\n return CommandResult.SUCCESS;\n }\n */\n if(files != null && files.size() > 0) {\n for(Resource f : files)\n displayFile(f.resolve(commandInvocation.getConfiguration().getAeshContext().getCurrentWorkingDirectory()).get(0),\n //PathResolver.resolvePath(f, commandInvocation.getAeshContext().getCurrentWorkingDirectory()).get(0),\n commandInvocation.getShell());\n\n return CommandResult.SUCCESS;\n }\n //read from stdin\n else {\n readFromStdin(commandInvocation);\n\n return CommandResult.SUCCESS;\n }\n }\n catch(FileNotFoundException fnfe) {\n commandInvocation.println(\"cat: \"+fnfe.getMessage());\n return CommandResult.FAILURE;\n }\n }\n\n private void displayFile(Resource f, Shell shell) throws FileNotFoundException {\n BufferedReader br = new BufferedReader(new InputStreamReader(f.read()));\n\n try {\n String line = br.readLine();\n while(line != null) {\n if(line.length() == 0) {\n if(currentBlank && squeezeBlank)\n prevBlank = true;\n currentBlank = true;\n }\n else\n prevBlank = currentBlank = false;\n\n displayLine(line, shell);\n\n line = br.readLine();\n }\n }\n catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void displayLine(String line, Shell shell) {\n if(numberNonBlank) {\n if(!currentBlank) {\n shell.write(Parser.padLeft(6, String.valueOf(counter)));\n shell.write(\" \");\n counter++;\n }\n }\n else if(number && !prevBlank) {\n shell.write(Parser.padLeft(6, String.valueOf(counter)));\n shell.write(' ');\n counter++;\n }\n\n if(showTabs) {\n if(line.contains(\"\\t\"))\n line = line.replaceAll(\"\\t\",\"^I\");\n if(!prevBlank)\n shell.write(line);\n }\n else {\n if(!prevBlank)\n shell.write(line);\n }\n\n if(showEnds && !prevBlank)\n shell.write('$');\n\n if(!prevBlank)\n shell.write(Config.getLineSeparator());\n }\n\n private void readFromStdin(CommandInvocation commandInvocation) {\n try {\n KeyAction input = commandInvocation.input();\n StringBuilder builder = new StringBuilder();\n while(!input.bufferEquals(Key.CTRL_C)) {\n if(input.bufferEquals( Key.ENTER)) {\n commandInvocation.println(\"\");\n displayLine(builder.toString(), commandInvocation.getShell());\n builder = new StringBuilder();\n }\n else {\n builder.append((char) input.getCodePointAt(0));\n commandInvocation.getShell().write((char) input.getCodePointAt(0));\n }\n\n input = commandInvocation.input();\n }\n\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}", "@CommandDefinition(name = \"cd\", description = \"change directory [dir]\")\npublic class Cd implements Command<CommandInvocation> {\n\n @Option(shortName = 'h', name = \"help\", hasValue = false, description = \"display this help and exit\")\n private boolean help;\n\n @Arguments(description = \"directory to change to\")\n private List<Resource> arguments;\n\n @Override\n public CommandResult execute(CommandInvocation commandInvocation) {\n if (help) {\n commandInvocation.println(commandInvocation.getHelpInfo(\"cd\"));\n return CommandResult.SUCCESS;\n }\n\n if (arguments == null) {\n updatePrompt(commandInvocation,\n commandInvocation.getConfiguration().getAeshContext().getCurrentWorkingDirectory().newInstance(Config.getHomeDir()));\n }\n else {\n List<Resource> files =\n arguments.get(0).resolve(commandInvocation.getConfiguration().getAeshContext().getCurrentWorkingDirectory());\n\n if(files.get(0).isDirectory())\n updatePrompt(commandInvocation, files.get(0));\n }\n return CommandResult.SUCCESS;\n }\n\n private void updatePrompt(CommandInvocation commandInvocation, Resource file) {\n commandInvocation.getConfiguration().getAeshContext().setCurrentWorkingDirectory(file);\n commandInvocation.setPrompt(new Prompt(\"[aesh@extensions:\"+file.toString()+\"]$ \"));\n }\n}", "public class AeshTestCommons {\n\n private ReadlineConsole console;\n private CommandRegistry registry;\n private TestConnection connection;\n\n private FileAttribute fileAttribute = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(\"rwxrwxrwx\"));\n\n public AeshTestCommons() {\n }\n\n protected String getStream() {\n return connection.getOutputBuffer();\n }\n\n protected TestConnection connection() {\n return connection;\n }\n\n protected void prepare(Class<? extends Command>... commands) throws IOException, CommandRegistryException {\n connection = new TestConnection(false);\n\n registry = AeshCommandRegistryBuilder.builder()\n .commands(commands)\n .create();\n\n Settings settings = SettingsBuilder.builder()\n .connection(connection)\n .commandRegistry(registry)\n .build();\n\n console = new ReadlineConsole(settings);\n console.start();\n }\n\n protected void finish() {\n smallPause();\n System.out.println(\"Got out: \" + connection.getOutputBuffer());\n console.stop();\n }\n\n protected void smallPause() {\n try {\n Thread.sleep(150);\n }\n catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n protected void pushToOutput(String literalCommand) throws IOException {\n connection.read(literalCommand);\n connection.read(Config.getLineSeparator());\n smallPause();\n }\n\n protected void output(String literalCommand) throws IOException {\n connection.write(literalCommand);\n smallPause();\n }\n\n protected AeshContext getAeshContext() {\n return console.context();\n }\n\n protected Path createTempDirectory() throws IOException {\n final Path tmp;\n if (Config.isOSPOSIXCompatible()) {\n tmp = Files.createTempDirectory(\"temp\", fileAttribute);\n } else {\n tmp = Files.createTempDirectory(\"temp\");\n }\n return tmp;\n }\n\n protected void deleteRecursiveTempDirectory(Path directory) throws IOException {\n Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.delete(file);\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n Files.delete(dir);\n return FileVisitResult.CONTINUE;\n }\n\n });\n }\n\n}", "@CommandDefinition(name = \"ls\", description = \"[OPTION]... [FILE]...\\n\" +\n \"List information about the FILEs (the current directory by default).\\n\" +\n \"Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\\n\")\npublic class Ls implements Command<CommandInvocation> {\n\n @Option(shortName = 'H', name = \"help\", hasValue = false,\n description = \"display this help and exit\")\n private boolean help;\n @Option(shortName = 'a', name = \"all\", hasValue = false,\n description = \"do not ignore entries starting with .\")\n private boolean all;\n @Option(shortName = 'd', name = \"directory\", hasValue = false,\n description = \"list directory entries instead of contents, and do not dereference symbolic links\")\n private boolean directory;\n @Option(shortName = 'l', name = \"longlisting\", hasValue = false,\n description = \"use a long listing format\")\n private boolean longListing;\n\n @Option(shortName = 's', name = \"size\", hasValue = false,\n description = \"print the allocated size of each file, in blocks\")\n private boolean size;\n\n @Option(shortName = 'h', name =\"human-readable\", hasValue = false,\n description = \"with -l, print sizes in human readable format (e.g., 1K 234M 2G)\")\n private boolean humanReadable;\n\n @Arguments\n private List<Resource> arguments;\n\n private static final char SPACE = ' ';\n\n private static final Class<? extends BasicFileAttributes> fileAttributes =\n Config.isOSPOSIXCompatible() ? PosixFileAttributes.class : DosFileAttributes.class;\n\n private static final DateFormat DATE_FORMAT = new SimpleDateFormat(\"MMM dd HH:mm\");\n private static final DateFormat OLD_FILE_DATE_FORMAT = new SimpleDateFormat(\"MMM dd yyyy\");\n\n private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(\".#\");\n\n private static final TerminalColor DIRECTORY_COLOR = new TerminalColor(Color.BLUE, Color.DEFAULT, Color.Intensity.BRIGHT);\n private static final TerminalColor SYMBOLIC_LINK_COLOR = new TerminalColor(Color.CYAN, Color.DEFAULT, Color.Intensity.BRIGHT);\n\n public Ls() {\n DECIMAL_FORMAT.setRoundingMode(RoundingMode.UP);\n }\n\n @Override\n public CommandResult execute(CommandInvocation commandInvocation) {\n //just display help and return\n if(help) {\n commandInvocation.getShell().writeln(commandInvocation.getHelpInfo(\"ls\"));\n return CommandResult.SUCCESS;\n }\n\n if(arguments == null) {\n arguments = new ArrayList<>(1);\n arguments.add(commandInvocation.getConfiguration().getAeshContext().getCurrentWorkingDirectory());\n }\n\n int counter = 0;\n for(Resource file : arguments) {\n if(counter > 0) {\n commandInvocation.getShell().writeln(Config.getLineSeparator()+file.getName()+\":\");\n }\n\n for(Resource f : file.resolve(commandInvocation.getConfiguration().getAeshContext().getCurrentWorkingDirectory())) {\n if(f.isDirectory())\n displayDirectory(f, commandInvocation.getShell());\n else if(f.isLeaf())\n displayFile(f,commandInvocation.getShell());\n else if(!f.exists()) {\n commandInvocation.getShell().writeln(\"ls: cannot access \"+\n f.toString()+\": No such file or directory\");\n }\n }\n counter++;\n }\n\n return CommandResult.SUCCESS;\n }\n\n private void displayDirectory(Resource input, Shell shell) {\n List<Resource> files = new ArrayList<>();\n\n if (all) {\n // add \".\" and \"..\" to list of files\n files.add(input.newInstance(\".\"));\n files.add(input.newInstance(\"..\"));\n files.addAll(input.list());\n\n }\n else {\n files = input.list(new NoDotNamesFilter());\n }\n\n Collections.sort(files, new PosixFileComparator());\n\n if (longListing) {\n shell.write(displayLongListing(files));\n }\n else {\n shell.write(Parser.formatDisplayCompactListTerminalString(\n formatFileList(files),\n shell.size().getWidth()));\n }\n }\n\n private List<TerminalString> formatFileList(List<Resource> fileList) {\n ArrayList<TerminalString> list = new ArrayList<>(fileList.size());\n for(Resource file : fileList) {\n if (file.isSymbolicLink()) {\n list.add(new TerminalString(file.getName(), SYMBOLIC_LINK_COLOR));\n } else if (file.isDirectory()) {\n list.add(new TerminalString(file.getName(), DIRECTORY_COLOR));\n } else {\n list.add(new TerminalString(file.getName()));\n }\n }\n return list;\n }\n\n private void displayFile(Resource input, Shell shell) {\n if(longListing) {\n List<Resource> resourceList = new ArrayList<>(1);\n resourceList.add(input);\n shell.write(displayLongListing(resourceList));\n }\n else {\n List<Resource> resourceList = new ArrayList<>(1);\n resourceList.add(input);\n shell.write(Parser.formatDisplayListTerminalString(\n formatFileList(resourceList), shell.size().getHeight(), shell.size().getWidth()));\n }\n }\n\n private String displayLongListing(List<Resource> files) {\n\n StringGroup access = new StringGroup(files.size());\n StringGroup size = new StringGroup(files.size());\n StringGroup owner = new StringGroup(files.size());\n StringGroup group = new StringGroup(files.size());\n StringGroup modified = new StringGroup(files.size());\n\n try {\n int counter = 0;\n for(Resource file : files) {\n BasicFileAttributes attr = file.readAttributes(fileAttributes, LinkOption.NOFOLLOW_LINKS);\n\n if (Config.isOSPOSIXCompatible()) {\n access.addString(AeshPosixFilePermissions.toString(((PosixFileAttributes) attr)), counter);\n } else {\n access.addString(\"\", counter);\n }\n\n size.addString(makeSizeReadable(attr.size()), counter);\n\n if (Config.isOSPOSIXCompatible()) {\n owner.addString(((PosixFileAttributes) attr).owner().getName(), counter);\n group.addString(((PosixFileAttributes) attr).group().getName(), counter);\n } else {\n owner.addString(\"\", counter);\n group.addString(\"\", counter);\n }\n\n // show year instead of time when file wasn't changed in actual year\n Date lastModifiedTime = new Date(attr.lastModifiedTime().toMillis());\n\n Calendar lastModifiedCalendar = Calendar.getInstance();\n lastModifiedCalendar.setTime(lastModifiedTime);\n\n Calendar nowCalendar = Calendar.getInstance();\n\n if (lastModifiedCalendar.get(Calendar.YEAR) == nowCalendar.get(Calendar.YEAR)) {\n modified.addString(DATE_FORMAT.format(lastModifiedTime), counter);\n } else {\n modified.addString(OLD_FILE_DATE_FORMAT.format(lastModifiedTime), counter);\n }\n\n counter++;\n }\n }\n catch (IOException e) {\n e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.\n }\n\n StringBuilder builder = new StringBuilder();\n\n for (int i = 0; i < files.size(); i++) {\n builder.append(access.getString(i))\n .append(owner.getFormattedStringPadRight(i))\n .append(group.getFormattedStringPadRight(i))\n .append(size.getFormattedString(i))\n .append(SPACE)\n .append(modified.getString(i))\n .append(SPACE);\n\n if (files.get(i).isSymbolicLink()) {\n builder.append(new TerminalString(files.get(i).getName(), SYMBOLIC_LINK_COLOR));\n builder.append(\" -> \");\n try {\n builder.append(files.get(i).readSymbolicLink());\n } catch (IOException ex) {\n ex.printStackTrace(); // this should not happen\n }\n } else if (files.get(i).isDirectory()) {\n builder.append(new TerminalString(files.get(i).getName(), DIRECTORY_COLOR));\n } else {\n builder.append(files.get(i).getName());\n }\n\n builder.append(Config.getLineSeparator());\n }\n\n return builder.toString();\n }\n\n private String makeSizeReadable(long size) {\n if(!humanReadable)\n return String.valueOf(size);\n else {\n if(size < 10000)\n return String.valueOf(size);\n else if(size < 10000000) //K\n return DECIMAL_FORMAT.format((double) size/1024)+\"K\";\n else if(size < 1000000000) //M\n return DECIMAL_FORMAT.format((double) size/(1048576))+\"M\";\n else\n return DECIMAL_FORMAT.format((double) size/(1048576*1014))+\"G\";\n }\n }\n\n class PosixFileComparator implements Comparator<Resource> {\n private PosixFileNameComparator posixFileNameComparator = new PosixFileNameComparator();\n\n @Override\n public int compare(Resource o1, Resource o2) {\n return posixFileNameComparator.compare(o1.getName(), o2.getName());\n }\n }\n}", "@CommandDefinition(name = \"mkdir\", description = \"create directory(ies), if they do not already exist.\")\npublic class Mkdir implements Command<CommandInvocation> {\n\n @Option(shortName = 'h', name = \"help\", hasValue = false, description = \"display this help and exit\")\n private boolean help;\n\n @Option(shortName = 'p', name = \"parents\", hasValue = false,\n description = \"make parent directories as needed\")\n private boolean parents;\n\n @Option(shortName = 'v', name = \"verbose\", hasValue = false,\n description = \"print a message for each created directory\")\n private boolean verbose;\n\n @Arguments(description = \"directory(ies) to create\")\n private List<Resource> arguments;\n\n @Override\n public CommandResult execute(CommandInvocation commandInvocation) {\n if (help || arguments == null || arguments.isEmpty()) {\n commandInvocation.getShell().writeln(commandInvocation.getHelpInfo(\"mkdir\"));\n return CommandResult.SUCCESS;\n }\n\n for (Resource f : arguments) {\n Resource currentWorkingDirectory = commandInvocation.getConfiguration().getAeshContext().getCurrentWorkingDirectory();\n Shell shell = commandInvocation.getShell();\n\n Resource pathResolved = f.resolve(currentWorkingDirectory).get(0);\n\n if (parents || f.getName().contains(Config.getPathSeparator())) {\n makeDirs(arguments, pathResolved, shell);\n } else {\n makeDir(pathResolved, shell);\n }\n }\n\n return CommandResult.SUCCESS;\n }\n\n private void makeDir(Resource dir, Shell shell) {\n if (!dir.exists()) {\n dir.mkdirs();\n if (verbose) {\n shell.writeln(\"created directory '\" + dir.getName() + \"'\");\n }\n } else {\n shell.writeln(\"cannot create directory '\" + dir.getName() + \"': Directory exists\");\n }\n }\n\n private void makeDirs(List<Resource> resources, Resource dir, Shell shell) {\n if (!dir.exists()) {\n dir.mkdirs();\n if (verbose) {\n for (Resource r : resources) {\n shell.writeln(\"created directory '\" + r.getName() + \"'\");\n }\n }\n }\n }\n\n}", "@CommandDefinition(name = \"touch\", description = \"create and change file timestamps\")\npublic class Touch implements Command<CommandInvocation> {\n\n @Option(shortName = 'h', name = \"help\", hasValue = false, description = \"display this help and exit\")\n private boolean help;\n\n @Option(shortName = 'a', name = \"access time\", hasValue = false, description = \"change only the access time\")\n private boolean changeOnlyAccessTime;\n\n @Option(shortName = 'm', name = \"modification time\", hasValue = false, description = \"change only the modification time\")\n private boolean changeOnlyModificationTime;\n\n @Option(shortName = 'c', name = \"no create\", hasValue = false, description = \"do not create any files\")\n private boolean noCreate;\n\n @Arguments\n private List<Resource> args;\n\n @Override\n public CommandResult execute(CommandInvocation ci) {\n if (help || args == null || args.isEmpty()) {\n ci.getShell().writeln(ci.getHelpInfo(\"touch\"));\n return CommandResult.SUCCESS;\n }\n\n Resource currentDir = ci.getConfiguration().getAeshContext().getCurrentWorkingDirectory();\n for (Resource r : args) {\n Resource res = r.resolve(currentDir).get(0);\n try {\n touch(res, ci);\n }\n catch (IOException e) {\n ci.println(\"failed to touch: \"+e.getMessage());\n }\n }\n return CommandResult.SUCCESS;\n }\n\n private void touch(Resource r, CommandInvocation ci) throws IOException {\n if (r.exists()) {\n if (changeOnlyAccessTime) {\n r.setLastAccessed(System.currentTimeMillis());\n }\n\n if (changeOnlyModificationTime) {\n r.setLastModified(System.currentTimeMillis());\n }\n } else {\n if (!noCreate) {\n create(r, ci);\n }\n }\n }\n\n private void create(Resource r, CommandInvocation ci) throws IOException {\n r.resolve(ci.getConfiguration().getAeshContext().getCurrentWorkingDirectory()).get(0).write(false);\n }\n}" ]
import org.aesh.extensions.touch.Touch; import org.aesh.readline.terminal.Key; import org.aesh.terminal.utils.Config; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Path; import org.aesh.command.registry.CommandRegistryException; import org.aesh.extensions.cat.Cat; import org.aesh.extensions.cd.Cd; import org.aesh.extensions.common.AeshTestCommons; import org.aesh.extensions.ls.Ls; import org.aesh.extensions.mkdir.Mkdir;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.aesh.extensions.rm; /** * @author <a href="mailto:[email protected]">Helio Frota</a> */ @Ignore public class RmTest extends AeshTestCommons { private Path tempDir; @Before public void before() throws IOException { tempDir = createTempDirectory(); } @After public void after() throws IOException { deleteRecursiveTempDirectory(tempDir); } @Test public void testRm() throws IOException, CommandRegistryException {
prepare(Touch.class, Mkdir.class, Cd.class, Cat.class, Ls.class, Rm.class);
0
handexing/geekHome
geekHome-web-ui/src/main/java/com/geekhome/controller/LabelController.java
[ "public enum ErrorCode {\n\t\n\tEXCEPTION(\"程序异常\", \"00001\"),\n\tUSER_NOT_EXIST(\"用户未注册\", \"00002\"),\n VERIFY_CODE_WRONG(\"验证码错误\",\"00003\"),\n OLD_PWD_WRONG(\"旧密码错误\",\"00004\"),\n USERNAME_PASSWORD_WRONG(\"用户名或密码错误\",\"00005\"),\n TODAY_HAVE_SIGN(\"今日已签到\",\"00006\");\n\n\tprivate String errorMsg;\n\tprivate String errorCode;\n\n\tprivate ErrorCode(final String errorMsg, final String errorCode) {\n\t\tthis.errorMsg = errorMsg;\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic String getErrorCode() {\n\t\treturn errorCode;\n\t}\n\n\tpublic String getErrorMsg() {\n\t\treturn errorMsg;\n\t}\n\n\tpublic void setErrorCode(String errorCode) {\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic void setErrorMsg(String errorMsg) {\n\t\tthis.errorMsg = errorMsg;\n\t}\n\n}", "public class ExecuteResult<T> {\n\t\n\tprivate final long timeOut = 50000L;\n\tprivate boolean isSuccess;\n\tprivate T data;\n\n\tprivate String errorCode;\n\tprivate String errorMsg;\n\tprivate String fromUrl;\n\n\tprivate Long processTime;\n\t@SuppressWarnings(\"unused\")\n\tprivate Long flushTimeOut;\n\n\tpublic T getData() {\n\t\treturn data;\n\t}\n\n\tpublic String getErrorCode() {\n\t\treturn errorCode == null ? \"\" : errorCode;\n\t}\n\n\tpublic String getErrorMsg() {\n\t\treturn errorMsg == null ? \"\" : errorMsg;\n\t}\n\n\tpublic boolean isSuccess() {\n\t\treturn isSuccess;\n\t}\n\n\tpublic void setData(T data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic void setErrorCode(String errorCode) {\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic void setErrorMsg(String errorMsg) {\n\t\tthis.errorMsg = errorMsg;\n\t}\n\n\tpublic void setSuccess(boolean isSuccess) {\n\t\tthis.isSuccess = isSuccess;\n\t}\n\n\tpublic Date getFlushTime() {\n\t\treturn new Date();\n\t\t// return flushTime;\n\t}\n\n\tpublic Long getProcessTime() {\n\t\treturn processTime;\n\t}\n\n\tpublic void setProcessTime(Long processTime) {\n\t\tthis.processTime = processTime;\n\t}\n\n\tpublic String getFromUrl() {\n\t\treturn fromUrl;\n\t}\n\n\tpublic void setFromUrl(String fromUrl) {\n\t\tthis.fromUrl = fromUrl;\n\t}\n\n\tpublic Long getFlushTimeOut() {\n\t\treturn timeOut;\n\t\t// return flushTimeOut;\n\t}\n\n\tpublic void setFlushTimeOut(Long flushTimeOut) {\n\t\tthis.flushTimeOut = flushTimeOut;\n\t}\n\n}", "public class TreeView {\n\n\tprivate String text;\n\tprivate List<TreeView> nodes;\n\tprivate String icon;\n\tprivate String selectedIcon;\n\tprivate Long labelId;\n\t\n\tpublic String getIcon() {\n\t\treturn icon;\n\t}\n\n\tpublic void setIcon(String icon) {\n\t\tthis.icon = icon;\n\t}\n\n\tpublic String getSelectedIcon() {\n\t\treturn selectedIcon;\n\t}\n\n\tpublic void setSelectedIcon(String selectedIcon) {\n\t\tthis.selectedIcon = selectedIcon;\n\t}\n\n\tpublic Long getLabelId() {\n\t\treturn labelId;\n\t}\n\n\tpublic void setLabelId(Long labelId) {\n\t\tthis.labelId = labelId;\n\t}\n\n\tpublic String getText() {\n\t\treturn text;\n\t}\n\n\tpublic void setText(String text) {\n\t\tthis.text = text;\n\t}\n\n\tpublic List<TreeView> getNodes() {\n\t\treturn nodes;\n\t}\n\n\tpublic void setNodes(List<TreeView> nodes) {\n\t\tthis.nodes = nodes;\n\t}\n\n\tpublic TreeView() {\n\t\tsuper();\n\t}\n\n\tpublic TreeView(String text, List<TreeView> nodes) {\n\t\tsuper();\n\t\tthis.text = text;\n\t\tthis.nodes = nodes;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"TreeView [text=\" + text + \", nodes=\" + nodes + \"]\";\n\t}\n\n}", "@Entity\n@Table(name = \"LABEL\")\npublic class Label implements Serializable {\n\n\t/**\n\t * 标签\n\t */\n\tpublic static final Integer LABLE = 1;\n\t/**\n\t * 开源\n\t */\n\tpublic static final Integer OPEN_SOURCE = 2;\n\t/**\n\t * 问与答\n\t */\n\tpublic static final Integer Q_A = 3;\n\n\t/**\n\t * 默认开启\n\t */\n\tpublic static final Integer LABEL_STATE_DEFAULT = 1;\n\t/**\n\t * 关闭\n\t */\n\tpublic static final Integer LABEL_STATE_CLOSE = 0;\n\n\tprivate static final long serialVersionUID = 2159291991132749505L;\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.AUTO)\n\t@Column(name = \"ID\")\n\tprivate Long id;\n\t@Column(name = \"LABLE_NAME\")\n\tprivate String lableName;\n\t@Column(name = \"PARENT_ID\")\n\tprivate Long parentId;\n\t@Column(name = \"SORT\")\n\tprivate Integer sort;\n\t@Column(name = \"TYPE\")\n\tprivate Integer type;\n\t@Column(name = \"STATUS\")\n\tprivate Integer status;\n\t@JsonSerialize(using = CustomDateSerializer.class)\n\t@Column(name = \"CREATE_TIME\")\n\tprivate Date createTime;\n\t@JsonSerialize(using = CustomDateSerializer.class)\n\t@Column(name = \"UPDATE_TIME\")\n\tprivate Date updateTime;\n\n\t@Transient\n\tprivate List<Label> childs;\n\t\n\tpublic Integer getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic void setStatus(Integer status) {\n\t\tthis.status = status;\n\t}\n\n\tpublic List<Label> getChilds() {\n\t\treturn childs;\n\t}\n\n\tpublic void setChilds(List<Label> childs) {\n\t\tthis.childs = childs;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getLableName() {\n\t\treturn lableName;\n\t}\n\n\tpublic void setLableName(String lableName) {\n\t\tthis.lableName = lableName;\n\t}\n\n\tpublic Long getParentId() {\n\t\treturn parentId;\n\t}\n\n\tpublic void setParentId(Long parentId) {\n\t\tthis.parentId = parentId;\n\t}\n\n\tpublic Integer getSort() {\n\t\treturn sort;\n\t}\n\n\tpublic void setSort(Integer sort) {\n\t\tthis.sort = sort;\n\t}\n\n\tpublic Integer getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(Integer type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic Date getCreateTime() {\n\t\treturn createTime;\n\t}\n\n\tpublic void setCreateTime(Date createTime) {\n\t\tthis.createTime = createTime;\n\t}\n\n\tpublic Date getUpdateTime() {\n\t\treturn updateTime;\n\t}\n\n\tpublic void setUpdateTime(Date updateTime) {\n\t\tthis.updateTime = updateTime;\n\t}\n\n\tpublic Label() {\n\t\tsuper();\n\t}\n\n\tpublic Label(Long id, String lableName, Long parentId, Integer sort, Integer type, Date createTime,\n\t\t\tDate updateTime) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.lableName = lableName;\n\t\tthis.parentId = parentId;\n\t\tthis.sort = sort;\n\t\tthis.type = type;\n\t\tthis.createTime = createTime;\n\t\tthis.updateTime = updateTime;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Label [id=\" + id + \", lableName=\" + lableName + \", parentId=\" + parentId + \", sort=\" + sort + \", type=\"\n\t\t\t\t+ type + \", createTime=\" + createTime + \", updateTime=\" + updateTime + \"]\";\n\t}\n\n}", "public interface LabelDao extends JpaRepository<Label, Long>{\n\n\t@Query(nativeQuery = true, value = \"SELECT * FROM LABEL WHERE PARENT_ID=:parentId ORDER BY SORT ASC,CREATE_TIME DESC\")\n\tpublic List<Label> findLabelByParentId(@Param(\"parentId\") Long parentId);\n\n\t@Modifying(clearAutomatically = true)\n\t@Transactional\n\t@Query(nativeQuery = true, value = \"UPDATE LABEL SET SORT=:sort WHERE ID =:id\")\n\tint updateOrder(@Param(\"id\") Long id, @Param(\"sort\") Integer sort);\n\n\t@Query(nativeQuery = true, value = \"SELECT * FROM LABEL WHERE STATUS=:status AND TYPE IN(:types) ORDER BY SORT ASC\")\n\tpublic List<Label> findLabelByStatusAndType(@Param(\"status\")Integer status, @Param(\"types\")List<Integer> types);\n\n\tpublic List<Label> findLabelByStatus(Integer labelStateDefault);\n\n\tpublic List<Label> findLabelByTypeAndLableName(Integer type, String lableName);\n\n\tpublic List<Label> findLabelByIdNotAndTypeAndLableName(Long id, Integer type, String lableName);\n\t\n}", "@Service\npublic class LabelService {\n\n\t@Autowired\n\tprivate LabelDao labelDao;\n\n\tpublic List<Label> getChildLabelList(ArrayList<Label> labelLists, Long parentId) {\n\n\t\tList<Label> List = labelDao.findLabelByParentId(parentId);\n\t\tfor (Label label : List) {\n\t\t\tlabelLists.add(label);\n\t\t\tgetChildLabelList(labelLists, label.getId());\n\t\t}\n\t\treturn labelLists;\n\t}\n\n\t@Transactional\n\tpublic Integer saveLabel(Label label) {\n\t\t\n\t\tif (label.getId() != null) {\n\t\t\tList<Label> list = labelDao.findLabelByIdNotAndTypeAndLableName(label.getId(), label.getType(), label.getLableName());\n\t\t\tif(list.isEmpty()) {\n\t\t\t\tLabel m = labelDao.findOne(label.getId());\n\t\t\t\tm.setUpdateTime(new Date());\n\t\t\t\tm.setLableName(label.getLableName());\n\t\t\t\tm.setType(label.getType());\n\t\t\t\tlabelDao.save(m);\n\t\t\t\t\n\t\t\t\tif (label.getParentId() != 0) {\n\t\t\t\t\tlabel = labelDao.findOne(label.getParentId());\n\t\t\t\t\tlabel.setUpdateTime(new Date());\n\t\t\t\t\tlabelDao.save(label);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn 1;\n\t\t\t}else {\n\t\t\t\treturn -1;// 相同类型相同名称已存在\n\t\t\t}\n\t\t} else {\n\t\t\tList<Label> list = labelDao.findLabelByTypeAndLableName(label.getType(), label.getLableName());\n\t\t\tif (list.isEmpty()) {\n\t\t\t\tlabel.setCreateTime(new Date());\n\t\t\t\tlabel.setSort(0);\n\t\t\t\tlabel.setStatus(Label.LABEL_STATE_DEFAULT);\n\t\t\t\tlabelDao.save(label);\n\t\t\t\treturn 1;\n\t\t\t} else {\n\t\t\t\treturn -1;// 相同类型相同名称已存在\n\t\t\t}\n\t\t}\n\n\t}\n}" ]
import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.geekhome.common.vo.ErrorCode; import com.geekhome.common.vo.ExecuteResult; import com.geekhome.common.vo.TreeView; import com.geekhome.entity.Label; import com.geekhome.entity.dao.LabelDao; import com.geekhome.entity.service.LabelService;
package com.geekhome.controller; @RestController @RequestMapping("label") public class LabelController { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
LabelService labelService;
5
tsaglam/EcoreMetamodelExtraction
src/main/java/eme/generator/EClassifierGenerator.java
[ "public class ExternalTypeHierarchy extends EPackageHierarchy {\n\n /**\n * Simple constructor, builds the base for the hierarchy.\n * @param root is the root {@link EPackage} of the metamodel.\n * @param properties is the instance of the {@link ExtractionProperties} class.\n */\n public ExternalTypeHierarchy(EPackage root, ExtractionProperties properties) {\n super(generatePackage(properties.get(TextProperty.DATATYPE_PACKAGE), root), properties);\n }\n\n /**\n * Adds an {@link EDataType} to the package hierarchy. Generates the missing packages for the hierarchy.\n * @param dataType is the new {@link EDataType}.\n */\n public void add(EDataType dataType) {\n String[] path = packagePath(dataType.getInstanceTypeName()); // get packages from name\n add(dataType, path); // call super class\n }\n}", "public class ExtractedClass extends ExtractedType {\n private final boolean abstractClass;\n private final boolean throwable;\n\n /**\n * Basic constructor.\n * @param fullName is the full name, containing name and package name.\n * @param abstractClass determines whether the class is abstract or not.\n * @param throwable determines whether the class inherits from {@link java.lang.Throwable}\n */\n public ExtractedClass(String fullName, boolean abstractClass, boolean throwable) {\n super(fullName);\n this.abstractClass = abstractClass;\n this.throwable = throwable;\n }\n\n /**\n * accessor for the super class.\n * @return the super class.\n */\n public ExtractedDataType getSuperClass() {\n return superClass;\n }\n\n /**\n * Checks whether the class is abstract.\n * @return true if class is abstract.\n */\n public boolean isAbstract() {\n return abstractClass;\n }\n\n /**\n * Checks whether the class is throwable.\n * @return true if class is throwable.\n */\n public boolean isThrowable() {\n return throwable;\n }\n\n /**\n * Sets a class as super class.\n * @param superClass is the new super class.\n */\n public void setSuperClass(ExtractedDataType superClass) {\n this.superClass = superClass;\n }\n}", "public class ExtractedEnum extends ExtractedType {\n private final List<ExtractedEnumConstant> constants;\n\n /**\n * Basic constructor.\n * @param fullName is the full name, containing name and package name.\n */\n public ExtractedEnum(String fullName) {\n super(fullName);\n constants = new LinkedList<ExtractedEnumConstant>();\n }\n\n /**\n * Adds a enumeral to the enum\n * @param constant is the new value.\n */\n public void addConstant(ExtractedEnumConstant constant) {\n constants.add(constant);\n }\n\n /**\n * accessor for the enumerals of the enumeration.\n * @return the enumerals in a List.\n */\n public List<ExtractedEnumConstant> getConstants() {\n return constants;\n }\n}", "public class ExtractedEnumConstant {\n private final String name;\n\n /**\n * Basic constructor. Sets the name.\n * @param name is the name of the enumeral.\n */\n public ExtractedEnumConstant(String name) {\n this.name = name;\n }\n\n /**\n * Accessor for the name of the enumeral.\n * @return the name.\n */\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n return name;\n }\n}", "public class ExtractedInterface extends ExtractedType {\n\n /**\n * Basic constructor.\n * @param fullName is the full name, containing name and package name.\n */\n public ExtractedInterface(String fullName) {\n super(fullName);\n }\n}", "public abstract class ExtractedType extends ExtractedElement {\n protected final List<ExtractedField> fields;\n protected final List<ExtractedMethod> methods;\n protected String outerType;\n protected ExtractedDataType superClass;\n protected final List<ExtractedDataType> superInterfaces;\n protected List<ExtractedTypeParameter> typeParameters;\n\n /**\n * Basic constructor.\n * @param fullName is the full name, containing name and package name.\n */\n public ExtractedType(String fullName) {\n super(fullName);\n superInterfaces = new LinkedList<ExtractedDataType>();\n methods = new LinkedList<ExtractedMethod>();\n fields = new LinkedList<ExtractedField>();\n typeParameters = new LinkedList<ExtractedTypeParameter>();\n }\n\n /**\n * Adds an {@link ExtractedField} to the type.\n * @param field is the new {@link ExtractedField}.\n */\n public void addField(ExtractedField field) {\n fields.add(field);\n }\n\n /**\n * Adds an interface as super interface.\n * @param superInterface is the new super interface.\n */\n public void addInterface(ExtractedDataType superInterface) {\n superInterfaces.add(superInterface);\n }\n\n /**\n * Adds a {@link ExtractedMethod} to the type.\n * @param method is the new {@link ExtractedMethod}.\n */\n public void addMethod(ExtractedMethod method) {\n methods.add(method);\n }\n\n /**\n * @see java.lang.Object#equals(java.lang.Object)\n */\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof ExtractedType) { // same class\n return getFullName().equals(((ExtractedType) obj).getFullName()); // same full name\n }\n return false;\n }\n\n /**\n * accessor for the list of {@link ExtractedField}s.\n * @return the list of attributes.\n */\n public List<ExtractedField> getFields() {\n return fields;\n }\n\n /**\n * accessor for the list of {@link ExtractedMethod}s.\n * @return the list of methods.\n */\n public List<ExtractedMethod> getMethods() {\n return methods;\n }\n\n /**\n * Accessor for the name of the types outer type.\n * @return the outer type name or null if it is not a inner type.\n */\n public String getOuterType() {\n return outerType;\n }\n\n /**\n * accessor for the list of super interfaces.\n * @return the list of super interfaces.\n */\n public List<ExtractedDataType> getSuperInterfaces() {\n return superInterfaces;\n }\n\n /**\n * accessor for the list of generic type parameters ({@link ExtractedTypeParameter}).\n * @return the list of generic type parameters.\n */\n public List<ExtractedTypeParameter> getTypeParameters() {\n return typeParameters;\n }\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + ((getFullName() == null) ? 0 : getFullName().hashCode());\n return result;\n }\n\n /**\n * Method checks whether the type is a inner type.\n * @return true if it is a inner type.\n */\n public boolean isInnerType() {\n return outerType != null;\n }\n\n /**\n * Mutator for the name of the types outer type.\n * @param outerType is the name.\n */\n public void setOuterType(String outerType) {\n this.outerType = outerType;\n }\n\n /**\n * Sets the generic type parameters.\n * @param typeParameters is the list of {@link ExtractedTypeParameter}s.\n */\n public void setTypeParameters(List<ExtractedTypeParameter> typeParameters) {\n this.typeParameters = typeParameters;\n }\n}", "public class IntermediateModel {\n private static final Logger logger = LogManager.getLogger(IntermediateModel.class.getName());\n private final Set<ExtractedType> externalTypes;\n private final Set<ExtractedPackage> packages;\n private final String projectName;\n private ExtractedPackage rootPackage;\n private final Set<ExtractedType> types;\n\n /**\n * Basic constructor.\n * @param projectName is the name of the project the model was extracted from.\n */\n public IntermediateModel(String projectName) {\n packages = new LinkedHashSet<ExtractedPackage>();\n types = new LinkedHashSet<ExtractedType>();\n externalTypes = new LinkedHashSet<ExtractedType>();\n this.projectName = projectName;\n }\n\n /**\n * Adds a new {@link ExtractedPackage} to the intermediate model if it is not\n * already added.\n * @param newPackage is the new {@link ExtractedPackage} to add.\n */\n public void add(ExtractedPackage newPackage) {\n if (packages.add(newPackage)) {\n if (rootPackage == null) { // if it is the first package\n rootPackage = newPackage; // add as root\n newPackage.setAsRoot(); // mark as root\n } else {\n getPackage(newPackage.getParentName()).add(newPackage);\n }\n }\n }\n\n /**\n * Adds a new {@link ExtractedType} to the intermediate model if it is not\n * already added. Finds parent {@link ExtractedPackage} automatically.\n * @param type is the new {@link ExtractedType} to add.\n */\n public void add(ExtractedType type) {\n addTo(type, getPackage(type.getParentName()));\n }\n\n /**\n * Adds a new external {@link ExtractedType} to the intermediate model.\n * @param type is the new external type to add.\n */\n public void addExternal(ExtractedType type) {\n externalTypes.add(type);\n }\n\n /**\n * Adds a new {@link ExtractedType} to the intermediate model and to a specific\n * parent {@link ExtractedPackage} if it is not already added.\n * @param type is the new {@link ExtractedType} to add.\n * @param parent is the parent {@link ExtractedPackage}.\n */\n public void addTo(ExtractedType type, ExtractedPackage parent) {\n if (!type.getParentName().contains(parent.getFullName())) {\n throw new IllegalArgumentException(\"Invalid parent declaration in \" + type + \" to \" + parent);\n } else if (types.add(type)) { // add class to list of classes.\n parent.add(type);\n }\n }\n\n /**\n * Checks whether the model contains an {@link ExtractedType} whose full name\n * matches a given full name.\n * @param fullName is the given full name.\n * @return true if it contains the {@link ExtractedType}, false if not.\n */\n public boolean contains(String fullName) {\n return getType(fullName) != null;\n }\n\n /**\n * Checks whether the model contains an external {@link ExtractedType} whose\n * full name matches a given full name.\n * @param fullName is the given full name.\n * @return true if it contains the external {@link ExtractedType}, false if not.\n */\n public boolean containsExternal(String fullName) {\n return getExternalType(fullName) != null;\n }\n\n /**\n * Returns the external {@link ExtractedType} of the intermediate model whose\n * full name matches the given full name.\n * @param fullName is the given full name.\n * @return the external {@link ExtractedType} with the matching name or null if\n * the name is not found.\n */\n public ExtractedType getExternalType(String fullName) {\n return getTypeFrom(fullName, externalTypes);\n }\n\n /**\n * Returns all the external {@link ExtractedType}s of the intermediate model.\n * @return the set of external {@link ExtractedType}s.\n */\n public Set<ExtractedType> getExternalTypes() {\n return externalTypes;\n }\n\n /**\n * Returns the {@link ExtractedPackage} of the intermediate model whose full\n * name matches the given full name.\n * @param fullName is the given full name.\n * @return the {@link ExtractedPackage} with the matching name.\n * @throws RuntimeException if the {@link ExtractedPackage} is not found. This\n * means this method cannot be used to check whether there is a certain package\n * in the model. It is explicitly used to find an existing package.\n */\n public ExtractedPackage getPackage(String fullName) {\n for (ExtractedPackage aPackage : packages) { // for all packages\n if (aPackage.getFullName().equals(fullName)) { // if parent\n return aPackage; // can only have on parent\n }\n }\n throw new IllegalArgumentException(\"Could not find package \" + fullName);\n }\n\n /**\n * accessor for the name of the project.\n * @return the name.\n */\n public String getProjectName() {\n return projectName;\n }\n\n /**\n * accessor for the root {@link ExtractedPackage} of the model.\n * @return the root package.\n */\n public ExtractedPackage getRoot() {\n return rootPackage;\n }\n\n /**\n * Returns the {@link ExtractedType} of the intermediate model whose full name\n * matches the given full name.\n * @param fullName is the given full name.\n * @return the {@link ExtractedType} with the matching name or null if the name\n * is not found.\n */\n public ExtractedType getType(String fullName) {\n return getTypeFrom(fullName, types);\n }\n\n /**\n * Checks whether the model contains a selected {@link ExtractedType} whose full\n * name matches a given full name.\n * @param fullName is the given full name.\n * @return true if it contains the {@link ExtractedType} and it is selected,\n * false if it is not selected or the model does not contain such type.\n */\n public boolean isTypeSelected(String fullName) {\n return contains(fullName) && getType(fullName).isSelected();\n }\n\n /**\n * Prints the model.\n */\n public void print() {\n logger.info(toString());\n logger.info(\" with packages \" + packages.toString());\n logger.info(\" with types \" + types.toString());\n logger.info(\" with external types \" + externalTypes.toString());\n }\n\n /**\n * Sorts the content of the root {@link ExtractedPackage}. Sorts its types, its\n * subpackages and all the content of every subpackage.\n */\n public void sort() {\n rootPackage.sort();\n }\n\n @Override\n public String toString() {\n return \"IntermediateModel of \" + projectName + \": [Packages=\" + packages.size() + \", Types=\" + types.size() + \", ExternalTypes=\"\n + externalTypes.size() + \"]\";\n }\n\n /**\n * Finds {@link ExtractedType} from set of {@link ExtractedType}s by its full\n * name.\n * @param fullName is full name.\n * @param typeSet is the set of {@link ExtractedType}s.\n * @return the {@link ExtractedType} with the matching name or null if the name\n * is not found.\n */\n private ExtractedType getTypeFrom(String fullName, Set<ExtractedType> typeSet) {\n for (ExtractedType type : typeSet) { // for all packages\n if (type.getFullName().equals(fullName)) { // if parent\n return type; // can only have on parent\n }\n }\n return null;\n }\n}", "public class ExtractedDataType {\n private final int arrayDimension;\n private String fullTypeName;\n private List<ExtractedDataType> genericArguments;\n private String typeName;\n private WildcardStatus wildcardStatus;\n\n /**\n * Basic constructor, takes the full and the simple name.\n * @param fullName is the full name of the data type, like \"java.lang.String\",\n * \"java.util.list\" and \"char\".\n * @param arrayDimension is the amount of array dimensions, should be 0 if it is\n * not an array.\n */\n public ExtractedDataType(String fullName, int arrayDimension) {\n this.fullTypeName = fullName;\n this.arrayDimension = arrayDimension;\n genericArguments = new LinkedList<ExtractedDataType>();\n wildcardStatus = WildcardStatus.NO_WILDCARD;\n buildNames(); // build full and simple name\n }\n\n /**\n * accessor for the array dimension.\n * @return the array dimension, 0 if the type is not an array.\n */\n public int getArrayDimension() {\n return arrayDimension;\n }\n\n /**\n * accessor for the full array type name, which includes the packages but NOT\n * array brackets.\n * @return the full type name.\n */\n public String getFullArrayType() { // TODO (MEDIUM) remove this and move [] naming to generator.\n if (isArray()) {\n return fullTypeName.substring(0, fullTypeName.length() - 2 * arrayDimension);\n }\n return fullTypeName;\n }\n\n /**\n * accessor for the full type name, which includes the packages and the array\n * brackets.\n * @return the full type name.\n */\n public String getFullType() {\n return fullTypeName;\n }\n\n /**\n * accessor for the generic arguments.\n * @return the List of generic arguments of this data type.\n */\n public List<ExtractedDataType> getGenericArguments() {\n return genericArguments;\n }\n\n /**\n * accessor for the simple type name, which is the basic name. If it is an array\n * it is the special array name which does not match the Java code (e.g.\n * intArray2D).\n * @return the simple type name or, if it is an array type, the array type name.\n */\n public String getType() {\n return typeName;\n }\n\n /**\n * Generates a type string for this {@link ExtractedDataType}. It contains\n * information about the data type and its generic arguments. For example\n * \"Map<String, Object>\".\n * @return the type string.\n */\n public String getTypeString() {\n String result = fullTypeName;\n if (!genericArguments.isEmpty()) {\n result += '<';\n for (ExtractedDataType argument : genericArguments) {\n result += argument.getFullType() + \", \";\n }\n result = result.substring(0, result.length() - 2) + '>';\n }\n return result;\n }\n\n /**\n * accessor for the wild card status.\n * @return the wild card status.\n */\n public WildcardStatus getWildcardStatus() {\n return wildcardStatus;\n }\n\n /**\n * Checks whether the data type is an array.\n * @return true if it is an array.\n */\n public boolean isArray() {\n return arrayDimension > 0;\n }\n\n /**\n * Checks whether the data type is a generic type.\n * @return true if it is generic.\n */\n public boolean isGeneric() {\n return !genericArguments.isEmpty();\n }\n\n /**\n * Checks whether the data type is a list type, which means it is of type\n * {@link List}.\n * @return true if it is.\n */\n public boolean isListType() {\n return List.class.getName().equals(fullTypeName) && genericArguments.size() == 1;\n }\n\n /**\n * Checks whether the data type is an wild card.\n * @return true if it is an wild card.\n */\n public boolean isWildcard() {\n return wildcardStatus != WildcardStatus.NO_WILDCARD;\n }\n\n /**\n * mutator for the generic arguments.\n * @param genericArguments is the list of generic arguments.\n */\n public void setGenericArguments(List<ExtractedDataType> genericArguments) {\n this.genericArguments = genericArguments;\n }\n\n /**\n * Sets the wild card status of the data type.\n * @param status is the status to set.\n */\n public void setWildcardStatus(WildcardStatus status) {\n wildcardStatus = status;\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName() + \"(\" + getTypeString() + \")\";\n }\n\n /**\n * Builds the full and simple name from the initial full name. The full name has\n * to be set.\n */\n private void buildNames() {\n typeName = fullTypeName.contains(\".\") ? fullTypeName.substring(fullTypeName.lastIndexOf('.') + 1) : fullTypeName;\n typeName = isArray() ? typeName + \"Array\" : typeName; // add \"Array\" if is array\n typeName = arrayDimension > 1 ? typeName + arrayDimension + \"D\" : typeName; // add dimension\n for (int i = 0; i < arrayDimension; i++) { // adjust array names to dimension\n this.fullTypeName += \"[]\";\n }\n }\n}" ]
import java.util.HashMap; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EGenericType; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcoreFactory; import eme.generator.hierarchies.ExternalTypeHierarchy; import eme.model.ExtractedClass; import eme.model.ExtractedEnum; import eme.model.ExtractedEnumConstant; import eme.model.ExtractedInterface; import eme.model.ExtractedType; import eme.model.IntermediateModel; import eme.model.datatypes.ExtractedDataType;
package eme.generator; /** * Generator class for Ecore classifiers ({@link EClassifier}s). * @author Timur Saglam */ public class EClassifierGenerator { private static final Logger logger = LogManager.getLogger(EClassifierGenerator.class.getName()); private final Map<EClass, ExtractedType> bareEClasses; private final Map<String, EClassifier> eClassifierMap; private final EcoreFactory ecoreFactory; private final ExternalTypeHierarchy externalTypes; private final EMemberGenerator memberGenerator; private final IntermediateModel model; private final SelectionHelper selector; private final EDataTypeGenerator typeGenerator; /** * Basic constructor. * @param model is the {@link IntermediateModel} which is used to extract a metamodel. * @param root is the root {@link EPackage} of the metamodel. * @param selector is the {@link SelectionHelper} instance. */ public EClassifierGenerator(IntermediateModel model, EPackage root, SelectionHelper selector) { this.model = model; this.selector = selector; ecoreFactory = EcoreFactory.eINSTANCE; eClassifierMap = new HashMap<String, EClassifier>(); bareEClasses = new HashMap<EClass, ExtractedType>(); externalTypes = new ExternalTypeHierarchy(root, selector.getProperties()); typeGenerator = new EDataTypeGenerator(model, eClassifierMap, externalTypes); memberGenerator = new EMemberGenerator(typeGenerator, selector, eClassifierMap); } /** * Completes the generation of the {@link EClassifier} objects. Adds methods and attributes to {@link EClass} * objects, adds type parameters and super interfaces and sorts the external types. */ public void completeEClassifiers() { for (EClass eClass : bareEClasses.keySet()) { // for every generated EClass ExtractedType extractedType = bareEClasses.get(eClass); typeGenerator.addTypeParameters(eClass, extractedType); // IMPORTANT: call after EClassifiers are created. memberGenerator.addFields(extractedType, eClass); // add attributes memberGenerator.addOperations(extractedType, eClass); // add methods addSuperInterfaces(extractedType, eClass); // IMPORTANT: needs to be called after type parameters are built } externalTypes.sort(); } /** * Generates a dummy {@link EClassifier}, which is a simple {@link EClass}. * @param name is the name of the dummy. * @return the dummy {@link EClassifier}, which is an empty {@link EClass}. */ public EClass generateDummy(String name) { EClass dummy = ecoreFactory.createEClass(); dummy.setName(name); return dummy; } /** * Generates an {@link EClassifier} from an ExtractedType, if the type was not already generated. * @param type is the {@link ExtractedType}. * @return the {@link EClassifier}, which is either an {@link EClass}, an {@link ExtractedInterface} or an * {@link EEnum}. */ public EClassifier generateEClassifier(ExtractedType type) { String fullName = type.getFullName(); if (eClassifierMap.containsKey(fullName)) { // if already created: return eClassifierMap.get(fullName); // just return from map. } EClassifier eClassifier = null; // TODO (LOW) Use visitor pattern. if (type.getClass() == ExtractedInterface.class) { // build interface: eClassifier = generateEClass(type, true, true); } else if (type.getClass() == ExtractedClass.class) { // build class: EClass eClass = generateEClass(type, ((ExtractedClass) type).isAbstract(), false); addSuperClass((ExtractedClass) type, eClass); // IMPORTANT: needs to be called after type params are built eClassifier = eClass;
} else if (type.getClass() == ExtractedEnum.class) { // build enum:
2
lazyparser/xbot_head
app/src/main/java/cn/ac/iscas/xlab/droidfacedog/mvp/commentary/CommentaryFragment.java
[ "public class ImagePreviewAdapter extends\n RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n // Store the context for later use\n private Context context;\n\n private ArrayList<Bitmap> bitmaps;\n private int check = 0;\n\n private ViewHolder.OnItemClickListener onItemClickListener;\n\n // Pass in the context and menuModels array into the constructor\n public ImagePreviewAdapter(Context context, ArrayList<Bitmap> bitmaps, ViewHolder.OnItemClickListener onItemClickListener) {\n\n this.context = context;\n this.bitmaps = bitmaps;\n this.onItemClickListener = onItemClickListener;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(context).\n inflate(R.layout.item_image_preview, viewGroup, false);\n // Return a new holder instance\n return new ViewHolder(itemView, onItemClickListener);\n }\n\n @Override\n public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int i) {\n final ViewHolder holder = (ViewHolder) viewHolder;\n if (i == check) {\n holder.layoutCheck.setVisibility(View.VISIBLE);\n } else {\n holder.layoutCheck.setVisibility(View.GONE);\n }\n\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, metrics);\n\n Bitmap bmp = Bitmap.createScaledBitmap(bitmaps.get(i), size, size, false);\n holder.imgPreview.setImageBitmap(bmp);\n }\n\n @Override\n public int getItemCount() {\n return bitmaps.size();\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n\n public void add(Bitmap bitmap) {\n\n insert(bitmap, bitmaps.size());\n }\n\n public void insert(Bitmap bitmap, int position) {\n bitmaps.add(position, bitmap);\n notifyItemInserted(position);\n }\n\n public void remove(int position) {\n bitmaps.remove(position);\n notifyDataSetChanged();\n }\n\n public void clearAll() {\n for (int i = 0; i < bitmaps.size(); i++) {\n if (bitmaps.get(i) != null)\n bitmaps.get(i).recycle();\n }\n bitmaps.clear();\n check = 0;\n notifyDataSetChanged();\n }\n\n public void addAll(ArrayList<Bitmap> bitmaps) {\n int startIndex = bitmaps.size();\n this.bitmaps.addAll(startIndex, bitmaps);\n notifyItemRangeInserted(startIndex, bitmaps.size());\n }\n\n public int getCheck() {\n return check;\n }\n\n public void setCheck(int check) {\n this.check = check;\n }\n\n\n // Provide a direct reference to each of the views within a data item\n // Used to cache the views within the item layout for fast access\n public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n private final OnItemClickListener onItemClickListenerListener;\n // Your holder should contain a member variable\n // for any view that will be set as you render a row\n public RelativeLayout layoutCheck;\n public ImageView imgPreview;\n\n // We also create a constructor that accepts the entire item row\n // and does the view lookups to find each subview\n public ViewHolder(View itemView, OnItemClickListener onItemClickListenerListener) {\n super(itemView);\n this.layoutCheck = (RelativeLayout) itemView.findViewById(R.id.layoutCheck);\n this.imgPreview = (ImageView) itemView.findViewById(R.id.imagePreview);\n this.onItemClickListenerListener = onItemClickListenerListener;\n itemView.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n v.setSelected(true);\n onItemClickListenerListener.onClick(v, getAdapterPosition());\n }\n\n public interface OnItemClickListener {\n void onClick(View v, int position);\n }\n }\n}", "public class RosConnectionService extends Service{\n\n public static final String TAG = \"RosConnectionService\";\n public static final String SUBSCRIBE_ROBOT_STATUS = \"/robot_status\";\n public static final String SUBSCRIBE_MUSEUM_POSITION = \"/museum_pos\";\n \n //解说词播放状态\n public static final String PUBLISH_TOPIC_AUDIO_STATUS = \"/pad_audio_status\";\n //签到状态\n public static final String PUBLISH_TOPIC_SIGN_COMPLETION = \"/pad_sign_completion\";\n\n public Binder proxy = new ServiceBinder();\n private ROSBridgeClient rosBridgeClient;\n\n private boolean isConnected = false;\n private Timer rosConnectionTimer;\n private TimerTask connectionTask;\n\n\n public class ServiceBinder extends Binder {\n public boolean isConnected(){\n return isConnected;\n }\n\n public void publishSignStatus(SignStatus signStatus){\n JSONObject body = new JSONObject();\n if (isConnected) {\n JSONObject jsonMsg = new JSONObject();\n try {\n jsonMsg.put(\"complete\", signStatus.isComplete());\n jsonMsg.put(\"success\", signStatus.isRecogSuccess());\n\n body.put(\"op\", \"publish\");\n body.put(\"topic\", PUBLISH_TOPIC_SIGN_COMPLETION);\n body.put(\"msg\", jsonMsg);\n rosBridgeClient.send(body.toString());\n Log.i(TAG, \"publish 'pad_sign_completion' topic to Ros Server :\" + body.toString());\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n public void publishAudioStatus(AudioStatus audioStatus) {\n JSONObject body = new JSONObject();\n if (isConnected()) {\n JSONObject jsonMsg = new JSONObject();\n try {\n jsonMsg.put(\"id\", audioStatus.getId());\n jsonMsg.put(\"iscomplete\", audioStatus.isComplete());\n\n body.put(\"op\", \"publish\");\n body.put(\"topic\", PUBLISH_TOPIC_AUDIO_STATUS);\n body.put(\"msg\", jsonMsg);\n rosBridgeClient.send(body.toString());\n Log.i(TAG, \"publish 'pad_audio_status' topic to Ros Server :\" + body.toString());\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n }\n\n //订阅某个topic或者取消订阅某个topic\n public void manipulateTopic(String topic, boolean isSubscribe) {\n if (isConnected()) {\n //订阅\n if (isSubscribe) {\n JSONObject subscribeMuseumPos = new JSONObject();\n try {\n subscribeMuseumPos.put(\"op\", \"subscribe\");\n subscribeMuseumPos.put(\"topic\", topic);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n rosBridgeClient.send(subscribeMuseumPos.toString());\n\n } else {//取消订阅\n JSONObject subscribeMuseumPos = new JSONObject();\n try {\n subscribeMuseumPos.put(\"op\", \"unsubscribe\");\n subscribeMuseumPos.put(\"topic\", topic);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n rosBridgeClient.send(subscribeMuseumPos.toString());\n }\n }\n }\n\n public void disConnect() {\n connectionTask.cancel();\n rosBridgeClient.disconnect();\n// onDestroy();\n }\n }\n\n //onCreate()会自动触发Ros服务器的连接\n @Override\n public void onCreate() {\n super.onCreate();\n Log.i(TAG, \"RosConnService--onCreate()\");\n rosConnectionTimer = new Timer();\n connectionTask = new TimerTask() {\n @Override\n public void run() {\n if (!isConnected) {\n String rosURL = \"ws://\" + Config.ROS_SERVER_IP + \":\" + Config.ROS_SERVER_PORT;\n Log.v(TAG, \"Connecting to ROS Server: \" + rosURL);\n rosBridgeClient = new ROSBridgeClient(rosURL);\n boolean conneSucc = rosBridgeClient.connect(new ROSClient.ConnectionStatusListener() {\n @Override\n public void onConnect() {\n rosBridgeClient.setDebug(true);\n Log.i(TAG, \"Ros ConnectionStatusListener--onConnect\");\n }\n\n @Override\n public void onDisconnect(boolean normal, String reason, int code) {\n Log.v(TAG, \"Ros ConnectionStatusListener--disconnect\");\n }\n\n @Override\n public void onError(Exception ex) {\n ex.printStackTrace();\n Log.i(TAG, \"Ros ConnectionStatusListener--ROS communication error\");\n }\n });\n isConnected = conneSucc;\n Intent broadcastIntent = new Intent(MainActivity.ROS_RECEIVER_INTENTFILTER);\n Bundle data = new Bundle();\n if (!isConnected) {\n data.putInt(\"ros_conn_status\", MainActivity.CONN_ROS_SERVER_ERROR);\n broadcastIntent.putExtras(data);\n sendBroadcast(broadcastIntent);\n } else{\n data.putInt(\"ros_conn_status\", MainActivity.CONN_ROS_SERVER_SUCCESS);\n broadcastIntent.putExtras(data);\n sendBroadcast(broadcastIntent);\n }\n } else {\n //如果连接成功则取消该定时任务\n cancel();\n }\n\n }\n };\n\n startRosConnectionTimer();\n //注册Eventbus\n EventBus.getDefault().register(this);\n }\n\n @Override\n public void onRebind(Intent intent) {\n Log.i(TAG, TAG + \" -- onRebind()\");\n super.onRebind(intent);\n }\n\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Log.i(TAG, \"RosConnService--onStartCommand()\");\n return super.onStartCommand(intent, flags, startId);\n }\n\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n Log.i(TAG, \"RosConnectionService onBind()\");\n\n return proxy;\n }\n\n //订阅某个topic后,接收到Ros服务器返回的message,回调此方法\n public void onEvent(PublishEvent event) {\n //topic的名称\n String topicName = event.name;\n Log.i(TAG, \"onEvent:\" + event.msg);\n //Topic为RobotStatus\n if (topicName.equals(SUBSCRIBE_ROBOT_STATUS)) {\n String msg = event.msg;\n JSONObject msgInfo;\n try {\n msgInfo = new JSONObject(msg);\n int id = msgInfo.getInt(\"id\");\n boolean isMoving = msgInfo.getBoolean(\"ismoving\");\n RobotStatus robotStatus = new RobotStatus(id, isMoving);\n EventBus.getDefault().post(robotStatus);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n } else if (topicName.equals(SUBSCRIBE_MUSEUM_POSITION)) {\n String msg = event.msg;\n try {\n JSONObject msgInfo = new JSONObject(msg);\n int id = msgInfo.getInt(\"id\");\n boolean isMoving = msgInfo.getBoolean(\"ismoving\");\n EventBus.getDefault().post(new MuseumPosition(id, isMoving));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n @Override\n public void onDestroy() {\n Log.i(TAG, \"RosConnService--onDestroy()\");\n EventBus.getDefault().unregister(this);\n super.onDestroy();\n }\n\n public void startRosConnectionTimer() {\n if (isConnected) {\n return;\n } else {\n rosConnectionTimer.schedule(connectionTask,0,3000);\n }\n }\n\n}", "public class FaceResult extends Object {\n\n private PointF midEye;\n private float eyeDist;\n private float confidence;\n private float pose;\n private int id;\n private long time;\n\n public FaceResult() {\n id = 0;\n midEye = new PointF(0.0f, 0.0f);\n eyeDist = 0.0f;\n confidence = 0.4f;\n pose = 0.0f;\n time = System.currentTimeMillis();\n }\n\n\n public void setFace(int id, PointF midEye, float eyeDist, float confidence, float pose, long time) {\n set(id, midEye, eyeDist, confidence, pose, time);\n }\n\n public void clear() {\n set(0, new PointF(0.0f, 0.0f), 0.0f, 0.4f, 0.0f, System.currentTimeMillis());\n }\n\n public synchronized void set(int id, PointF midEye, float eyeDist, float confidence, float pose, long time) {\n this.id = id;\n this.midEye.set(midEye);\n this.eyeDist = eyeDist;\n this.confidence = confidence;\n this.pose = pose;\n this.time = time;\n }\n\n public float eyesDistance() {\n return eyeDist;\n }\n\n public void setEyeDist(float eyeDist) {\n this.eyeDist = eyeDist;\n }\n\n public void getMidPoint(PointF pt) {\n pt.set(midEye);\n }\n\n public PointF getMidEye() {\n return midEye;\n }\n\n public void setMidEye(PointF midEye) {\n this.midEye = midEye;\n }\n\n public float getConfidence() {\n return confidence;\n }\n\n public void setConfidence(float confidence) {\n this.confidence = confidence;\n }\n\n public float getPose() {\n return pose;\n }\n\n public void setPose(float pose) {\n this.pose = pose;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public long getTime() {\n return time;\n }\n\n public void setTime(long time) {\n this.time = time;\n }\n\n @Override\n public String toString() {\n return \"FaceResult{\" +\n \"midEye=\" + midEye +\n \", eyeDist=\" + eyeDist +\n \", confidence=\" + confidence +\n \", pose=\" + pose +\n \", id=\" + id +\n \", time=\" + time +\n '}';\n }\n}", "public class ImageUtils {\n\n public static int calculateInSampleSize(\n BitmapFactory.Options options, int reqWidth, int reqHeight) {\n // Raw height and width of image\n final int height = options.outHeight;\n final int width = options.outWidth;\n int inSampleSize = 1;\n\n if (height > reqHeight || width > reqWidth) {\n\n final int halfHeight = height / 2;\n final int halfWidth = width / 2;\n\n // Calculate the largest inSampleSize value that is a power of 2 and keeps both\n // height and width larger than the requested height and width.\n while ((halfHeight / inSampleSize) > reqHeight\n && (halfWidth / inSampleSize) > reqWidth) {\n inSampleSize *= 2;\n }\n }\n return inSampleSize;\n }\n\n //Get Path Image file\n public final static String getRealPathFromURI(Context context, Uri contentUri) {\n Cursor cursor = null;\n try {\n String[] proj = {MediaStore.Images.Media.DATA};\n cursor = context.getContentResolver().query(contentUri, proj, null, null, null);\n int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\n cursor.moveToFirst();\n return cursor.getString(column_index);\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n\n //Rotate Bitmap\n public final static Bitmap rotate(Bitmap b, float degrees) {\n if (degrees != 0 && b != null) {\n Matrix m = new Matrix();\n m.setRotate(degrees, (float) b.getWidth() / 2,\n (float) b.getHeight() / 2);\n\n Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),\n b.getHeight(), m, true);\n if (b != b2) {\n b.recycle();\n b = b2;\n }\n\n }\n return b;\n }\n\n\n public static Bitmap getBitmap(String filePath, int width, int height) {\n final BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(filePath, options);\n options.inSampleSize = ImageUtils.calculateInSampleSize(options, width, height);\n options.inJustDecodeBounds = false;\n options.inPreferredConfig = Bitmap.Config.RGB_565;\n\n Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);\n\n if (bitmap != null) {\n try {\n ExifInterface ei = new ExifInterface(filePath);\n int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);\n switch (orientation) {\n case ExifInterface.ORIENTATION_ROTATE_90:\n bitmap = ImageUtils.rotate(bitmap, 90);\n break;\n case ExifInterface.ORIENTATION_ROTATE_180:\n bitmap = ImageUtils.rotate(bitmap, 180);\n break;\n case ExifInterface.ORIENTATION_ROTATE_270:\n bitmap = ImageUtils.rotate(bitmap, 270);\n break;\n default:\n break;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return bitmap;\n }\n\n\n public static Bitmap cropBitmap(Bitmap bitmap, Rect rect) {\n int w = rect.right - rect.left;\n int h = rect.bottom - rect.top;\n Bitmap ret = Bitmap.createBitmap(w, h, bitmap.getConfig());\n Canvas canvas = new Canvas(ret);\n canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);\n bitmap.recycle();\n return ret;\n }\n\n\n public static Bitmap cropFace(FaceResult face, Bitmap bitmap, int rotate) {\n Bitmap bmp;\n\n float eyesDis = face.eyesDistance();\n PointF mid = new PointF();\n face.getMidPoint(mid);\n\n Rect rect = new Rect(\n (int) (mid.x - eyesDis * 1.20f),\n (int) (mid.y - eyesDis * 0.55f),\n (int) (mid.x + eyesDis * 1.20f),\n (int) (mid.y + eyesDis * 1.85f));\n\n Bitmap.Config config = Bitmap.Config.RGB_565;\n if (bitmap.getConfig() != null) config = bitmap.getConfig();\n bmp = bitmap.copy(config, true);\n\n switch (rotate) {\n case 90:\n bmp = ImageUtils.rotate(bmp, 90);\n break;\n case 180:\n bmp = ImageUtils.rotate(bmp, 180);\n break;\n case 270:\n bmp = ImageUtils.rotate(bmp, 270);\n break;\n }\n\n bmp = ImageUtils.cropBitmap(bmp, rect);\n return bmp;\n }\n\n\n public static RectF getPreviewFaceRectF(PointF pointF,float eyeDistance) {\n return new RectF(\n (int) (pointF.x - eyeDistance * 1.20f),\n (int) (pointF.y - eyeDistance * 1.7f),\n (int) (pointF.x + eyeDistance * 1.20f),\n (int) (pointF.y + eyeDistance * 1.9f));\n }\n\n public static RectF getCheckFaceRectF(PointF pointF, float eyeDistance) {\n return new RectF(\n (pointF.x - eyeDistance * 1.5f),\n (pointF.y - eyeDistance * 1.9f),\n (pointF.x + eyeDistance * 1.5f),\n (pointF.y + eyeDistance * 2.2f));\n }\n\n public static RectF getDrawFaceRectF(PointF mid,float eyesDis,float scaleX,float scaleY) {\n return new RectF(\n (mid.x - eyesDis * 1.1f) * scaleX,\n (mid.y - eyesDis * 1.3f) * scaleY,\n (mid.x + eyesDis * 1.1f) * scaleX,\n (mid.y + eyesDis * 1.7f) * scaleY);\n\n }\n\n //将人脸Bitmap转为Base64编码,以发送给优图服务器\n public static String encodeBitmapToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality)\n {\n ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();\n image.compress(compressFormat, quality, byteArrayOS);\n return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);\n }\n\n //将从优图服务器获取到的base64 String解码为Bitmap\n public static Bitmap decodeBase64ToBitmap(String base64Str){\n byte[] bitmapBytes = Base64.decode(base64Str, Base64.DEFAULT);\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);\n\n //获取到来自服务器的原始图像的宽高\n int width = options.outWidth;\n int height = options.outHeight;\n// options.inSampleSize = calculateInSampleSize(options,width/3,height/3);\n options.inSampleSize = 2;\n options.inJustDecodeBounds = false;\n\n return BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length,options);\n }\n\n}", "public class Util {\n\n //将十六进制的字符串还原为utf-8中文名\n public static String hexStringToString(String s) {\n if (s == null || s.equals(\"\")) {\n return null;\n }\n s = s.replace(\" \", \"\");\n byte[] baKeyword = new byte[s.length() / 2];\n for (int i = 0; i < baKeyword.length; i++) {\n try {\n baKeyword[i] = (byte) (0xff & Integer.parseInt(\n s.substring(i * 2, i * 2 + 2), 16));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n try {\n s = new String(baKeyword, \"utf-8\");\n } catch (Exception e1) {\n e1.printStackTrace();\n }\n return s;\n }\n\n //sizes是支持的size集合,width和height是期望展示的图像宽高\n public static Size getPreferredPreviewSize(Size[] sizes, int width, int height) {\n List<Size> collectorSizes = new ArrayList<>();\n for (Size option : sizes) {\n //找到长宽都大于指定宽高的size,把这些size放在List中\n if (width > height) {\n if (option.getWidth() > width && option.getHeight() > height) {\n collectorSizes.add(option);\n }\n } else {\n if (option.getHeight() > width && option.getWidth() > height) {\n collectorSizes.add(option);\n }\n }\n }\n if (collectorSizes.size() > 0) {\n return Collections.min(collectorSizes, new Comparator<Size>() {\n @Override\n public int compare(Size s1, Size s2) {\n return Long.signum(s1.getWidth() * s1.getHeight() - s2.getWidth() * s2.getHeight());\n }\n });\n }\n return sizes[0];\n }\n\n //将中文用户名转换为十六进制字符串形式\n public static String makeUserNameToHex(String userName) {\n byte[] src = new byte[0];\n try {\n src = userName.getBytes(\"utf-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n StringBuilder stringBuilder = new StringBuilder(\"\");\n if (src == null || src.length <= 0) {\n return null;\n }\n for (int i = 0; i < src.length; i++) {\n int v = src[i] & 0xFF;\n String hv = Integer.toHexString(v);\n if (hv.length() < 2) {\n stringBuilder.append(0);\n }\n stringBuilder.append(hv);\n }\n return stringBuilder.toString();\n }\n}" ]
import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.ImageFormat; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.TotalCaptureResult; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.FaceDetector; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.Size; import android.util.SparseIntArray; import android.view.LayoutInflater; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Timer; import java.util.TimerTask; import cn.ac.iscas.xlab.droidfacedog.ImagePreviewAdapter; import cn.ac.iscas.xlab.droidfacedog.R; import cn.ac.iscas.xlab.droidfacedog.RosConnectionService; import cn.ac.iscas.xlab.droidfacedog.entity.FaceResult; import cn.ac.iscas.xlab.droidfacedog.util.ImageUtils; import cn.ac.iscas.xlab.droidfacedog.util.Util;
public void setPresenter(CommentaryContract.Presenter presenter) { this.presenter = presenter; } private void initCallbackAndListeners() { cameraCallback = new CameraDevice.StateCallback() { @Override public void onOpened(@NonNull CameraDevice camera) { log("CameraStateCallback -- onOpened()"); cameraDevice = camera; //startPreview(); } @Override public void onDisconnected(@NonNull CameraDevice camera) { log("CameraStateCallback -- onDisconnected()"); if (cameraDevice != null) { cameraDevice.close(); } } @Override public void onError(@NonNull CameraDevice camera,int error) { log("CameraStateCallback -- onOpened()"); } }; surfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) { log("TextureView.SurfaceTextureListener -- onSurfaceTextureAvailable()"); surfaceTexture = surface; startPreview(); startTimerTask(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { log("TextureView.SurfaceTextureListener -- onSurfaceTextureSizeChanged()"); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { log("TextureView.SurfaceTextureListener -- onSurfaceTextureDestroyed()"); return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { Log.v(TAG,"TextureView.SurfaceTextureListener -- onSurfaceTextureUpdated()"); } }; captureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) { Log.v(TAG,"CameraCaptureSession.CaptureCallback -- onCaptureStarted()"); super.onCaptureStarted(session, request, timestamp, frameNumber); } @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { Log.v(TAG,"CameraCaptureSession.CaptureCallback -- onCaptureCompleted()"); super.onCaptureCompleted(session, request, result); } }; captureSessionCallback = new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession session) { log("CameraCaptureSession.StateCallback -- onConfigured"); if (cameraDevice == null) { return; } cameraCaptureSession = session; captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH); CaptureRequest request = captureBuilder.build(); try { cameraCaptureSession.setRepeatingRequest(request, captureCallback, backgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { log("CameraCaptureSession.StateCallback -- onConfigureFailed"); } }; textureView.setSurfaceTextureListener(surfaceTextureListener); } private void initCamera() { cameraId = "" + CameraCharacteristics.LENS_FACING_BACK; cameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE); try { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getContext(), "没有相机权限", Toast.LENGTH_SHORT).show(); } else { cameraManager.openCamera(cameraId, cameraCallback, backgroundHandler); } } catch (CameraAccessException e) { e.printStackTrace(); } } private void startPreview() { try { CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId); StreamConfigurationMap configMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size previewSize = Util.getPreferredPreviewSize(
4
vanniktech/espresso-utils
espresso-core-utils/src/androidTest/java/com/vanniktech/espresso/core/utils/AttributeMatcherTest.java
[ "@CheckResult public static AttributeMatcher withAttr(@AttrRes final int attr, @ColorInt final int color) {\n return new AttributeMatcher(attr, null, ColorChecker.from(color));\n}", "@CheckResult public static AttributeMatcher withAttrRes(@AttrRes final int attr, @ColorRes final int colorRes) {\n return new AttributeMatcher(attr, null, ColorChecker.fromRes(colorRes));\n}", "@CheckResult public static AttributeMatcher withColorAccent(@ColorInt final int color) {\n return new AttributeMatcher(R.attr.colorAccent, \"colorAccent\", ColorChecker.from(color));\n}", "@CheckResult public static AttributeMatcher withColorAccentRes(@ColorRes final int colorRes) {\n return new AttributeMatcher(R.attr.colorAccent, \"colorAccent\", ColorChecker.fromRes(colorRes));\n}", "@CheckResult public static AttributeMatcher withColorButtonNormal(@ColorInt final int color) {\n return new AttributeMatcher(R.attr.colorButtonNormal, \"colorButtonNormal\", ColorChecker.from(color));\n}", "@CheckResult public static AttributeMatcher withColorButtonNormalRes(@ColorRes final int colorRes) {\n return new AttributeMatcher(R.attr.colorButtonNormal, \"colorButtonNormal\", ColorChecker.fromRes(colorRes));\n}", "static final int VIEW_ID = 1234;" ]
import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.rule.ActivityTestRule; import com.vanniktech.espresso.core.utils.test.R; import junit.framework.AssertionFailedError; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import static android.graphics.Color.BLUE; import static android.graphics.Color.GREEN; import static android.graphics.Color.RED; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static com.vanniktech.espresso.core.utils.AttributeMatcher.withAttr; import static com.vanniktech.espresso.core.utils.AttributeMatcher.withAttrRes; import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorAccent; import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorAccentRes; import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorButtonNormal; import static com.vanniktech.espresso.core.utils.AttributeMatcher.withColorButtonNormalRes; import static com.vanniktech.espresso.core.utils.AttributeMatcherActivity.VIEW_ID;
package com.vanniktech.espresso.core.utils; @RunWith(AndroidJUnit4.class) public final class AttributeMatcherTest { @Rule public final ExpectedException expectedException = ExpectedException.none(); @Rule public final ActivityTestRule<AttributeMatcherActivity> activityTestRule = new ActivityTestRule<>(AttributeMatcherActivity.class); @Test public void withAttrResMatches() {
onView(withId(VIEW_ID)).check(matches(withAttrRes(R.attr.colorError, R.color.blue)));
6
Gikkman/Java-Twirk
src/main/java/com/gikk/twirk/types/usernotice/DefaultUsernoticeBuilder.java
[ "public interface TagMap extends Map<String, String>{\n //***********************************************************\n\t// \t\t\t\tPUBLIC\n\t//***********************************************************\n\t/**Fetches a certain field value that might have been present in the tag.\n\t * If the field was not present in the tag, or the field's value was empty,\n\t * this method returns <code>NULL</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if there was any. <code>NULL</code> otherwise\n\t */\n\tpublic String getAsString(String identifier);\n\n\t/**Fetches a certain field value that might have been present in the tag, and\n\t * tries to parse it into an <code>int</code>. If the field was not present in the tag,\n\t * or the field's value was empty, this method returns <code>-1</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if it was present and an int. <code>-1</code> otherwise\n\t */\n\tpublic int getAsInt(String identifier);\n\n /**Fetches a certain field value that might have been present in the tag, and\n\t * tries to parse it into a <code>long</code>. If the field was not present in the tag,\n\t * or the field's value was empty, this method returns <code>-1</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if it was present and a long. <code>-1</code> otherwise\n\t */\n long getAsLong(String identifier);\n\n\t/**Fetches a certain field value that might have been present in the tag, and\n\t * tries to parse it into a <code>boolean</code>. For parsing purpose, <code>1</code> is interpreted\n\t * as <code>true</code>, anything else as <code>false</code>.\n\t * If the field was not present in the tag, or the field's value was empty, this method returns <code>false</code>\n\t *\n\t * @param identifier The fields identifier. See {@link TwitchTags}\n\t * @return The fields value, if it was present and could be parsed to a boolean. <code>false</code> otherwise\n\t */\n\tpublic boolean getAsBoolean(String identifier);\n\n /**Creates a new TagMap using the default TagMap implementation.\n *\n * @param tag\n * @return the default tag map\n */\n static TagMap getDefault(String tag){\n return new TagMapImpl(tag);\n }\n}", "public class TwitchTags {\n\n\t/**Denotes the message's unique ID\n\t */\n\tpublic static final String ID\t\t\t= \"id\";\n\n\t/**Denotes the user's unique ID\n\t */\n\tpublic static final String USER_ID \t\t= \"user-id\";\n\n\t/**The users display name (on Twitch). Escaped like the following:<br><br><table style=\"width:500\"><tr>\n\t *<td><b>CHARACTER\t\t</b></td><td><b>ESCAPED BY</b></td><tr>\n\t *<td>; (semicolon)\t</td><td>\\: (backslash and colon)</td><tr>\n\t *<td>SPACE\t\t\t</td><td>\\s </td><tr>\n\t *<td>\\\t\t\t\t</td><td>\\\\ </td><tr>\n\t *<td>CR\t\t\t</td><td>\\r </td><tr>\n\t *<td>LF\t\t\t</td><td>\\n </td><tr>\n\t *<td>all others\t</td><td>the character itself</td></tr></table>\n\t */\n\tpublic static final String DISPLAY_NAME\t= \"display-name\";\n\n\t/**Denotes badges this message has. Can be:<br>\n\t * {@code staff, admin, global_mod, moderator, subscriber, turbo } and/or {@code bits}\n\t */\n\tpublic static final String BADGES \t\t= \"badges\";\n\n /**Denotes the number of bits that was cheered in this message\n */\n public static final String BITS = \"bits\";\n\n\t/**Denotes the users color. This comes as a hexadecimal value. Can be empty if never set by the user\n\t */\n\tpublic static final String COLOR \t\t= \"color\";\n\n\t/**Denotes if the user is a subscriber or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic static final String IS_SUB \t\t= \"subscriber\";\n\n\t/**Denotes if the user is a moderator or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic static final String IS_MOD \t\t= \"mod\";\n\n\t/**Denotes if the user has turbo or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic static final String IS_TURBO \t= \"turbo\";\n\n\t/**Is either <code>empty, mod, global_mod, admin</code> or <code>staff</code>.\n\t* <li>The broadcaster can have any of these, including empty.\n\t*/\n\tpublic static final String USERTYPE \t= \"user-type\";\n\n\t/**Contains information to replace text in the message with the emote images and <b>can be empty</b>. The format is as follows:<br><br>\n\t * <code>emote_id:first_index-last_index,another_first-another_last/another_emote_id:first_index-last_index</code><br><br>\n\t *\n\t * <code>emote_id</code> is the number to use in this URL: <code>http://static-cdn.jtvnw.net/emoticons/v1/:emote_id/:size</code> (<i>size is 1.0, 2.0 or 3.0</i>)<br><br>\n\t *\n\t * Emote indexes are simply character indexes. <code>ACTION</code> does not count and indexing starts from the first character that is part of the user's \"actual message\".<br>\n\t * Both start and end is inclusive. If the message is \"Kappa\" (emote id 25), start is from character 0 (K) to character 4 (a).\n\t */\n\tpublic static final String EMOTES\t\t = \"emotes\";\n\n\t/** Contains your emote set, which you can use to request a subset of <a href=\"https://github.com/justintv/Twitch-API/blob/master/v3_resources/chat.md#get-chatemoticon_images\">/chat/emoticon_images</a>\n\t * <li>Always contains at least {@code 0}\n\t * <li>Ex: <code>https://api.twitch.tv/kraken/chat/emoticon_images?emotesets=0,33,50,237,793,2126,3517,4578,5569,9400,10337,12239</code>\n\t */\n\tpublic static final String EMOTE_SET\t= \"emote-sets\";\n\n\t/** The user's login name. Can be different from the user's display name\n\t */\n\tpublic final static String LOGIN_NAME \t= \"login\";\n\n\t/** Identifies what kind of notice it was.\n\t */\n\tpublic final static String MESSAGE_ID \t= \"msg-id\";\n\n\t/** The message printed in chat along with this notice.\n\t */\n\tpublic final static String SYSTEM_MESSAGE = \"system-msg\";\n\n\t/** The number of cumulative months the user has subscribed for in a resub notice.\n\t */\n\tpublic final static String PARAM_MONTHS = \"msg-param-cumulative-months\";\n\n\t/** The number of consecutive months the user has subscribed for in a resub notice.\n\t */\n\tpublic final static String PARAM_STREAK = \"msg-param-streak-months\";\n\n\t/** Denotes if the user share the streak or not. <code>1</code> for <code>true</code>, <code>0</code> for <code>false</code>\n\t */\n\tpublic final static String PARAM_SHARE_STREAK = \"msg-param-should-share-streak\";\n\n /** The type of subscription plan being used.\n * Valid values: Prime, 1000, 2000, 3000. 1000, 2000, and 3000 refer to the\n * first, second, and third levels of paid subscriptions,\n * respectively (currently $4.99, $9.99, and $24.99).\n */\n public final static String PARAM_SUB_PLAN = \"msg-param-sub-plan\";\n\n /** The display name of the subscription plan. This may be a default name or\n * one created by the channel owner.\n */\n public static String PARAM_SUB_PLAN_NAME = \"msg-param-sub-plan-name\";\n\n\t/** Denotes the room's ID which the message what sent to. Each room's ID is unique\n\t */\n\tpublic static final String ROOM_ID \t\t= \"room-id\";\n\n\t/** <code>broadcaster-lang</code> is the chat language when <a href=\"https://blog.twitch.tv/your-channel-your-chat-your-language-80306ab98a59#.i4rpk1gn1\">broadcaster language mode</a> is enabled, and empty otherwise. <br>\n\t * A few examples would be en for English, fi for Finnish and es-MX for Mexican variant of Spanish\n\t */\n\tpublic static final String ROOM_LANG \t= \"broadcaster-lang\";\n\n\t/** Messages with more than 9 characters must be unique. 0 means disabled, 1 enabled\n\t */\n\tpublic static final String R9K_ROOM \t= \"r9k\";\n\n\t/** Only subscribers and moderators can chat. 0 disabled, 1 enabled.\n\t */\n\tpublic static final String SUB_ONLY_ROOM= \"subs-only\";\n\n\t/** Only followers can chat. -1 disabled, 0 all followers can chat, > 0 only users following for at least the specified number of minutes can chat.\n\t */\n\tpublic static final String FOLLOWERS_ONLY_ROOM = \"followers-only\";\n\n\t/** Emote-only mode. If enabled, only emotes are allowed in chat. Valid values: 0 (disabled) or 1 (enabled).\n\t */\n\tpublic static final String EMOTE_ONLY_ROOM = \"emote-only\";\n\n\t/** Determines how many seconds chatters without moderator privileges must wait between sending messages\n\t */\n\tpublic static final String SLOW_DURATION= \"slow\";\n\n\t/** The duration of the timeout in seconds. The tag is omitted on permanent bans.\n\t */\n\tpublic static final String BAN_DURATION = \"ban-duration\";\n\n\t/** The reason the moderator gave for the timeout or ban.\n\t */\n\tpublic static final String BAN_REASON = \"ban-reason\";\n\n /** The UNIX timestamp a message reached the Twitch server\n */\n public static final String TMI_SENT_TS = \"tmi-sent-ts\";\n\n /** The number of viewers which participates in a raid\n */\n public static final String PARAM_VIEWER_COUNT = \"msg-param-viewerCount\";\n\n /** The login name of the user initiating a raid\n */\n public static final String PARAM_LOGIN_NAME = \"msg-param-login\";\n\n /** The display name of a user initiating a raid\n */\n public static final String PARAM_DISPLAY_NAME = \"msg-param-displayName\";\n\n /** The name of the ritual this notice is for. Valid value: new_chatter\n */\n public static String PARAM_RITUAL_NAME = \"msg-param-ritual-name\";\n\n /** The display name of the subscriber gift receiver.\n */\n public static String PARAM_RECIPIANT_NAME = \"msg-param-recipient-name\";\n\n /** The display name of the subscriber gift receiver.\n */\n public static String PARAM_RECIPIANT_DISPLAY_NAME = \"msg-param-recipient-display-name\";\n\n /** The user ID of the subscriber gift receiver.\n */\n public static String PARAM_RECIPIANT_ID = \"msg-param-recipient-id\";\n}", "public interface Emote {\n\t/** Fetches the emotes ID as String. This became necessary after Twitch start\n\t * including other characters than numbers in emote IDs\n\t *\n\t * @return The emotes ID\n\t */\n\tString getEmoteIDString();\n\t\n\t/** A list of pairs on indices. Each pair is a BEGIN-END pair of a emote occurrence in the message.<br><br>\n\t * \n\t * For example, if the message is: {@code Kappa PogChamp Kappa}<br> the list for emote 'Kappa' will include these pairs:<ul>\n\t * <li> (0,5)\n\t * <li> (15,20)\n\t * </ul>\n\t * \n\t * @return The indices this emote takes up in the associated message\n\t */\n\tLinkedList<EmoteIndices> getIndices();\n\t\n\t/** The emote's pattern. For example: 'Kappa'\n\t * \n\t * @return The emote's pattern\n\t */\n\tString getPattern();\n\t\n\t/**Emote images can be downloaded from Twitch's server, and come in three\n\t * sizes. Use this method to get the address for the emote.\n\t * \n\t * @param imageSize Emotes comes in three sizes. Specify which size you want\n\t * @return The address for the emote's image\n\t */\n\tString getEmoteImageUrl(EMOTE_SIZE imageSize);\n\t\n\t/**Class for representing the beginning and end of an emote occurrence within a message\n\t * \n\t * @author Gikkman\n\t */\t\n\tclass EmoteIndices{\n\t\tpublic final int beingIndex;\n\t\tpublic final int endIndex;\n\t\t\n\t\tpublic EmoteIndices(int begin, int end){\n\t\t\tthis.beingIndex = begin;\n\t\t\tthis.endIndex = end;\n\t\t}\n\t\t\n\t\tpublic String toString(){\n\t\t\treturn \"(\" +beingIndex + \",\" + endIndex + \")\";\n\t\t}\n\t}\n}", "public interface TwitchMessage extends AbstractEmoteMessage {\n\n\t/**Retrieves this message's tag segment. Should always starts with a @. Note that the\n\t * Tag segment will look vastly different for different Twitch commands, and some won't\n\t * even have a tag.\n\t *\n\t * @return The tag segment, or {@code \"\"} if no tag was present\n\t */\n\tpublic String getTag();\n\n\t/**Retrieves the message's prefix.<br><br>\n\t *\n\t * A typical Twitch message looks something line this:<br>\n\t * <code>:[email protected] COMMAND #channel :message</code> <br><br>\n\t *\n\t * The prefix is the part before the first space. It usually only contains data about the sender of\n\t * the message, but it might sometimes contain other information (PING messages for example just have PING as\n\t * their prefix).<br><br>\n\t *\n\t * @return The messages prefix\n\t */\n\tpublic String getPrefix();\n\n\t/**Retrieves the message's command.<br>\n\t * The command tells us what action triggered this message being sent.<br><br>\n\t *\n\t * @return The message's command\n\t */\n\tpublic String getCommand();\n\n\t/**Retrieves the message's target.<br>\n\t * The target tells us whom the message is intended towards. It can be a user,\n * a channel, or something else (though mostly the channel).\n * <p>\n\t * This segment is not always present.\n\t *\n\t * @return The message's target, or {@code \"\"} if no target\n\t */\n\tpublic String getTarget();\n\n\t/**Retrieves the message's content.<br>\n\t * The content is the commands parameters. Most often, this is the actual chat message, but it may be many\n\t * other things for other commands.<br><br>\n\t *\n\t * This segment is not always present.\n\t *\n\t * @return The message's content, or {@code \"\"} if no content\n\t */\n\tpublic String getContent();\n\n /**Tells whether this message was a cheer event or not.\n *\n * @return {@code true} if the message contains bits, <code>false</code> otherwise\n */\n public boolean isCheer();\n\n /**Fetches a list of all all cheers in this message. Each cheer is encapsulated in a {@link Cheer}.\n\t * The list might be empty, if the message contained no cheers.\n *\n\t * @return List of emotes (might be empty)\n\t */\n public List<Cheer> getCheers();\n\n /**Fetches the total number of bits that this message contained.\n * This method is short-hand for:\n * <pre>\n * int bits = 0;\n * for(Cheer c : getCheers())\n * bits += c.getBits();\n * return bits;\n * </pre>\n * @return number of bits\n */\n public int getBits();\n\n /**Fetches the {@link TagMap} that has parsed the message's tag into a key-value map.\n * For a list of different identifiers that can occur in a tag, check the {@link TwitchTags} class.\n */\n public TagMap getTagMap();\n}", "public interface Raid {\n\n /**Fetches the display name of the user whom initiated the raid.\n *\n * @return the display name of the raid initiator\n */\n public String getSourceDisplayName();\n\n /**Fetches the login name of the user whom initiated the raid. This will\n * also give you the name of the channel which the raid originated from.\n *\n * @return the login name of the raid initiator\n */\n public String getSourceLoginName();\n\n\n /**Fetches the number of users participating in the raid.\n *\n * @return number of raiders\n */\n public int getRaidCount();\n}", "public interface Ritual {\n /**Fetches the name of the Ritual\n *\n * @return the ritual name\n */\n public String getRitualName();\n}", "public interface Subscription {\n public SubscriptionPlan getSubscriptionPlan();\n\n /**Get the number of month's the subscription's been active. New subscriptions\n * return 1, whilst re-subscriptions tells which month was just activated.\n *\n * @return number of months\n */\n public int getMonths();\n\n /**Get the number of month's the subscription's been active consecutive.\n *\n * @return number of months\n */\n public int getStreak();\n\n /** Returns if user decide to share the streak, this decide if the value of {@code getStreak} its zero or another.\n *\n * @return {@code true} if user share the streak\n */\n public boolean isSharedStreak();\n\n /**Returns the name of the purchased subscription plan. This may be a\n * default name or one created by the channel owner.\n *\n * @return display name of the subscription plan\n */\n public String getSubscriptionPlanName();\n\n /**Returns whether this was a new sub or a re-sub.\n *\n * @return {@code true} if this was a re-subscription\n */\n public boolean isResub();\n\n /**Tells whether this is a subscription gift or not.\n *\n * @return {@code true} if this was a gift\n */\n public boolean isGift();\n\n /**Retrieves the SubscriptionGift item, which holds information about the\n * gift and the recipiant of the gift. The Optional object wraps the\n * SubscriptionGift object (as an alternative to returning {@code null}).\n *\n * @return the subscription gift, wrapped in a {@link Optional}\n */\n public Optional<SubscriptionGift> getSubscriptionGift();\n}" ]
import com.gikk.twirk.types.TagMap; import com.gikk.twirk.types.TwitchTags; import com.gikk.twirk.types.emote.Emote; import com.gikk.twirk.types.twitchMessage.TwitchMessage; import com.gikk.twirk.types.usernotice.subtype.Raid; import com.gikk.twirk.types.usernotice.subtype.Ritual; import com.gikk.twirk.types.usernotice.subtype.Subscription; import java.util.List;
package com.gikk.twirk.types.usernotice; class DefaultUsernoticeBuilder implements UsernoticeBuilder{ String rawLine; List<Emote> emotes; String messageID; int roomID; long sentTimestamp; String systemMessage; Subscription subscription; Raid raid; Ritual ritual; String message; @Override public Usernotice build(TwitchMessage message) { this.rawLine = message.getRaw(); this.emotes = message.getEmotes();
TagMap map = message.getTagMap();
0
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/ui/fragment/JokeImageListFragments.java
[ "public interface JokeImageListContract {\n interface View {\n /**\n * 获取数据\n *\n * @param newsList newsList\n */\n void onRefreshData(List<Contentlist> newsList);\n\n /**\n * 添加数据\n *\n * @param newsList add newsList\n */\n void onReceiveMoreListData(List<Contentlist> newsList);\n\n /**\n * 显示信息 e.g. 没有网络、正在加载、异常\n *\n * @param INFOType 枚举值\n * @param infoText 提示的文本内容\n * @see Constant.INFO_TYPE\n */\n void showInfo(Constant.INFO_TYPE INFOType, String infoText);\n\n void hideInfo();\n\n }\n\n interface Presenter {\n void getRefreshData();\n\n void getMoreData();\n }\n}", "public class JokeImageRoot {\n private int showapi_res_code;\n\n private String showapi_res_error;\n\n private Showapi_res_body showapi_res_body;\n\n public void setShowapi_res_code(int showapi_res_code) {\n this.showapi_res_code = showapi_res_code;\n }\n\n public int getShowapi_res_code() {\n return this.showapi_res_code;\n }\n\n public void setShowapi_res_error(String showapi_res_error) {\n this.showapi_res_error = showapi_res_error;\n }\n\n public String getShowapi_res_error() {\n return this.showapi_res_error;\n }\n\n public void setShowapi_res_body(Showapi_res_body showapi_res_body) {\n this.showapi_res_body = showapi_res_body;\n }\n\n public Showapi_res_body getShowapi_res_body() {\n return this.showapi_res_body;\n }\n\n public static class Showapi_res_body {\n private int allNum;\n\n private int allPages;\n\n private List<Contentlist> contentlist;\n\n private int currentPage;\n\n private int maxResult;\n\n private int ret_code;\n\n public void setAllNum(int allNum) {\n this.allNum = allNum;\n }\n\n public int getAllNum() {\n return this.allNum;\n }\n\n public void setAllPages(int allPages) {\n this.allPages = allPages;\n }\n\n public int getAllPages() {\n return this.allPages;\n }\n\n public void setContentlist(List<Contentlist> contentlist) {\n this.contentlist = contentlist;\n }\n\n public List<Contentlist> getContentlist() {\n return this.contentlist;\n }\n\n public void setCurrentPage(int currentPage) {\n this.currentPage = currentPage;\n }\n\n public int getCurrentPage() {\n return this.currentPage;\n }\n\n public void setMaxResult(int maxResult) {\n this.maxResult = maxResult;\n }\n\n public int getMaxResult() {\n return this.maxResult;\n }\n\n public void setRet_code(int ret_code) {\n this.ret_code = ret_code;\n }\n\n public int getRet_code() {\n return this.ret_code;\n }\n\n }\n\n /**\n * Created by cchao on 2016/4/25.\n * E-mail: [email protected]\n * Description:\n */\n public static class Contentlist {\n private String ct;\n\n private String img;\n\n private String title;\n\n private int type;\n\n public void setCt(String ct) {\n this.ct = ct;\n }\n\n public String getCt() {\n return this.ct;\n }\n\n public void setImg(String img) {\n this.img = img;\n }\n\n public String getImg() {\n return this.img;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getTitle() {\n return this.title;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n\n public int getType() {\n return this.type;\n }\n\n }\n}", "public class JokeImageListPresenter implements JokeImageListContract.Presenter {\n JokeImageListContract.View mView;\n BaiDuApiService mBaiDBaiDuApiService;\n int mCurrentPage = 1;\n\n public JokeImageListPresenter(JokeImageListContract.View view) {\n mView = view;\n mBaiDBaiDuApiService = BaseApplication.getAppComponent().getBaiDuApiService();\n }\n\n @Override\n public void getRefreshData() {\n //无网刷新数据>底部显示SnackBar>点击打开设置界面\n if (!NetUtil.isConnected()) {\n mView.showInfo(Constant.INFO_TYPE.NO_NET, null);\n } else {\n mView.showInfo(Constant.INFO_TYPE.LOADING, null);\n mBaiDBaiDuApiService.getJokeImage(Keys.BAI_DU_KEY, \"1\")\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Action1<JokeImageRoot>() {\n @Override\n public void call(JokeImageRoot jokeimageRoot) {\n if (jokeimageRoot.getShowapi_res_code() == 0 && jokeimageRoot.getShowapi_res_body() != null) {\n\n List<JokeImageRoot.Contentlist> contentlist = jokeimageRoot.getShowapi_res_body().getContentlist();\n mView.hideInfo();\n if (jokeimageRoot.getShowapi_res_body().getCurrentPage() == 1) {\n mView.onRefreshData(contentlist);\n } else {\n mView.onReceiveMoreListData(contentlist);\n }\n }\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n LogUtil.e(throwable.toString());\n }\n });\n }\n }\n\n @Override\n public void getMoreData() {\n //无网刷新数据>底部显示SnackBar>点击打开设置界面\n if (!NetUtil.isConnected()) {\n mView.showInfo(Constant.INFO_TYPE.NO_NET, null);\n } else {\n mView.showInfo(Constant.INFO_TYPE.LOADING, null);\n mBaiDBaiDuApiService.getJokeImage(Keys.BAI_DU_KEY, ++mCurrentPage + \"\")\n .subscribeOn(Schedulers.newThread())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new Action1<JokeImageRoot>() {\n @Override\n public void call(JokeImageRoot jokeimageRoot) {\n if (jokeimageRoot.getShowapi_res_code() == 0 && jokeimageRoot.getShowapi_res_body() != null) {\n\n List<JokeImageRoot.Contentlist> contentlist = jokeimageRoot.getShowapi_res_body().getContentlist();\n mView.hideInfo();\n if (jokeimageRoot.getShowapi_res_body().getCurrentPage() == 1) {\n mView.onRefreshData(contentlist);\n } else {\n mView.onReceiveMoreListData(contentlist);\n }\n }\n }\n }, new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n LogUtil.e(throwable.toString());\n }\n });\n }\n }\n\n}", "public class JokeImageListRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n private static final int TYPE_ITEM = 0;\n private static final int TYPE_FOOTER = 1;\n public Context mContext;\n public List<JokeImageRoot.Contentlist> mData;\n public LayoutInflater mLayoutInflater;\n\n// private View.OnClickListener mOnClickListener;\n\n public JokeImageListRecyclerAdapter(Context context, List<JokeImageRoot.Contentlist> data) {\n mContext = context;\n mData = data;\n mLayoutInflater = LayoutInflater.from(context);\n }\n\n @Override\n public int getItemViewType(int position) {\n if (position + 1 == getItemCount()) {\n return TYPE_FOOTER;\n } else {\n return TYPE_ITEM;\n }\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n if (viewType == TYPE_ITEM) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_joke_image, parent, false);\n return new MViewHolder(view);\n } else {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view_footer, parent, false);\n return new RecyclerView.ViewHolder(view) {\n @Override\n public String toString() {\n return super.toString();\n }\n };\n }\n }\n\n @Override\n public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {\n if (holder instanceof MViewHolder) {\n JokeImageRoot.Contentlist contentEntity = mData.get(position);\n ((MViewHolder) holder).mTitle.setText(contentEntity.getTitle());\n final ImageView imageView = ((MViewHolder) holder).mImage;\n ImageUtil.displayImage(mContext, contentEntity.getImg(), imageView);\n\n imageView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(mContext, ImageBrowseActivity.class);\n intent.putExtra(\"url\", mData.get(position).getImg());\n// View transitionView = view.findViewById(R.id.ivNews);\n ActivityOptionsCompat options =\n ActivityOptionsCompat.makeSceneTransitionAnimation((HomeActivity) mContext,\n imageView, mContext.getString(R.string.transition__img));\n\n ActivityCompat.startActivity((HomeActivity) mContext, intent, options.toBundle());\n\n }\n });\n }\n }\n\n @Override\n public int getItemCount() {\n return mData.size() + 1;\n }\n\n public class MViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n public TextView mTitle;\n public ImageView mImage;\n\n public MViewHolder(View view) {\n super(view);\n mTitle = (TextView) view.findViewById(R.id.tv_title);\n mImage = (ImageView) view.findViewById(R.id.imageView);\n }\n\n @Override\n public void onClick(View v) {\n /* Intent intent = new Intent ( mContext, NewsDetailActivity.class );\n intent.putExtra ( \"contentList\", mData.get ( this.getLayoutPosition ( ) ) );\n// View transitionView = view.findViewById(R.id.ivNews);\n ActivityOptionsCompat options =\n ActivityOptionsCompat.makeSceneTransitionAnimation ( ( HomeActivity ) mContext,\n mImage, mContext.getString ( R.string.transition__img ) );\n\n ActivityCompat.startActivity ( ( HomeActivity ) mContext, intent, options.toBundle ( ) );*/\n\n }\n }\n}", "public abstract class BaseFragment extends BaseLazyFragment {\n protected Toolbar mToolbar;\n protected View mRootView;\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n mRootView = inflater.inflate(getLayoutId(), null);\n ButterKnife.bind(this, mRootView);\n mToolbar = ButterKnife.findById(mRootView, R.id.toolbar);\n return mRootView;\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n initialize();\n }\n\n protected void initialize() {\n }\n\n @Override\n public void onFirstUserVisible() {\n super.onFirstUserVisible();\n setSupportActionBar();\n }\n\n //布局ID\n protected abstract\n @LayoutRes\n int getLayoutId();\n\n @Override\n public void onUserVisible() {\n super.onUserVisible();\n setSupportActionBar();\n }\n\n /**\n * 设置toolbar\n */\n private void setSupportActionBar() {\n ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);\n ((HomeActivity) getActivity()).addDrawerListener(mToolbar);\n }\n}", "public class Constant {\n /**\n * 显示提示信息给用户 e.g. 没有网络、正在加载、异常\n *\n * @see\n */\n public enum INFO_TYPE {\n NO_NET, ALERT, LOADING, EMPTY, ORIGIN\n }\n\n}", "public class NetUtil {\n private NetUtil() {\n /* cannot be instantiated */\n throw new UnsupportedOperationException(\"cannot be instantiated\");\n }\n\n /**\n * 判断网络是否连接\n *\n * @return s\n */\n public static boolean isConnected() {\n\n ConnectivityManager connectivity = (ConnectivityManager) BaseApplication.getContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n\n if (null != connectivity) {\n\n NetworkInfo info = connectivity.getActiveNetworkInfo();\n if (null != info && info.isConnected()) {\n if (info.getState() == NetworkInfo.State.CONNECTED) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * 判断是否是wifi连接\n */\n public static boolean isWifi(Context context) {\n ConnectivityManager cm = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n\n if (cm == null)\n return false;\n return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;\n\n }\n\n /**\n * 打开网络设置界面\n */\n public static void openSetting(Context context) {\n Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);\n context.startActivity(intent);\n }\n\n}", "public class SnackBarUtil {\n public static Snackbar showShort(@NonNull View view, @StringRes int resId) {\n\n Snackbar snackbar = Snackbar.make(view, resId, Snackbar.LENGTH_SHORT);\n snackbar.show();\n return snackbar;\n }\n\n public static Snackbar showLong(@NonNull View view, @StringRes int resId) {\n\n Snackbar snackbar = Snackbar.make(view, resId, Snackbar.LENGTH_LONG);\n snackbar.show();\n return snackbar;\n }\n\n public static Snackbar shoShort(@NonNull View view, @NonNull String string) {\n Snackbar snackbar = Snackbar.make(view, string, Snackbar.LENGTH_SHORT);\n snackbar.show();\n return snackbar;\n }\n\n public static Snackbar showLong(@NonNull View view, @NonNull String string) {\n Snackbar snackbar = Snackbar.make(view, string, Snackbar.LENGTH_LONG);\n snackbar.show();\n return snackbar;\n }\n}", "public class VaryViewWidget {\n\n /**\n * 原来的View\n */\n public View mOriginView;\n /**\n * 提示View\n */\n public View mAlertView;\n /**\n * 没网View\n */\n public View mNoNetView;\n /**\n * 正在加载View\n */\n public View mLoadingView;\n /**\n * 数据为空的View\n */\n public View mEmptyView;\n /**\n * 正在加载View\n */\n// public ProgressWheel mLoadingProgress;\n ViewGroup mParentViewGroup;\n int mOriginViewIndex;\n ViewGroup.LayoutParams layoutParams;\n\n public VaryViewWidget(View originView) {\n setOriginView(originView);\n\n layoutParams = mOriginView.getLayoutParams();\n mParentViewGroup = (ViewGroup) mOriginView.getParent();\n if (mParentViewGroup == null) {\n throw new IllegalArgumentException(originView.getClass().getSimpleName() + \"目标View 需要有ViewGroup父布局\");\n }\n if (mOriginViewIndex == -1) {\n for (int index = 0; index < mParentViewGroup.getChildCount(); index++) {\n if (mOriginView == mParentViewGroup.getChildAt(index)) {\n mOriginViewIndex = index;\n break;\n }\n }\n }\n }\n\n public View getAlertView() {\n return mAlertView;\n }\n\n public void setAlertView(View alertView, View.OnClickListener listener) {\n mAlertView = alertView;\n if (listener != null) {\n mAlertView.setOnClickListener(listener);\n }\n }\n\n public View getOriginView() {\n return mOriginView;\n }\n\n public void setOriginView(View originView) {\n mOriginView = originView;\n }\n\n public View getLoadingView() {\n return mLoadingView;\n }\n\n public void setLoadingView(View loadingView) {\n mLoadingView = loadingView;\n }\n\n public View getNoNetView() {\n return mNoNetView;\n }\n\n public void setNoNetView(View noNetView) {\n mNoNetView = noNetView;\n }\n\n public View getEmptyView() {\n return mEmptyView;\n }\n\n public void setEmptyView(View emptyView) {\n mEmptyView = emptyView;\n }\n\n public void showView(Constant.INFO_TYPE INFOType) {\n View infoView = null;\n switch (INFOType) {\n case LOADING:\n infoView = mLoadingView;\n break;\n case NO_NET:\n infoView = mNoNetView;\n break;\n case ALERT:\n infoView = mAlertView;\n break;\n case EMPTY:\n infoView = mEmptyView;\n break;\n case ORIGIN:\n infoView = mOriginView;\n break;\n }\n if (mParentViewGroup.getChildAt(mOriginViewIndex) != infoView) {\n if (infoView != null) {\n ViewGroup parent = (ViewGroup) infoView.getParent();\n if (parent != null) {\n parent.removeView(infoView);\n }\n mParentViewGroup.removeViewAt(mOriginViewIndex);\n mParentViewGroup.addView(infoView, mOriginViewIndex, layoutParams);\n }\n }\n }\n\n public void hideInfo() {\n showView(Constant.INFO_TYPE.ORIGIN);\n }\n\n public void reinitializeVaryView() {\n mAlertView = null;\n mLoadingView = null;\n mEmptyView = null;\n }\n\n public static class Builder {\n private View mAlertView;\n public View mNoNetView;\n private View mLoadingView;\n private View mEmptyView;\n private View mOriginView;\n private View.OnClickListener mListener;\n\n public Builder(View originView) {\n mOriginView = originView;\n }\n\n public Builder setAlertView(View alertView, View.OnClickListener listener) {\n mAlertView = alertView;\n mAlertView.setOnClickListener(listener);\n return this;\n }\n\n public Builder setLoadingView(View loadingView) {\n mLoadingView = loadingView;\n return this;\n }\n\n public View getNoNetView() {\n return mNoNetView;\n }\n\n public void setNoNetView(View noNetView) {\n mNoNetView = noNetView;\n }\n\n public Builder setEmptyView(View emptyView) {\n mEmptyView = emptyView;\n return this;\n }\n\n public Builder setOriginView(View originView) {\n mOriginView = originView;\n return this;\n }\n\n public VaryViewWidget build() {\n VaryViewWidget widget = new VaryViewWidget(mOriginView);\n if (mOriginView != null) {\n widget.setEmptyView(mEmptyView);\n }\n if (mNoNetView != null) {\n widget.setEmptyView(mEmptyView);\n }\n if (mEmptyView != null) {\n widget.setEmptyView(mEmptyView);\n }\n if (mAlertView != null) {\n widget.setAlertView(mAlertView, mListener);\n }\n if (mLoadingView != null) {\n widget.setLoadingView(mLoadingView);\n }\n return widget;\n }\n\n\n }\n\n}" ]
import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import com.apkfuns.logutils.LogUtils; import com.github.cchao.touchnews.R; import com.github.cchao.touchnews.contract.JokeImageListContract; import com.github.cchao.touchnews.javaBean.joke.JokeImageRoot; import com.github.cchao.touchnews.presenter.JokeImageListPresenter; import com.github.cchao.touchnews.ui.adapter.JokeImageListRecyclerAdapter; import com.github.cchao.touchnews.ui.fragment.base.BaseFragment; import com.github.cchao.touchnews.util.Constant; import com.github.cchao.touchnews.util.NetUtil; import com.github.cchao.touchnews.util.SnackBarUtil; import com.github.cchao.touchnews.widget.VaryViewWidget; import java.util.ArrayList; import java.util.List; import butterknife.Bind;
package com.github.cchao.touchnews.ui.fragment; /** * Created by cchao on 2016/3/30. * E-mail: [email protected] * Description: 开心一刻- 图片类Fragment */ public class JokeImageListFragments extends BaseFragment implements JokeImageListContract.View, SwipeRefreshLayout.OnRefreshListener { @Bind(R.id.swipe_refresh_joke_image_list) SwipeRefreshLayout mSwipeRefreshLayout; @Bind(R.id.recycle_view_joke_image) RecyclerView mRecyclerView; View mRootView; List<JokeImageRoot.Contentlist> mContentList; JokeImageListRecyclerAdapter mRecyclerAdapter; JokeImageListContract.Presenter mPresenter; VaryViewWidget mVaryViewWidget; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onFirstUserVisible() { super.onFirstUserVisible(); initViews(); mPresenter = new JokeImageListPresenter(this); mPresenter.getRefreshData(); } private void initViews() { mContentList = new ArrayList<>(); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext)); mRecyclerAdapter = new JokeImageListRecyclerAdapter(mContext, mContentList); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { private int lastVisibleItem; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); lastVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition(); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mRecyclerAdapter.getItemCount()) { //加载更多 LogUtils.d(getClass().getSimpleName(), "info_loading more data"); mPresenter.getMoreData(); } } }); mRecyclerView.setAdapter(mRecyclerAdapter); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark); mSwipeRefreshLayout.setOnRefreshListener(this); } @Override protected int getLayoutId() { return R.layout.fragment_joke_image; } @Override public void onRefresh() { mPresenter.getRefreshData(); } /** * 刷新数据 * * @param newsList newsList */ @Override public void onRefreshData(List<JokeImageRoot.Contentlist> newsList) { mContentList.clear(); mContentList.addAll(newsList); mRecyclerAdapter.notifyDataSetChanged(); mSwipeRefreshLayout.setRefreshing(false); if (mContentList.size() < 7) { mPresenter.getMoreData(); } } /** * 上拉添加数据 * * @param newsList add newsList */ @Override public void onReceiveMoreListData(List<JokeImageRoot.Contentlist> newsList) { mContentList.addAll(newsList); mRecyclerAdapter.notifyDataSetChanged(); if (mContentList.size() < 7) { mPresenter.getMoreData(); } } /** * @param INFOType 枚举值 e.g. 没有网络、正在加载、异常 * @param infoText infoText 提示的文本内容 */ @Override public void showInfo(Constant.INFO_TYPE INFOType, String infoText) { if (mVaryViewWidget == null) { mVaryViewWidget = new VaryViewWidget(mSwipeRefreshLayout); } View infoView = null; switch (INFOType) { case LOADING: infoView = LayoutInflater.from(mContext).inflate(R.layout.info_loading, null); break; case NO_NET: //已有数据(那就是刷新或者加载更多)-> 那么在底部snack检测网络设置 if (mContentList.size() > 1) {
SnackBarUtil.showLong(mRootView, R.string.none_net_show_action).setAction(R.string.set, new View.OnClickListener() {
7
otale/tale
src/main/java/com/tale/service/CommentsService.java
[ "public class TaleConst {\n\n public static final String CLASSPATH = new File(AdminApiController.class.getResource(\"/\").getPath()).getPath() + File.separatorChar;\n\n public static final String REMEMBER_IN_COOKIE = \"remember_me\";\n public static final String LOGIN_ERROR_COUNT = \"login_error_count\";\n public static String LOGIN_SESSION_KEY = \"login_user\";\n public static String REMEMBER_TOKEN = \"\";\n public static Environment OPTIONS = Environment.of(new HashMap<>());\n public static Boolean INSTALLED = false;\n public static Boolean ENABLED_CDN = true;\n public static Environment BCONF = null;\n\n /**\n * 最大页码\n */\n public static final int MAX_PAGE = 100;\n\n /**\n * 最大获取文章条数\n */\n public static final int MAX_POSTS = 9999;\n\n /**\n * 文章最多可以输入的文字数\n */\n public static final int MAX_TEXT_COUNT = 200000;\n\n /**\n * 文章标题最多可以输入的文字个数\n */\n public static final int MAX_TITLE_COUNT = 200;\n\n /**\n * 插件菜单\n */\n public static final List<PluginMenu> PLUGIN_MENUS = new ArrayList<>();\n\n /**\n * 上传文件最大20M\n */\n public static Integer MAX_FILE_SIZE = 204800;\n\n /**\n * 要过滤的ip列表\n */\n public static final Set<String> BLOCK_IPS = new HashSet<>(16);\n\n public static final String SLUG_HOME = \"/\";\n public static final String SLUG_ARCHIVES = \"archives\";\n public static final String SLUG_CATEGRORIES = \"categories\";\n public static final String SLUG_TAGS = \"tags\";\n\n /**\n * 静态资源URI\n */\n public static final String STATIC_URI = \"/static\";\n\n /**\n * 安装页面URI\n */\n public static final String INSTALL_URI = \"/install\";\n\n /**\n * 后台URI前缀\n */\n public static final String ADMIN_URI = \"/admin\";\n\n /**\n * 后台登录地址\n */\n public static final String LOGIN_URI = \"/admin/login\";\n\n /**\n * 插件菜单 Attribute Name\n */\n public static final String PLUGINS_MENU_NAME = \"plugin_menus\";\n\n public static final String ENV_SUPPORT_163_MUSIC = \"app.support_163_music\";\n public static final String ENV_SUPPORT_GIST = \"app.support_gist\";\n public static final String MP3_PREFIX = \"[mp3:\";\n public static final String MUSIC_IFRAME = \"<iframe frameborder=\\\"no\\\" border=\\\"0\\\" marginwidth=\\\"0\\\" marginheight=\\\"0\\\" width=350 height=106 src=\\\"//music.163.com/outchain/player?type=2&id=$1&auto=0&height=88\\\"></iframe>\";\n public static final String MUSIC_REG_PATTERN = \"\\\\[mp3:(\\\\d+)\\\\]\";\n public static final String GIST_PREFIX_URL = \"https://gist.github.com/\";\n public static final String GIST_REG_PATTERN = \"&lt;script src=\\\"https://gist.github.com/(\\\\w+)/(\\\\w+)\\\\.js\\\">&lt;/script>\";\n public static final String GIST_REPLATE_PATTERN = \"<script src=\\\"https://gist.github.com/$1/$2\\\\.js\\\"></script>\";\n\n\n public static final String SQL_QUERY_METAS = \"select a.*, count(b.cid) as count from t_metas a left join `t_relationships` b on a.mid = b.mid \" +\n \"where a.type = ? and a.name = ? group by a.mid\";\n\n public static final String SQL_QUERY_ARTICLES = \"select a.* from t_contents a left join t_relationships b on a.cid = b.cid \" +\n \"where b.mid = ? and a.status = 'publish' and a.type = 'post' order by a.created desc\";\n\n public static final String COMMENT_APPROVED = \"approved\";\n public static final String COMMENT_NO_AUDIT = \"no_audit\";\n\n public static final String OPTION_CDN_URL = \"cdn_url\";\n public static final String OPTION_SITE_THEME = \"site_theme\";\n public static final String OPTION_ALLOW_INSTALL = \"allow_install\";\n public static final String OPTION_ALLOW_COMMENT_AUDIT = \"allow_comment_audit\";\n public static final String OPTION_ALLOW_CLOUD_CDN = \"allow_cloud_CDN\";\n public static final String OPTION_SAFE_REMEMBER_ME = \"safe_remember_me\";\n\n}", "public final class Commons {\n\n private static final String TEMPLATES = \"/templates/\";\n\n public static void setSiteService(SiteService ss) {\n Theme.setSiteService(ss);\n }\n\n /**\n * 判断分页中是否有数据\n *\n * @param paginator\n * @return\n */\n public static boolean is_empty(Page<?> paginator) {\n return null == paginator || BladeKit.isEmpty(paginator.getRows());\n }\n\n /**\n * 判断字符串不为空\n *\n * @param str\n * @return\n */\n public static boolean not_empty(String str) {\n return StringKit.isNotBlank(str);\n }\n\n /**\n * 返回网站首页链接,如:http://tale.biezhi.me\n *\n * @return\n */\n public static String site_url() {\n return site_url(\"\");\n }\n\n /**\n * 返回当前主题名称\n *\n * @return\n */\n public static String site_theme() {\n return site_option(\"site_theme\", \"default\");\n }\n\n /**\n * 返回网站链接下的全址\n *\n * @param sub 后面追加的地址\n * @return\n */\n public static String site_url(String sub) {\n return site_option(\"site_url\") + sub;\n }\n\n /**\n * 网站标题\n *\n * @return\n */\n public static String site_title() {\n return site_option(\"site_title\");\n }\n\n /**\n * 网站子标题\n *\n * @return\n */\n public static String site_subtitle() {\n return site_option(\"site_subtitle\");\n }\n\n /**\n * 是否允许使用云公共静态资源\n *\n * @return\n */\n public static String allow_cloud_CDN() {\n return site_option(\"allow_cloud_CDN\");\n }\n\n /**\n * 网站配置项\n *\n * @param key\n * @return\n */\n public static String site_option(String key) {\n return site_option(key, \"\");\n }\n\n /**\n * 网站配置项\n *\n * @param key\n * @param defalutValue 默认值\n * @return\n */\n public static String site_option(String key, String defalutValue) {\n if (StringKit.isBlank(key)) {\n return \"\";\n }\n return TaleConst.OPTIONS.get(key, defalutValue);\n }\n\n /**\n * 返回站点设置的描述信息\n *\n * @return\n */\n public static String site_description() {\n return site_option(\"site_description\");\n }\n\n /**\n * 截取字符串\n *\n * @param str\n * @param len\n * @return\n */\n public static String substr(String str, int len) {\n if (str.length() > len) {\n return str.substring(0, len);\n }\n return str;\n }\n\n /**\n * 返回主题URL\n *\n * @return\n */\n public static String theme_url() {\n return Commons.site_url(TEMPLATES + BaseController.THEME);\n }\n\n /**\n * 返回主题下的文件路径\n *\n * @param sub\n * @return\n */\n public static String theme_url(String sub) {\n return Commons.site_url(TEMPLATES + BaseController.THEME + sub);\n }\n\n\n /**\n * 返回gravatar头像地址\n *\n * @param email\n * @return\n */\n public static String gravatar(String email) {\n String avatarUrl = \"https://cn.gravatar.com/avatar\";\n if (StringKit.isBlank(email)) {\n return avatarUrl;\n }\n String hash = EncryptKit.md5(email.trim().toLowerCase());\n return avatarUrl + \"/\" + hash;\n }\n\n /**\n * 格式化unix时间戳为日期\n *\n * @param unixTime\n * @return\n */\n public static String fmtdate(Integer unixTime) {\n return fmtdate(unixTime, \"yyyy-MM-dd\");\n }\n\n /**\n * 格式化日期\n *\n * @param date\n * @param fmt\n * @return\n */\n public static String fmtdate(Date date, String fmt) {\n return DateKit.toString(date, fmt);\n }\n\n /**\n * 格式化unix时间戳为日期\n *\n * @param unixTime\n * @param patten\n * @return\n */\n public static String fmtdate(Integer unixTime, String patten) {\n if (null != unixTime && StringKit.isNotBlank(patten)) {\n return DateKit.toString(unixTime, patten);\n }\n return \"\";\n }\n\n /**\n * 获取随机数\n *\n * @param max\n * @param str\n * @return\n */\n public static String random(int max, String str) {\n return UUID.random(1, max) + str;\n }\n\n /**\n * An :grinning:awesome :smiley:string &#128516;with a few :wink:emojis!\n * <p>\n * 这种格式的字符转换为emoji表情\n *\n * @param value\n * @return\n */\n public static String emoji(String value) {\n return EmojiParser.parseToUnicode(value);\n }\n\n private static final Pattern SRC_PATTERN = Pattern.compile(\"src\\\\s*=\\\\s*\\'?\\\"?(.*?)(\\'|\\\"|>|\\\\s+)\");\n /**\n * 获取文章第一张图片\n *\n * @return\n */\n public static String show_thumb(String content) {\n content = TaleUtils.mdToHtml(content);\n if (content.contains(\"<img\")) {\n String img = \"\";\n String regEx_img = \"<img.*src\\\\s*=\\\\s*(.*?)[^>]*?>\";\n Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);\n Matcher m_image = p_image.matcher(content);\n if (m_image.find()) {\n img = img + \",\" + m_image.group();\n // //匹配src\n Matcher m = SRC_PATTERN.matcher(img);\n if (m.find()) {\n return m.group(1);\n }\n }\n }\n return \"\";\n }\n\n}", "@Data\n@ToString(callSuper = true)\n@EqualsAndHashCode(callSuper = true)\npublic class Comment extends Comments {\n\n private int levels;\n private List<Comments> children;\n\n public Comment(Comments comments) {\n setAuthor(comments.getAuthor());\n setMail(comments.getMail());\n setCoid(comments.getCoid());\n setAuthorId(comments.getAuthorId());\n setUrl(comments.getUrl());\n setCreated(comments.getCreated());\n setAgent(comments.getAgent());\n setIp(comments.getIp());\n setContent(comments.getContent());\n setOwnerId(comments.getOwnerId());\n setCid(comments.getCid());\n }\n\n}", "@Data\n@Table(name = \"t_comments\", pk = \"coid\")\npublic class Comments extends Model {\n\n // comment表主键\n private Integer coid;\n\n // post表主键,关联字段\n private Integer cid;\n\n // 评论生成时的GMT unix时间戳\n private Integer created;\n\n // 评论作者\n private String author;\n\n // 评论所属用户id\n private Integer authorId;\n\n // 评论所属内容作者id\n private Integer ownerId;\n\n // 评论者邮件\n private String mail;\n\n // 评论者网址\n private String url;\n\n // 评论者ip地址\n private String ip;\n\n // 评论者客户端\n private String agent;\n\n // 评论内容\n private String content;\n\n // 评论类型\n private String type;\n\n // 评论状态\n private String status;\n\n // 父级评论\n private Integer parent;\n\n}", "@Data\n@Table(name = \"t_contents\", pk = \"cid\")\npublic class Contents extends Model {\n\n /**\n * 文章表主键\n */\n private Integer cid;\n\n /**\n * 文章标题\n */\n private String title;\n\n /**\n * 文章缩略名\n */\n private String slug;\n\n /**\n * 文章创建时间戳\n */\n private Integer created;\n\n /**\n * 文章修改时间戳\n */\n private Integer modified;\n\n /**\n * 文章内容\n */\n private String content;\n\n /**\n * 文章创建用户\n */\n private Integer authorId;\n\n /**\n * 文章点击次数\n */\n private Integer hits;\n\n /**\n * 文章类型: PAGE、POST\n */\n private String type;\n\n /**\n * 内容类型,markdown或者html\n */\n private String fmtType;\n\n /**\n * 文章缩略图\n */\n private String thumbImg;\n\n /**\n * 标签列表\n */\n private String tags;\n\n /**\n * 分类列表\n */\n private String categories;\n\n /**\n * 内容状态\n */\n private String status;\n\n /**\n * 内容所属评论数\n */\n private Integer commentsNum;\n\n /**\n * 是否允许评论\n */\n private Boolean allowComment;\n\n /**\n * 是否允许ping\n */\n private Boolean allowPing;\n\n /**\n * 允许出现在Feed中\n */\n private Boolean allowFeed;\n\n @Ignore\n private String url;\n}", "@Data\n@ToString(callSuper = true)\npublic class CommentParam extends PageParam {\n\n private Integer excludeUID;\n\n}", "public class TaleUtils {\n\n /**\n * 一周\n */\n private static final int ONE_MONTH = 7 * 24 * 60 * 60;\n\n /**\n * 匹配邮箱正则\n */\n private static final Pattern VALID_EMAIL_ADDRESS_REGEX =\n Pattern.compile(\"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\\\.[A-Z]{2,6}$\", Pattern.CASE_INSENSITIVE);\n\n private static final Pattern SLUG_REGEX = Pattern.compile(\"^[A-Za-z0-9_-]{3,50}$\", Pattern.CASE_INSENSITIVE);\n\n /**\n * 设置记住密码 cookie\n */\n public static void setCookie(RouteContext context, Integer uid) {\n boolean isSSL = Commons.site_url().startsWith(\"https\");\n\n String token = EncryptKit.md5(UUID.UU64());\n RememberMe rememberMe = new RememberMe();\n rememberMe.setUid(uid);\n rememberMe.setExpires(DateKit.nowUnix() + ONE_MONTH);\n rememberMe.setRecentIp(Collections.singletonList(context.address()));\n rememberMe.setToken(token);\n\n long count = select().from(Options.class).where(Options::getName, OPTION_SAFE_REMEMBER_ME).count();\n if (count == 0) {\n Options options = new Options();\n options.setName(OPTION_SAFE_REMEMBER_ME);\n options.setValue(JsonKit.toString(rememberMe));\n options.setDescription(\"记住我 Token\");\n options.save();\n } else {\n update().from(Options.class).set(Options::getValue, JsonKit.toString(rememberMe))\n .where(Options::getName, OPTION_SAFE_REMEMBER_ME)\n .execute();\n }\n\n Cookie cookie = new Cookie();\n cookie.name(REMEMBER_IN_COOKIE);\n cookie.value(token);\n cookie.httpOnly(true);\n cookie.secure(isSSL);\n cookie.maxAge(ONE_MONTH);\n cookie.path(\"/\");\n\n context.response().cookie(cookie);\n }\n\n public static Integer getCookieUid(RouteContext context) {\n String rememberToken = context.cookie(REMEMBER_IN_COOKIE);\n if (null == rememberToken || rememberToken.isEmpty() || REMEMBER_TOKEN.isEmpty()) {\n return null;\n }\n if (!REMEMBER_TOKEN.equals(rememberToken)) {\n return null;\n }\n Options options = select().from(Options.class).where(Options::getName, OPTION_SAFE_REMEMBER_ME).one();\n if (null == options) {\n return null;\n }\n RememberMe rememberMe = JsonKit.formJson(options.getValue(), RememberMe.class);\n if (rememberMe.getExpires() < DateKit.nowUnix()) {\n return null;\n }\n if (!rememberMe.getRecentIp().contains(context.address())) {\n return null;\n }\n return rememberMe.getUid();\n }\n\n /**\n * 返回当前登录用户\n */\n public static Users getLoginUser() {\n Session session = com.blade.mvc.WebContext.request().session();\n if (null == session) {\n return null;\n }\n Users user = session.attribute(TaleConst.LOGIN_SESSION_KEY);\n return user;\n }\n\n /**\n * 退出登录状态\n */\n public static void logout(RouteContext context) {\n TaleConst.REMEMBER_TOKEN = \"\";\n context.session().remove(TaleConst.LOGIN_SESSION_KEY);\n context.response().removeCookie(TaleConst.REMEMBER_IN_COOKIE);\n context.redirect(Commons.site_url());\n }\n\n /**\n * markdown转换为html\n */\n public static String mdToHtml(String markdown) {\n if (StringKit.isBlank(markdown)) {\n return \"\";\n }\n\n List<Extension> extensions = Collections.singletonList(TablesExtension.create());\n Parser parser = Parser.builder().extensions(extensions).build();\n Node document = parser.parse(markdown);\n HtmlRenderer renderer = HtmlRenderer.builder()\n .attributeProviderFactory(context -> new LinkAttributeProvider())\n .extensions(extensions).build();\n\n String content = renderer.render(document);\n content = Commons.emoji(content);\n\n // 支持网易云音乐输出\n if (TaleConst.BCONF.getBoolean(ENV_SUPPORT_163_MUSIC, true) && content.contains(MP3_PREFIX)) {\n content = content.replaceAll(MUSIC_REG_PATTERN, MUSIC_IFRAME);\n }\n // 支持gist代码输出\n if (TaleConst.BCONF.getBoolean(ENV_SUPPORT_GIST, true) && content.contains(GIST_PREFIX_URL)) {\n content = content.replaceAll(GIST_REG_PATTERN, GIST_REPLATE_PATTERN);\n }\n return content;\n }\n\n static class LinkAttributeProvider implements AttributeProvider {\n @Override\n public void setAttributes(Node node, String tagName, Map<String, String> attributes) {\n if (node instanceof Link) {\n attributes.put(\"target\", \"_blank\");\n }\n if (node instanceof org.commonmark.node.Image) {\n attributes.put(\"title\", attributes.get(\"alt\"));\n }\n }\n }\n\n /**\n * 提取html中的文字\n */\n public static String htmlToText(String html) {\n if (StringKit.isNotBlank(html)) {\n return html.replaceAll(\"(?s)<[^>]*>(\\\\s*<[^>]*>)*\", \" \");\n }\n return \"\";\n }\n\n /**\n * 判断文件是否是图片类型\n */\n public static boolean isImage(File imageFile) {\n if (!imageFile.exists()) {\n return false;\n }\n try {\n Image img = ImageIO.read(imageFile);\n if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {\n return false;\n }\n return true;\n } catch (Exception e) {\n return false;\n }\n }\n\n /**\n * 判断是否是邮箱\n */\n public static boolean isEmail(String emailStr) {\n Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);\n return matcher.find();\n }\n\n /**\n * 判断是否是合法路径\n */\n public static boolean isPath(String slug) {\n if (StringKit.isNotBlank(slug)) {\n if (slug.contains(\"/\") || slug.contains(\" \") || slug.contains(\".\")) {\n return false;\n }\n Matcher matcher = SLUG_REGEX.matcher(slug);\n return matcher.find();\n }\n return false;\n }\n\n /**\n * 获取RSS输出\n */\n public static String getRssXml(java.util.List<Contents> articles) throws FeedException {\n Channel channel = new Channel(\"rss_2.0\");\n channel.setTitle(TaleConst.OPTIONS.get(\"site_title\", \"\"));\n channel.setLink(Commons.site_url());\n channel.setDescription(TaleConst.OPTIONS.get(\"site_description\", \"\"));\n channel.setLanguage(\"zh-CN\");\n java.util.List<Item> items = new ArrayList<>();\n articles.forEach(post -> {\n Item item = new Item();\n item.setTitle(post.getTitle());\n Content content = new Content();\n String value = Theme.article(post.getContent());\n\n char[] xmlChar = value.toCharArray();\n for (int i = 0; i < xmlChar.length; ++i) {\n if (xmlChar[i] > 0xFFFD) {\n //直接替换掉0xb\n xmlChar[i] = ' ';\n } else if (xmlChar[i] < 0x20 && xmlChar[i] != 't' & xmlChar[i] != 'n' & xmlChar[i] != 'r') {\n //直接替换掉0xb\n xmlChar[i] = ' ';\n }\n }\n\n value = new String(xmlChar);\n\n content.setValue(value);\n item.setContent(content);\n item.setLink(Theme.permalink(post.getCid(), post.getSlug()));\n item.setPubDate(DateKit.toDate(post.getCreated()));\n items.add(item);\n });\n channel.setItems(items);\n WireFeedOutput out = new WireFeedOutput();\n return out.outputString(channel);\n }\n\n private static final String SITEMAP_HEAD = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" +\n \"<urlset xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:schemaLocation=\\\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\\\" xmlns=\\\"http://www.sitemaps.org/schemas/sitemap/0.9\\\">\";\n\n static class Url {\n String loc;\n String lastmod;\n\n public Url(String loc) {\n this.loc = loc;\n }\n }\n\n public static String getSitemapXml(List<Contents> articles) {\n List<Url> urls = articles.stream()\n .map(TaleUtils::parse)\n .collect(Collectors.toList());\n urls.add(new Url(Commons.site_url() + \"/archives\"));\n\n String urlBody = urls.stream()\n .map(url -> {\n String s = \"<url><loc>\" + url.loc + \"</loc>\";\n if (null != url.lastmod) {\n s += \"<lastmod>\" + url.lastmod + \"</lastmod>\";\n }\n return s + \"</url>\";\n })\n .collect(Collectors.joining(\"\\n\"));\n\n return SITEMAP_HEAD + urlBody + \"</urlset>\";\n }\n\n private static Url parse(Contents contents) {\n Url url = new Url(Commons.site_url() + \"/article/\" + contents.getCid());\n url.lastmod = DateKit.toString(contents.getModified(), \"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\");\n return url;\n }\n\n /**\n * 替换HTML脚本\n */\n public static String cleanXSS(String value) {\n //You'll need to remove the spaces from the html entities below\n value = value.replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n value = value.replaceAll(\"\\\\(\", \"&#40;\").replaceAll(\"\\\\)\", \"&#41;\");\n value = value.replaceAll(\"'\", \"&#39;\");\n value = value.replaceAll(\"eval\\\\((.*)\\\\)\", \"\");\n value = value.replaceAll(\"[\\\\\\\"\\\\\\'][\\\\s]*javascript:(.*)[\\\\\\\"\\\\\\']\", \"\\\"\\\"\");\n value = value.replaceAll(\"script\", \"\");\n return value;\n }\n\n /**\n * 获取某个范围内的随机数\n *\n * @param max 最大值\n * @param len 取多少个\n * @return\n */\n public static int[] random(int max, int len) {\n int values[] = new int[max];\n int temp1, temp2, temp3;\n for (int i = 0; i < values.length; i++) {\n values[i] = i + 1;\n }\n //随机交换values.length次\n for (int i = 0; i < values.length; i++) {\n temp1 = Math.abs(ThreadLocalRandom.current().nextInt()) % (values.length - 1); //随机产生一个位置\n temp2 = Math.abs(ThreadLocalRandom.current().nextInt()) % (values.length - 1); //随机产生另一个位置\n if (temp1 != temp2) {\n temp3 = values[temp1];\n values[temp1] = values[temp2];\n values[temp2] = temp3;\n }\n }\n return Arrays.copyOf(values, len);\n }\n\n /**\n * 将list转为 (1, 2, 4) 这样的sql输出\n *\n * @param list\n * @param <T>\n * @return\n */\n public static <T> String listToInSql(java.util.List<T> list) {\n StringBuffer sbuf = new StringBuffer();\n list.forEach(item -> sbuf.append(',').append(item.toString()));\n sbuf.append(')');\n return '(' + sbuf.substring(1);\n }\n\n public static final String UP_DIR = CLASSPATH.substring(0, CLASSPATH.length() - 1);\n\n public static String getFileKey(String name) {\n String prefix = \"/upload/\" + DateKit.toString(new Date(), \"yyyy/MM\");\n String dir = UP_DIR + prefix;\n if (!Files.exists(Paths.get(dir))) {\n new File(dir).mkdirs();\n }\n return prefix + \"/\" + com.blade.kit.UUID.UU32() + \".\" + StringKit.fileExt(name);\n }\n\n public static String getFileName(String path) {\n File tempFile = new File(path.trim());\n String fileName = tempFile.getName();\n\n return fileName;\n }\n\n public static String buildURL(String url) {\n if (url.endsWith(\"/\")) {\n url = url.substring(0, url.length() - 1);\n }\n if (!url.startsWith(\"http\")) {\n url = \"http://\".concat(url);\n }\n return url;\n }\n}", "public class TaleConst {\n\n public static final String CLASSPATH = new File(AdminApiController.class.getResource(\"/\").getPath()).getPath() + File.separatorChar;\n\n public static final String REMEMBER_IN_COOKIE = \"remember_me\";\n public static final String LOGIN_ERROR_COUNT = \"login_error_count\";\n public static String LOGIN_SESSION_KEY = \"login_user\";\n public static String REMEMBER_TOKEN = \"\";\n public static Environment OPTIONS = Environment.of(new HashMap<>());\n public static Boolean INSTALLED = false;\n public static Boolean ENABLED_CDN = true;\n public static Environment BCONF = null;\n\n /**\n * 最大页码\n */\n public static final int MAX_PAGE = 100;\n\n /**\n * 最大获取文章条数\n */\n public static final int MAX_POSTS = 9999;\n\n /**\n * 文章最多可以输入的文字数\n */\n public static final int MAX_TEXT_COUNT = 200000;\n\n /**\n * 文章标题最多可以输入的文字个数\n */\n public static final int MAX_TITLE_COUNT = 200;\n\n /**\n * 插件菜单\n */\n public static final List<PluginMenu> PLUGIN_MENUS = new ArrayList<>();\n\n /**\n * 上传文件最大20M\n */\n public static Integer MAX_FILE_SIZE = 204800;\n\n /**\n * 要过滤的ip列表\n */\n public static final Set<String> BLOCK_IPS = new HashSet<>(16);\n\n public static final String SLUG_HOME = \"/\";\n public static final String SLUG_ARCHIVES = \"archives\";\n public static final String SLUG_CATEGRORIES = \"categories\";\n public static final String SLUG_TAGS = \"tags\";\n\n /**\n * 静态资源URI\n */\n public static final String STATIC_URI = \"/static\";\n\n /**\n * 安装页面URI\n */\n public static final String INSTALL_URI = \"/install\";\n\n /**\n * 后台URI前缀\n */\n public static final String ADMIN_URI = \"/admin\";\n\n /**\n * 后台登录地址\n */\n public static final String LOGIN_URI = \"/admin/login\";\n\n /**\n * 插件菜单 Attribute Name\n */\n public static final String PLUGINS_MENU_NAME = \"plugin_menus\";\n\n public static final String ENV_SUPPORT_163_MUSIC = \"app.support_163_music\";\n public static final String ENV_SUPPORT_GIST = \"app.support_gist\";\n public static final String MP3_PREFIX = \"[mp3:\";\n public static final String MUSIC_IFRAME = \"<iframe frameborder=\\\"no\\\" border=\\\"0\\\" marginwidth=\\\"0\\\" marginheight=\\\"0\\\" width=350 height=106 src=\\\"//music.163.com/outchain/player?type=2&id=$1&auto=0&height=88\\\"></iframe>\";\n public static final String MUSIC_REG_PATTERN = \"\\\\[mp3:(\\\\d+)\\\\]\";\n public static final String GIST_PREFIX_URL = \"https://gist.github.com/\";\n public static final String GIST_REG_PATTERN = \"&lt;script src=\\\"https://gist.github.com/(\\\\w+)/(\\\\w+)\\\\.js\\\">&lt;/script>\";\n public static final String GIST_REPLATE_PATTERN = \"<script src=\\\"https://gist.github.com/$1/$2\\\\.js\\\"></script>\";\n\n\n public static final String SQL_QUERY_METAS = \"select a.*, count(b.cid) as count from t_metas a left join `t_relationships` b on a.mid = b.mid \" +\n \"where a.type = ? and a.name = ? group by a.mid\";\n\n public static final String SQL_QUERY_ARTICLES = \"select a.* from t_contents a left join t_relationships b on a.cid = b.cid \" +\n \"where b.mid = ? and a.status = 'publish' and a.type = 'post' order by a.created desc\";\n\n public static final String COMMENT_APPROVED = \"approved\";\n public static final String COMMENT_NO_AUDIT = \"no_audit\";\n\n public static final String OPTION_CDN_URL = \"cdn_url\";\n public static final String OPTION_SITE_THEME = \"site_theme\";\n public static final String OPTION_ALLOW_INSTALL = \"allow_install\";\n public static final String OPTION_ALLOW_COMMENT_AUDIT = \"allow_comment_audit\";\n public static final String OPTION_ALLOW_CLOUD_CDN = \"allow_cloud_CDN\";\n public static final String OPTION_SAFE_REMEMBER_ME = \"safe_remember_me\";\n\n}" ]
import com.blade.exception.ValidatorException; import com.blade.ioc.annotation.Bean; import com.blade.kit.BladeKit; import com.blade.kit.DateKit; import com.tale.bootstrap.TaleConst; import com.tale.extension.Commons; import com.tale.model.dto.Comment; import com.tale.model.entity.Comments; import com.tale.model.entity.Contents; import com.tale.model.params.CommentParam; import com.tale.utils.TaleUtils; import com.vdurmont.emoji.EmojiParser; import io.github.biezhi.anima.Anima; import io.github.biezhi.anima.enums.OrderBy; import io.github.biezhi.anima.page.Page; import java.util.ArrayList; import java.util.List; import static com.tale.bootstrap.TaleConst.*; import static io.github.biezhi.anima.Anima.select; import static io.github.biezhi.anima.Anima.update;
package com.tale.service; /** * 评论Service * * @author biezhi * @since 1.3.1 */ @Bean public class CommentsService { /** * 保存评论 * * @param comments */ public void saveComment(Comments comments) { comments.setAuthor(TaleUtils.cleanXSS(comments.getAuthor())); comments.setContent(TaleUtils.cleanXSS(comments.getContent())); comments.setAuthor(EmojiParser.parseToAliases(comments.getAuthor())); comments.setContent(EmojiParser.parseToAliases(comments.getContent())); Contents contents = select().from(Contents.class).byId(comments.getCid()); if (null == contents) { throw new ValidatorException("不存在的文章"); } try { comments.setOwnerId(contents.getAuthorId()); comments.setAuthorId(null == comments.getAuthorId() ? 0 : comments.getAuthorId()); comments.setCreated(DateKit.nowUnix()); comments.setParent(null == comments.getCoid() ? 0 : comments.getCoid()); comments.setCoid(null); comments.save(); new Contents().set(Contents::getCommentsNum, contents.getCommentsNum() + 1).updateById(contents.getCid()); } catch (Exception e) { throw e; } } /** * 删除评论,暂时没用 * * @param coid * @param cid * @throws Exception */ public void delete(Integer coid, Integer cid) { Anima.delete().from(Comments.class).deleteById(coid); Contents contents = select().from(Contents.class).byId(cid); if (null != contents && contents.getCommentsNum() > 0) { update().from(Contents.class).set(Contents::getCommentsNum, contents.getCommentsNum() - 1).updateById(cid); } } /** * 获取文章下的评论 * * @param cid * @param page * @param limit * @return */
public Page<Comment> getComments(Integer cid, int page, int limit) {
2
kevinmmarlow/Dreamer
volley/src/main/java/com/android/fancyblurdemo/volley/toolbox/StringRequest.java
[ "public class NetworkResponse {\n /**\n * Creates a new network response.\n * @param statusCode the HTTP status code\n * @param data Response body\n * @param headers Headers returned with this response, or null for none\n * @param notModified True if the server returned a 304 and the data was already in cache\n */\n public NetworkResponse(int statusCode, byte[] data, Map<String, String> headers,\n boolean notModified) {\n this.statusCode = statusCode;\n this.data = data;\n this.headers = headers;\n this.notModified = notModified;\n }\n\n public NetworkResponse(byte[] data) {\n this(HttpStatus.SC_OK, data, Collections.<String, String>emptyMap(), false);\n }\n\n public NetworkResponse(byte[] data, Map<String, String> headers) {\n this(HttpStatus.SC_OK, data, headers, false);\n }\n\n /** The HTTP status code. */\n public final int statusCode;\n\n /** Raw data from this response. */\n public final byte[] data;\n\n /** Response headers. */\n public final Map<String, String> headers;\n\n /** True if the server returned a 304 (Not Modified). */\n public final boolean notModified;\n}", "public abstract class Request<T> implements Comparable<Request<T>> {\n\n /**\n * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}.\n */\n private static final String DEFAULT_PARAMS_ENCODING = \"UTF-8\";\n\n /**\n * Supported request methods.\n */\n public interface Method {\n int DEPRECATED_GET_OR_POST = -1;\n int GET = 0;\n int POST = 1;\n int PUT = 2;\n int DELETE = 3;\n int HEAD = 4;\n int OPTIONS = 5;\n int TRACE = 6;\n int PATCH = 7;\n }\n\n /** An event log tracing the lifetime of this request; for debugging. */\n private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;\n\n /**\n * Request method of this request. Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS,\n * TRACE, and PATCH.\n */\n private final int mMethod;\n\n /** URL of this request. */\n private final String mUrl;\n\n /** Default tag for {@link android.net.TrafficStats}. */\n private final int mDefaultTrafficStatsTag;\n\n /** Listener interface for errors. */\n private final Response.ErrorListener mErrorListener;\n\n /** Sequence number of this request, used to enforce FIFO ordering. */\n private Integer mSequence;\n\n /** The request queue this request is associated with. */\n private RequestQueue mRequestQueue;\n\n /** Whether or not responses to this request should be cached. */\n private boolean mShouldCache = true;\n\n /** Whether or not this request has been canceled. */\n private boolean mCanceled = false;\n\n /** Whether or not a response has been delivered for this request yet. */\n private boolean mResponseDelivered = false;\n\n // A cheap variant of request tracing used to dump slow requests.\n private long mRequestBirthTime = 0;\n\n /** Threshold at which we should log the request (even when debug logging is not enabled). */\n private static final long SLOW_REQUEST_THRESHOLD_MS = 3000;\n\n /** The retry policy for this request. */\n private RetryPolicy mRetryPolicy;\n\n /**\n * When a request can be retrieved from cache but must be refreshed from\n * the network, the cache entry will be stored here so that in the event of\n * a \"Not Modified\" response, we can be sure it hasn't been evicted from cache.\n */\n private Cache.Entry mCacheEntry = null;\n\n /** An opaque token tagging this request; used for bulk cancellation. */\n private Object mTag;\n\n /**\n * Creates a new request with the given URL and error listener. Note that\n * the normal response listener is not provided here as delivery of responses\n * is provided by subclasses, who have a better idea of how to deliver an\n * already-parsed response.\n *\n * @deprecated Use {@link #Request(int, String, com.android.fancyblurdemo.volley.Response.ErrorListener)}.\n */\n @Deprecated\n public Request(String url, Response.ErrorListener listener) {\n this(Method.DEPRECATED_GET_OR_POST, url, listener);\n }\n\n /**\n * Creates a new request with the given method (one of the values from {@link com.android.fancyblurdemo.volley.Request.Method}),\n * URL, and error listener. Note that the normal response listener is not provided here as\n * delivery of responses is provided by subclasses, who have a better idea of how to deliver\n * an already-parsed response.\n */\n public Request(int method, String url, Response.ErrorListener listener) {\n mMethod = method;\n mUrl = url;\n mErrorListener = listener;\n setRetryPolicy(new DefaultRetryPolicy());\n\n mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);\n }\n\n /**\n * Return the method for this request. Can be one of the values in {@link com.android.fancyblurdemo.volley.Request.Method}.\n */\n public int getMethod() {\n return mMethod;\n }\n\n /**\n * Set a tag on this request. Can be used to cancel all requests with this\n * tag by {@link RequestQueue#cancelAll(Object)}.\n *\n * @return This Request object to allow for chaining.\n */\n public Request<?> setTag(Object tag) {\n mTag = tag;\n return this;\n }\n\n /**\n * Returns this request's tag.\n * @see com.android.fancyblurdemo.volley.Request#setTag(Object)\n */\n public Object getTag() {\n return mTag;\n }\n\n /**\n * @return A tag for use with {@link android.net.TrafficStats#setThreadStatsTag(int)}\n */\n public int getTrafficStatsTag() {\n return mDefaultTrafficStatsTag;\n }\n\n /**\n * @return The hashcode of the URL's host component, or 0 if there is none.\n */\n private static int findDefaultTrafficStatsTag(String url) {\n if (!TextUtils.isEmpty(url)) {\n Uri uri = Uri.parse(url);\n if (uri != null) {\n String host = uri.getHost();\n if (host != null) {\n return host.hashCode();\n }\n }\n }\n return 0;\n }\n\n /**\n * Sets the retry policy for this request.\n *\n * @return This Request object to allow for chaining.\n */\n public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {\n mRetryPolicy = retryPolicy;\n return this;\n }\n\n /**\n * Adds an event to this request's event log; for debugging.\n */\n public void addMarker(String tag) {\n if (MarkerLog.ENABLED) {\n mEventLog.add(tag, Thread.currentThread().getId());\n } else if (mRequestBirthTime == 0) {\n mRequestBirthTime = SystemClock.elapsedRealtime();\n }\n }\n\n /**\n * Notifies the request queue that this request has finished (successfully or with error).\n *\n * <p>Also dumps all events from this request's event log; for debugging.</p>\n */\n void finish(final String tag) {\n if (mRequestQueue != null) {\n mRequestQueue.finish(this);\n }\n if (MarkerLog.ENABLED) {\n final long threadId = Thread.currentThread().getId();\n if (Looper.myLooper() != Looper.getMainLooper()) {\n // If we finish marking off of the main thread, we need to\n // actually do it on the main thread to ensure correct ordering.\n Handler mainThread = new Handler(Looper.getMainLooper());\n mainThread.post(new Runnable() {\n @Override\n public void run() {\n mEventLog.add(tag, threadId);\n mEventLog.finish(this.toString());\n }\n });\n return;\n }\n\n mEventLog.add(tag, threadId);\n mEventLog.finish(this.toString());\n } else {\n long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;\n if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {\n VolleyLog.d(\"%d ms: %s\", requestTime, this.toString());\n }\n }\n }\n\n /**\n * Associates this request with the given queue. The request queue will be notified when this\n * request has finished.\n *\n * @return This Request object to allow for chaining.\n */\n public Request<?> setRequestQueue(RequestQueue requestQueue) {\n mRequestQueue = requestQueue;\n return this;\n }\n\n /**\n * Sets the sequence number of this request. Used by {@link RequestQueue}.\n *\n * @return This Request object to allow for chaining.\n */\n public final Request<?> setSequence(int sequence) {\n mSequence = sequence;\n return this;\n }\n\n /**\n * Returns the sequence number of this request.\n */\n public final int getSequence() {\n if (mSequence == null) {\n throw new IllegalStateException(\"getSequence called before setSequence\");\n }\n return mSequence;\n }\n\n /**\n * Returns the URL of this request.\n */\n public String getUrl() {\n return mUrl;\n }\n\n /**\n * Returns the cache key for this request. By default, this is the URL.\n */\n public String getCacheKey() {\n return getUrl();\n }\n\n /**\n * Annotates this request with an entry retrieved for it from cache.\n * Used for cache coherency support.\n *\n * @return This Request object to allow for chaining.\n */\n public Request<?> setCacheEntry(Cache.Entry entry) {\n mCacheEntry = entry;\n return this;\n }\n\n /**\n * Returns the annotated cache entry, or null if there isn't one.\n */\n public Cache.Entry getCacheEntry() {\n return mCacheEntry;\n }\n\n /**\n * Mark this request as canceled. No callback will be delivered.\n */\n public void cancel() {\n mCanceled = true;\n }\n\n /**\n * Returns true if this request has been canceled.\n */\n public boolean isCanceled() {\n return mCanceled;\n }\n\n /**\n * Returns a list of extra HTTP headers to go along with this request. Can\n * throw {@link AuthFailureError} as authentication may be required to\n * provide these values.\n * @throws AuthFailureError In the event of auth failure\n */\n public Map<String, String> getHeaders() throws AuthFailureError {\n return Collections.emptyMap();\n }\n\n /**\n * Returns a Map of POST parameters to be used for this request, or null if\n * a simple GET should be used. Can throw {@link AuthFailureError} as\n * authentication may be required to provide these values.\n *\n * <p>Note that only one of getPostParams() and getPostBody() can return a non-null\n * value.</p>\n * @throws AuthFailureError In the event of auth failure\n *\n * @deprecated Use {@link #getParams()} instead.\n */\n @Deprecated\n protected Map<String, String> getPostParams() throws AuthFailureError {\n return getParams();\n }\n\n /**\n * Returns which encoding should be used when converting POST parameters returned by\n * {@link #getPostParams()} into a raw POST body.\n *\n * <p>This controls both encodings:\n * <ol>\n * <li>The string encoding used when converting parameter names and values into bytes prior\n * to URL encoding them.</li>\n * <li>The string encoding used when converting the URL encoded parameters into a raw\n * byte array.</li>\n * </ol>\n *\n * @deprecated Use {@link #getParamsEncoding()} instead.\n */\n @Deprecated\n protected String getPostParamsEncoding() {\n return getParamsEncoding();\n }\n\n /**\n * @deprecated Use {@link #getBodyContentType()} instead.\n */\n @Deprecated\n public String getPostBodyContentType() {\n return getBodyContentType();\n }\n\n /**\n * Returns the raw POST body to be sent.\n *\n * @throws AuthFailureError In the event of auth failure\n *\n * @deprecated Use {@link #getBody()} instead.\n */\n @Deprecated\n public byte[] getPostBody() throws AuthFailureError {\n // Note: For compatibility with legacy clients of volley, this implementation must remain\n // here instead of simply calling the getBody() function because this function must\n // call getPostParams() and getPostParamsEncoding() since legacy clients would have\n // overridden these two member functions for POST requests.\n Map<String, String> postParams = getPostParams();\n if (postParams != null && postParams.size() > 0) {\n return encodeParameters(postParams, getPostParamsEncoding());\n }\n return null;\n }\n\n /**\n * Returns a Map of parameters to be used for a POST or PUT request. Can throw\n * {@link AuthFailureError} as authentication may be required to provide these values.\n *\n * <p>Note that you can directly override {@link #getBody()} for custom data.</p>\n *\n * @throws AuthFailureError in the event of auth failure\n */\n protected Map<String, String> getParams() throws AuthFailureError {\n return null;\n }\n\n /**\n * Returns which encoding should be used when converting POST or PUT parameters returned by\n * {@link #getParams()} into a raw POST or PUT body.\n *\n * <p>This controls both encodings:\n * <ol>\n * <li>The string encoding used when converting parameter names and values into bytes prior\n * to URL encoding them.</li>\n * <li>The string encoding used when converting the URL encoded parameters into a raw\n * byte array.</li>\n * </ol>\n */\n protected String getParamsEncoding() {\n return DEFAULT_PARAMS_ENCODING;\n }\n\n public String getBodyContentType() {\n return \"application/x-www-form-urlencoded; charset=\" + getParamsEncoding();\n }\n\n /**\n * Returns the raw POST or PUT body to be sent.\n *\n * @throws AuthFailureError in the event of auth failure\n */\n public byte[] getBody() throws AuthFailureError {\n Map<String, String> params = getParams();\n if (params != null && params.size() > 0) {\n return encodeParameters(params, getParamsEncoding());\n }\n return null;\n }\n\n /**\n * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.\n */\n private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {\n StringBuilder encodedParams = new StringBuilder();\n try {\n for (Map.Entry<String, String> entry : params.entrySet()) {\n encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));\n encodedParams.append('=');\n encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));\n encodedParams.append('&');\n }\n return encodedParams.toString().getBytes(paramsEncoding);\n } catch (UnsupportedEncodingException uee) {\n throw new RuntimeException(\"Encoding not supported: \" + paramsEncoding, uee);\n }\n }\n\n /**\n * Set whether or not responses to this request should be cached.\n *\n * @return This Request object to allow for chaining.\n */\n public final Request<?> setShouldCache(boolean shouldCache) {\n mShouldCache = shouldCache;\n return this;\n }\n\n /**\n * Returns true if responses to this request should be cached.\n */\n public final boolean shouldCache() {\n return mShouldCache;\n }\n\n /**\n * Priority values. Requests will be processed from higher priorities to\n * lower priorities, in FIFO order.\n */\n public enum Priority {\n LOW,\n NORMAL,\n HIGH,\n IMMEDIATE\n }\n\n /**\n * Returns the {@link com.android.fancyblurdemo.volley.Request.Priority} of this request; {@link com.android.fancyblurdemo.volley.Request.Priority#NORMAL} by default.\n */\n public Priority getPriority() {\n return Priority.NORMAL;\n }\n\n /**\n * Returns the socket timeout in milliseconds per retry attempt. (This value can be changed\n * per retry attempt if a backoff is specified via backoffTimeout()). If there are no retry\n * attempts remaining, this will cause delivery of a {@link TimeoutError} error.\n */\n public final int getTimeoutMs() {\n return mRetryPolicy.getCurrentTimeout();\n }\n\n /**\n * Returns the retry policy that should be used for this request.\n */\n public RetryPolicy getRetryPolicy() {\n return mRetryPolicy;\n }\n\n /**\n * Mark this request as having a response delivered on it. This can be used\n * later in the request's lifetime for suppressing identical responses.\n */\n public void markDelivered() {\n mResponseDelivered = true;\n }\n\n /**\n * Returns true if this request has had a response delivered for it.\n */\n public boolean hasHadResponseDelivered() {\n return mResponseDelivered;\n }\n\n /**\n * Subclasses must implement this to parse the raw network response\n * and return an appropriate response type. This method will be\n * called from a worker thread. The response will not be delivered\n * if you return null.\n * @param response Response from the network\n * @return The parsed response, or null in the case of an error\n */\n abstract protected Response<T> parseNetworkResponse(NetworkResponse response);\n\n /**\n * Subclasses can override this method to parse 'networkError' and return a more specific error.\n *\n * <p>The default implementation just returns the passed 'networkError'.</p>\n *\n * @param volleyError the error retrieved from the network\n * @return an NetworkError augmented with additional information\n */\n protected VolleyError parseNetworkError(VolleyError volleyError) {\n return volleyError;\n }\n\n /**\n * Subclasses must implement this to perform delivery of the parsed\n * response to their listeners. The given response is guaranteed to\n * be non-null; responses that fail to parse are not delivered.\n * @param response The parsed response returned by\n * {@link #parseNetworkResponse(NetworkResponse)}\n */\n abstract protected void deliverResponse(T response);\n\n /**\n * Delivers error message to the ErrorListener that the Request was\n * initialized with.\n *\n * @param error Error details\n */\n public void deliverError(VolleyError error) {\n if (mErrorListener != null) {\n mErrorListener.onErrorResponse(error);\n }\n }\n\n /**\n * Our comparator sorts from high to low priority, and secondarily by\n * sequence number to provide FIFO ordering.\n */\n @Override\n public int compareTo(Request<T> other) {\n Priority left = this.getPriority();\n Priority right = other.getPriority();\n\n // High-priority requests are \"lesser\" so they are sorted to the front.\n // Equal priorities are sorted by sequence number to provide FIFO ordering.\n return left == right ?\n this.mSequence - other.mSequence :\n right.ordinal() - left.ordinal();\n }\n\n @Override\n public String toString() {\n String trafficStatsTag = \"0x\" + Integer.toHexString(getTrafficStatsTag());\n return (mCanceled ? \"[X] \" : \"[ ] \") + getUrl() + \" \" + trafficStatsTag + \" \"\n + getPriority() + \" \" + mSequence;\n }\n}", "public class Response<T> {\n\n /** Callback interface for delivering parsed responses. */\n public interface Listener<T> {\n /** Called when a response is received. */\n public void onResponse(T response);\n }\n\n /** Callback interface for delivering error responses. */\n public interface ErrorListener {\n /**\n * Callback method that an error has been occurred with the\n * provided error code and optional user-readable message.\n */\n public void onErrorResponse(VolleyError error);\n }\n\n /** Returns a successful response containing the parsed result. */\n public static <T> Response<T> success(T result, Cache.Entry cacheEntry) {\n return new Response<T>(result, cacheEntry);\n }\n\n /**\n * Returns a failed response containing the given error code and an optional\n * localized message displayed to the user.\n */\n public static <T> Response<T> error(VolleyError error) {\n return new Response<T>(error);\n }\n\n /** Parsed response, or null in the case of error. */\n public final T result;\n\n /** Cache metadata for this response, or null in the case of error. */\n public final Cache.Entry cacheEntry;\n\n /** Detailed error information if <code>errorCode != OK</code>. */\n public final VolleyError error;\n\n /** True if this response was a soft-expired one and a second one MAY be coming. */\n public boolean intermediate = false;\n\n /**\n * Returns whether this response is considered successful.\n */\n public boolean isSuccess() {\n return error == null;\n }\n\n\n private Response(T result, Cache.Entry cacheEntry) {\n this.result = result;\n this.cacheEntry = cacheEntry;\n this.error = null;\n }\n\n private Response(VolleyError error) {\n this.result = null;\n this.cacheEntry = null;\n this.error = error;\n }\n}", "public interface ErrorListener {\n /**\n * Callback method that an error has been occurred with the\n * provided error code and optional user-readable message.\n */\n public void onErrorResponse(VolleyError error);\n}", "public interface Listener<T> {\n /** Called when a response is received. */\n public void onResponse(T response);\n}" ]
import com.android.fancyblurdemo.volley.NetworkResponse; import com.android.fancyblurdemo.volley.Request; import com.android.fancyblurdemo.volley.Response; import com.android.fancyblurdemo.volley.Response.ErrorListener; import com.android.fancyblurdemo.volley.Response.Listener; import java.io.UnsupportedEncodingException;
/* * Copyright (C) 2011 The Android Open Source Project * * 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 com.android.fancyblurdemo.volley.toolbox; /** * A canned request for retrieving the response body at a given URL as a String. */ public class StringRequest extends Request<String> { private final Listener<String> mListener; /** * Creates a new request with the given method. * * @param method the request {@link Method} to use * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(int method, String url, Listener<String> listener, ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; } /** * Creates a new GET request. * * @param url URL to fetch the string at * @param listener Listener to receive the String response * @param errorListener Error listener, or null to ignore errors */ public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) { this(Method.GET, url, listener, errorListener); } @Override protected void deliverResponse(String response) { mListener.onResponse(response); } @Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
0
larusba/neo4j-jdbc
neo4j-jdbc-bolt/src/test/java/org/neo4j/jdbc/bolt/BoltNeo4jStatementTest.java
[ "public abstract class Neo4jStatement implements Statement, Loggable {\n\n\tprotected Neo4jConnection connection;\n\tprotected ResultSet currentResultSet;\n\tprotected int currentUpdateCount;\n\tprotected List<String> batchStatements;\n\tprotected boolean debug;\n\tprotected int debugLevel;\n\tprotected int[] resultSetParams;\n\tprivate int maxRows;\n\tprivate int queryTimeout;\n\n\t/**\n\t * Default constructor with JDBC connection.\n\t *\n\t * @param connection The JDBC connection\n\t */\n\tprotected Neo4jStatement(Neo4jConnection connection) {\n\t\tthis.connection = connection;\n\t\tthis.currentResultSet = null;\n\t\tthis.currentUpdateCount = -1;\n\n\t\tthis.maxRows = 0;\n\t\tif (connection != null && connection.getProperties() != null) {\n\t\t\tthis.maxRows = Integer.parseInt(connection.getProperties().getProperty(\"maxrows\", \"0\"));\n\t\t}\n\t}\n\n\t/**\n\t * Check if this statement is closed or not.\n\t * If it is, we throw an exception.\n\t *\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkClosed() throws SQLException {\n\t\tif (this.isClosed()) {\n\t\t\tthrow new SQLException(\"Statement already closed\");\n\t\t}\n\t}\n\n\t/*------------------------------------*/\n\t/* Default implementation */\n\t/*------------------------------------*/\n\n\t@Override public Neo4jConnection getConnection() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn this.connection;\n\t}\n\n\t/**\n\t * /!\\ Like javadoc said, this method should be called one times.\n\t * Bolt statement always return two results : ResulSet and updatecount.\n\t * Because each time we retrieve a data we set it to the default value\n\t * here we have two cases :\n\t * - if there a resultset : we tell it by responding -1\n\t * - otherwise we give the updatecount and reset its value to default\n\t */\n\t@Override public int getUpdateCount() throws SQLException {\n\t\tthis.checkClosed();\n\t\tint update = this.currentUpdateCount;\n\n\t\tif (this.currentResultSet != null) {\n\t\t\tupdate = -1;\n\t\t} else {\n\t\t\tthis.currentUpdateCount = -1;\n\t\t}\n\t\treturn update;\n\t}\n\n\t/**\n\t * Like javadoc said, this method should be called one times.\n\t */\n\t@Override public ResultSet getResultSet() throws SQLException {\n\t\tthis.checkClosed();\n\t\tResultSet rs = this.currentResultSet;\n\t\tthis.currentResultSet = null;\n\t\treturn rs;\n\t}\n\n\t@Override public int getMaxRows() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn this.maxRows;\n\t}\n\n\t@Override public void setMaxRows(int max) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.maxRows = max;\n\t}\n\n\t@Override public boolean isClosed() throws SQLException {\n\t\treturn !(connection != null && !connection.isClosed());\n\t}\n\n\t@Override public void close() throws SQLException {\n\t\tif (!this.isClosed()) {\n\t\t\tif (this.currentResultSet != null && !this.currentResultSet.isClosed()) {\n\t\t\t\tthis.currentResultSet.close();\n\t\t\t}\n\t\t\tthis.currentUpdateCount = -1;\n\t\t\tthis.connection = null;\n\t\t}\n\t}\n\n\t@Override public <T> T unwrap(Class<T> iface) throws SQLException {\n\t\treturn org.neo4j.jdbc.Wrapper.unwrap(iface, this);\n\t}\n\n\t@Override public boolean isWrapperFor(Class<?> iface) throws SQLException {\n\t\treturn org.neo4j.jdbc.Wrapper.isWrapperFor(iface, this.getClass());\n\t}\n\n\t/**\n\t * Some tools call this method, so this just a workaround to make it work.\n\t * If you set the fetch at Integer.MIN_VALUE, or if you put maxRows to -1, there is no exception.\n\t * It's pretty much the same hack as the mysql connector.\n\t */\n\t@Override public void setFetchSize(int rows) throws SQLException {\n\t\tthis.checkClosed();\n\t\tif (rows != Integer.MIN_VALUE && (this.getMaxRows() > 0 && rows > this.getMaxRows())) {\n\t\t\tthrow new UnsupportedOperationException(\"Not implemented yet. => maxRow :\" + getMaxRows() + \" rows :\" + rows);\n\t\t}\n\t}\n\n\t/**\n\t * Some tools call this method, so for now just respond false.\n\t */\n\t@Override public boolean getMoreResults() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn !(this.currentResultSet == null && this.currentUpdateCount == -1);\n\t}\n\n\t/**\n\t * Some tool call this method, so for now just respond null.\n\t * It will be possible to implement this an explain.\n\t */\n\t@Override public SQLWarning getWarnings() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn null;\n\t}\n\n\t/**\n\t * Some tool call this method.\n\t */\n\t@Override public void clearWarnings() throws SQLException {\n\t\tthis.checkClosed();\n\t\t// nothing yet\n\t}\n\n\t/**\n\t * Added just for value memorization\n\t *\n\t * @return the current query timeout limit in seconds; zero means there is no limit\n\t * @throws SQLException if a database error occurs\n\t */\n\t@Override public int getQueryTimeout() throws SQLException {\n\t\treturn this.queryTimeout;\n\t}\n\n\t/**\n\t * Added just for value memorization\n\t *\n\t * @param seconds the new query timeout limit in seconds; zero means there is no limit\n\t * @throws SQLException if a database error occurs\n\t */\n\t@Override public void setQueryTimeout(int seconds) throws SQLException {\n\t\tthis.queryTimeout = seconds;\n\t}\n\n\t@Override public void addBatch(String sql) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.batchStatements.add(sql);\n\t}\n\n\t@Override public void clearBatch() throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.batchStatements.clear();\n\t}\n\n\t@Override public int getResultSetConcurrency() throws SQLException {\n\t\tthis.checkClosed();\n\t\tif (currentResultSet != null) {\n\t\t\treturn currentResultSet.getConcurrency();\n\t\t}\n\t\tif (this.resultSetParams.length > 1) {\n\t\t\treturn this.resultSetParams[1];\n\t\t}\n\t\treturn Neo4jResultSet.DEFAULT_CONCURRENCY;\n\t}\n\n\t@Override public int getResultSetType() throws SQLException {\n\t\tthis.checkClosed();\n\t\tif (currentResultSet != null) {\n\t\t\treturn currentResultSet.getType();\n\t\t}\n\t\tif (this.resultSetParams.length > 0) {\n\t\t\treturn this.resultSetParams[0];\n\t\t}\n\t\treturn Neo4jResultSet.DEFAULT_TYPE;\n\t}\n\n\t@Override public int getResultSetHoldability() throws SQLException {\n\t\tthis.checkClosed();\n\t\tif (currentResultSet != null) {\n\t\t\treturn currentResultSet.getHoldability();\n\t\t}\n\t\tif (this.resultSetParams.length > 2) {\n\t\t\treturn this.resultSetParams[2];\n\t\t}\n\t\treturn Neo4jResultSet.DEFAULT_HOLDABILITY;\n\t}\n\n\t/*---------------------------------*/\n\t/* Not implemented yet */\n\t/*---------------------------------*/\n\n\t@Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public boolean execute(String sql, int[] columnIndexes) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public boolean execute(String sql, String[] columnNames) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int executeUpdate(String sql, String[] columnNames) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int getMaxFieldSize() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setMaxFieldSize(int max) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setEscapeProcessing(boolean enable) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setCursorName(String name) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setFetchDirection(int direction) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int getFetchDirection() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int getFetchSize() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public boolean getMoreResults(int current) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public ResultSet getGeneratedKeys() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void cancel() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setPoolable(boolean poolable) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public boolean isPoolable() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int[] executeBatch() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void closeOnCompletion() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public boolean isCloseOnCompletion() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public boolean hasDebug() {\n\t\treturn this.debug;\n\t}\n\n\t@Override public void setDebug(boolean debug) {\n\t\tthis.debug = debug;\n\t}\n\n\t@Override public void setDebugLevel(int level) {\n\t\tthis.debugLevel = level;\n\t}\n\n\t@Override public int getDebugLevel() {\n\t\treturn this.debugLevel;\n\t}\n}", "public class StatementData {\n\tpublic static String STATEMENT_MATCH_ALL = \"MATCH (n) RETURN n;\";\n\tpublic static String STATEMENT_MATCH_ALL_STRING = \"MATCH (n:User) RETURN n.name;\";\n\tpublic static String STATEMENT_MATCH_NODES = \"MATCH (n:User) RETURN n;\";\n\tpublic static String STATEMENT_MATCH_NODES_MORE = \"MATCH (n:User)-[]->(s:Session) RETURN n, s;\";\n\tpublic static String STATEMENT_MATCH_MISC = \"MATCH (n:User) RETURN n, n.name;\";\n\tpublic static String STATEMENT_MATCH_RELATIONS = \"MATCH ()-[r:CONNECTED_IN]-() RETURN r;\";\n\tpublic static String STATEMENT_MATCH_NODES_RELATIONS = \"MATCH (n:User)-[r:CONNECTED_IN]->(s:Session) RETURN n, r, s\";\n\tpublic static String STATEMENT_CREATE = \"CREATE (n:User {name:\\\"test\\\"});\";\n\tpublic static String STATEMENT_CREATE_REV = \"MATCH (n:User {name:\\\"test\\\"}) DELETE n;\";\n\tpublic static String STATEMENT_CREATE_TWO_PROPERTIES = \"CREATE (n:User {name:\\\"test\\\", surname:\\\"testAgain\\\"});\";\n\tpublic static String STATEMENT_CREATE_TWO_PROPERTIES_REV = \"MATCH (n:USer {name:\\\"test\\\", surname:\\\"testAgain\\\"}) DETACH DELETE n;\";\n\tpublic static String STATEMENT_MATCH_ALL_STRING_PARAMETRIC = \"MATCH (n) WHERE n.name = ? RETURN n.surname;\";\n\tpublic static String STATEMENT_MATCH_ALL_STRING_PARAMETRIC_NAMED = \"MATCH (n) WHERE n.name = {1} RETURN n.surname;\";\n\tpublic static String STATEMENT_CREATE_OTHER_TYPE_AND_RELATIONS = \"MATCH (n:User) CREATE (n)-[:CONNECTED_IN {date:1459248821051}]->(:Session {status:true});\";\n\tpublic static String STATEMENT_CREATE_OTHER_TYPE_AND_RELATIONS_REV = \"MATCH (s:Session) DETACH DELETE s;\";\n\tpublic static String STATEMENT_CREATE_TWO_PROPERTIES_PARAMETRIC = \"CREATE (n:User {name:?, surname:?});\";\n\tpublic static String STATEMENT_CREATE_TWO_PROPERTIES_PARAMETRIC_REV = \"MATCH (n:User {name:?, surname:?}) DETACH DELETE n;\";\n\tpublic static String STATEMENT_CLEAR_DB = \"MATCH (n) DETACH DELETE n;\";\n\tpublic static String STATEMENT_COUNT_NODES = \"MATCH (n) RETURN count(n) AS total;\";\n}", "public class BoltNeo4jConnectionImpl extends Neo4jConnectionImpl implements BoltNeo4jConnection {\n\n\tprivate Session session;\n\tprivate Transaction transaction;\n\tprivate boolean autoCommit = true;\n\n\tprivate static final Logger LOGGER = Logger.getLogger(BoltNeo4jConnectionImpl.class.getName());\n\n\t/**\n\t * Constructor with Session and Properties.\n\t *\n\t * @param session Bolt Session\n\t * @param properties Driver properties\n\t * @param url Url used for this connection\n\t */\n\tpublic BoltNeo4jConnectionImpl(Session session, Properties properties, String url) {\n\t\tsuper(properties, url, BoltNeo4jResultSet.DEFAULT_HOLDABILITY);\n\t\tthis.session = session;\n\t}\n\n\t/**\n\t * Constructor with Session.\n\t *\n\t * @param session Bolt Session\n\t */\n\tpublic BoltNeo4jConnectionImpl(Session session) {\n\t\tthis(session, new Properties(), \"\");\n\t}\n\n\tpublic static BoltNeo4jConnection newInstance(Session session, Properties info, String url) {\n\t\tBoltNeo4jConnection boltConnection = new BoltNeo4jConnectionImpl(session, info, url);\n\t\treturn (BoltNeo4jConnection) Proxy\n\t\t\t\t.newProxyInstance(BoltNeo4jConnectionImpl.class.getClassLoader(), new Class[] { Connection.class, BoltNeo4jConnection.class },\n\t\t\t\t\t\tnew Neo4jInvocationHandler(boltConnection, BoltNeo4jConnectionImpl.hasDebug(info)));\n\t}\n\n\t/**\n\t * Getter for transaction.\n\t *\n\t * @return the transaction\n\t */\n\t@Override public Transaction getTransaction() {\n\t\treturn this.transaction;\n\t}\n\n\t/**\n\t * Getter for session.\n\t *\n\t * @return the internal session\n\t */\n\t@Override public Session getSession() {\n\t\treturn this.session;\n\t}\n\n\t@Override public Neo4jDatabaseMetaData getMetaData() throws SQLException {\n\t\treturn new BoltNeo4jDatabaseMetaData(this);\n\t}\n\n\t/*------------------------------*/\n\t/* Commit, rollback */\n\t/*------------------------------*/\n\n\t@Override public void setAutoCommit(boolean autoCommit) throws SQLException {\n\t\tif (this.autoCommit != autoCommit) {\n\t\t\tif (this.transaction != null && !this.autoCommit) {\n\t\t\t\tthis.commit();\n\t\t\t\tthis.transaction.close();\n\t\t\t}\n\n\t\t\tif (this.autoCommit) {\n\t\t\t\t//Simply restart the transaction\n\t\t\t\tthis.transaction = this.session.beginTransaction();\n\t\t\t}\n\n\t\t\tthis.autoCommit = autoCommit;\n\t\t}\n\t}\n\n\t@Override public boolean getAutoCommit() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn autoCommit;\n\t}\n\n\t@Override public void commit() throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.checkAutoCommit();\n\t\tif (this.transaction == null) {\n\t\t\tthrow new SQLException(\"The transaction is null\");\n\t\t}\n\t\tthis.transaction.success();\n\t\tthis.transaction.close();\n\t\tthis.transaction = this.session.beginTransaction();\n\t}\n\n\t@Override public void rollback() throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.checkAutoCommit();\n\t\tif (this.transaction == null) {\n\t\t\tthrow new SQLException(\"The transaction is null\");\n\t\t}\n\t\tthis.transaction.failure();\n\t}\n\n\t/*------------------------------*/\n\t/* Create Statement */\n\t/*------------------------------*/\n\n\t@Override public Statement createStatement() throws SQLException {\n\t\tif (this.transaction == null && !this.autoCommit) {\n\t\t\tthis.transaction = this.session.beginTransaction();\n\t\t}\n\t\treturn createStatement(Neo4jResultSet.TYPE_FORWARD_ONLY, Neo4jResultSet.CONCUR_READ_ONLY, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);\n\t}\n\n\t@Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {\n\t\treturn createStatement(resultSetType, resultSetConcurrency, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);\n\t}\n\n\t@Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.checkTypeParams(resultSetType);\n\t\tthis.checkConcurrencyParams(resultSetConcurrency);\n\t\tthis.checkHoldabilityParams(resultSetHoldability);\n\t\treturn BoltNeo4jStatement.newInstance(false, this, resultSetType, resultSetConcurrency, resultSetHoldability);\n\t}\n\n\t/*-------------------------------*/\n\t/* Prepare Statement */\n\t/*-------------------------------*/\n\n\t@Override public PreparedStatement prepareStatement(String sql) throws SQLException {\n\t\treturn prepareStatement(nativeSQL(sql), Neo4jResultSet.TYPE_FORWARD_ONLY, Neo4jResultSet.CONCUR_READ_ONLY, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);\n\t}\n\n\t@Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {\n\t\treturn prepareStatement(nativeSQL(sql), resultSetType, resultSetConcurrency, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);\n\t}\n\n\t@Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.checkTypeParams(resultSetType);\n\t\tthis.checkConcurrencyParams(resultSetConcurrency);\n\t\tthis.checkHoldabilityParams(resultSetHoldability);\n\t\treturn BoltNeo4jPreparedStatement.newInstance(false, this, nativeSQL(sql), resultSetType, resultSetConcurrency, resultSetHoldability);\n\t}\n\n\t/*-------------------*/\n\t/* Close */\n\t/*-------------------*/\n\n\t@Override public boolean isClosed() throws SQLException {\n\t\treturn !this.session.isOpen();\n\t}\n\n\t@Override public void close() throws SQLException {\n\t\ttry {\n\t\t\tif (!this.isClosed()) {\n\t\t\t\tsession.close();\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new SQLException(\"A database access error has occurred: \" + e.getMessage());\n\t\t}\n\t}\n\n\t/*-------------------*/\n\t/* isValid */\n\t/*-------------------*/\n\t@Override public boolean isValid(int timeout) throws SQLException {\n\t\tif (timeout < 0) {\n\t\t\tthrow new SQLException(\"Timeout can't be less than zero\");\n\t\t}\n\t\tif (this.isClosed()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tRunnable r = new Runnable() {\n\t\t\t@Override public void run() {\n\t\t\t\tSession s = getSession();\n\t\t\t\tTransaction tr = getTransaction();\n\t\t\t\tif (tr != null && tr.isOpen()) {\n\t\t\t\t\ttr.run(FASTEST_STATEMENT);\n\t\t\t\t} else {\n\t\t\t\t\ts.run(FASTEST_STATEMENT);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tTimeLimitedCodeBlock.runWithTimeout(r, timeout, TimeUnit.SECONDS);\n\t\t} catch (Exception e) { // also timeout\n\t\t\tLOGGER.log(Level.FINEST, \"Catch exception totally fine\", e);\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n}", "public class Mocker {\n\n\tpublic static Session mockSessionOpen() {\n\t\tSession session = mock(Session.class);\n\t\twhen(session.isOpen()).thenReturn(true);\n\t\tTransaction transaction = mock(Transaction.class);\n\t\twhen(session.beginTransaction()).thenReturn(transaction);\n\t\treturn session;\n\t}\n\n\tpublic static Session mockSessionClosed() {\n\t\treturn mock(Session.class);\n\t}\n\n\tpublic static Session mockSessionOpenSlow() {\n\t\tSession session = mock(Session.class);\n\t\twhen(session.isOpen()).thenReturn(true);\n\t\tTransaction transaction = mock(Transaction.class);\n\t\twhen(session.beginTransaction()).thenReturn(transaction);\n\t\twhen(session.run(anyString())).thenAnswer(new Answer<ResultSet>() {\n\t\t\t@Override public ResultSet answer(InvocationOnMock invocation) {\n\t\t\t\ttry {\n\t\t\t\t\tTimeUnit.SECONDS.sleep(5);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t});\n\t\treturn session;\n\t}\n\n\tpublic static Session mockSessionException() {\n\t\tSession session = mock(Session.class);\n\t\twhen(session.isOpen()).thenReturn(true);\n\t\tTransaction transaction = mock(Transaction.class);\n\t\twhen(session.beginTransaction()).thenReturn(transaction);\n\t\twhen(session.run(anyString())).thenThrow(new RuntimeException(\"RuntimeException THROWN\"));\n\t\treturn session;\n\t}\n\n\tpublic static BoltNeo4jConnectionImpl mockConnectionOpen() throws SQLException {\n\t\tBoltNeo4jConnectionImpl mockConnection = mock(BoltNeo4jConnectionImpl.class);\n\t\twhen(mockConnection.isClosed()).thenReturn(false);\n\t\treturn mockConnection;\n\t}\n\n\tpublic static BoltNeo4jConnectionImpl mockConnectionClosed() throws SQLException {\n\t\tBoltNeo4jConnectionImpl mockConnection = mock(BoltNeo4jConnectionImpl.class);\n\t\twhen(mockConnection.isClosed()).thenReturn(true);\n\t\treturn mockConnection;\n\t}\n\n\tpublic static BoltNeo4jConnectionImpl mockConnectionOpenWithTransactionThatReturns(StatementResult cur) throws SQLException {\n\t\tTransaction mockTransaction = mock(Transaction.class);\n\t\twhen(mockTransaction.run(anyString())).thenReturn(cur);\n\t\twhen(mockTransaction.run(anyString(), any(HashMap.class))).thenReturn(cur);\n\n\t\tBoltNeo4jConnectionImpl mockConnection = mockConnectionOpen();\n\t\twhen(mockConnection.getTransaction()).thenReturn(mockTransaction);\n\t\treturn mockConnection;\n\t}\n\n\tpublic static Driver mockDriver() {\n\t\tDriver mockedDriver = mock(org.neo4j.driver.v1.Driver.class);\n\t\tConnectionProvider connectionProvider = mock(ConnectionProvider.class, RETURNS_MOCKS);\n\t\tMockito.when(mockedDriver.session()).thenReturn(new NetworkSession(connectionProvider, AccessMode.READ,null, DevNullLogging.DEV_NULL_LOGGING));\n\t\treturn mockedDriver;\n\t}\n}", "public class Neo4jInvocationHandler implements InvocationHandler {\n\n\tprivate static final Logger LOGGER = Logger.getLogger(Neo4jInvocationHandler.class.getName());\n\n\tprivate final Map<String, Method> methods = new HashMap<>();\n\n\tprivate Object target;\n\tprivate boolean debug;\n\n\tpublic Neo4jInvocationHandler(Object target, boolean debug) {\n\t\tthis.target = target;\n\t\tthis.debug = debug;\n\n\t\tfor (Method method : target.getClass().getMethods()) {\n\t\t\tString key = getUniqueKeyFromMethod(method);\n\t\t\tthis.methods.put(key, method);\n\t\t}\n\t}\n\n\t@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n\t\ttry {\n\t\t\tObject result = methods.get(getUniqueKeyFromMethod(method)).invoke(target, args);\n\n\t\t\tif (debug) {\n\t\t\t\tLOGGER.info(\"[\" + target.getClass().getCanonicalName() + \"] \" + method.getName());\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch (InvocationTargetException e) {\n\t\t\tthrow e.getCause();\n\t\t}\n\t}\n\n\tprivate String getUniqueKeyFromMethod(Method method) {\n\t\tString key = method.getName() + \"_\";\n\t\tfor(Class type : method.getParameterTypes()) {\n\t\t\tkey += type.getCanonicalName() + \"_\";\n\t\t}\n\t\treturn key;\n\t}\n}", "public class Mocker {\n\n\tpublic static Session mockSessionOpen() {\n\t\tSession session = mock(Session.class);\n\t\twhen(session.isOpen()).thenReturn(true);\n\t\tTransaction transaction = mock(Transaction.class);\n\t\twhen(session.beginTransaction()).thenReturn(transaction);\n\t\treturn session;\n\t}\n\n\tpublic static Session mockSessionClosed() {\n\t\treturn mock(Session.class);\n\t}\n\n\tpublic static Session mockSessionOpenSlow() {\n\t\tSession session = mock(Session.class);\n\t\twhen(session.isOpen()).thenReturn(true);\n\t\tTransaction transaction = mock(Transaction.class);\n\t\twhen(session.beginTransaction()).thenReturn(transaction);\n\t\twhen(session.run(anyString())).thenAnswer(new Answer<ResultSet>() {\n\t\t\t@Override public ResultSet answer(InvocationOnMock invocation) {\n\t\t\t\ttry {\n\t\t\t\t\tTimeUnit.SECONDS.sleep(5);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t});\n\t\treturn session;\n\t}\n\n\tpublic static Session mockSessionException() {\n\t\tSession session = mock(Session.class);\n\t\twhen(session.isOpen()).thenReturn(true);\n\t\tTransaction transaction = mock(Transaction.class);\n\t\twhen(session.beginTransaction()).thenReturn(transaction);\n\t\twhen(session.run(anyString())).thenThrow(new RuntimeException(\"RuntimeException THROWN\"));\n\t\treturn session;\n\t}\n\n\tpublic static BoltNeo4jConnectionImpl mockConnectionOpen() throws SQLException {\n\t\tBoltNeo4jConnectionImpl mockConnection = mock(BoltNeo4jConnectionImpl.class);\n\t\twhen(mockConnection.isClosed()).thenReturn(false);\n\t\treturn mockConnection;\n\t}\n\n\tpublic static BoltNeo4jConnectionImpl mockConnectionClosed() throws SQLException {\n\t\tBoltNeo4jConnectionImpl mockConnection = mock(BoltNeo4jConnectionImpl.class);\n\t\twhen(mockConnection.isClosed()).thenReturn(true);\n\t\treturn mockConnection;\n\t}\n\n\tpublic static BoltNeo4jConnectionImpl mockConnectionOpenWithTransactionThatReturns(StatementResult cur) throws SQLException {\n\t\tTransaction mockTransaction = mock(Transaction.class);\n\t\twhen(mockTransaction.run(anyString())).thenReturn(cur);\n\t\twhen(mockTransaction.run(anyString(), any(HashMap.class))).thenReturn(cur);\n\n\t\tBoltNeo4jConnectionImpl mockConnection = mockConnectionOpen();\n\t\twhen(mockConnection.getTransaction()).thenReturn(mockTransaction);\n\t\treturn mockConnection;\n\t}\n\n\tpublic static Driver mockDriver() {\n\t\tDriver mockedDriver = mock(org.neo4j.driver.v1.Driver.class);\n\t\tConnectionProvider connectionProvider = mock(ConnectionProvider.class, RETURNS_MOCKS);\n\t\tMockito.when(mockedDriver.session()).thenReturn(new NetworkSession(connectionProvider, AccessMode.READ,null, DevNullLogging.DEV_NULL_LOGGING));\n\t\treturn mockedDriver;\n\t}\n}" ]
import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.internal.util.reflection.Whitebox; import org.neo4j.driver.v1.Session; import org.neo4j.driver.v1.StatementResult; import org.neo4j.driver.v1.Transaction; import org.neo4j.driver.v1.summary.ResultSummary; import org.neo4j.driver.v1.summary.SummaryCounters; import org.neo4j.jdbc.Neo4jStatement; import org.neo4j.jdbc.bolt.data.StatementData; import org.neo4j.jdbc.bolt.impl.BoltNeo4jConnectionImpl; import org.neo4j.jdbc.bolt.utils.Mocker; import org.neo4j.jdbc.utils.Neo4jInvocationHandler; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.lang.reflect.Proxy; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; import static org.neo4j.jdbc.bolt.utils.Mocker.*; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyStatic;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 19/02/16 */ package org.neo4j.jdbc.bolt; /** * @author AgileLARUS * @since 3.0.0 */ @RunWith(PowerMockRunner.class) @PrepareForTest({ BoltNeo4jStatement.class, BoltNeo4jResultSet.class, Session.class }) public class BoltNeo4jStatementTest { @Rule public ExpectedException expectedEx = ExpectedException.none(); private BoltNeo4jResultSet mockedRS; @Before public void interceptBoltResultSetConstructor() throws Exception { mockedRS = mock(BoltNeo4jResultSet.class); doNothing().when(mockedRS).close(); mockStatic(BoltNeo4jResultSet.class); PowerMockito.when(BoltNeo4jResultSet.newInstance(anyBoolean(), any(Neo4jStatement.class), any(StatementResult.class))).thenReturn(mockedRS); } /*------------------------------*/ /* close */ /*------------------------------*/ @Test public void closeShouldCloseExistingResultSet() throws Exception { Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null)); statement.executeQuery(StatementData.STATEMENT_MATCH_ALL); statement.close(); verify(mockedRS, times(1)).close(); } @Test public void closeShouldNotCallCloseOnAnyResultSet() throws Exception { Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null)); statement.close(); verify(mockedRS, never()).close(); } @Test public void closeMultipleTimesIsNOOP() throws Exception { Statement statement = BoltNeo4jStatement.newInstance(false, mockConnectionOpenWithTransactionThatReturns(null)); statement.executeQuery(StatementData.STATEMENT_MATCH_ALL); statement.close(); statement.close(); statement.close(); verify(mockedRS, times(1)).close(); } @Test public void closeShouldNotTouchTheTransaction() throws Exception { Transaction mockTransaction = mock(Transaction.class);
BoltNeo4jConnectionImpl mockConnection = mockConnectionOpen();
2
Xilef11/runesofwizardry-classics
src/main/java/xilef11/mc/runesofwizardry_classics/runes/entity/RuneEntityProtection.java
[ "public final class Refs {\n\tprivate Refs(){}\n\tpublic static final String MODID = \"runesofwizardry_classics\";\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String NAME=\"Runes of Wizardry - Classic Dusts Pack\";\n\tpublic static final String GUI_FACTORY=\"xilef11.mc.runesofwizardry_classics.client.gui.GuiFactory\";\n\tpublic static final String CLIENT_PROXY = \"xilef11.mc.runesofwizardry_classics.proxy.ClientProxy\",\n\t\t\t\t\t\t\t SERVER_PROXY=\"xilef11.mc.runesofwizardry_classics.proxy.ServerProxy\";\n\tpublic static final String PATTERN_PATH=MODID+\":patterns/\";\n\tpublic static final String TEXTURE_PATH=MODID+\":\";\n\tpublic static final int TICKS_PER_DAY=24000;\n\tpublic static final int TPS=20;\n\tpublic static final class Lang{\n\t\tprivate Lang(){}\n\t\tpublic static final String RUNE=MODID+\".rune\";\n\t\tpublic static final String CONFIG=MODID+\".configuration\";\n\t\tpublic static final String DEC=RUNE+\".decorative\";\n\t\t\n\t\tpublic static final class Jei{\n\t\t\tprivate Jei(){}\n\t\t\tpublic static final String JEI=MODID+\".jei\";\n\t\t\tpublic static final String SPIRIT_SWORD=JEI+\".spirit_sword\";\n\t\t\tpublic static final String SPIRIT_PICKAXE=JEI+\".spirit_pickaxe\";\n\t\t}\n\t}\n}", "public enum EnumDustTypes {\n\tPLANT (0x629B26, 0x8AD041, 0xC2E300),\n\tGUNPOWDER(0x696969, 0x979797, 0x666464),\n\tLAPIS(0x345EC3, 0x5A82E2, 0x0087FF),\n\tBLAZE(0xEA8A00, 0xFFFE31, 0xFF6E1E);\n\t/*\n\t * In order of least valuable to most valuable:\n\t 2xTall Grass or Saplings or Leaves or Seeds + 1xCoal = 8xPlant Runic Dust\n 2xPlant Runic Dust + 1xGunpowder = 12xGunpowder Runic Dust\n 3xLapis + 1xCoal = 8xLapis Runic Dust\n 3xLapis Runic Dust + 1xBlaze Powder = 12xBlaze Runic Dust\n\t */\n\tpublic final int primaryColor, secondaryColor,floorColor;\n\t//constructor for our dust types\n\tEnumDustTypes(int primaryColor, int secondaryColor,int floorColor){\n\t\tthis.primaryColor=primaryColor;\n\t\tthis.secondaryColor=secondaryColor;\n\t\tthis.floorColor = floorColor;\n\t}\n\t/** returns the metadata value associated with a dust type **/\n\tpublic int meta(){\n\t\treturn this.ordinal();\n\t}\n\tpublic ItemStack getStack(int amount){\n\t\treturn new ItemStack(ClassicDusts.instance,amount,this.meta());\n\t}\n\t/** returns the dust type associated with the given meta **/\n\tpublic static EnumDustTypes getByMeta(int meta){\n \t\tif(meta>=EnumDustTypes.values().length){\n\t\t\tIllegalArgumentException e = new IllegalArgumentException(\"meta: \"+meta);\n\t\t\tRunesofWizardry_Classics.log().error(\"Invalid Classic Dusts metadata\",e);\n\t\t\treturn EnumDustTypes.PLANT;\n\t\t}\n\t\treturn EnumDustTypes.values()[meta];\n\t}\n}", "public class RuneProtection extends VariableRune {\n\t@Override\n\tprotected ItemStack[][] setupPattern() throws IOException {\n\t\treturn PatternUtils.importFromJson(Refs.PATTERN_PATH+\"runeprotection.json\");\n\t}\n\t@Override\n\tpublic String getID() {\n\t\treturn \"runeProtection\";\n\t}\n\t@Override\n\tprotected Vec3i setupEntityPos() {\n\t\treturn new Vec3i(1,1,0);\n\t}\n\t@Override\n\tprotected ItemStack[][] setupSacrifice() {\n\t\tItemStack villagerEgg = new ItemStack(Items.SPAWN_EGG);\n\t\tNBTTagCompound id = new NBTTagCompound();\n\t\tid.setString(\"id\", \"villager\");\n\t\tNBTTagCompound eggTag = new NBTTagCompound();\n\t\teggTag.setTag(\"EntityTag\", id);\n\t\tvillagerEgg.setTagCompound(eggTag);\n\t\treturn new ItemStack[][]{\n\t\t\t\t{villagerEgg}\n\t\t\t\t};\n\t\t//take 15 XP\n\t}\n\t@Override\n\tpublic String getName() {\n\t\treturn Refs.Lang.RUNE+\".protection\";\n\t}\n\t@Override\n\tpublic RuneEntity createRune(ItemStack[][] actualPattern, EnumFacing front,\n\t\t\tSet<BlockPos> dusts, TileEntityDustActive entity) {\n\t\treturn new RuneEntityProtection(actualPattern, front, dusts, entity, this);\n\t}\n}", "public class Utils {\n\tprivate Utils(){}\n\tpublic static void spawnItemCentered(World world, BlockPos pos, ItemStack stack){\n\t\tEntityItem item = new EntityItem(world, pos.getX()+0.5, pos.getY()+0.5, pos.getZ()+0.5, stack);\n\t\titem.setDefaultPickupDelay();\n\t\tworld.spawnEntity(item);\n\t}\n\t/**\n\t * Attempts to remove experience levels from the player.\n\t * @param player the player from which to take XP\n\t * @param levels the number of XP levels to take\n\t * @return true if the levels have been removed, false if the player didn't have enough\n\t */\n\tpublic static boolean takeXP(EntityPlayer player, int levels){\n\t\tif(player.capabilities.isCreativeMode)return true;\n\t\tboolean enough =player.experienceLevel>=levels;\n\t\tif(enough){\n\t\t\tplayer.addExperienceLevel(-levels);\n\t\t}\n\t\treturn enough;\n\t}\n\t/** stores coordinates for an array or whatever**/\n\tpublic static class Coords{\n\t\tpublic final int row,col;\n\t\tpublic Coords(int r, int c) {\n\t\t\tthis.row = r;\n\t\t\tthis.col = c;\n\t\t}\n\t\t/* (non-Javadoc)\n\t\t * @see java.lang.Object#hashCode()\n\t\t */\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\treturn row+col;//not the best, but should be sufficient\n\t\t}\n\t\t/* (non-Javadoc)\n\t\t * @see java.lang.Object#equals(java.lang.Object)\n\t\t */\n\t\t@Override\n\t\tpublic boolean equals(Object obj) {\n\t\t\tif(obj==this)return true;\n\t\t\tif(!(obj instanceof Coords))return false;\n\t\t\tCoords o = (Coords)obj;\n\t\t\treturn this.row==o.row && this.col==o.col;\n\t\t}\n\t}\n}", "public static class Coords{\n\tpublic final int row,col;\n\tpublic Coords(int r, int c) {\n\t\tthis.row = r;\n\t\tthis.col = c;\n\t}\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#hashCode()\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\treturn row+col;//not the best, but should be sufficient\n\t}\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#equals(java.lang.Object)\n\t */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif(obj==this)return true;\n\t\tif(!(obj instanceof Coords))return false;\n\t\tCoords o = (Coords)obj;\n\t\treturn this.row==o.row && this.col==o.col;\n\t}\n}" ]
import java.util.List; import java.util.Set; import com.zpig333.runesofwizardry.tileentity.TileEntityDustActive; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import xilef11.mc.runesofwizardry_classics.Refs; import xilef11.mc.runesofwizardry_classics.items.EnumDustTypes; import xilef11.mc.runesofwizardry_classics.runes.RuneProtection; import xilef11.mc.runesofwizardry_classics.utils.Utils; import xilef11.mc.runesofwizardry_classics.utils.Utils.Coords;
package xilef11.mc.runesofwizardry_classics.runes.entity; public class RuneEntityProtection extends FueledRuneEntity { public RuneEntityProtection(ItemStack[][] actualPattern, EnumFacing facing,
Set<BlockPos> dusts, TileEntityDustActive entity, RuneProtection creator) {
2
Keridos/FloodLights
src/main/java/de/keridos/floodlights/tileentity/TileEntityMetaFloodlight.java
[ "public class NetworkDataList extends NonNullList<Object> {\n\n public NetworkDataList() {\n super();\n }\n}", "public class ConfigHandler {\n private static ConfigHandler instance = null;\n\n public static boolean electricFloodlight;\n public static boolean smallElectricFloodlight;\n public static boolean carbonFloodlight;\n public static boolean uvFloodlight;\n public static boolean growLight;\n public static int energyBufferSize;\n public static int energyUsage;\n public static int energyUsageSmallFloodlight;\n public static int energyUsageUVFloodlight;\n public static int energyUsageGrowLight;\n public static int carbonTime;\n public static int rangeStraightFloodlight;\n public static int rangeConeFloodlight;\n public static int rangeUVFloodlight;\n public static float chanceGrowLight;\n public static int timeoutFloodlights;\n public static boolean uvLightRendered;\n public static boolean IGWNotifierEnabled;\n\n public static float damageUVFloodlight;\n\n private ConfigHandler() {\n }\n\n public static ConfigHandler getInstance() {\n if (instance == null) {\n instance = new ConfigHandler();\n }\n return instance;\n }\n\n public void initConfig(Configuration config) {\n config.load();\n config.getCategory(\"blocks\");\n electricFloodlight = config.getBoolean(\"electricFloodlightEnabled\", \"blocks\", true, \"Enables the electric FloodLight\");\n smallElectricFloodlight = config.getBoolean(\"smallElectricFloodlightEnabled\", \"blocks\", true, \"Enables the small electric FloodLight\");\n carbonFloodlight = config.getBoolean(\"carbonFloodlightEnabled\", \"blocks\", true, \"Enables the carbon FloodLight\");\n uvFloodlight = config.getBoolean(\"uvFloodlightEnabled\", \"blocks\", true, \"Enables the UV FloodLight\");\n growLight = config.getBoolean(\"growLightEnabled\", \"blocks\", true, \"Enables the Grow Light\");\n\n config.getCategory(\"general\");\n energyBufferSize = config.getInt(\"energyBufferSize\", \"general\", 50000, 1000, 10000000, \"Size of electric floodlights' internal energy buffer, in RF\");\n energyUsage = config.getInt(\"energyUsage\", \"general\", 20, 0, 1000, \"Energy Usage in RF/t for the electric FloodLight (x4 for the cone floodlights)\");\n energyUsageSmallFloodlight = config.getInt(\"energyUsageSmallFloodlight\", \"general\", 2, 0, 100, \"Energy Usage in RF/t for the small electric FloodLight\");\n energyUsageUVFloodlight = config.getInt(\"energyUsageUVFloodlight\", \"general\", 80, 0, 800, \"Energy Usage in RF/t for the UV FloodLight\");\n energyUsageGrowLight = config.getInt(\"energyUsageGrowLight\", \"general\", 40, 0, 800, \"Energy Usage in RF/t for the Grow Light\");\n carbonTime = config.getInt(\"carbonTime\", \"general\", 300, 0, 1000, \"How many seconds should 1 coal last in the carbon floodlight (quarter of that for the cone floodlights)? Default:300\");\n rangeStraightFloodlight = config.getInt(\"rangeStraightFloodlight\", \"general\", 64, 1, 128, \"How far should the straight Floodlights go?\");\n rangeConeFloodlight = config.getInt(\"rangeConeFloodlight\", \"general\", 32, 1, 64, \"How far should the cone floodlights go? (mind that wide only goes quarter as far) Default:32 \");\n rangeUVFloodlight = config.getInt(\"rangeUVFloodlight\", \"general\", 8, 1, 32, \"How far should the UV Floodlights go?\");\n chanceGrowLight = config.getFloat(\"chanceGrowLight\", \"general\", 0.05F, 0F, 1F, \"How big should the chance for the growlight for a growtick per second be?\");\n timeoutFloodlights = config.getInt(\"timeoutFloodlights\", \"general\", 40, 1, 240, \"How long should the timeout for turning on floodlights again be in ticks?\");\n damageUVFloodlight = config.getFloat(\"damageUVFloodlight\", \"general\", 4.0F, 1.0F, 16.0F, \"How much damage should the UV Floodlights do per second?\");\n uvLightRendered = config.getBoolean(\"uvLightRendered\", \"general\", true, \"Should the UV Light Block be visible?\");\n IGWNotifierEnabled = config.getBoolean(\"IGWNotifierEnabled\", \"general\", true, \"Should the IGW Notifier be shown?\");\n config.save();\n }\n}", "@SuppressWarnings(\"unused\")\[email protected]\npublic class ModBlocks {\n public static Block blockElectricFloodlight = new BlockElectricFloodlight();\n public static Block blockCarbonFloodlight = new BlockCarbonFloodlight();\n public static Block blockSmallElectricLight = new BlockSmallElectricFloodlight();\n public static Block blockUVFloodlight = new BlockUVFloodlight();\n public static Block blockGrowLight = new BlockGrowLight();\n public static Block blockPhantomLight = new BlockPhantomLight();\n public static Block blockPhantomUVLight = new BlockPhantomUVLight();\n\n @SubscribeEvent\n public static void registerBlocks(RegistryEvent.Register<Block> event) {\n //registry.register(getBlock(blockSmallElectricLight, ItemBlockSmallElectricMetaBlock.class, Names.Blocks.SMALL_ELECTRIC_FLOODLIGHT);\n event.getRegistry().registerAll(\n blockElectricFloodlight,\n blockCarbonFloodlight,\n blockSmallElectricLight,\n blockUVFloodlight,\n blockGrowLight,\n blockPhantomLight,\n blockPhantomUVLight\n );\n }\n\n @SuppressWarnings(\"ConstantConditions\")\n @SubscribeEvent\n public static void registerItemBlocks(RegistryEvent.Register<Item> event) {\n event.getRegistry().registerAll(\n new ElectricItemBlock(blockElectricFloodlight).setRegistryName(blockElectricFloodlight.getRegistryName()),\n new ItemBlock(blockCarbonFloodlight).setRegistryName(blockCarbonFloodlight.getRegistryName()),\n new ItemBlockSmallElectricMetaBlock(blockSmallElectricLight).setRegistryName(blockSmallElectricLight.getRegistryName()),\n new ElectricItemBlock(blockUVFloodlight).setRegistryName(blockUVFloodlight.getRegistryName()),\n new ElectricItemBlock(blockGrowLight).setRegistryName(blockGrowLight.getRegistryName()),\n new ItemBlock(blockPhantomLight).setRegistryName(blockPhantomLight.getRegistryName()),\n new ItemBlock(blockPhantomUVLight).setRegistryName(blockPhantomUVLight.getRegistryName())\n );\n }\n\n public static void registerTileEntities() {\n GameRegistry.registerTileEntity(TileEntityElectricFloodlight.class, Reference.MOD_ID.toLowerCase() + \":\" + Names.Blocks.ELECTRIC_FLOODLIGHT);\n GameRegistry.registerTileEntity(TileEntityCarbonFloodlight.class, Reference.MOD_ID.toLowerCase() + \":\" + Names.Blocks.CARBON_FLOODLIGHT);\n GameRegistry.registerTileEntity(TileEntitySmallFloodlight.class, Reference.MOD_ID.toLowerCase() + \":\" + Names.Blocks.SMALL_ELECTRIC_FLOODLIGHT);\n GameRegistry.registerTileEntity(TileEntityUVFloodlight.class, Reference.MOD_ID.toLowerCase() + \":\" + Names.Blocks.UV_FLOODLIGHT);\n GameRegistry.registerTileEntity(TileEntityPhantomLight.class, Reference.MOD_ID.toLowerCase() + \":\" + Names.Blocks.PHANTOM_LIGHT);\n GameRegistry.registerTileEntity(TileEntityGrowLight.class, Reference.MOD_ID.toLowerCase() + \":\" + Names.Blocks.GROW_LIGHT);\n }\n}", "public class Names {\n\n public static final String MOD_ID = Reference.MOD_ID;\n\n public static final class Blocks {\n public static final String ELECTRIC_FLOODLIGHT = \"electricFloodlight\";\n public static final String SMALL_ELECTRIC_FLOODLIGHT = \"smallElectricFloodlightMetaBlock\";\n public static final String CARBON_FLOODLIGHT = \"carbonFloodlight\";\n public static final String UV_FLOODLIGHT = \"uvFloodlight\";\n public static final String GROW_LIGHT = \"growLight\";\n public static final String PHANTOM_LIGHT = \"phantomLight\";\n public static final String PHANTOM_UV_LIGHT = \"phantomUVLight\";\n }\n\n public static final class Items {\n public static final String RAW_FILAMENT = \"rawFilament\";\n public static final String GLOWING_FILAMENT = \"glowingFilament\";\n public static final String ELECTRIC_INCANDESCENT_LIGHT_BULB = \"electricIncandescentLightBulb\";\n public static final String CARBON_DISSOLVER = \"carbonDissolver\";\n public static final String CARBON_LANTERN = \"carbonLantern\";\n public static final String MANTLE = \"mantle\";\n public static final String LIGHT_DEBUG_TOOL = \"lightDebugTool\";\n }\n\n public static final class Localizations {\n public static final String NONELECTRIC_GUI_TEXT = \"gui.floodlights:nonElectricFloodlightTimeRemaining\";\n public static final String RF_STORAGE = \"gui.floodlights:RFStorage\";\n public static final String MODE = \"gui.floodlights:mode\";\n public static final String INVERT = \"gui.floodlights:invert\";\n public static final String TRUE = \"gui.floodlights:true\";\n public static final String FALSE = \"gui.floodlights:false\";\n public static final String STRAIGHT = \"gui.floodlights:straight\";\n public static final String NARROW_CONE = \"gui.floodlights:narrowCone\";\n public static final String WIDE_CONE = \"gui.floodlights:wideCone\";\n public static final String MACHINE_ENABLED_ERROR = \"gui.floodlights:machineEnabledError\";\n public static final String LIGHTING = \"gui.floodlights:growLightLighting\";\n public static final String DARK_LIGHT = \"gui.floodlights:growLightDarkLight\";\n }\n\n public static final class NBT {\n public static final String ITEMS = \"Items\";\n public static final String INVERT = \"inverted\";\n public static final String TIME_REMAINING = \"timeRemaining\";\n public static final String STORAGE_FE = \"storageFE\";\n public static final String COLOR = \"color\";\n public static final String MODE = \"teState\";\n public static final String LIGHT = \"teLight\";\n public static final String WAS_ACTIVE = \"wasActive\";\n public static final String HAS_REDSTONE = \"teRedstone\";\n public static final String CURRENT_RANGE = \"teRange\";\n public static final String FLOODLIGHT_ID = \"floodlightId\";\n public static final String CUSTOM_NAME = \"CustomName\";\n public static final String DIRECTION = \"teDirection\";\n public static final String ROTATION_STATE = \"teRotationState\";\n public static final String OWNER = \"owner\";\n public static final String SOURCES = \"sources\";\n public static final String LIGHT_BLOCK = \"lightBlock\";\n public static final String CLOAK_BLOCK = \"cloakBlock\";\n public static final String CLOAK_BLOCKSTATE = \"cloakBlockState\";\n }\n\n public static final class DamageSources {\n public static final String UV_LIGHT = \"floodlights:uvlight\";\n }\n\n /**\n * Converts given string (block or item name) to underscore-based, which is used as a registry name.\n */\n public static String convertToUnderscore(String input) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < input.length(); i++) {\n char c = input.charAt(i);\n if (Character.isUpperCase(c))\n builder.append(\"_\").append(Character.toLowerCase(c));\n else\n builder.append(c);\n }\n\n return builder.toString();\n }\n}", "public class MathUtil {\n\n // This is for rotation a coordinate from the +x direction to another axis around (0, 0, 0)\n public static double[] rotateD(double x, double y, double z, EnumFacing direction) {\n double[] result = new double[3];\n switch (direction) {\n case DOWN:\n result[0] = y;\n result[1] = 1 - x;\n result[2] = z;\n break;\n case UP:\n result[0] = 1 - y;\n result[1] = x;\n result[2] = z;\n break;\n case NORTH:\n result[0] = z;\n result[1] = y;\n result[2] = 1 - x;\n break;\n case SOUTH:\n result[0] = 1 - z;\n result[1] = y;\n result[2] = x;\n break;\n case WEST:\n result[0] = 1 - x;\n result[1] = y;\n result[2] = z;\n break;\n case EAST:\n result[0] = x;\n result[1] = y;\n result[2] = z;\n break;\n }\n return result;\n }\n\n public static int[] rotate(int x, int y, int z, EnumFacing direction) {\n int[] result = new int[3];\n switch (direction) {\n case DOWN:\n result[0] = y;\n result[1] = -x;\n result[2] = z;\n break;\n case UP:\n result[0] = -y;\n result[1] = x;\n result[2] = z;\n break;\n case NORTH:\n result[0] = z;\n result[1] = y;\n result[2] = -x;\n break;\n case SOUTH:\n result[0] = -z;\n result[1] = y;\n result[2] = x;\n break;\n case WEST:\n result[0] = -x;\n result[1] = y;\n result[2] = z;\n break;\n case EAST:\n result[0] = x;\n result[1] = y;\n result[2] = z;\n break;\n }\n return result;\n }\n\n public static int truncateDoubleToInt(double number) {\n return (int) Math.floor(number);\n }\n\n public static int roundDoubleToInt(double number) {\n return (int) Math.floor(number + 0.5D);\n }\n}", "public static final PropertyBool UPDATE = PropertyBool.create(\"update\");", "public static BlockPos getPosFromPosFacing(BlockPos pos, EnumFacing facing) {\n return new BlockPos(pos.getX() + facing.getFrontOffsetX(),\n pos.getY() + facing.getFrontOffsetY(),\n pos.getZ() + facing.getFrontOffsetZ());\n}", "@SuppressWarnings(\"deprecation\")\npublic static String safeLocalize(String key) {\n String translation = I18n.translateToLocal(key);\n if (translation.equals(key))\n translation = I18n.translateToFallback(key);\n\n return translation;\n}" ]
import de.keridos.floodlights.core.NetworkDataList; import de.keridos.floodlights.handler.ConfigHandler; import de.keridos.floodlights.init.ModBlocks; import de.keridos.floodlights.reference.Names; import de.keridos.floodlights.util.MathUtil; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemAir; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.IThreadListener; import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; import static de.keridos.floodlights.block.BlockPhantomLight.UPDATE; import static de.keridos.floodlights.util.GeneralUtil.getPosFromPosFacing; import static de.keridos.floodlights.util.GeneralUtil.safeLocalize;
package de.keridos.floodlights.tileentity; /** * Created by Keridos on 06.05.2015. * This Class */ @SuppressWarnings({"WeakerAccess", "NullableProblems"}) public abstract class TileEntityMetaFloodlight extends TileEntityFL implements ITickable { protected boolean active; protected boolean wasActive; protected boolean hasRedstone; protected int timeout; protected ItemStackHandler inventory; protected Block lightBlock = ModBlocks.blockPhantomLight; protected int rangeStraight = ConfigHandler.rangeStraightFloodlight; protected int rangeCone = ConfigHandler.rangeConeFloodlight; protected int currentRange = rangeStraight; protected int lightBlockStep = 2; protected int floodlightId = new Random().nextInt(); private AtomicBoolean executorActive = new AtomicBoolean(false); private boolean hasLight; public TileEntityMetaFloodlight() { super(); inventory = createInventory(); } public void setHasRedstoneSignal(boolean hasSignal) { // Light blocks are managed in the update() method hasRedstone = hasSignal; active = hasRedstone ^ inverted; syncData(); } public void toggleInverted() { inverted = !inverted; active = hasRedstone ^ inverted; syncData(); } /** * Notifies this machine that a container block has been removed and the tile entity is about to be destroyed. */ public void notifyBlockRemoved() { if (world.isRemote) return; lightSource(true); } /** * Creates new phantom light (depending on the {@link #lightBlock} field) at given position. */ @SuppressWarnings("ConstantConditions") protected void createPhantomLight(BlockPos pos) { if (world.setBlockState(pos, lightBlock.getDefaultState(), 19)) { TileEntityPhantomLight light = (TileEntityPhantomLight) world.getTileEntity(pos); light.addSource(this.pos, floodlightId); } } @Override public void update() { if (world.isRemote) return; if (timeout > 0) { timeout--; return; } // Energy itself is handled in one of the derived classes if (active && hasEnergy() && (wasActive != active || !hasLight)) { // Spawn phantom lights lightSource(false); wasActive = active; } else if ((active && !hasEnergy()) || (!active && wasActive)) { // A floodlight just run out of energy or was shut down - deactivate it lightSource(true); timeout = ConfigHandler.timeoutFloodlights + 10; wasActive = false; } } /** * Returns whether this machine is ready - no active timeouts etc. */ protected boolean isCooledDown() { return timeout == 0 && !executorActive.get(); } /** * Whether this machine has electric, heat or any other energy type required to operate. */ protected boolean hasEnergy() { return false; } /** * Whether this machine can perform any task at the moment. Used in the {@link #update()} method. */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") protected boolean isReady() { return timeout == 0; } protected ItemStackHandler createInventory() { return new ItemStackHandler(getInventorySize()) { @Override protected void onContentsChanged(int slot) { if (slot == 1 && supportsCloak()) { Item item = getStackInSlot(slot).getItem(); if (item instanceof ItemAir) { setCloak(null); } else if (item instanceof ItemBlock && (getCloak() == null || !Block.isEqualTo(((ItemBlock) item).getBlock(), getCloak().getBlock()))) { setCloak(((ItemBlock) item).getBlock().getDefaultState()); } } super.onContentsChanged(slot); markDirty(); } }; } protected int getInventorySize() { return 1; } @Override public void readOwnFromNBT(NBTTagCompound nbtTagCompound) { super.readOwnFromNBT(nbtTagCompound);
if (nbtTagCompound.hasKey(Names.NBT.WAS_ACTIVE))
3
cuberact/cuberact-json
src/main/java/org/cuberact/json/parser/JsonScanner.java
[ "public class JsonException extends RuntimeException {\r\n\r\n private static final long serialVersionUID = 1L;\r\n\r\n public JsonException(String message) {\r\n super(message);\r\n }\r\n\r\n public JsonException(Throwable t) {\r\n super(t);\r\n }\r\n\r\n public JsonException(String message, Throwable t) {\r\n super(message, t);\r\n }\r\n}\r", "public final class JsonNumber implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"RedundantIfStatement\")\n public static final Function<JsonNumber, Object> CONVERTER_DYNAMIC = jsonNumber -> {\n if (jsonNumber.isFloatingNumber()) {\n double doubleValue = jsonNumber.asDouble();\n if (doubleValue == (double) (float) doubleValue) {\n return (float) doubleValue;\n }\n return doubleValue;\n }\n long longValue = jsonNumber.asLong();\n int intValue = (int) longValue;\n if (intValue == longValue) {\n return intValue;\n }\n return longValue;\n };\n\n public static final Function<JsonNumber, Object> CONVERTER_INT_FLOAT = jsonNumber -> {\n if (jsonNumber.isFloatingNumber()) {\n return jsonNumber.asFloat();\n }\n return jsonNumber.asInt();\n };\n\n public static final Function<JsonNumber, Object> CONVERTER_LONG_DOUBLE = jsonNumber -> {\n if (jsonNumber.isFloatingNumber()) {\n return jsonNumber.asDouble();\n }\n return jsonNumber.asLong();\n };\n\n private final char[] charNumber;\n private final boolean floatingNumber;\n private transient String strNumber;\n\n public JsonNumber(char[] charNumber, int count, boolean floatingNumber) {\n this.charNumber = new char[count];\n System.arraycopy(charNumber, 0, this.charNumber, 0, count);\n this.floatingNumber = floatingNumber;\n }\n\n public boolean isFloatingNumber() {\n return floatingNumber;\n }\n\n public Number asNumber(Class<? extends Number> type) {\n if (Integer.class.equals(type)) {\n return asInt();\n } else if (Long.class.equals(type)) {\n return asLong();\n } else if (Float.class.equals(type)) {\n return asFloat();\n } else if (Double.class.equals(type)) {\n return asDouble();\n } else if (BigInteger.class.equals(type)) {\n return asBigInt();\n } else if (BigDecimal.class.equals(type)) {\n return asBigDecimal();\n }\n throw new JsonException(\"Unknown number type \" + type);\n }\n\n public int asInt() {\n int result = 0;\n int sign = 1;\n char c = charNumber[0];\n if (c == '-') {\n sign = -1;\n } else if (c == '.') {\n return 0;\n } else {\n result = toInt(c);\n }\n for (int i = 1; i < charNumber.length; i++) {\n if (charNumber[i] == '.') break;\n result = result * 10 + toInt(charNumber[i]);\n }\n return sign * result;\n }\n\n public long asLong() {\n long result = 0L;\n long sign = 1L;\n char c = charNumber[0];\n if (c == '-') {\n sign = -1L;\n } else if (c == '.') {\n return 0;\n } else {\n result = toLong(c);\n }\n for (int i = 1; i < charNumber.length; i++) {\n if (charNumber[i] == '.') break;\n result = result * 10L + toLong(charNumber[i]);\n }\n return sign * result;\n }\n\n public float asFloat() {\n return Float.parseFloat(toString());\n }\n\n public double asDouble() {\n return Double.parseDouble(toString());\n }\n\n public BigInteger asBigInt() {\n if (floatingNumber) {\n int indexOfDot = toString().indexOf(\".\");\n if (indexOfDot != -1) {\n String number = toString().substring(0, indexOfDot);\n return number.length() == 0 ? BigInteger.ZERO : new BigInteger(number);\n }\n }\n return new BigInteger(toString());\n }\n\n public BigDecimal asBigDecimal() {\n return new BigDecimal(toString());\n }\n\n public int length() {\n return charNumber.length;\n }\n\n public char charAt(int index) {\n return charNumber[index];\n }\n\n @Override\n public int hashCode() {\n return 31 * Boolean.hashCode(floatingNumber) + Arrays.hashCode(charNumber);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n JsonNumber that = (JsonNumber) o;\n return floatingNumber == that.floatingNumber && (charNumber != null ? Arrays.equals(charNumber, that.charNumber) : that.charNumber == null);\n }\n\n @Override\n public String toString() {\n if (strNumber == null) {\n strNumber = new String(charNumber);\n }\n return strNumber;\n }\n}", "public interface JsonInput {\r\n\r\n char END_OF_INPUT = '\\uFFFF';\r\n\r\n /**\r\n * @return next char of input or END_OF_INPUT.\r\n */\r\n char nextChar();\r\n\r\n /**\r\n * @return actual position in input. Used only for error message.\r\n */\r\n int position();\r\n}\r", "public static int hexBitShift(int order) {\r\n return HEX_BIT_SHIFT[order];\r\n}\r", "public static int toInt(char c) {\r\n return CHAR_TO_INT[c];\r\n}\r" ]
import org.cuberact.json.JsonException; import org.cuberact.json.JsonNumber; import org.cuberact.json.input.JsonInput; import static org.cuberact.json.input.JsonInput.END_OF_INPUT; import static org.cuberact.json.optimize.CharTable.hexBitShift; import static org.cuberact.json.optimize.CharTable.toInt;
/* * Copyright 2017 Michal Nikodim * * 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.cuberact.json.parser; /** * @author Michal Nikodim ([email protected]) */ final class JsonScanner { private final JsonInput input; private final char[] buffer = new char[4096]; char lastReadChar; JsonScanner(JsonInput input) { this.input = input; } private char nextChar() { return lastReadChar = input.nextChar(); } char nextImportantChar() { for (; ; ) { nextChar(); if (!(lastReadChar == ' ' || lastReadChar == '\n' || lastReadChar == '\r' || lastReadChar == '\t')) { return lastReadChar; } } } String consumeString() { StringBuilder token = null; int count = 0; for (; ; ) { nextChar(); if (lastReadChar == '"') { nextImportantChar(); if (token == null) return new String(buffer, 0, count); token.append(buffer, 0, count); return token.toString(); } else if (lastReadChar == '\\') { nextChar(); switch (lastReadChar) { case 'b': lastReadChar = '\b'; break; case 'f': lastReadChar = '\f'; break; case 'n': lastReadChar = '\n'; break; case 'r': lastReadChar = '\r'; break; case 't': lastReadChar = '\t'; break; case 'u': lastReadChar = consumeUnicodeChar(); break; } } else if (lastReadChar == END_OF_INPUT) { break; } buffer[count++] = lastReadChar; if (count == 4096) { count = 0; if (token == null) { token = new StringBuilder(8000); } token.append(buffer); } } throw jsonException("Expected \""); } void consumeTrue() { if (nextChar() == 'r' && nextChar() == 'u' && nextChar() == 'e') { nextImportantChar(); return; } throw jsonException("Expected true"); } void consumeFalse() { if (nextChar() == 'a' && nextChar() == 'l' && nextChar() == 's' && nextChar() == 'e') { nextImportantChar(); return; } throw jsonException("Expected false"); } void consumeNull() { if (nextChar() == 'u' && nextChar() == 'l' && nextChar() == 'l') { nextImportantChar(); return; } throw jsonException("Expected null"); }
JsonNumber consumeNumber() {
1
MiniDigger/projecttd
core/src/me/minidigger/projecttd/screens/GameScreen.java
[ "public class GameGestureProcessor extends GestureDetector.GestureAdapter {\n\n private GameScreen gameScreen;\n\n public GameGestureProcessor(GameScreen gameScreen) {\n this.gameScreen = gameScreen;\n }\n\n @Override\n public boolean pan(float x, float y, float deltaX, float deltaY) {\n gameScreen.panCamera(deltaX);\n Gdx.app.debug(\"PTD\", \"Pan \" + deltaX);\n return true;\n }\n}", "public class GameInputProcessor extends InputAdapter {\n\n private GameScreen gameScreen;\n\n public GameInputProcessor(GameScreen gameScreen) {\n this.gameScreen = gameScreen;\n }\n\n @Override\n public boolean touchUp(int screenX, int screenY, int pointer, int button) {\n gameScreen.debugTouch(screenX, screenY, pointer, button);\n\n return true;\n }\n\n @Override\n public boolean keyDown(int keycode) {\n if (keycode == Input.Keys.D) {\n if (Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT)) {\n gameScreen.toggleDebugRendering();\n }\n }\n\n return true;\n }\n}", "public class Minion {\n\n public static PooledEngine ENGINE;\n public static Sprite SPRITE;\n\n public static Entity newMinion(Vector2 spawn) {\n Entity entity = ENGINE.createEntity();\n\n SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class);\n spriteComponent.sprite = SPRITE;\n entity.add(spriteComponent);\n\n VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class);\n entity.add(velocityComponent);\n\n TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class);\n transformComponent.position = spawn;\n entity.add(transformComponent);\n\n HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class);\n healthComponent.health = 100;\n entity.add(healthComponent);\n\n PathComponent pathComponent = ENGINE.createComponent(PathComponent.class);\n entity.add(pathComponent);\n\n MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class);\n entity.add(minionComponent);\n\n ENGINE.addEntity(entity);\n return entity;\n }\n\n public enum MinionType{\n LAND,\n WATER,\n AIR;\n }\n}", "public class Tower {\n\n public static PooledEngine ENGINE;\n public static Sprite SPRITE;\n\n public static Entity newTower(Vector2 spawn) {\n Entity entity = ENGINE.createEntity();\n\n CoordinateUtil.alignToGrid(spawn);\n\n SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class);\n spriteComponent.sprite = SPRITE;\n entity.add(spriteComponent);\n\n TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class);\n transformComponent.position = spawn;\n entity.add(transformComponent);\n\n TurretComponent turretComponent = ENGINE.createComponent(TurretComponent.class);\n entity.add(turretComponent);\n\n ENGINE.addEntity(entity);\n return entity;\n }\n}", "public class Level {\n\n private String name;\n private String file;\n private String author;\n private String thumbnail;\n private List<Wave> waves;\n\n public Level(String name, String file, String author, String thumbnail, List<Wave> waves) {\n this.name = name;\n this.file = file;\n this.author = author;\n this.thumbnail = thumbnail;\n this.waves = waves;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getFile() {\n return file;\n }\n\n public void setFile(String file) {\n this.file = file;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public String getThumbnail() {\n return thumbnail;\n }\n\n public void setThumbnail(String thumbnail) {\n this.thumbnail = thumbnail;\n }\n\n public List<Wave> getWaves() {\n return waves;\n }\n\n public void setWaves(List<Wave> waves) {\n this.waves = waves;\n }\n}", "public class HudScene implements Disposable {\n\n private Stage stage;\n private SpriteBatch batch;\n\n private int score = 0;\n private int balance = 0;\n\n private Label scoreLabel;\n private Label balanceLabel;\n\n private RingButton ringButton;\n\n public HudScene(SpriteBatch batch, ShapeRenderer shapeRenderer, ArcRenderer arcRenderer) {\n this.batch = batch;\n stage = new Stage();\n\n VisUI.load();\n\n Table table = new Table();\n table.top();\n table.setFillParent(true);\n\n scoreLabel = new Label(\"\", new Label.LabelStyle(new BitmapFont(), Color.VIOLET));\n setScore(score);\n balanceLabel = new Label(\"\", new Label.LabelStyle(new BitmapFont(), Color.VIOLET));\n setBalance(balance);\n\n table.add(scoreLabel).align(Align.left).expandX();\n table.add(balanceLabel).align(Align.right).expandX();\n\n stage.addActor(table);\n\n\n ringButton = new RingButton(shapeRenderer, arcRenderer);\n ringButton.setBounds(10, 10, 100, 100);\n stage.addActor(ringButton);\n }\n\n public void setScore(int score) {\n scoreLabel.setText(score + \" PTS\");\n }\n\n public void setBalance(int balance) {\n this.balance = balance;\n balanceLabel.setText(balance + \" $\");\n }\n\n @Override\n public void dispose() {\n VisUI.dispose();\n stage.dispose();\n }\n\n public Stage getStage() {\n return stage;\n }\n\n public void render() {\n batch.setProjectionMatrix(stage.getCamera().combined);\n stage.act();\n stage.draw();\n }\n\n public int getBalance() {\n return balance;\n }\n\n public int getScore() {\n return score;\n }\n}", "public class ArcRenderer {\n public enum ShapeType {\n Point(GL20.GL_POINTS), Line(GL20.GL_LINES), Filled(GL20.GL_TRIANGLES);\n\n private final int glType;\n\n ShapeType(int glType) {\n this.glType = glType;\n }\n\n public int getGlType() {\n return glType;\n }\n }\n\n private final ImmediateModeRenderer renderer;\n private boolean matrixDirty = false;\n private final Matrix4 projectionMatrix = new Matrix4();\n private final Matrix4 transformMatrix = new Matrix4();\n private final Matrix4 combinedMatrix = new Matrix4();\n private final Vector2 tmp = new Vector2();\n private final Color color = new Color(1, 1, 1, 1);\n private ShapeType shapeType;\n private boolean autoShapeType;\n private float defaultRectLineWidth = 0.75f;\n\n public ArcRenderer() {\n this(5000);\n }\n\n public ArcRenderer(int maxVertices) {\n this(maxVertices, null);\n }\n\n public ArcRenderer(int maxVertices, ShaderProgram defaultShader) {\n if (defaultShader == null) {\n renderer = new ImmediateModeRenderer20(maxVertices, false, true, 0);\n } else {\n renderer = new ImmediateModeRenderer20(maxVertices, false, true, 0, defaultShader);\n }\n projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n matrixDirty = true;\n }\n\n /**\n * Sets the color to be used by the next shapes drawn.\n */\n public void setColor(Color color) {\n this.color.set(color);\n }\n\n /**\n * Sets the color to be used by the next shapes drawn.\n */\n public void setColor(float r, float g, float b, float a) {\n this.color.set(r, g, b, a);\n }\n\n public Color getColor() {\n return color;\n }\n\n public void updateMatrices() {\n matrixDirty = true;\n }\n\n /**\n * Sets the projection matrix to be used for rendering. Usually this will be set to {@link Camera#combined}.\n *\n * @param matrix\n */\n public void setProjectionMatrix(Matrix4 matrix) {\n projectionMatrix.set(matrix);\n matrixDirty = true;\n }\n\n /**\n * If the matrix is modified, {@link #updateMatrices()} must be called.\n */\n public Matrix4 getProjectionMatrix() {\n return projectionMatrix;\n }\n\n public void setTransformMatrix(Matrix4 matrix) {\n transformMatrix.set(matrix);\n matrixDirty = true;\n }\n\n /**\n * If the matrix is modified, {@link #updateMatrices()} must be called.\n */\n public Matrix4 getTransformMatrix() {\n return transformMatrix;\n }\n\n /**\n * Sets the transformation matrix to identity.\n */\n public void identity() {\n transformMatrix.idt();\n matrixDirty = true;\n }\n\n /**\n * Multiplies the current transformation matrix by a translation matrix.\n */\n public void translate(float x, float y, float z) {\n transformMatrix.translate(x, y, z);\n matrixDirty = true;\n }\n\n /**\n * Multiplies the current transformation matrix by a rotation matrix.\n */\n public void rotate(float axisX, float axisY, float axisZ, float degrees) {\n transformMatrix.rotate(axisX, axisY, axisZ, degrees);\n matrixDirty = true;\n }\n\n /**\n * Multiplies the current transformation matrix by a scale matrix.\n */\n public void scale(float scaleX, float scaleY, float scaleZ) {\n transformMatrix.scale(scaleX, scaleY, scaleZ);\n matrixDirty = true;\n }\n\n /**\n * If true, when drawing a shape cannot be performed with the current shape type, the batch is flushed and the shape type is\n * changed automatically. This can increase the number of batch flushes if care is not taken to draw the same type of shapes\n * together. Default is false.\n */\n public void setAutoShapeType(boolean autoShapeType) {\n this.autoShapeType = autoShapeType;\n }\n\n /**\n * Begins a new batch without specifying a shape type.\n *\n * @throws IllegalStateException if {@link #autoShapeType} is false.\n */\n public void begin() {\n if (!autoShapeType)\n throw new IllegalStateException(\"autoShapeType must be true to use this method.\");\n begin(ShapeType.Line);\n }\n\n /**\n * Starts a new batch of shapes. Shapes drawn within the batch will attempt to use the type specified. The call to this method\n * must be paired with a call to {@link #end()}.\n *\n * @see #setAutoShapeType(boolean)\n */\n public void begin(ShapeType type) {\n if (shapeType != null)\n throw new IllegalStateException(\"Call end() before beginning a new shape batch.\");\n shapeType = type;\n if (matrixDirty) {\n combinedMatrix.set(projectionMatrix);\n Matrix4.mul(combinedMatrix.val, transformMatrix.val);\n matrixDirty = false;\n }\n renderer.begin(combinedMatrix, shapeType.getGlType());\n }\n\n public void set(ShapeType type) {\n if (shapeType == type) return;\n if (shapeType == null) throw new IllegalStateException(\"begin must be called first.\");\n if (!autoShapeType) throw new IllegalStateException(\"autoShapeType must be enabled.\");\n end();\n begin(type);\n }\n\n public void arc(float x, float y, float radius, float start, float degrees) {\n arc(x, y, radius, start, degrees, Math.max(1, (int) (6 * (float) Math.cbrt(radius) * (degrees / 360.0f))));\n }\n\n public void arc(float x, float y, float radius, float start, float degrees, int segments) {\n if (segments <= 0) throw new IllegalArgumentException(\"segments must be > 0.\");\n float colorBits = color.toFloatBits();\n float theta = (2 * MathUtils.PI * (degrees / 360.0f)) / segments;\n float cos = MathUtils.cos(theta);\n float sin = MathUtils.sin(theta);\n float cx = radius * MathUtils.cos(start * MathUtils.degreesToRadians);\n float cy = radius * MathUtils.sin(start * MathUtils.degreesToRadians);\n\n if (shapeType == ShapeType.Line) {\n check(ShapeType.Line, ShapeType.Filled, segments * 2 + 2);\n\n renderer.color(colorBits);\n for (int i = 0; i < segments; i++) {\n renderer.color(colorBits);\n renderer.vertex(x + cx, y + cy, 0);\n float temp = cx;\n cx = cos * cx - sin * cy;\n cy = sin * temp + cos * cy;\n renderer.color(colorBits);\n renderer.vertex(x + cx, y + cy, 0);\n }\n renderer.color(colorBits);\n } else {\n check(ShapeType.Line, ShapeType.Filled, segments * 3 + 3);\n\n for (int i = 0; i < segments; i++) {\n renderer.color(colorBits);\n renderer.vertex(x, y, 0);\n renderer.color(colorBits);\n renderer.vertex(x + cx, y + cy, 0);\n float temp = cx;\n cx = cos * cx - sin * cy;\n cy = sin * temp + cos * cy;\n renderer.color(colorBits);\n renderer.vertex(x + cx, y + cy, 0);\n }\n renderer.color(colorBits);\n renderer.vertex(x, y, 0);\n renderer.color(colorBits);\n renderer.vertex(x + cx, y + cy, 0);\n }\n\n float temp = cx;\n cx = 0;\n cy = 0;\n renderer.color(colorBits);\n renderer.vertex(x + cx, y + cy, 0);\n }\n\n private void check(ShapeType preferred, ShapeType other, int newVertices) {\n if (shapeType == null) throw new IllegalStateException(\"begin must be called first.\");\n\n if (shapeType != preferred && shapeType != other) {\n // Shape type is not valid.\n if (!autoShapeType) {\n if (other == null)\n throw new IllegalStateException(\"Must call begin(ShapeType.\" + preferred + \").\");\n else\n throw new IllegalStateException(\"Must call begin(ShapeType.\" + preferred + \") or begin(ShapeType.\" + other + \").\");\n }\n end();\n begin(preferred);\n } else if (matrixDirty) {\n // Matrix has been changed.\n ShapeType type = shapeType;\n end();\n begin(type);\n } else if (renderer.getMaxVertices() - renderer.getNumVertices() < newVertices) {\n // Not enough space.\n ShapeType type = shapeType;\n end();\n begin(type);\n }\n }\n\n /**\n * Finishes the batch of shapes and ensures they get rendered.\n */\n public void end() {\n renderer.end();\n shapeType = null;\n }\n\n public void flush() {\n ShapeType type = shapeType;\n end();\n begin(type);\n }\n}", "public class CoordinateUtil {\n\n private static Vector3 vector3 = new Vector3();\n\n public static Vector2 touchToWorld(Vector2 point, Camera camera) {\n vector3.set(point, 0);\n camera.unproject(vector3);\n point.set(vector3.x, vector3.y);\n return point;\n }\n\n public static Vector2 worldToTouch(Vector2 point, Camera camera) {\n vector3.set(point, 0);\n camera.project(vector3);\n point.set(vector3.x, vector3.y);\n return point;\n }\n\n public static Vector2 alignToGrid(Vector2 input) {\n input.x = (int) (input.x) + 0.5f;\n input.y = (int) (input.y) + 0.5f;\n return input;\n }\n}" ]
import com.badlogic.ashley.core.PooledEngine; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.input.GestureDetector; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Stage; import com.kotcrab.vis.ui.VisUI; import me.minidigger.projecttd.GameGestureProcessor; import me.minidigger.projecttd.GameInputProcessor; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.entities.Tower; import me.minidigger.projecttd.level.Level; import me.minidigger.projecttd.scenes.HudScene; import me.minidigger.projecttd.systems.*; import me.minidigger.projecttd.utils.ArcRenderer; import me.minidigger.projecttd.utils.CoordinateUtil;
package me.minidigger.projecttd.screens; /** * Created by Martin on 01.04.2017. */ public class GameScreen implements Screen { private TiledMap map; private OrthogonalTiledMapRenderer tiledMapRenderer; private OrthographicCamera camera; private ShapeRenderer shapeRenderer = new ShapeRenderer(); private ArcRenderer arcRenderer = new ArcRenderer(); private BitmapFont font = new BitmapFont(); private SpriteBatch spriteBatch = new SpriteBatch(); private HudScene hud; private int mapHeight; private int mapWidth; private int tilewidth; private PooledEngine engine; private Sprite minionSprite; private Sprite towerSprite; private Vector2 touchPoint = new Vector2(); private Vector2 spawnPoint = new Vector2(); private boolean debugRendering = false; private PathFindingSystem pathFindingSystem; private TurretSystem turretSystem; public Level level; public static GameScreen INSTANCE; public GameScreen() { INSTANCE = this; } @Override public void show() { // ui hud = new HudScene(spriteBatch, shapeRenderer, arcRenderer); //input InputMultiplexer multiplexer = new InputMultiplexer(); multiplexer.addProcessor(hud.getStage());
multiplexer.addProcessor(new GestureDetector(new GameGestureProcessor(this)));
0
heroku/heroku.jar
heroku-api/src/main/java/com/heroku/api/request/team/TeamAppCreate.java
[ "public class App implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n String name;\n Domain domain_name;\n String created_at;\n App.Owner owner;\n String web_url;\n App.Stack stack;\n String requested_stack;\n String git_url;\n String buildpack_provided_description;\n String released_at;\n long slug_size;\n long repo_size;\n boolean maintenance;\n App.Space space;\n\n /**\n * Builder method for specifying the name of an app.\n * @param name The name to give an app.\n * @return A copy of the {@link App}\n */\n public App named(String name) {\n App newApp = copy();\n newApp.name = name;\n return newApp;\n }\n\n /**\n * Builder method for specifying the stack an app should be created on.\n * @param stack Stack to create the app on.\n * @return A copy of the {@link App}\n */\n public App on(Heroku.Stack stack) {\n App newApp = copy();\n newApp.stack = new App.Stack(stack);\n return newApp;\n }\n\n public boolean isMaintenance() {\n return maintenance;\n }\n\n public void setMaintenance(boolean maintenance) {\n this.maintenance = maintenance;\n }\n\n private void setweb_url(String webUrl) {\n web_url = webUrl;\n }\n\n private void setId(String id) {\n this.id = id;\n }\n\n private void setName(String name) {\n this.name = name;\n }\n\n private void setDomain(Domain domain) {\n this.domain_name = domain;\n }\n\n private void setCreated_at(String created_at) {\n this.created_at = created_at;\n }\n\n private void setOwner(App.Owner owner) {\n this.owner = owner;\n }\n\n private void setStack(App.Stack stack) {\n this.stack = stack;\n }\n\n private void setRequested_stack(String requested_stack) {\n this.requested_stack = requested_stack;\n }\n\n private void setGit_url(String git_url) {\n this.git_url = git_url;\n }\n\n private void setBuildpack_provided_description(String buildpack_provided_description) {\n this.buildpack_provided_description = buildpack_provided_description;\n }\n\n private void setSlug_size(long slug_size) {\n this.slug_size = slug_size;\n }\n\n private void setRepo_size(long repo_size) {\n this.repo_size = repo_size;\n }\n\n public String getId() {\n return id;\n }\n\n public void setDomain_name(Domain domain_name) {\n this.domain_name = domain_name;\n }\n\n public String getName() {\n\n return name;\n }\n\n public Domain getDomain() {\n return domain_name;\n }\n\n public String getWebUrl() {\n return web_url;\n }\n\n public String getGitUrl() {\n return git_url;\n }\n\n public String getBuildpackProvidedDescription() {\n return buildpack_provided_description;\n }\n\n public String getCreatedAt() {\n return created_at;\n }\n\n public App.Stack getStack() {\n return stack;\n }\n\n public String getRequestedStack() {\n return requested_stack;\n }\n\n public long getSlugSize() {\n return slug_size;\n }\n\n public long getRepoSize() {\n return repo_size;\n }\n\n public App.Owner getOwner() {\n return owner;\n }\n\n public String getReleasedAt(){\n return released_at;\n }\n\n public void setReleased_at(String at){\n released_at = at;\n }\n\n private App copy() {\n App copy = new App();\n copy.name = this.name;\n copy.stack = this.stack;\n return copy;\n }\n\n public Space getSpace() {\n return space;\n }\n\n public void setSpace(Space space) {\n this.space = space;\n }\n\n public static class Owner implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String email;\n\n public Owner() {\n\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getEmail() {\n return email;\n }\n }\n\n public static class Stack implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n String name;\n\n public Stack() {\n\n }\n\n public Stack(Heroku.Stack herokuStack) {\n this.name = herokuStack.value;\n }\n\n public Stack(String name) {\n this.name = name;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n }\n\n public static class Space implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n String name;\n Boolean shield;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Boolean getShield() {\n return shield;\n }\n\n public void setShield(Boolean shield) {\n this.shield = shield;\n }\n }\n}", "public class Heroku {\n\n\n public enum Config {\n ENDPOINT(\"HEROKU_HOST\", \"heroku.host\", \"heroku.com\");\n public final String environmentVariable;\n public final String systemProperty;\n public final String defaultValue;\n public final String value;\n\n Config(String environmentVariable, String systemProperty, String defaultValue) {\n this.environmentVariable = environmentVariable;\n this.systemProperty = systemProperty;\n this.defaultValue = defaultValue;\n String envVal = System.getenv(environmentVariable);\n String configVal = System.getProperty(systemProperty, envVal == null ? defaultValue : envVal);\n this.value = configVal.matches(\"^https?:\\\\/\\\\/.*\") ? configVal : \"https://api.\" + configVal;\n }\n\n public boolean isDefault() {\n return defaultValue.equals(value);\n }\n\n }\n\n public static enum JarProperties {\n ;\n\n static final Properties properties = new Properties();\n\n static {\n try {\n InputStream jarProps = JarProperties.class.getResourceAsStream(\"/heroku.jar.properties\");\n properties.load(jarProps);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n \n public static String getProperty(String propName) {\n return properties.getProperty(propName);\n }\n\n public static Properties getProperties() {\n return properties;\n }\n }\n\n public static SSLContext herokuSSLContext() {\n return sslContext(Config.ENDPOINT.isDefault());\n }\n\n public static SSLContext sslContext(boolean verify) {\n try {\n SSLContext ctx = SSLContext.getInstance(\"TLS\");\n TrustManager[] tmgrs = null;\n if (!verify) {\n tmgrs = trustAllTrustManagers();\n }\n /*\nInitializes this context.\nEither of the first two parameters may be null in which case the installed security providers will be searched\nfor the highest priority implementation of the appropriate factory.\nLikewise, the secure random parameter may be null in which case the default implementation will be used.\n */\n ctx.init(null, tmgrs, null);\n return ctx;\n } catch (NoSuchAlgorithmException e) {\n throw new HerokuAPIException(\"NoSuchAlgorithmException while trying to setup SSLContext\", e);\n } catch (KeyManagementException e) {\n throw new HerokuAPIException(\"KeyManagementException while trying to setup SSLContext\", e);\n }\n }\n\n public static HostnameVerifier hostnameVerifier(boolean verify) {\n HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();\n if (!verify) {\n verifier = new HostnameVerifier() {\n @Override\n public boolean verify(String s, SSLSession sslSession) {\n return true;\n }\n };\n }\n return verifier;\n }\n\n public static HostnameVerifier herokuHostnameVerifier() {\n return hostnameVerifier(Config.ENDPOINT.isDefault());\n }\n\n public static enum ResponseKey {\n Name(\"name\"),\n DomainName(\"domain_name\"),\n CreateStatus(\"create_status\"),\n Stack(\"stack\"),\n SlugSize(\"slug_size\"),\n RequestedStack(\"requested_stack\"),\n CreatedAt(\"created_at\"),\n WebUrl(\"web_url\"),\n RepoMigrateStatus(\"repo_migrate_status\"),\n Id(\"id\"),\n GitUrl(\"git_url\"),\n RepoSize(\"repo_size\"),\n Dynos(\"dynos\"),\n Workers(\"workers\");\n\n public final String value;\n \n // From Effective Java, Second Edition\n private static final Map<String, ResponseKey> stringToResponseKey = new HashMap<String, ResponseKey>();\n static {\n for (ResponseKey key : values())\n stringToResponseKey.put(key.toString(), key);\n }\n \n ResponseKey(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n \n public static ResponseKey fromString(String keyName) {\n return stringToResponseKey.get(keyName);\n }\n }\n\n public static enum RequestKey {\n Slug(\"slug\"),\n StackName(\"name\"),\n Stack(\"stack\"),\n AppMaintenance(\"maintenance\"),\n AddonName(\"addon\"),\n AddonPlan(\"plan\"),\n AddonConfig(\"config\"),\n AddonAttachment(\"attachment\"),\n AddonAttachmentName(\"name\"),\n AppName(\"name\"),\n SSHKey(\"public_key\"),\n Collaborator(\"user\"),\n TransferAppName(\"app\"),\n TransferOwner(\"recipient\"),\n Release(\"release\"),\n CreateDomain(\"hostname\"),\n DeleteDomain(\"hostname\"),\n ProcessTypes(\"process_types\"),\n Dyno(\"dyno\"),\n LogLines(\"lines\"),\n LogSource(\"source\"),\n LogTail(\"tail\"),\n SourceBlob(\"source_blob\"),\n SourceBlobUrl(\"url\"),\n SourceBlobChecksum(\"checksum\"),\n SourceBlobVersion(\"version\"),\n Buildpacks(\"buildpacks\"),\n BuildpackUrl(\"url\"),\n Space(\"space\"),\n SpaceId(\"id\"),\n SpaceName(\"name\"),\n SpaceShield(\"shield\"),\n Quantity(\"quantity\"),\n Team(\"team\"),\n TeamName(\"name\");\n\n public final String queryParameter;\n\n RequestKey(String queryParameter) {\n this.queryParameter = queryParameter;\n }\n }\n\n\n public static enum Stack {\n Cedar14(\"cedar-14\"),\n Container(\"container\"),\n Heroku16(\"heroku-16\"),\n Heroku18(\"heroku-18\");\n\n public final String value;\n\n // From Effective Java, Second Edition\n private static final Map<String, Stack> stringToEnum = new HashMap<String, Stack>();\n static {\n for (Stack s : values())\n stringToEnum.put(s.toString(), s);\n }\n\n Stack(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public static Stack fromString(String stackName) {\n return stringToEnum.get(stackName);\n }\n }\n\n\n public static enum Resource {\n Apps(\"/apps\"),\n App(\"/apps/%s\"),\n AppTransfer(\"/account/app-transfers\"),\n Addons(\"/addons\"),\n AppAddons(App.value + \"/addons\"),\n AppAddon(AppAddons.value + \"/%s\"),\n Builds(\"/apps/%s/builds\"),\n BuildInfo(\"/apps/%s/builds/%s\"),\n BuildResult(\"/apps/%s/builds/%s/result\"),\n User(\"/account\"),\n Key(User.value + \"/keys/%s\"),\n Keys(User.value + \"/keys\"),\n Collaborators(App.value + \"/collaborators\"),\n Collaborator(Collaborators.value + \"/%s\"),\n ConfigVars(App.value + \"/config-vars\"),\n Logs(App.value + \"/log-sessions\"),\n Process(App.value + \"/ps\"),\n Restart(Process.value + \"/restart\"),\n Stop(Process.value + \"/stop\"),\n Scale(Process.value + \"/scale\"),\n Releases(App.value + \"/releases\"),\n Release(Releases.value + \"/%s\"),\n Slugs(App.value + \"/slugs\"),\n Slug(Slugs.value + \"/%s\"),\n Sources(\"/sources\"),\n Status(App.value + \"/status\"),\n Stacks(\"/stacks\"),\n Domains(App.value + \"/domains\"),\n Domain(Domains.value + \"/%s\"),\n Dynos(\"/apps/%s/dynos\"),\n Dyno(Dynos.value + \"/%s\"),\n Formations(App.value + \"/formation\"),\n Formation(Formations.value + \"/%s\"),\n BuildpackInstalltions(\"/apps/%s/buildpack-installations\"),\n TeamApps(\"/teams/%s/apps\"),\n TeamAppsAll(\"/teams/apps\"),\n TeamApp(\"/teams/apps/%s\"),\n Team(\"/teams/%s\"),\n Teams(\"/teams\"),\n TeamInvoices(\"/teams/%s/invoices\"),\n TeamInvoice(\"/teams/%s/invoices/%s\"),;\n\n public final String value;\n\n Resource(String value) {\n this.value = value;\n }\n\n public String format(String... values) {\n return String.format(value, values);\n }\n }\n\n public enum ApiVersion implements Http.Header {\n\n v2(2), v3(3);\n\n public static final String HEADER = \"Accept\";\n\n public final int version;\n\n ApiVersion(int version) {\n this.version = version;\n }\n\n @Override\n public String getHeaderName() {\n return HEADER;\n }\n\n @Override\n public String getHeaderValue() {\n return \"application/vnd.heroku+json; version=\" + Integer.toString(version);\n }\n }\n\n public static TrustManager[] trustAllTrustManagers() {\n return new TrustManager[]{new X509TrustManager() {\n @Override\n public void checkClientTrusted(final X509Certificate[] chain, final String authType) {\n }\n\n @Override\n public void checkServerTrusted(final X509Certificate[] chain, final String authType) {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }};\n }\n}", "public class TeamApp extends App {\n\n private static final long serialVersionUID = 1L;\n\n boolean joined;\n boolean locked;\n Team team;\n\n public TeamApp withTeam(Team team) {\n TeamApp newApp = copy();\n newApp.team = team;\n return newApp;\n }\n\n @Override\n public TeamApp on(Heroku.Stack stack) {\n TeamApp newApp = copy();\n newApp.stack = new App.Stack(stack);\n return newApp;\n }\n\n private TeamApp copy() {\n TeamApp copy = new TeamApp();\n copy.name = this.name;\n copy.stack = this.stack;\n copy.team = this.team;\n return copy;\n }\n\n public boolean isJoined() {\n return joined;\n }\n\n public void setJoined(boolean joined) {\n this.joined = joined;\n }\n\n public boolean isLocked() {\n return locked;\n }\n\n public void setLocked(boolean locked) {\n this.locked = locked;\n }\n\n public Team getTeam() {\n return team;\n }\n\n public void setTeam(Team team) {\n this.team = team;\n }\n\n}", "public class RequestFailedException extends HerokuAPIException {\n\n String responseBody;\n int statusCode;\n\n public RequestFailedException(String msg, int code, byte[] in) {\n this(msg, code, getBodyFromInput(in));\n\n }\n\n private static String getBodyFromInput(byte[] in) {\n try {\n return HttpUtil.getUTF8String(in);\n } catch (Exception e) {\n return \"There was also an error reading the response body.\";\n }\n }\n\n public RequestFailedException(String msg, int code, String body) {\n super(msg + \" statuscode:\" + code + \" responseBody:\" + body);\n responseBody = body;\n statusCode = code;\n }\n\n\n public String getResponseBody() {\n return responseBody;\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n}", "public class Http {\n /**\n * HTTP Accept header model.\n */\n public static enum Accept implements Header {\n JSON(\"application/json\"),\n TEXT(\"text/plain\");\n\n private String value;\n static String ACCEPT = \"Accept\";\n\n Accept(String val) {\n this.value = val;\n }\n\n @Override\n public String getHeaderName() {\n return ACCEPT;\n }\n\n @Override\n public String getHeaderValue() {\n return value;\n }\n\n }\n\n /**\n * HTTP Content-Type header model.\n */\n public static enum ContentType implements Header {\n JSON(\"application/json\"),\n FORM_URLENCODED(\"application/x-www-form-urlencoded\"),\n SSH_AUTHKEY(\"text/ssh-authkey\");\n\n private String value;\n static String CONTENT_TYPE = \"Content-Type\";\n\n ContentType(String val) {\n this.value = val;\n }\n\n @Override\n public String getHeaderName() {\n return CONTENT_TYPE;\n }\n\n @Override\n public String getHeaderValue() {\n return value;\n }\n\n }\n\n /**\n * HTTP User-Agent header model.\n *\n * @see UserAgentValueProvider\n */\n public static enum UserAgent implements Header {\n LATEST(loadValueProvider());\n\n static final String USER_AGENT = \"User-Agent\";\n private final UserAgentValueProvider userAgentValueProvider;\n\n UserAgent(UserAgentValueProvider userAgentValueProvider) {\n this.userAgentValueProvider = userAgentValueProvider;\n }\n\n @Override\n public String getHeaderName() {\n return USER_AGENT;\n }\n\n @Override\n public String getHeaderValue() {\n return userAgentValueProvider.getHeaderValue();\n }\n\n public String getHeaderValue(String customPart) {\n return userAgentValueProvider.getHeaderValue(customPart);\n }\n\n private static UserAgentValueProvider loadValueProvider() {\n final Iterator<UserAgentValueProvider> customProviders =\n ServiceLoader.load(UserAgentValueProvider.class, UserAgent.class.getClassLoader()).iterator();\n\n if (customProviders.hasNext()) {\n return customProviders.next();\n } else {\n return new UserAgentValueProvider.DEFAULT();\n }\n }\n }\n\n /**\n * Represent a name/value pair for a HTTP header. Not all are implemented. Only those used by the Heroku API.\n */\n public static interface Header {\n\n public static class Util {\n public static Map<String, String> setHeaders(Header... headers) {\n Map<String, String> headerMap = new HashMap<String, String>();\n for (Header h : headers) {\n headerMap.put(h.getHeaderName(), h.getHeaderValue());\n }\n return headerMap;\n }\n }\n\n String getHeaderName();\n\n String getHeaderValue();\n\n }\n\n /**\n * HTTP Methods. Not all are implemented. Only those used by the Heroku API.\n */\n public static enum Method {GET, PUT, POST, DELETE, PATCH}\n\n /**\n * HTTP Status codes. Not all are implemented. Only those used by the Heroku API.\n */\n public static enum Status {\n OK(200), CREATED(201), ACCEPTED(202), PAYMENT_REQUIRED(402), FORBIDDEN(403), NOT_FOUND(404), UNPROCESSABLE_ENTITY(422), INTERNAL_SERVER_ERROR(500), SERVICE_UNAVAILABLE(503);\n\n public final int statusCode;\n\n Status(int statusCode) {\n this.statusCode = statusCode;\n }\n\n public boolean equals(int code) {\n return statusCode == code;\n }\n }\n}", "public interface Request<T> {\n\n\n /**\n * HTTP method. e.g. GET, POST, PUT, DELETE\n * @return The HTTP method used in the request.\n */\n Http.Method getHttpMethod();\n\n /**\n * Path and query parameters of a URL.\n * @return The path and query parameters as a String.\n */\n String getEndpoint();\n\n /**\n * Whether or not the request has a body.\n * @return true if it has a request body, otherwise false\n */\n boolean hasBody();\n\n /**\n * Value of the request body.\n * @return Body\n * @throws UnsupportedOperationException Generally thrown if {@link #hasBody()} returns false\n */\n String getBody();\n\n /**\n * Value of the request body as a Map.\n * @return Body\n * @throws UnsupportedOperationException Generally thrown if {@link #hasBody()} returns false\n */\n Map<String, ?> getBodyAsMap();\n\n /**\n * HTTP Accept header.\n * @return The Accept header to be used in the request. Typically \"application/json\" or \"text/xml\"\n * @see com.heroku.api.http.Http.Accept\n */\n Http.Accept getResponseType();\n\n /**\n * {@link Map} of request-specific HTTP headers.\n * @return Name/value pairs of HTTP headers.\n */\n Map<String, String> getHeaders();\n\n /**\n * Response handler.\n * @param bytes Data returned from the request.\n * @param status HTTP status code.\n * @return The type {@link T} as specified by an individual request.\n * @throws com.heroku.api.exception.RequestFailedException Generally thrown when the HTTP status code is 4XX.\n */\n T getResponse(byte[] bytes, int status, Map<String,String> headers);\n\n}", "public class RequestConfig {\n\n private String appName;\n\n private final Map<Heroku.RequestKey, RequestConfig.Either> config = new EnumMap<Heroku.RequestKey, RequestConfig.Either>(Heroku.RequestKey.class);\n\n /**\n * Sets the {Heroku.RequestKey.AppName} parameter.\n * @param appName Name of the app to specify in the config.\n * @return A new {@link RequestConfig}\n */\n public RequestConfig app(String appName) {\n this.appName = appName;\n return this;\n }\n\n public String getAppName() {\n return this.appName;\n }\n\n /**\n * Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.\n * @param key Heroku request key\n * @param value value of the property\n * @return A new {@link RequestConfig}\n */\n public RequestConfig with(Heroku.RequestKey key, String value) {\n RequestConfig newConfig = copy();\n newConfig.config.put(key, new Either(value));\n return newConfig;\n }\n\n /**\n * Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.\n * @param key Heroku request key\n * @param value value of the property\n * @return A new {@link RequestConfig}\n */\n public RequestConfig with(Heroku.RequestKey key, Map<Heroku.RequestKey, Either> value) {\n RequestConfig newConfig = copy();\n newConfig.config.put(key, new Either(value));\n return newConfig;\n }\n\n /**\n * Sets a {@link com.heroku.api.Heroku.RequestKey} parameter.\n * @param key Heroku request key\n * @param data arbitrary key/value map\n * @return A new {@link RequestConfig}\n */\n public RequestConfig withOptions(Heroku.RequestKey key, Map<String, String> data) {\n RequestConfig newConfig = copy();\n newConfig.config.put(key, new Either(new Data(data)));\n return newConfig;\n }\n\n public String get(Heroku.RequestKey key) {\n return config.get(key).string();\n }\n\n public Map<Heroku.RequestKey, Either> getMap(Heroku.RequestKey key) {\n return config.get(key).map();\n }\n\n public boolean has(Heroku.RequestKey key){\n return config.containsKey(key);\n }\n\n public String asJson() {\n return Json.encode(asMap());\n }\n\n public Map<String,Object> asMap() {\n return stringifyMap(config);\n }\n\n private Map<String,Object> stringifyMap(Map<Heroku.RequestKey, Either> map) {\n Map<String,Object> jsonMap = new HashMap<>();\n for (Heroku.RequestKey key : map.keySet()) {\n RequestConfig.Either either = map.get(key);\n if (either.is(String.class)) {\n jsonMap.put(key.queryParameter, either.string());\n } else if (either.is(Boolean.class)) {\n jsonMap.put(key.queryParameter, either.bool());\n } else if (either.is(Data.class)) {\n jsonMap.put(key.queryParameter, either.data());\n } else {\n jsonMap.put(key.queryParameter, stringifyMap(either.map()));\n }\n }\n return jsonMap;\n }\n\n private RequestConfig copy() {\n RequestConfig newConfig = new RequestConfig();\n newConfig.app(this.appName);\n newConfig.config.putAll(config);\n return newConfig;\n }\n\n public static class Either {\n\n private Class type;\n\n private String string;\n\n private Boolean bool;\n\n private Data data;\n\n private Map<Heroku.RequestKey, Either> map;\n\n public Either(Boolean value) {\n this.type = Boolean.class;\n this.bool = value;\n }\n\n public Either(String value) {\n this.type = String.class;\n this.string = value;\n }\n\n public Either(Data data) {\n this.type = Data.class;\n this.data = data;\n }\n\n public Either(Map<Heroku.RequestKey, Either> value) {\n this.type = Map.class;\n this.map = value;\n }\n\n public String string() {\n return string;\n }\n\n public Boolean bool() {\n return bool;\n }\n\n public Map<String,String> data() {\n return data.map();\n }\n\n public Map<Heroku.RequestKey, Either> map() {\n return map;\n }\n\n public Boolean is(Class c) {\n return c.equals(type);\n }\n }\n\n public static class Data {\n\n private Map<String, String> map;\n\n public Data(Map<String, String> map) {\n this.map = map;\n }\n\n public Map<String, String> map() {\n return map;\n }\n\n }\n}", "public static <T> T parse(byte[] data, Type type) {\n return Holder.parser.parse(data, type);\n}" ]
import com.heroku.api.App; import com.heroku.api.Heroku; import com.heroku.api.TeamApp; import com.heroku.api.exception.RequestFailedException; import com.heroku.api.http.Http; import com.heroku.api.request.Request; import com.heroku.api.request.RequestConfig; import java.util.Collections; import java.util.Map; import static com.heroku.api.parser.Json.parse;
package com.heroku.api.request.team; /** * TODO: Javadoc * * @author Naaman Newbold */ public class TeamAppCreate implements Request<TeamApp> { private final RequestConfig config; public TeamAppCreate(TeamApp app) { RequestConfig builder = new RequestConfig();
builder = builder.with(Heroku.RequestKey.Team, app.getTeam().getName());
1
rprobinson/MediPi
MediPiPatient/MediPi/src/main/java/org/medipi/devices/drivers/Omron708BT.java
[ "public class MediPiMessageBox {\r\n\r\n private MediPi medipi;\r\n private HashMap<String, Alert> liveMessages = new HashMap<>();\r\n\r\n private MediPiMessageBox() {\r\n }\r\n\r\n /**\r\n * returns the one and only instance of the singleton\r\n *\r\n * @return singleton instance\r\n */\r\n public static MediPiMessageBox getInstance() {\r\n return MediPiHolder.INSTANCE;\r\n }\r\n\r\n /**\r\n * Sets a reference to the main MediPi class for callbacks and access\r\n *\r\n * @param m medipi reference to the main class\r\n */\r\n public void setMediPi(MediPi m) {\r\n medipi = m;\r\n }\r\n\r\n /**\r\n * Method for displaying an error messagebox to the screen.\r\n *\r\n * @param message String message\r\n * @param except exception which this message arose from - null if not\r\n * applicable\r\n */\r\n public void makeErrorMessage(String message, Exception except) {\r\n try {\r\n String uniqueString;\r\n if (except == null) {\r\n uniqueString = message;\r\n } else {\r\n uniqueString = message + except.getLocalizedMessage();\r\n }\r\n String debugString = getDebugString(except);\r\n\r\n MediPiLogger.getInstance().log(MediPiMessageBox.class.getName() + \".makeErrorMessage\", \"MediPi informed the user that: \" + message + \" \" + except);\r\n if (except != null) {\r\n except.printStackTrace();\r\n }\r\n\r\n if (Platform.isFxApplicationThread()) {\r\n AlertBox ab = new AlertBox();\r\n ab.showAlertBox(uniqueString, message, debugString, liveMessages, medipi);\r\n } else {\r\n Platform.runLater(() -> {\r\n AlertBox ab = new AlertBox();\r\n ab.showAlertBox(uniqueString, message, debugString, liveMessages, medipi);\r\n });\r\n }\r\n } catch (Exception ex) {\r\n medipi.makeFatalErrorMessage(\"Fatal Error - Unable to display error message\", ex);\r\n }\r\n }\r\n\r\n /**\r\n * Method to make a general information message\r\n *\r\n * @param message String representation of the message to be displayed\r\n */\r\n public void makeMessage(String message) {\r\n try {\r\n String uniqueString = message;\r\n\r\n MediPiLogger.getInstance().log(MediPiMessageBox.class.getName() + \".makeMessage\", \"MediPi informed the user that: \" + message);\r\n if (Platform.isFxApplicationThread()) {\r\n AlertBox ab = new AlertBox();\r\n ab.showMessageBox(uniqueString, message, liveMessages, medipi);\r\n } else {\r\n Platform.runLater(() -> {\r\n AlertBox ab = new AlertBox();\r\n ab.showMessageBox(uniqueString, message, liveMessages, medipi);\r\n });\r\n }\r\n } catch (Exception ex) {\r\n medipi.makeFatalErrorMessage(\"Fatal Error - Unable to display error message\", ex);\r\n }\r\n }\r\n\r\n private String getDebugString(Exception ex) {\r\n if (ex == null) {\r\n return \"\";\r\n } else {\r\n return \"\\n\" + ex.toString();\r\n }\r\n }\r\n\r\n private static class MediPiHolder {\r\n\r\n private static final MediPiMessageBox INSTANCE = new MediPiMessageBox();\r\n }\r\n}\r", "@SuppressWarnings(\"restriction\")\r\npublic abstract class BloodPressure extends Device {\r\n\r\n private final String GENERIC_DEVICE_NAME = \"Blood Pressure\";\r\n private String profileId = \"urn:nhs-en:profile:BloodPressure\";\r\n private VBox meterWindow;\r\n\r\n private Label lastSystolDB;\r\n private Label lastSystol;\r\n private Label lastDiastolDB;\r\n private Label lastDiastol;\r\n private Label lastPulseDB;\r\n private Label lastPulse;\r\n private Label measurementTimeTF;\r\n private Label measurementTimeLabel;\r\n\r\n protected String measurementContext = null;\r\n\r\n protected Button downloadButton;\r\n protected static String initialButtonText;\r\n protected static ImageView initialGraphic = null;\r\n\r\n private ArrayList<ArrayList<String>> deviceData = new ArrayList<>();\r\n private Instant schedStartTime = null;\r\n private Instant schedExpireTime = null;\r\n private final StringProperty resultsSummary = new SimpleStringProperty();\r\n private DeviceTimestampChecker deviceTimestampChecker;\r\n protected IntegerProperty systol = new SimpleIntegerProperty(0);\r\n protected IntegerProperty diastol = new SimpleIntegerProperty(0);\r\n protected IntegerProperty heartrate = new SimpleIntegerProperty(0);\r\n private final StringProperty lastMeasurementTime = new SimpleStringProperty();\r\n\r\n protected ProgressBar downProg = new ProgressBar(0.0F);\r\n\r\n protected ArrayList<String> metadata = new ArrayList<>();\r\n\r\n protected ArrayList<String> columns = new ArrayList<>();\r\n protected ArrayList<String> format = new ArrayList<>();\r\n protected ArrayList<String> units = new ArrayList<>();\r\n\r\n /**\r\n * This is the data separator from the MediPi.properties file\r\n *\r\n */\r\n protected String separator;\r\n\r\n /**\r\n * This defines how many steps there are in the progress bar - 0 means that\r\n * no progress bar is shown\r\n */\r\n protected Double progressBarResolution = null;\r\n\r\n /**\r\n * Constructor for Generic Blood Pressure Meter\r\n *\r\n */\r\n public BloodPressure() {\r\n }\r\n\r\n /**\r\n * Initiation method called for this Element.\r\n *\r\n * Successful initiation of the this class results in a null return. Any\r\n * other response indicates a failure with the returned content being a\r\n * reason for the failure\r\n *\r\n * @return populated or null for whether the initiation was successful\r\n * @throws java.lang.Exception\r\n */\r\n @Override\r\n public String init() throws Exception {\r\n\r\n String uniqueDeviceName = getClassTokenName();\r\n measurementContext = MediPiProperties.getInstance().getProperties().getProperty(MediPi.ELEMENTNAMESPACESTEM + uniqueDeviceName + \".measurementcontext\");\r\n if (measurementContext != null) {\r\n final StringBuilder pid = new StringBuilder(measurementContext.length());\r\n\r\n for (final String word : measurementContext.split(\" \")) {\r\n if (!word.isEmpty()) {\r\n pid.append(word.substring(0, 1).toUpperCase());\r\n pid.append(word.substring(1).toLowerCase());\r\n }\r\n }\r\n profileId = profileId + pid.toString();\r\n }\r\n separator = medipi.getDataSeparator();\r\n ImageView iw = medipi.utils.getImageView(\"medipi.images.arrow\", 20, 20);\r\n iw.setRotate(90);\r\n downloadButton = new Button(initialButtonText, initialGraphic);\r\n downloadButton.setId(\"button-download\");\r\n meterWindow = new VBox();\r\n meterWindow.setPadding(new Insets(0, 5, 0, 5));\r\n meterWindow.setSpacing(5);\r\n meterWindow.setMinSize(800, 300);\r\n meterWindow.setMaxSize(800, 300);\r\n downProg.setVisible(false);\r\n HBox buttonHbox = new HBox();\r\n buttonHbox.setSpacing(10);\r\n buttonHbox.getChildren().add(downloadButton);\r\n if (progressBarResolution > 0D) {\r\n buttonHbox.getChildren().add(downProg);\r\n }\r\n Guide guide = new Guide(MediPi.ELEMENTNAMESPACESTEM + uniqueDeviceName + \".guide\");\r\n //ascertain if this element is to be displayed on the dashboard\r\n String b = MediPiProperties.getInstance().getProperties().getProperty(MediPi.ELEMENTNAMESPACESTEM + uniqueDeviceName + \".showdashboardtile\");\r\n if (b == null || b.trim().length() == 0) {\r\n showTile = new SimpleBooleanProperty(true);\r\n } else {\r\n showTile = new SimpleBooleanProperty(!b.toLowerCase().startsWith(\"n\"));\r\n }\r\n //Set the initial values of the simple results\r\n lastSystol = new Label(\"--\");\r\n lastSystol.setId(\"resultstext\");\r\n lastSystolDB = new Label(\"\");\r\n lastDiastol = new Label(\"--\");\r\n lastDiastol.setId(\"resultstext\");\r\n lastDiastolDB = new Label(\"\");\r\n lastPulse = new Label(\"--\");\r\n lastPulse.setId(\"resultstext\");\r\n lastPulseDB = new Label(\"\");\r\n measurementTimeTF = new Label(\"\");\r\n measurementTimeTF.setId(\"resultstimetext\");\r\n measurementTimeLabel = new Label(\"\");\r\n\r\n // create the large result box for the last measurement\r\n // downloaded from the device\r\n // Systolic reading\r\n HBox systolHbox = new HBox();\r\n systolHbox.setAlignment(Pos.CENTER_LEFT);\r\n systolHbox.setPadding(new Insets(0, 0, 0, 10));\r\n Label mmhg = new Label(\"mmHg\");\r\n mmhg.setId(\"resultsunits\");\r\n systolHbox.getChildren().addAll(\r\n lastSystol,\r\n mmhg\r\n );\r\n // Diastolic reading\r\n HBox diastolHbox = new HBox();\r\n diastolHbox.setAlignment(Pos.CENTER_LEFT);\r\n diastolHbox.setPadding(new Insets(0, 0, 0, 10));\r\n Label mmhg2 = new Label(\"mmHg\");\r\n mmhg2.setId(\"resultsunits\");\r\n diastolHbox.getChildren().addAll(\r\n lastDiastol,\r\n mmhg2\r\n );\r\n // Heart Rate reading\r\n HBox pulseHbox = new HBox();\r\n pulseHbox.setAlignment(Pos.CENTER_LEFT);\r\n pulseHbox.setPadding(new Insets(0, 0, 0, 10));\r\n Label bpm = new Label(\"BPM\");\r\n bpm.setId(\"resultsunits\");\r\n pulseHbox.getChildren().addAll(\r\n lastPulse,\r\n bpm\r\n );\r\n VBox meterVBox = new VBox();\r\n meterVBox.setAlignment(Pos.CENTER);\r\n meterVBox.setId(\"resultsbox\");\r\n meterVBox.setPrefWidth(200);\r\n\r\n meterVBox.getChildren().addAll(\r\n systolHbox,\r\n diastolHbox,\r\n pulseHbox,\r\n measurementTimeLabel,\r\n measurementTimeTF\r\n );\r\n\r\n //create the main window HBox\r\n HBox dataHBox = new HBox();\r\n dataHBox.getChildren().addAll(\r\n guide.getGuide(),\r\n meterVBox\r\n );\r\n\r\n meterWindow.getChildren().addAll(\r\n dataHBox\r\n );\r\n // set main Element window\r\n window.setCenter(meterWindow);\r\n\r\n setButton2(downloadButton);\r\n\r\n downloadButton(meterVBox);\r\n lastSystol.textProperty().bind(\r\n Bindings.when(systol.isEqualTo(0))\r\n .then(\"--\")\r\n .otherwise(systol.asString())\r\n );\r\n lastSystolDB.textProperty().bind(\r\n Bindings.when(systol.isEqualTo(0))\r\n .then(\"\")\r\n .otherwise(systol.asString())\r\n );\r\n lastDiastol.textProperty().bind(\r\n Bindings.when(diastol.isEqualTo(0))\r\n .then(\"--\")\r\n .otherwise(diastol.asString())\r\n );\r\n lastDiastolDB.textProperty().bind(\r\n Bindings.when(diastol.isEqualTo(0))\r\n .then(\"\")\r\n .otherwise(diastol.asString())\r\n );\r\n lastPulse.textProperty().bind(\r\n Bindings.when(heartrate.isEqualTo(0))\r\n .then(\"--\")\r\n .otherwise(heartrate.asString())\r\n );\r\n lastPulseDB.textProperty().bind(\r\n Bindings.when(heartrate.isEqualTo(0))\r\n .then(\"\")\r\n .otherwise(heartrate.asString())\r\n );\r\n measurementTimeTF.textProperty().bind(\r\n Bindings.when(lastMeasurementTime.isEqualTo(\"\"))\r\n .then(\"\")\r\n .otherwise(lastMeasurementTime)\r\n );\r\n measurementTimeLabel.textProperty().bind(\r\n Bindings.when(lastMeasurementTime.isEqualTo(\"\"))\r\n .then(\"\")\r\n .otherwise(\"measured at\")\r\n );\r\n window.visibleProperty().addListener((ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {\r\n if (newValue) {\r\n guide.reset();\r\n\r\n }\r\n });\r\n // bind the button disable to the time sync indicator\r\n downloadButton.disableProperty().bind(medipi.timeSync.not());\r\n // This class is used to deny access to recording data if time has not been synchronised\r\n deviceTimestampChecker = new DeviceTimestampChecker(medipi, this);\r\n // successful initiation of the this class results in a null return\r\n return null;\r\n }\r\n\r\n private void downloadButton(VBox meterVBox) {\r\n // Setup download button action to run in its own thread\r\n downloadButton.setOnAction((ActionEvent t) -> {\r\n if (confirmReset()) {\r\n resetDevice();\r\n downloadData(meterVBox);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * method to get the generic device name of the device\r\n *\r\n * @return generic device name e.g. Blood Pressure\r\n */\r\n @Override\r\n public String getGenericDeviceDisplayName() {\r\n if (measurementContext != null) {\r\n return GENERIC_DEVICE_NAME + \" (\" + measurementContext + \")\";\r\n } else {\r\n return GENERIC_DEVICE_NAME;\r\n }\r\n }\r\n\r\n @Override\r\n public String getProfileId() {\r\n return profileId;\r\n }\r\n\r\n // reset the device\r\n @Override\r\n public void resetDevice() {\r\n deviceData = new ArrayList<>();\r\n hasData.set(false);\r\n metadata.clear();\r\n systol.set(0);\r\n diastol.set(0);\r\n heartrate.set(0);\r\n lastMeasurementTime.set(\"\");\r\n resultsSummary.setValue(\"\");\r\n schedStartTime = null;\r\n schedExpireTime = null;\r\n }\r\n\r\n /**\r\n * Gets a DeviceDataDO representation of the data\r\n *\r\n * @return DevicedataDO containing the payload\r\n */\r\n @Override\r\n public DeviceDataDO getData() {\r\n DeviceDataDO payload = new DeviceDataDO(UUID.randomUUID().toString());\r\n StringBuilder sb = new StringBuilder();\r\n //Add MetaData\r\n sb.append(\"metadata->persist->medipiversion->\").append(medipi.getVersion()).append(\"\\n\");\r\n for (String s : metadata) {\r\n sb.append(\"metadata->persist->\").append(s).append(\"\\n\");\r\n }\r\n sb.append(\"metadata->make->\").append(getMake()).append(\"\\n\");\r\n sb.append(\"metadata->model->\").append(getModel()).append(\"\\n\");\r\n sb.append(\"metadata->displayname->\").append(getSpecificDeviceDisplayName()).append(\"\\n\");\r\n sb.append(\"metadata->datadelimiter->\").append(medipi.getDataSeparator()).append(\"\\n\");\r\n if (medipi.getScheduler() != null) {\r\n sb.append(\"metadata->scheduleeffectivedate->\").append(Utilities.ISO8601FORMATDATEMILLI_UTC.format(schedStartTime)).append(\"\\n\");\r\n sb.append(\"metadata->scheduleexpirydate->\").append(Utilities.ISO8601FORMATDATEMILLI_UTC.format(schedExpireTime)).append(\"\\n\");\r\n }\r\n sb.append(\"metadata->columns->\");\r\n for (String string : columns) {\r\n sb.append(string).append(medipi.getDataSeparator());\r\n }\r\n //replace the last separator with a new line\r\n sb.replace(sb.length() - medipi.getDataSeparator().length(), sb.length(), \"\\n\");\r\n\r\n sb.append(\"metadata->format->\");\r\n for (String string : format) {\r\n sb.append(string).append(medipi.getDataSeparator());\r\n }\r\n //replace the last separator with a new line\r\n sb.replace(sb.length() - medipi.getDataSeparator().length(), sb.length(), \"\\n\");\r\n\r\n sb.append(\"metadata->units->\");\r\n for (String string : units) {\r\n sb.append(string).append(medipi.getDataSeparator());\r\n }\r\n //replace the last separator with a new line\r\n sb.replace(sb.length() - medipi.getDataSeparator().length(), sb.length(), \"\\n\");\r\n\r\n // Add Downloaded data\r\n for (ArrayList<String> dataLine : deviceData) {\r\n for (String data : dataLine) {\r\n sb.append(data).append(separator);\r\n }\r\n //replace the last separator with a new line\r\n sb.replace(sb.length() - separator.length(), sb.length(), \"\\n\");\r\n }\r\n\r\n payload.setProfileId(profileId);\r\n payload.setPayload(sb.toString());\r\n return payload;\r\n }\r\n\r\n /**\r\n * method to return the component to the dashboard\r\n *\r\n * @return @throws Exception\r\n */\r\n @Override\r\n public BorderPane getDashboardTile() throws Exception {\r\n DashboardTile dashComponent = new DashboardTile(this, showTile);\r\n dashComponent.addTitle(getGenericDeviceDisplayName());\r\n dashComponent.addOverlay(lastSystolDB, \"mmHg\");\r\n dashComponent.addOverlay(lastDiastolDB, \"mmHg\");\r\n dashComponent.addOverlay(lastPulseDB, \"BPM\");\r\n dashComponent.addOverlay(Color.LIGHTGREEN, hasDataProperty());\r\n return dashComponent.getTile();\r\n }\r\n\r\n @Override\r\n public void setData(ArrayList<ArrayList<String>> data) {\r\n data = deviceTimestampChecker.checkTimestamp(data);\r\n String dataCheckMessage = null;\r\n if ((dataCheckMessage = deviceTimestampChecker.getMessages()) != null) {\r\n MediPiMessageBox.getInstance().makeMessage(getSpecificDeviceDisplayName() + \"\\n\" + dataCheckMessage);\r\n }\r\n if (data == null || data.isEmpty()) {\r\n } else {\r\n for (ArrayList<String> a : data) {\r\n Instant i = Instant.parse(a.get(0));\r\n final int systol = Integer.parseInt(a.get(1));\r\n final int diastol = Integer.parseInt(a.get(2));\r\n final int pulse = Integer.parseInt(a.get(3));\r\n displayData(i, systol, diastol, pulse);\r\n hasData.set(true);\r\n }\r\n deviceData = data;\r\n Scheduler scheduler = null;\r\n if ((scheduler = medipi.getScheduler()) != null) {\r\n schedStartTime = scheduler.getCurrentScheduleStartTime();\r\n schedExpireTime = scheduler.getCurrentScheduleExpiryTime();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Private method to add data to the internal structure and propogate it to\r\n * the UI\r\n *\r\n * @param time\r\n * @param systol reading\r\n * @param diastol reading\r\n * @param heartrate reading\r\n */\r\n private void displayData(Instant time, int systol, int diastol, int heartrate) {\r\n\r\n Platform.runLater(() -> {\r\n this.systol.set(systol);\r\n this.diastol.set(diastol);\r\n this.heartrate.set(heartrate);\r\n this.lastMeasurementTime.set(Utilities.DISPLAY_DEVICE_FORMAT_LOCALTIME.format(time));\r\n resultsSummary.set(getGenericDeviceDisplayName() + \" - \"\r\n + this.systol.getValue().toString()\r\n + \"/\"\r\n + this.diastol.getValue().toString()\r\n + \"mmHg \"\r\n + this.heartrate.getValue().toString()\r\n + \"BPM\"\r\n );\r\n });\r\n }\r\n\r\n /**\r\n * Abstract method to download data from the device driver\r\n *\r\n * @param meterVBox\r\n */\r\n public abstract void downloadData(VBox meterVBox);\r\n\r\n @Override\r\n public StringProperty getResultsSummary() {\r\n return resultsSummary;\r\n }\r\n\r\n}\r", "public class ContinuaBloodPressure implements ContinuaMeasurement {\n\n public static final int MMHG = 3872;\n public static final int BPM = 2720;\n public static final int DIMENTIONLESS = 512;\n\n private String dataValue[];\n private String time;\n private int reportedIdentifier;\n private int measurementSetID;\n\n public ContinuaBloodPressure() {\n }\n\n @Override\n public void insertData(String in, int id) throws Exception {\n String[] dataPoints = in.split(\" \");\n\n if (dataPoints.length != 4) {\n throw new Exception(\"Device Data in wrong format - not in 4 parts\");\n }\n if (!dataPoints[2].equals(\"@\")) {\n throw new Exception(\"Device Data in wrong format - time format\");\n }\n switch (dataPoints[1]) {\n case \"mmHg\":\n reportedIdentifier = MMHG;\n String dp = dataPoints[0].replace(\"(\", \"\").replace(\")\", \"\");\n dataValue = dp.split(\",\");\n if (dataValue.length != 3) {\n throw new Exception(\"Device Data in wrong format - not in 3 parts\");\n }\n int counter = 0;\n for (String s : dataValue) {\n dataValue[counter] = ContinuaData.removeUnwantedDecimalPoints(s);\n counter++;\n }\n break;\n case \"bpm\":\n reportedIdentifier = BPM;\n dataValue= new String[1];\n dataValue[0] = ContinuaData.removeUnwantedDecimalPoints(dataPoints[0]);\n break;\n case \"\":\n reportedIdentifier = DIMENTIONLESS;\n dataValue= new String[1];\n String s = ContinuaData.removeUnwantedDecimalPoints(dataPoints[0]);\n if(s.equals(\"256\")){\n dataValue[0] = \"true\";\n }else if(s.equals(\"0\")){\n dataValue[0] = \"false\";\n }else{\n dataValue[0] = \"true\";\n throw new Exception(\"Irregular Heart Beat units unrecognised\");\n }\n break;\n default:\n throw new Exception(\"Device Data units unrecognised\");\n }\n\n time = dataPoints[3];\n measurementSetID = id;\n }\n\n public int getReportedIdentifier() {\n return reportedIdentifier;\n }\n\n public String[] getDataValue() {\n return dataValue;\n }\n\n public void setDataValue(String[] dataValue) {\n this.dataValue = dataValue;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public int getMeasurementSetID() {\n return measurementSetID;\n }\n\n}", "public class ContinuaData {\n\n private int dataSetCounter=-1;\n private String manufacturer; \n private String model; \n private final ArrayList<ContinuaMeasurement> measurement = new ArrayList();\n\n public static String removeUnwantedDecimalPoints(String s) {\n return s.indexOf(\".\") < 0 ? s : s.replaceAll(\"0*$\", \"\").replaceAll(\"\\\\.$\", \"\");\n }\n public ContinuaData() {\n }\n\n public ArrayList<ContinuaMeasurement> getMeasurements() {\n return measurement;\n }\n\n public void addMeasurement(ContinuaMeasurement measurement) {\n this.measurement.add(measurement);\n }\n\n public int getDataSetCounter() {\n return dataSetCounter;\n }\n public void addDataSetCounter() {\n dataSetCounter++;\n }\n\n public String getManufacturer() {\n return manufacturer;\n }\n\n public void setManufacturer(String manufacturer) {\n this.manufacturer = manufacturer;\n }\n\n public String getModel() {\n return model;\n }\n\n public void setModel(String model) {\n this.model = model;\n }\n\n}", "public class ContinuaManager {\n\n Process healthdProcess = null;\n\n public enum ReadingStatus {\n NOTHING,\n WAITING,\n CONNECTED,\n CONFIGURATION,\n ATTRIBUTES,\n MEASUREMENT,\n DISASSOCIATED,\n DISCONNECTED;\n }\n\n private boolean isDataComplete = false;\n private ReadingStatus isReading = ReadingStatus.NOTHING;\n private ContinuaData continuaDataSet = new ContinuaData();\n private int measurementAttributeIDCounter = 0;\n private ArrayList<Integer> referenceList = new ArrayList();\n private final ContinuaMeasurementFactory measurementFactory = new ContinuaMeasurementFactory();\n private String specialisation = \"\";\n private Process process = null;\n private final String agentScript;\n private final String managerScript;\n private static Exception bootException = null;\n\n private ContinuaManager() {\n managerScript = MediPiProperties.getInstance().getProperties().getProperty(\"medipi.iee11073.manager.python\");\n if (managerScript == null || managerScript.trim().length() == 0) {\n String error = \"Cannot find python ieee11073 manager script\";\n MediPiLogger.getInstance().log(ContinuaManager.class.getName(), error);\n bootException = new Exception(\"Cannot find python ieee11073 manager script\");\n }\n startHealthd();\n agentScript = MediPiProperties.getInstance().getProperties().getProperty(\"medipi.iee11073.agent.python\");\n if (agentScript == null || agentScript.trim().length() == 0) {\n String error = \"Cannot find python ieee11073 agent script\";\n MediPiLogger.getInstance().log(ContinuaManager.class.getName(), error);\n bootException = new Exception(\"Cannot find python ieee11073 agent script\");\n }\n }\n\n public static ContinuaManager getInstance() throws Exception {\n if (bootException != null) {\n throw bootException;\n }\n return ContinuaManagerHolder.INSTANCE;\n }\n\n private static class ContinuaManagerHolder {\n\n private static final ContinuaManager INSTANCE = new ContinuaManager();\n }\n\n private void startHealthd() {\n //call healthd\n stopHealthd();\n try {\n System.out.println(\"start healthd\");\n String[] callAndArgs = {managerScript};\n healthdProcess = Runtime.getRuntime().exec(callAndArgs);\n BufferedReader stdInput = new BufferedReader(new InputStreamReader(healthdProcess.getInputStream()));\n } catch (Exception ex) {\n MediPiMessageBox.getInstance().makeErrorMessage(\"Unable to start healthd service, try restarting MediPi\", ex);\n }\n }\n\n public BufferedReader callIEEE11073Agent(String specialisation) {\n stopIEEE11073Agent();\n if (healthdProcess == null || !healthdProcess.isAlive()) {\n startHealthd();\n }\n try {\n System.out.println(agentScript);\n String[] callAndArgs = {\"python\", agentScript, \"--interpret\", \"--set-time\", \"--mds\", \"--agent-type\", specialisation};\n process = Runtime.getRuntime().exec(callAndArgs);\n BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));\n return stdInput;\n } catch (Exception ex) {\n MediPiMessageBox.getInstance().makeErrorMessage(\"Download of data unsuccessful\", ex);\n return null;\n }\n\n }\n\n public void stopIEEE11073Agent() {\n if (process != null && process.isAlive()) {\n process.destroy();\n }\n stopHealthd();\n }\n\n public void stopHealthd() {\n if (healthdProcess != null && healthdProcess.isAlive()) {\n healthdProcess.destroy();\n }\n }\n\n public void reset() {\n stopIEEE11073Agent();\n stopHealthd();\n isDataComplete = false;\n isReading = ReadingStatus.NOTHING;\n continuaDataSet = new ContinuaData();\n measurementAttributeIDCounter = -1;\n referenceList = new ArrayList();\n specialisation = \"\";\n }\n\n public ReadingStatus getStatus() {\n return isReading;\n }\n\n public boolean parse(String data) throws Exception {\n if (data.equals(\"START\")) {\n isReading = ReadingStatus.NOTHING;\n isDataComplete = false;\n } else if (data.equals(\"healthd service not found, waiting...\") || data.equals(\"Detaching...\")) {\n isReading = ReadingStatus.NOTHING;\n isDataComplete = false;\n startHealthd();\n } else if (data.equals(\"END\")) {\n isReading = ReadingStatus.NOTHING;\n isDataComplete = true;\n stopHealthd();\n } else if (data.equals(\"\")) {\n isReading = ReadingStatus.NOTHING;\n } else if (data.equals(\"Waiting...\")) {\n isReading = ReadingStatus.WAITING;\n } else if (data.startsWith(\"Connected\")) {\n isReading = ReadingStatus.CONNECTED;\n } else if (data.equals(\"Configuration\")) {\n isReading = ReadingStatus.CONFIGURATION;\n } else if (data.equals(\"Device Attributes\")) {\n isReading = ReadingStatus.ATTRIBUTES;\n } else if (data.equals(\"Measurement\")) {\n isReading = ReadingStatus.MEASUREMENT;\n measurementAttributeIDCounter = -1;\n continuaDataSet.addDataSetCounter();\n } else if (data.startsWith(\"\\t\")) {\n if (null != isReading) {\n switch (isReading) {\n case CONFIGURATION:\n if (data.indexOf(\"\tNumeric unit \") == 0) {\n String s = data.substring(\"\tNumeric unit \".length());\n referenceList.add(Integer.valueOf(s));\n } else {\n //THROW error in reading attribute\n throw new Exception(\"error in reading configuration from device\");\n }\n break;\n case ATTRIBUTES:\n if (data.indexOf(\"\tSpecializations: \") == 0) {\n String s = data.substring(\"\tSpecializations: \".length());\n specialisation = s.trim();\n }\n if (data.indexOf(\"\tManufacturer: \") == 0) {\n String s = data.substring(\"\tManufacturer: \".length());\n String[] details = s.trim().split(\" Model: \");\n continuaDataSet.setManufacturer(details[0]);\n continuaDataSet.setModel(details[1]);\n }\n break;\n case MEASUREMENT:\n if (specialisation.equals(\"\")) {\n //THROW error in reading specialisation\n throw new Exception(\"no specialisation found on device, please retry\");\n }\n measurementAttributeIDCounter++;\n if (data.indexOf(\"\t\") == 0) {\n ContinuaMeasurement continuaMeasurement = measurementFactory.getMeasurementClass(specialisation);\n continuaMeasurement.insertData(data.trim(), continuaDataSet.getDataSetCounter());\n //check that the unit identifiers match\n int unitIdentifier = referenceList.get(measurementAttributeIDCounter);\n if (unitIdentifier != continuaMeasurement.getReportedIdentifier()) {\n throw new Exception(\"error in matching attribute to measurement in device\");\n } else {\n continuaDataSet.addMeasurement(continuaMeasurement);\n }\n\n } else {\n //THROW error in reading measurements\n throw new Exception(\"error in reading measurements from device, please retry\");\n }\n break;\n default:\n break;\n }\n }\n } else if (data.startsWith(\"Disassociated\")) {\n isReading = ReadingStatus.DISASSOCIATED;\n } else if (data.startsWith(\"Disconnected\")) {\n isReading = ReadingStatus.DISCONNECTED;\n }\n return isDataComplete;\n }\n\n public ContinuaData getData() throws Exception {\n if (isDataComplete) {\n return continuaDataSet;\n } else {\n //THROW error in reading measurements\n throw new Exception(\"Request for data before data has been fully downloaded\");\n }\n }\n\n}", "public interface ContinuaMeasurement {\n\n\n public void insertData(String in, int id) throws Exception;\n\n public int getReportedIdentifier();\n\n public int getMeasurementSetID();\n\n public String[] getDataValue();\n\n public String getTime();\n \n}" ]
import java.io.BufferedReader; import java.util.ArrayList; import java.util.Arrays; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.concurrent.Task; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import org.medipi.MediPiMessageBox; import org.medipi.devices.BloodPressure; import org.medipi.devices.drivers.domain.ContinuaBloodPressure; import org.medipi.devices.drivers.domain.ContinuaData; import org.medipi.devices.drivers.domain.ContinuaManager; import org.medipi.devices.drivers.domain.ContinuaMeasurement;
/* Copyright 2016 Richard Robinson @ NHS Digital <[email protected]> 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.medipi.devices.drivers; /** * A concrete implementation of a specific device - Omron708BT Blood Pressure * meter * * The class uses the Continua Manager class which uses Antidote IEEE 11073 Library to retrieve * the data via the stdout of the script. * * This class defines the device which is to be connected, defines the data to * be collected and passes this forward to the generic device class * * * @author [email protected] */ @SuppressWarnings("restriction") public class Omron708BT extends BloodPressure { private static final String MAKE = "Omron"; private static final String MODEL = "708-BT"; private static final String DISPLAYNAME = "Omron 708-BT Blood Pressure Meter"; private static final String STARTBUTTONTEXT = "Start"; // The number of increments of the progress bar - a value of 0 removes the progBar private static final Double PROGBARRESOLUTION = 60D; private ImageView stopImg; private Task<String> task = null; private Process process = null; String pythonScript; private ImageView graphic; /** * Constructor for BeurerBM55 */ public Omron708BT() { } // initialise and load the configuration data @Override public String init() throws Exception { progressBarResolution = PROGBARRESOLUTION; stopImg = medipi.utils.getImageView("medipi.images.no", 20, 20); graphic = medipi.utils.getImageView("medipi.images.arrow", 20, 20); graphic.setRotate(90); initialGraphic = graphic; initialButtonText = STARTBUTTONTEXT; // define the data to be collected columns.add("iso8601time"); columns.add("systol"); columns.add("diastol"); columns.add("pulserate"); columns.add("MAP"); columns.add("irregularHeartBeat"); format.add("DATE"); format.add("INTEGER"); format.add("INTEGER"); format.add("INTEGER"); format.add("INTEGER"); format.add("BOOLEAN"); units.add("NONE"); units.add("mmHg"); units.add("mmHg"); units.add("BPM"); units.add("NONE"); units.add("NONE"); return super.init(); } /** * Method to to download the data from the device. This data is digested by * the generic device class */ @Override public void downloadData(VBox v) { if (task == null || !task.isRunning()) { resetDevice(); processData(); } else { Platform.runLater(() -> { task.cancel(); }); } } protected void processData() { task = new Task<String>() { ArrayList<ArrayList<String>> data = new ArrayList<>(); ContinuaManager continuaManager = null; @Override protected String call() throws Exception { try { continuaManager = ContinuaManager.getInstance(); continuaManager.reset(); setButton2Name("Stop", stopImg); // input datastream from the device driver BufferedReader stdInput = continuaManager.callIEEE11073Agent("0x1007"); if (stdInput != null) { String readData = new String(); while ((readData = stdInput.readLine()) != null) { System.out.println(readData); if (continuaManager.parse(readData)) { ContinuaData cd = continuaManager.getData(); if (!cd.getManufacturer().equals("OMRON HEALTHCARE")) { return "Expected device manufacturer is OMRON HEALTHCARE but returned device manufacturer is: "+cd.getManufacturer(); } if (!cd.getModel().equals("HEM-7081-IT")) { return "Expected device model is HEM-7081-IT but returned device model is: "+cd.getModel(); } int setId = 0; while (cd.getDataSetCounter() >= setId) { String sys = null; String dia = null; String mean = null; String heartRate = null; String irregular = null; String time = null; for (ContinuaMeasurement cm : cd.getMeasurements()) { if (cm.getMeasurementSetID() == setId) {
if (cm.getReportedIdentifier() == ContinuaBloodPressure.MMHG) {
2
pugwoo/nimble-orm
src/main/java/com/pugwoo/dbhelper/impl/part/P5_DeleteOp.java
[ "public class DBHelperInterceptor {\n\n\t/**\n\t * select前执行。不会拦截getCount计算总数和getAllKey只查询key这2个接口。\n\t * @param clazz 查询的对象\n\t * @param sql 查询的完整sql\n\t * @param args 查询的完整参数。理论上,拦截器就有可能修改args里面的object的值的,请小心。不建议修改args的值。\n\t * @return 返回true,则查询继续; 返回false将终止查询并抛出NotAllowQueryException\n\t */\n\tpublic boolean beforeSelect(Class<?> clazz, String sql, List<Object> args) {\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * select后执行。不会拦截getCount计算总数和getAllKey只查询key这2个接口。\n\t * @param clazz 查询的对象,这个参数之所以是必须的,因为查询结果可能为空,此时便获取不到clazz\n\t * @param sql 查询的完整sql\n\t * @param args 查询的完整参数\n\t * @param result 查询结果值,对于返回值是一个的,也放入该list中。对于没有的,这里会传入空list。\n\t * @param count 当查询总数或有分页总数时,该数有值。该值为-1时,表示未知总数。\n\t * @return DBHelper会使用返回值作为新的查询结果值,因此,没修改时请务必将result返回。\n\t * 对于机密的数据,请直接设置result的对象属性为null。\n\t */\n\tpublic <T> List<T> afterSelect(Class<?> clazz, String sql, List<Object> args,\n\t\t\tList<T> result, long count) {\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * insert前执行\n\t * @param list 插入的对象列表。可以修改list中的元素,请小心操作;但删除list元素则不一定会影响insert。\n\t * @return 返回true继续执行,返回false中断执行并抛出NotAllowQueryException\n\t */\n\tpublic boolean beforeInsert(List<Object> list) {\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * insert后执行\n\t * @param list 插入的对象列表,对于有自增id的值,返回的list已经设置上了主键。\n\t * @param affectedRows 实际影响的数据库条数。注意list可能有值而affectedRows数据小于list个数,说明有的没有插入到数据库\n\t */\n\tpublic void afterInsert(List<Object> list, int affectedRows) {\n\t}\n\t\n\t// 对于更新拦截器,只提供当前要更新的值。由于更新有自写set语句的接口,因此提供两个beforeUpdate\n\n\t/**\n\t * update前执行\n\t * @param tList 更新前的对象列表\n\t * @param setSql 如果使用了updateCustom方法,传入的setSql将传入。否则该值为null\n\t * @param setSqlArgs 如果使用了updateCustom方法,传入的args将传入,否则该值为null。\n\t * 注意,修改此值会修改实际被设置的值,谨慎!\n\t * @return 返回true继续执行,返回false中断执行并抛出NotAllowQueryException\n\t */\n public boolean beforeUpdate(List<Object> tList, String setSql, List<Object> setSqlArgs) {\n \treturn true;\n }\n \n /**\n * update前执行\n * @param clazz 更新的类\n * @param sql 自定义更新的update sql,完整的sql\n * @param args sql的参数,理论上可以修改到args的值,请小心操作。\n * @param customsSets 允许拦截器自行增加若干set语句,每个语句一个,不需要带set关键字,例如a=?\n * @param customsParams 允许拦截器自行添加若干set语句,这里是对应的参数\n * @return 返回true继续执行,返回false中断执行并抛出NotAllowQueryException\n */\n public boolean beforeUpdateAll(Class<?> clazz, String sql,\n \t\tList<String> customsSets, List<Object> customsParams,\n \t\tList<Object> args) {\n \treturn true;\n }\n \n /**\n * update后执行\n * @param affectedRows 实际修改数据库条数\n */\n public void afterUpdate(List<Object> tList, int affectedRows) {\n }\n \n // 删除相关的\n \n /**\n * delete前执行,包括软删除和物理删除\n * @param tList 删除前的对象列表\n * @return 返回true继续执行,返回false中断执行并抛出NotAllowQueryException\n */\n public boolean beforeDelete(List<Object> tList) {\n \treturn true;\n }\n\n /**\n * delete后执行\n * @param affectedRows 实际修改数据库条数\n */\n public void afterDelete(List<Object> tList, int affectedRows) {\n }\n\n}", "public class InvalidParameterException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic InvalidParameterException() {\n\t}\n\t\n\tpublic InvalidParameterException(String errMsg) {\n\t\tsuper(errMsg);\n\t}\n\n\tpublic InvalidParameterException(Throwable e) {\n\t\tsuper(e);\n\t}\n}", "public class MustProvideConstructorException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic MustProvideConstructorException() {\n\t}\n\t\n\tpublic MustProvideConstructorException(String errMsg) {\n\t\tsuper(errMsg);\n\t}\n\n\tpublic MustProvideConstructorException(Throwable e) {\n\t\tsuper(e);\n\t}\n\n}", "public class NotAllowQueryException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic NotAllowQueryException() {\n\t}\n\t\n\tpublic NotAllowQueryException(String errMsg) {\n\t\tsuper(errMsg);\n\t}\n\n\tpublic NotAllowQueryException(Throwable e) {\n\t\tsuper(e);\n\t}\n}", "public class NullKeyValueException extends RuntimeException {\r\n\r\n\tprivate static final long serialVersionUID = 1L;\r\n\r\n\tpublic NullKeyValueException() {\r\n\t}\r\n\t\r\n\tpublic NullKeyValueException(String errMsg) {\r\n\t\tsuper(errMsg);\r\n\t}\r\n\r\n\tpublic NullKeyValueException(Throwable e) {\r\n\t\tsuper(e);\r\n\t}\r\n}\r", "public class SQLAssert {\n\n\tpublic static void onlyOneKeyColumn(Class<?> clazz) {\n\t\t\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(clazz);\n\n\t\tif (keyFields.size() != 1) {\n\t\t\tthrow new NotOnlyOneKeyColumnException(\n\t\t\t\t\t\"must have only one key column, actually has \"\n\t\t\t\t\t\t\t+ keyFields.size() + \" key columns\");\n\t\t}\n\t\t\n\t}\n\t\n\tpublic static <T> void allSameClass(Collection<T> list) throws InvalidParameterException {\n\t\tif(!isAllSameClass(list)) {\n\t\t\tthrow new InvalidParameterException(\"list elements must be same class\");\n\t\t}\n\t}\n\t\n\tpublic static <T> boolean isAllSameClass(Collection<T> list) {\n\t\tif(list == null || list.isEmpty()) {\n return true;\n }\n\t\tClass<?> clazz = null;\n\t\tfor(T t : list) {\n\t\t\tif (t == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(clazz == null) {\n\t\t\t\tclazz = t.getClass();\n\t\t\t} else {\n\t\t\t\tif (clazz != t.getClass()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\t\n}", "public class SQLUtils {\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(SQLUtils.class);\n\t\n\t/**\n\t * 展开子查询SubQuery子句。该方法不支持子查询嵌套,由上一层方法来嵌套调用以实现SubQuery子句嵌套。\n\t * 该方法会自动处理软删除标记。\n\t * @param subQuery 子查询DTO\n\t * @param values 带回去的参数列表\n\t * @return 拼凑完的SQL\n\t */\n\tpublic static String expandSubQuery(SubQuery subQuery, List<Object> values) {\n\t\tif(subQuery.getArgs() != null) {\n\t\t\tvalues.addAll(Arrays.asList(subQuery.getArgs()));\n\t\t}\n\t\treturn \"SELECT * FROM (SELECT \" +\n\t\t\t\tsubQuery.getField() +\n\t\t\t\t\" FROM \" + getTableName(subQuery.getClazz()) + // 注意:subQuery这里不用table的alias\n\t\t\t\t\" \" + SQLUtils.autoSetSoftDeleted(subQuery.getPostSql(), subQuery.getClazz()) +\n\t\t\t\t\") sub \";\n\t}\n\t\n\t/**\n\t * select 字段 from t_table, 不包含where子句及以后的语句\n\t * @param clazz 注解了Table的类\n\t * @param selectOnlyKey 是否只查询key\n\t * @param isSelect1 是否只select 1,不查询实际字段;当该值为true时,selectOnlyKey无效。\n\t * @param features 将dbHelper的特性开关传入,用于处理生成的SQL\n\t * @param postSql 将postSql传入,目前仅用于确定select 1字段的附加computed字段是否加入\n\t * @return 返回拼凑返回的SQL\n\t */\n\tpublic static String getSelectSQL(Class<?> clazz, boolean selectOnlyKey, boolean isSelect1,\n\t\t\t\t\t\t\t\t\t Map<FeatureEnum, Boolean> features, String postSql) {\n\t\tStringBuilder sql = new StringBuilder();\n\t\tsql.append(\"SELECT \");\n\n\t\t// 处理join方式clazz\n\t\tJoinTable joinTable = DOInfoReader.getJoinTable(clazz);\n\t\tif(joinTable != null) {\n\t\t\tField leftTableField = DOInfoReader.getJoinLeftTable(clazz);\n\t\t\tField rightTableField = DOInfoReader.getJoinRightTable(clazz);\n\t\t\t\n\t\t\tJoinLeftTable joinLeftTable = leftTableField.getAnnotation(JoinLeftTable.class);\n\t\t\tJoinRightTable joinRightTable = rightTableField.getAnnotation(JoinRightTable.class);\n\n\t\t\tif(isSelect1) {\n\t\t\t sql.append(\"1\");\n\t\t\t\tString computedColumnsForCountSelect = getComputedColumnsForCountSelect(\n\t\t\t\t\t\tleftTableField.getType(), joinLeftTable.alias() + \".\", features, postSql);\n\t\t\t\tif (!computedColumnsForCountSelect.trim().isEmpty()) {\n\t\t\t\t\tsql.append(\",\").append(computedColumnsForCountSelect);\n\t\t\t\t}\n\t\t\t\tcomputedColumnsForCountSelect = getComputedColumnsForCountSelect(\n\t\t\t\t\t\trightTableField.getType(), joinRightTable.alias() + \".\", features, postSql);\n\t\t\t\tif (!computedColumnsForCountSelect.trim().isEmpty()) {\n\t\t\t\t\tsql.append(\",\").append(computedColumnsForCountSelect);\n\t\t\t\t}\n } else {\n List<Field> fields1 = DOInfoReader.getColumnsForSelect(leftTableField.getType(), selectOnlyKey);\n List<Field> fields2 = DOInfoReader.getColumnsForSelect(rightTableField.getType(), selectOnlyKey);\n sql.append(join(fields1, \",\", joinLeftTable.alias() + \".\", features));\n sql.append(\",\");\n sql.append(join(fields2, \",\", joinRightTable.alias() + \".\", features));\n }\n\n\t sql.append(\" FROM \").append(getTableName(leftTableField.getType()))\n\t .append(\" \").append(joinLeftTable.alias()).append(\" \");\n\t sql.append(joinTable.joinType().getCode()).append(\" \");\n\t sql.append(getTableName(rightTableField.getType())).append(\" \").append(joinRightTable.alias());\n\t if(joinTable.on().trim().isEmpty()) {\n\t \tthrow new OnConditionIsNeedException(\"join table :\" + clazz.getName());\n\t }\n\t sql.append(\" on \").append(joinTable.on().trim());\n\t \n\t\t} else {\n\t\t\tTable table = DOInfoReader.getTable(clazz);\n\n\t\t\tif(isSelect1) {\n\t\t\t sql.append(\"1\");\n\t\t\t\tString computedColumnsForCountSelect = getComputedColumnsForCountSelect(\n\t\t\t\t\t\tclazz, null, features, postSql);\n\t\t\t\tif (!computedColumnsForCountSelect.trim().isEmpty()) {\n\t\t\t\t\tsql.append(\",\").append(computedColumnsForCountSelect);\n\t\t\t\t}\n\t\t\t} else {\n List<Field> fields = DOInfoReader.getColumnsForSelect(clazz, selectOnlyKey);\n sql.append(join(fields, \",\", features));\n }\n\n\t\t\tsql.append(\" FROM \").append(getTableName(clazz)).append(\" \").append(table.alias());\n\t\t}\n\t\t\n\t\treturn sql.toString();\n\t}\n\n\t/**\n\t * 获得计算列同时也是postSql中出现的列的Column的集合\n\t */\n\tprivate static String getComputedColumnsForCountSelect(Class<?> clazz, String fieldPrefix,\n\t\t\t\t\t\t\t\t\t\t\t\t\tMap<FeatureEnum, Boolean> features, String postSql) {\n\t\tList<Field> fields = DOInfoReader.getColumnsForSelect(clazz, false);\n\n\t\tList<Field> field2 = new ArrayList<>();\n\t\tfor (Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif (column != null && !column.computed().trim().isEmpty()) {\n\t\t\t\t// 这里用简单的postSql是否出现计算列的字符串来判断计算列是否要加入,属于放宽松的做法,程序不会有bug,但优化有空间\n\t\t\t\tif (postSql != null && postSql.contains(column.value())) {\n\t\t\t\t\tfield2.add(field);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (field2.isEmpty()) {\n\t\t\treturn \"\";\n\t\t} else {\n\t\t\treturn join(field2, \",\", fieldPrefix, features);\n\t\t}\n\t}\n\t\n\t/**\n\t * select count(1) from t_table, 不包含where子句及以后的语句\n\t * @param clazz 注解了Table的表\n\t * @return 生成的SQL\n\t */\n\tpublic static String getSelectCountSQL(Class<?> clazz) {\n\t\tStringBuilder sql = new StringBuilder();\n\t\tsql.append(\"SELECT count(*)\");\n\t\t\n\t\t// 处理join方式clazz\n\t\tJoinTable joinTable = DOInfoReader.getJoinTable(clazz);\n\t\tif(joinTable != null) {\n\t\t\tField leftTableField = DOInfoReader.getJoinLeftTable(clazz);\n\t\t\tField rightTableField = DOInfoReader.getJoinRightTable(clazz);\n\t\t\t\n\t\t\tJoinLeftTable joinLeftTable = leftTableField.getAnnotation(JoinLeftTable.class);\n\t\t\tJoinRightTable joinRightTable = rightTableField.getAnnotation(JoinRightTable.class);\n\n\t sql.append(\" FROM \").append(getTableName(leftTableField.getType()))\n\t .append(\" \").append(joinLeftTable.alias()).append(\" \");\n\t sql.append(joinTable.joinType().getCode()).append(\" \");\n\t sql.append(getTableName(rightTableField.getType())).append(\" \").append(joinRightTable.alias());\n\t if(joinTable.on().trim().isEmpty()) {\n\t \tthrow new OnConditionIsNeedException(\"join table VO:\" + clazz.getName());\n\t }\n\t sql.append(\" on \").append(joinTable.on().trim());\n\t \n\t\t} else {\n\t\t\tTable table = DOInfoReader.getTable(clazz);\n\t\t\tsql.append(\" FROM \").append(getTableName(clazz)).append(\" \").append(table.alias());\n\t\t}\n\t\t\n\t\treturn sql.toString();\n\t}\n\t\n\t/**\n\t * 获得主键where子句,包含where关键字。会自动处理软删除条件\n\t * \n\t * @param t 注解了Table的类的对象\n\t * @param keyValues 返回传入sql的参数,如果提供list则写入\n\t * @return 返回值前面会带空格,以确保安全。\n\t * @throws NoKeyColumnAnnotationException 当t的类没有注解任何isKey=true的列时抛出\n\t * @throws NullKeyValueException 当t中的主键都是null时抛出\n\t */\n\tpublic static <T> String getKeysWhereSQL(T t, List<Object> keyValues) \n\t throws NoKeyColumnAnnotationException, NullKeyValueException {\n\t\t\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(t.getClass());\n\t\t\n\t\tList<Object> _keyValues = new ArrayList<>();\n\t\tString where = joinWhereAndGetValue(keyFields, \"AND\", _keyValues, t);\n\t\t\n\t\t// 检查主键不允许为null\n\t\tfor(Object value : _keyValues) {\n\t\t\tif(value == null) {\n\t\t\t\tthrow new NullKeyValueException();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(keyValues != null) {\n\t\t\tkeyValues.addAll(_keyValues);\n\t\t}\n\t\t\n\t\treturn autoSetSoftDeleted(\"WHERE \" + where, t.getClass());\n\t}\n\t\n\t/**\n\t * 获得主键where子句,包含where关键字。会自动处理软删除条件\n\t * \n\t * @param clazz 注解了Table的类\n\t * @throws NoKeyColumnAnnotationException 当没有注解isKey=1的列时抛出\n\t */\n\tpublic static String getKeysWhereSQL(Class<?> clazz) \n\t\t\tthrows NoKeyColumnAnnotationException {\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(clazz);\n\t\tString where = joinWhere(keyFields, \"AND\");\n\t\treturn autoSetSoftDeleted(\"WHERE \" + where, clazz);\n\t}\n\t\n\t/**\n\t * 获得主键in(?)的where子句,包含where关键字。会自动处理软删除条件\n\t * @param clazz 注解了Table的类\n\t * @return 生成的where子句的SQL\n\t */\n\tpublic static String getKeyInWhereSQL(Class<?> clazz) {\n\t\tField keyField = DOInfoReader.getOneKeyColumn(clazz);\n\t\treturn autoSetSoftDeleted(\"WHERE \" +\n\t getColumnName(keyField.getAnnotation(Column.class)) + \" in (?)\", clazz);\n\t}\n\t\n\t/**\n\t * 生成insert语句insert into (...) values (?,?,?),将值放到values中。\n\t * @param t 注解了Table的对象\n\t * @param values 必须,要插入的参数值\n\t * @param isWithNullValue 标记是否将null字段放到insert语句中\n\t * @return 生成的SQL\n\t */\n\tpublic static <T> String getInsertSQL(T t, List<Object> values, boolean isWithNullValue) {\n StringBuilder sql = new StringBuilder(\"INSERT INTO \");\n\n List<Field> fields = DOInfoReader.getColumns(t.getClass());\n\n sql.append(getTableName(t.getClass())).append(\" (\");\n List<Object> _values = new ArrayList<>(); // 之所以增加一个临时变量,是避免values初始不是空的易错情况\n String fieldSql = joinAndGetValue(fields, \",\", _values, t, isWithNullValue);\n sql.append(fieldSql);\n sql.append(\") VALUES \");\n String dotSql = \"(\" + join(\"?\", _values.size(), \",\") + \")\";\n sql.append(dotSql);\n values.addAll(_values);\n\n return sql.toString();\n\t}\n\n\t/**\n\t * 生成insert语句insert into (...) values (?,?,?),将值放到values中。\n\t * @param list 要插入的数据,非空\n\t * @param values 返回的参数列表\n\t * @return 插入的SQL\n\t */\n\tpublic static <T> String getInsertSQLForBatch(Collection<T> list, List<Object[]> values) {\n\t\tStringBuilder sql = new StringBuilder(\"INSERT INTO \");\n\n\t\t// 获得元素的class,list非空,因此clazz和t肯定有值\n\t\tClass<?> clazz = null;\n\t\tfor (T t1 : list) {\n\t\t\tclazz = t1.getClass();\n\t\t\tbreak;\n\t\t}\n\n\t\tList<Field> fields = DOInfoReader.getColumns(clazz);\n\n\t\tsql.append(getTableName(clazz)).append(\" (\");\n\n\t\tboolean isFirst = true;\n\t\tfor (T t : list) {\n\t\t\tList<Object> _values = new ArrayList<>();\n\t\t\tString fieldSql = joinAndGetValue(fields, \",\", _values, t, true);\n\t\t\tif (isFirst) {\n\t\t\t\tsql.append(fieldSql);\n\t\t\t\tsql.append(\") VALUES \");\n\t\t\t\tString dotSql = \"(\" + join(\"?\", _values.size(), \",\") + \")\";\n\t\t\t\tsql.append(dotSql);\n\t\t\t}\n\t\t\tisFirst = false;\n\t\t\tvalues.add(_values.toArray());\n\t\t}\n\n\t\treturn sql.toString();\n\t}\n\t\n\t/**\n\t * 生成insert into (...) select ?,?,? from where not exists (select 1 from where)语句\n\t * @param t 注解了Table的对象\n\t * @param values 要插入的参数\n\t * @param whereSql 附带的where子句\n\t * @return 生成的SQL\n\t */\n\tpublic static <T> String getInsertWhereNotExistSQL(T t, List<Object> values,\n\t\t\tboolean isWithNullValue, String whereSql) {\n\t\tStringBuilder sql = new StringBuilder(\"INSERT INTO \");\n\t\t\n\t\tList<Field> fields = DOInfoReader.getColumns(t.getClass());\n\t\tString tableName = getTableName(t.getClass());\n\t\t\n\t\tsql.append(tableName).append(\" (\");\n\t\tsql.append(joinAndGetValue(fields, \",\", values, t, isWithNullValue));\n\t\tsql.append(\") select \");\n\t\tsql.append(join(\"?\", values.size(), \",\"));\n\t\tsql.append(\" from dual where not exists (select 1 from \");\n\t\t\n\t\tif(!whereSql.trim().toUpperCase().startsWith(\"WHERE \")) {\n\t\t\twhereSql = \"where \" + whereSql;\n\t\t}\n\t\twhereSql = autoSetSoftDeleted(whereSql, t.getClass());\n\t\t\n\t\tsql.append(tableName).append(\" \").append(whereSql).append(\" limit 1)\");\n\t\t\n\t\treturn sql.toString();\n\t}\n\t\n\t/**\n\t * 生成update语句\n\t * @param t 注解了Table的对象\n\t * @param values 要更新的值\n\t * @param withNull 是否更新null值\n\t * @param postSql 附带的where子句\n\t * @return 返回值为null表示不需要更新操作,这个是这个方法特别之处\n\t */\n\tpublic static <T> String getUpdateSQL(T t, List<Object> values,\n\t\t\tboolean withNull, String postSql) {\n\t\t\n\t\tStringBuilder sql = new StringBuilder();\n\t\tsql.append(\"UPDATE \");\n\t\t\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(t.getClass());\n\t\tList<Field> notKeyFields = DOInfoReader.getNotKeyColumns(t.getClass());\n\t\t\n\t\tsql.append(getTableName(t.getClass())).append(\" SET \");\n\t\t\n\t\tList<Object> setValues = new ArrayList<>();\n\t\tString setSql = joinSetAndGetValue(notKeyFields, setValues, t, withNull);\n\t\tif(setValues.isEmpty()) {\n\t\t\treturn null; // all field is empty, not need to update\n\t\t}\n\t\tsql.append(setSql);\n\t\tvalues.addAll(setValues);\n\t\t\n\t\tList<Object> whereValues = new ArrayList<>();\n\t\tString where = \"WHERE \" + joinWhereAndGetValue(keyFields, \"AND\", whereValues, t);\n\t\t// 检查key值是否有null的,不允许有null\n\t\tfor(Object v : whereValues) {\n\t\t\tif(v == null) {\n\t\t\t\tthrow new NullKeyValueException();\n\t\t\t}\n\t\t}\n\t\tvalues.addAll(whereValues);\n\n\t\tField casVersionField = DOInfoReader.getCasVersionColumn(t.getClass());\n\t\tif(casVersionField != null) {\n\t\t\tList<Field> casVersionFields = new ArrayList<>();\n\t\t\tcasVersionFields.add(casVersionField);\n\t\t\tList<Object> casValues = new ArrayList<>();\n\t\t\tString casWhere = joinWhereAndGetValue(casVersionFields, \"AND\", casValues, t);\n\t\t\tif(casValues.size() != 1 || casValues.get(0) == null) {\n\t\t\t\tthrow new CasVersionNotMatchException(\"casVersion column value is null\");\n\t\t\t}\n\t\t\tvalues.add(casValues.get(0));\n\t\t\twhere = where + \" AND \" + casWhere;\n\t\t}\n\t\t\n\t\t// 带上postSql\n\t\tif(postSql != null) {\n\t\t\tpostSql = postSql.trim();\n\t\t\tif(!postSql.isEmpty()) {\n\t\t\t\tif(postSql.startsWith(\"where\")) {\n\t\t\t\t\tpostSql = \" AND \" + postSql.substring(5);\n\t\t\t\t}\n\t\t\t\twhere = where + postSql;\n\t\t\t}\n\t\t}\n\t\t\n\t\tsql.append(autoSetSoftDeleted(where, t.getClass()));\n\t\t\n\t\treturn sql.toString();\n\t}\n\t\n\t/**\n\t * 获得批量更新sql\n\t * @param clazz 注解了Table的类\n\t * @param setSql update的set子句\n\t * @param whereSql 附带的where子句\n\t * @param extraWhereSql 会放在最后,以满足update子select语句的要求\n\t * @return 生成的SQL\n\t */\n\tpublic static <T> String getUpdateAllSQL(Class<T> clazz, String setSql, String whereSql,\n\t\t\tString extraWhereSql) {\n\t\tStringBuilder sql = new StringBuilder();\n\t\tsql.append(\"UPDATE \");\n\t\t\n\t\tList<Field> fields = DOInfoReader.getColumns(clazz);\n\t\t\n\t\tsql.append(getTableName(clazz)).append(\" \");\n\t\t\n\t\tif(setSql.trim().toLowerCase().startsWith(\"set \")) {\n\t\t\tsql.append(setSql);\n\t\t} else {\n\t\t\tsql.append(\"SET \").append(setSql);\n\t\t}\n\t\t\n\t\t// 加上更新时间和updateValueScript\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\n\t\t\tif(column.setTimeWhenUpdate() && Date.class.isAssignableFrom(field.getType())) {\n\t\t\t\tsql.append(\",\").append(getColumnName(column))\n\t\t\t\t .append(\"=\").append(getDateString(new Date()));\n\t\t\t}\n\n\t\t\tString updateValueScript = column.updateValueScript().trim();\n\t\t\tif(!updateValueScript.isEmpty()) {\n\t\t\t\tObject value = ScriptUtils.getValueFromScript(column.ignoreScriptError(), updateValueScript);\n\t\t\t\tif(value != null) {\n\t\t\t\t\tsql.append(\",\").append(getColumnName(column)).append(\"=\")\n\t\t\t\t\t\t\t.append(TypeAutoCast.toSqlValueStr(value));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tsql.append(autoSetSoftDeleted(whereSql, clazz, extraWhereSql));\n\t\treturn sql.toString();\n\t}\n\n\t/**\n\t * 获得自定义更新的sql\n\t * @param t 注解了Table的对象\n\t * @param values 要update的参数值\n\t * @param setSql set子句SQL\n\t * @return 生成的SQL\n\t */\n\tpublic static <T> String getCustomUpdateSQL(T t, List<Object> values, String setSql) {\n\t\tStringBuilder sql = new StringBuilder();\n\t\tsql.append(\"UPDATE \");\n\t\t\n\t\tList<Field> fields = DOInfoReader.getColumns(t.getClass());\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(t.getClass());\n\t\t\n\t\tsql.append(getTableName(t.getClass())).append(\" \");\n\t\t\n\t\tif(setSql.trim().toLowerCase().startsWith(\"set \")) {\n\t\t\tsql.append(setSql);\n\t\t} else {\n\t\t\tsql.append(\"SET \").append(setSql);\n\t\t}\n\t\t\n\t\t// 加上更新时间和casVersion字段、updateValueScript字段\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\n\t\t\tif(column.setTimeWhenUpdate() && Date.class.isAssignableFrom(field.getType())) {\n\t\t\t\tsql.append(\",\").append(getColumnName(column))\n\t\t\t\t .append(\"=\").append(getDateString(new Date()));\n\t\t\t}\n\n\t\t\tif(column.casVersion()) {\n\t\t\t\tObject value = DOInfoReader.getValue(field, t);\n\t\t\t\tif(value == null) {\n\t\t\t\t\tthrow new CasVersionNotMatchException(\"casVersion column value is null\");\n\t\t\t\t}\n\t\t\t\tlong _v;\n\t\t\t\tif(value instanceof Long) {\n\t\t\t\t\t_v = (Long) value;\n\t\t\t\t} else if (value instanceof Integer) {\n\t\t\t\t\t_v = ((Integer) value).longValue();\n\t\t\t\t} else {\n\t\t\t\t\tthrow new CasVersionNotMatchException(\"casVersion column value type must be Integer or Long\");\n\t\t\t\t}\n\t\t\t\tsql.append(\",\").append(getColumnName(column)).append(\"=\").append(_v + 1);\n\t\t\t}\n\n\t\t\tString updateValueScript = column.updateValueScript().trim();\n\t\t\tif(!updateValueScript.isEmpty()) {\n\t\t\t\tObject value = ScriptUtils.getValueFromScript(t, column.ignoreScriptError(), updateValueScript);\n\t\t\t\tif(value != null) {\n\t\t\t\t\tsql.append(\",\").append(getColumnName(column)).append(\"=\")\n\t\t\t\t\t\t\t.append(TypeAutoCast.toSqlValueStr(value));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tList<Object> whereValues = new ArrayList<>();\n\t\tString where = \"WHERE \" + joinWhereAndGetValue(keyFields, \"AND\", whereValues, t);\n\t\t\n\t\tfor(Object value : whereValues) {\n\t\t\tif(value == null) {\n\t\t\t\tthrow new NullKeyValueException();\n\t\t\t}\n\t\t}\n\t\tvalues.addAll(whereValues);\n\n\t\tField casVersionField = DOInfoReader.getCasVersionColumn(t.getClass());\n\t\tif(casVersionField != null) {\n\t\t\tList<Field> casVersionFields = new ArrayList<>();\n\t\t\tcasVersionFields.add(casVersionField);\n\t\t\tList<Object> casValues = new ArrayList<>();\n\t\t\tString casWhere = joinWhereAndGetValue(casVersionFields, \"AND\", casValues, t);\n\t\t\tif(casValues.size() != 1 || casValues.get(0) == null) {\n\t\t\t\tthrow new CasVersionNotMatchException(\"casVersion column value is null\");\n\t\t\t}\n\t\t\tvalues.add(casValues.get(0));\n\t\t\twhere = where + \" AND \" + casWhere;\n\t\t}\n\t\t\n\t\tsql.append(autoSetSoftDeleted(where, t.getClass()));\n\t\t\n\t\treturn sql.toString();\n\t}\n\t\n\t/**\n\t * 获得软删除SQL\n\t * @param t 注解了Table的对象\n\t * @param values 要传回给调用方的更新值\n\t * @return 生成的SQL\n\t */\n\tpublic static <T> String getSoftDeleteSQL(T t, Column softDeleteColumn, List<Object> values) {\n\t\tStringBuilder setSql = new StringBuilder(getColumnName(softDeleteColumn) + \"=\"\n\t\t\t\t+ softDeleteColumn.softDelete()[1]);\n\n\t\t// 处理deleteValueScript\n List<Field> notKeyFields = DOInfoReader.getNotKeyColumns(t.getClass());\n for(Field field : notKeyFields) {\n Column column = field.getAnnotation(Column.class);\n\n String deleteValueScript = column.deleteValueScript().trim();\n if(!deleteValueScript.isEmpty()) {\n Object value = DOInfoReader.getValue(field, t);\n if(value != null) {\n setSql.append(\",\").append(getColumnName(column))\n\t\t\t\t\t\t\t.append(\"=\").append(TypeAutoCast.toSqlValueStr(value));\n }\n }\n }\n\n\t\treturn getCustomDeleteSQL(t, values, setSql.toString());\n\t}\n\t\n\t/**\n\t * 获得自定义删除SQL\n\t */\n\tpublic static <T> String getCustomDeleteSQL(Class<T> clazz, String postSql) {\n\n\t\t// 物理删除也执行deleteValueScript,但是不关心其返回值\n List<Field> fields = DOInfoReader.getColumns(clazz);\n for(Field field : fields) {\n Column column = field.getAnnotation(Column.class);\n\n String deleteValueScript = column.deleteValueScript().trim();\n if(!deleteValueScript.isEmpty()) {\n ScriptUtils.getValueFromScript(column.ignoreScriptError(), deleteValueScript);\n }\n }\n\n\t\treturn \"DELETE FROM \" +\n\t\t\t\tgetTableName(clazz) +\n\t\t\t\tautoSetSoftDeleted(postSql, clazz);\n\t}\n\t\n\tpublic static <T> String getCustomSoftDeleteSQL(Class<T> clazz, String postSql, Field softDelete) {\n\t\t\n\t\tList<Field> fields = DOInfoReader.getColumns(clazz);\n\t\tColumn softDeleteColumn = softDelete.getAnnotation(Column.class);\n\t\t\n\t\tStringBuilder sql = new StringBuilder();\n\t\t\n\t\tsql.append(\"UPDATE \").append(getTableName(clazz));\n\t\tsql.append(\" SET \").append(getColumnName(softDeleteColumn));\n\t\tsql.append(\"=\").append(softDeleteColumn.softDelete()[1]);\n\t\t\n\t\t// 特殊处理@Column setTimeWhenDelete时间,还有deleteValueScript\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(column.setTimeWhenDelete() && Date.class.isAssignableFrom(field.getType())) {\n\t\t\t\tsql.append(\",\").append(getColumnName(column)).append(\"='\");\n\t\t\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSS\");\n\t\t\t\tsql.append(df.format(new Date())).append(\"'\");\n\t\t\t}\n\n\t\t\tString deleteValueScript = column.deleteValueScript().trim();\n\t\t\tif(!deleteValueScript.isEmpty()) {\n\t\t\t Object value = ScriptUtils.getValueFromScript(column.ignoreScriptError(), deleteValueScript);\n\t\t\t if(value != null) {\n\t\t\t sql.append(\",\").append(getColumnName(column)).append(\"=\")\n .append(TypeAutoCast.toSqlValueStr(value));\n }\n\t\t\t}\n\t\t}\n\n\t\tsql.append(autoSetSoftDeleted(postSql, clazz));\n\t\t\n\t\treturn sql.toString();\n\t}\n\n\t/**\n\t * 获得自定义更新的sql\n\t */\n\tpublic static <T> String getCustomDeleteSQL(T t, List<Object> values, String setSql) {\n\t\tStringBuilder sql = new StringBuilder();\n\t\tsql.append(\"UPDATE \");\n\n\t\tList<Field> fields = DOInfoReader.getColumns(t.getClass());\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(t.getClass());\n\n\t\tsql.append(getTableName(t.getClass())).append(\" \");\n\n\t\tif(setSql.trim().toLowerCase().startsWith(\"set \")) {\n\t\t\tsql.append(setSql);\n\t\t} else {\n\t\t\tsql.append(\"SET \").append(setSql);\n\t\t}\n\n\t\t// 加上删除时间\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(column.setTimeWhenDelete() && Date.class.isAssignableFrom(field.getType())) {\n\t\t\t\tsql.append(\",\").append(getColumnName(column))\n\t\t\t\t\t\t.append(\"=\").append(getDateString(new Date()));\n\t\t\t}\n\t\t}\n\n\t\tList<Object> whereValues = new ArrayList<>();\n\t\tString where = \"WHERE \" + joinWhereAndGetValue(keyFields, \"AND\", whereValues, t);\n\n\t\tfor(Object value : whereValues) {\n\t\t\tif(value == null) {\n\t\t\t\tthrow new NullKeyValueException();\n\t\t\t}\n\t\t}\n\t\tvalues.addAll(whereValues);\n\n\t\tsql.append(autoSetSoftDeleted(where, t.getClass()));\n\n\t\treturn sql.toString();\n\t}\n\n\n\t/**\n\t * 获得硬删除SQL\n\t */\n\tpublic static <T> String getDeleteSQL(T t, List<Object> values) {\n\t\t\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(t.getClass());\n\t\t\n\t\tStringBuilder sql = new StringBuilder();\n\t\t\n\t\tsql.append(\"DELETE FROM \");\n\t\tsql.append(getTableName(t.getClass()));\n\t\t\n\t\tList<Object> _values = new ArrayList<>();\n\t\tString where = \"WHERE \" + joinWhereAndGetValue(keyFields, \"AND\", _values, t);\n\t\tfor(Object value : _values) { // 检查key的值是不是null\n\t\t\tif(value == null) {\n\t\t\t\tthrow new NullKeyValueException();\n\t\t\t}\n\t\t}\n\t\tvalues.addAll(_values);\n\t\t\n\t\tsql.append(autoSetSoftDeleted(where, t.getClass()));\n\t\t\n\t\treturn sql.toString();\n\t}\n\n\t/**\n\t * 往where sql里面插入AND关系的表达式。\n\t * \n\t * 例如:whereSql为 where a!=3 or a!=2 limit 1\n\t * condExpress为 deleted=0\n\t * 那么返回:where (deleted=0 and (a!=3 or a!=2)) limit 1\n\t * \n\t * @param whereSql 从where起的sql子句,如果有where必须带上where关键字。\n\t * @param condExpression 例如a=? 不带where或and关键字。\n\t * @return 注意返回字符串前面没有空格\n\t * @throws JSQLParserException SQL解析错误时抛出\n\t */\n\tpublic static String insertWhereAndExpression(String whereSql, String condExpression) \n\t\t\tthrows JSQLParserException {\n\t\t\n\t\tif(condExpression == null || condExpression.trim().isEmpty()) {\n\t\t\treturn whereSql == null ? \"\" : whereSql;\n\t\t}\n\t\tif(whereSql == null || whereSql.trim().isEmpty()) {\n\t\t\treturn \"WHERE \" + condExpression;\n\t\t}\n\t\t\n\t\twhereSql = whereSql.trim();\n\t\tif(!whereSql.toUpperCase().startsWith(\"WHERE \")) {\n\t\t\treturn \"WHERE \" + condExpression + \" \" + whereSql;\n\t\t}\n\t\t\n\t\t// 为解决JSqlParse对复杂的condExpression不支持的问题,这里用替换的形式来达到目的\n\t String magic = \"A\" + UUID.randomUUID().toString().replace(\"-\", \"\");\n\t\t\n\t\tString selectSql = \"select * from dual \"; // 辅助where sql解析用\n\t\tStatement statement = CCJSqlParserUtil.parse(selectSql + whereSql);\n\t\tSelect selectStatement = (Select) statement;\n\t\tPlainSelect plainSelect = (PlainSelect)selectStatement.getSelectBody();\n\t\t\n\t\tExpression ce = CCJSqlParserUtil.parseCondExpression(magic);\n\t\tExpression oldWhere = plainSelect.getWhere();\n\t\tExpression newWhere = new FixedAndExpression(oldWhere, ce);\n\t\tplainSelect.setWhere(newWhere);\n\t\t\n\t\tString result = plainSelect.toString().substring(selectSql.length());\n\t\treturn result.replace(magic, condExpression);\n\t}\n\n\tpublic static String autoSetSoftDeleted(String whereSql, Class<?> clazz) {\n\t\treturn autoSetSoftDeleted(whereSql, clazz, \"\");\n\t}\n\t\n\t/**\n\t * 自动为【最后】where sql字句加上软删除查询字段\n\t * @param whereSql 如果有where条件的,【必须】带上where关键字;如果是group by或空的字符串或null都可以\n\t * @param clazz 要操作的DO类\n\t * @param extraWhere 附带的where语句,会加进去,不能带where关键字,仅能是where的条件字句,该子句会放到最后\n\t * @return 无论如何前面会加空格,更安全\n\t */\n\tpublic static String autoSetSoftDeleted(String whereSql, Class<?> clazz, String extraWhere) {\n\t\tif(whereSql == null) {\n\t\t\twhereSql = \"\";\n\t\t}\n\t\textraWhere = extraWhere == null ? \"\" : extraWhere.trim();\n\t\tif(!extraWhere.isEmpty()) {\n\t\t\textraWhere = \"(\" + extraWhere + \")\";\n\t\t}\n\t\t\n\t\tString deletedExpression = \"\";\n\t\t\n\t\t// 处理join方式clazz\n\t\tJoinTable joinTable = DOInfoReader.getJoinTable(clazz);\n\t\tif(joinTable != null) {\n\t\t\tField leftTableField = DOInfoReader.getJoinLeftTable(clazz);\n\t\t\tField rightTableField = DOInfoReader.getJoinRightTable(clazz);\n\t\t\t\n\t\t\tJoinLeftTable joinLeftTable = leftTableField.getAnnotation(JoinLeftTable.class);\n\t\t\tJoinRightTable joinRightTable = rightTableField.getAnnotation(JoinRightTable.class);\n\t\t\t\n\t\t\tField softDeleteT1 = DOInfoReader.getSoftDeleteColumn(leftTableField.getType());\n\t\t\tField softDeleteT2 = DOInfoReader.getSoftDeleteColumn(rightTableField.getType());\n\t\t\t\n\t\t\tif(softDeleteT1 == null && softDeleteT2 == null) {\n\t\t\t\ttry {\n\t\t\t\t\treturn \" \" + insertWhereAndExpression(whereSql, extraWhere);\n\t\t\t\t} catch (JSQLParserException e) {\n\t\t\t\t\tLOGGER.error(\"Bad sql syntax,whereSql:{},deletedExpression:{}\",\n\t\t\t\t\t\t\twhereSql, deletedExpression, e);\n\t\t\t\t\tthrow new BadSQLSyntaxException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tStringBuilder deletedExpressionSb = new StringBuilder();\n\t\t\tif(softDeleteT1 != null) {\n\t\t\t\tColumn softDeleteColumn = softDeleteT1.getAnnotation(Column.class);\n\t\t\t\tString columnName = getColumnName(softDeleteColumn);\n\t\t\t\tif(joinTable.joinType() == JoinTypeEnum.RIGHT_JOIN) {\n\t\t\t\t\tdeletedExpressionSb.append(\"(\").append(joinLeftTable.alias()).append(\".\")\n\t\t\t\t\t\t\t.append(columnName).append(\"=\").append(softDeleteColumn.softDelete()[0])\n\t\t\t\t\t .append(\" or \").append(joinLeftTable.alias()).append(\".\")\n\t\t\t\t\t .append(columnName).append(\" is null)\");\n\t\t\t\t} else {\n\t\t\t\t\tdeletedExpressionSb.append(joinLeftTable.alias()).append(\".\")\n\t\t\t\t\t\t\t.append(columnName).append(\"=\").append(softDeleteColumn.softDelete()[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(softDeleteT2 != null) {\n\t\t\t\tif(softDeleteT1 != null) {\n\t\t\t\t\tdeletedExpressionSb.append(\" AND \");\n\t\t\t\t}\n\t\t\t\tColumn softDeleteColumn = softDeleteT2.getAnnotation(Column.class);\n\t\t\t\tString columnName = getColumnName(softDeleteColumn);\n\t\t\t\tif(joinTable.joinType() == JoinTypeEnum.LEFT_JOIN) {\n\t\t\t\t\tdeletedExpressionSb.append(\"(\").append(joinRightTable.alias()).append(\".\")\n\t\t\t\t\t\t\t.append(columnName).append(\"=\").append(softDeleteColumn.softDelete()[0])\n\t\t\t\t\t .append(\" or \").append(joinRightTable.alias()).append(\".\")\n\t\t\t\t\t .append(columnName).append(\" is null)\");\n\t\t\t\t} else {\n\t\t\t\t\tdeletedExpressionSb.append(joinRightTable.alias()).append(\".\")\n\t\t\t\t\t\t\t.append(columnName).append(\"=\").append(softDeleteColumn.softDelete()[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tdeletedExpression = deletedExpressionSb.toString();\t\t\n\t\t} else {\n\t\t\tField softDelete = DOInfoReader.getSoftDeleteColumn(clazz);\n\t\t\tif(softDelete == null) {\n\t\t\t\ttry {\n\t\t\t\t\treturn \" \" + insertWhereAndExpression(whereSql, extraWhere);\n\t\t\t\t} catch (JSQLParserException e) {\n\t\t\t\t\tLOGGER.error(\"Bad sql syntax,whereSql:{},deletedExpression:{}\",\n\t\t\t\t\t\t\twhereSql, deletedExpression, e);\n\t\t\t\t\tthrow new BadSQLSyntaxException(e);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tColumn softDeleteColumn = softDelete.getAnnotation(Column.class);\n\t\t\tdeletedExpression = getColumnName(softDeleteColumn) + \"=\" \n\t\t\t + softDeleteColumn.softDelete()[0];\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tif(!extraWhere.isEmpty()) {\n\t\t\t\tdeletedExpression = \"(\" + deletedExpression + \" and \" + extraWhere + \")\";\n\t\t\t}\n\t\t\treturn \" \" + SQLUtils.insertWhereAndExpression(whereSql, deletedExpression);\n\t\t} catch (JSQLParserException e) {\n\t\t\tLOGGER.error(\"Bad sql syntax,whereSql:{},deletedExpression:{}\",\n\t\t\t\t\twhereSql, deletedExpression, e);\n\t\t\tthrow new BadSQLSyntaxException(e);\n\t\t}\n\t}\n\t\n\t/**\n\t * 拼凑limit字句。前面有空格。\n\t * @param offset 可以为null\n\t * @param limit 不能为null\n\t * @return 生成的SQL\n\t */\n\tpublic static String genLimitSQL(Integer offset, Integer limit) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif (limit != null) {\n\t\t\tsb.append(\" limit \");\n\t\t\tif(offset != null) {\n\t\t\t\tsb.append(offset).append(\",\");\n\t\t\t}\n\t\t\tsb.append(limit);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * 拿到computed SQL在特性开关的情况下的返回值。说明:调用此方法请确保计算列是非空的。\n\t * @param column 列注解\n\t * @param features 特性开关map\n\t * @return 返回计算列的结果SQL\n\t */\n\tpublic static String getComputedColumn(Column column, Map<FeatureEnum, Boolean> features) {\n\t\tString computed = column.computed();\n\n\t\tBoolean autoSumNullToZero = features.get(FeatureEnum.AUTO_SUM_NULL_TO_ZERO);\n\t\tif (autoSumNullToZero != null && autoSumNullToZero) {\n\t\t\tString computedLower = computed.toLowerCase().trim();\n\t\t\tif (computedLower.startsWith(\"sum(\") && computedLower.endsWith(\")\")) {\n\t\t\t\tcomputed = \"COALESCE(\" + computed + \",0)\";\n\t\t\t}\n\t\t}\n\n\t\treturn computed;\n\t}\n\n\t/**\n\t * 判断postSql是否包含了limit子句\n\t * @param postSql 从where开始的子句\n\t * @return 是返回true,否返回false;如果解析异常返回false\n\t */\n\tpublic static boolean isContainsLimit(String postSql) {\n\t\tBoolean result = containsLimitCache.get(postSql);\n\t\tif (result != null) {\n\t\t\treturn result;\n\t\t}\n\n\t\tString selectSql = \"select * from dual \"; // 辅助where sql解析用\n\t\ttry {\n\t\t\tStatement statement = CCJSqlParserUtil.parse(selectSql + postSql);\n\t\t\tSelect selectStatement = (Select) statement;\n\t\t\tPlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody();\n\t\t\tLimit limit = plainSelect.getLimit();\n\t\t\tboolean isContainsLimit = limit != null;\n\t\t\tcontainsLimitCache.put(postSql, isContainsLimit);\n\t\t\treturn isContainsLimit;\n\t\t} catch (JSQLParserException e) {\n\t\t\tthrow new BadSQLSyntaxException(e);\n\t\t}\n\t}\n\n\tprivate static Map<String, Boolean> containsLimitCache = new ConcurrentHashMap<>();\n\n /**\n * 拼凑select的field的语句\n */\n\tprivate static String join(List<Field> fields, String sep, Map<FeatureEnum, Boolean> features) {\n\t return join(fields, sep, null, features);\n }\n\t\n /**\n * 拼凑select的field的语句\n */\n private static String join(List<Field> fields, String sep, String fieldPrefix,\n\t\t\t\t\t\t\t Map<FeatureEnum, Boolean> features) {\n \treturn joinAndGetValueForSelect(fields, sep, fieldPrefix, features);\n }\n\t\n\t/**\n\t * 拼凑where子句,并把需要的参数写入到values中。返回sql【不】包含where关键字\n\t * \n\t * @param fields 注解了Column的field\n\t * @param logicOperate 操作符,例如AND\n\t * @param values where条件的参数值\n\t */\n\tprivate static String joinWhereAndGetValue(List<Field> fields,\n\t\t\tString logicOperate, List<Object> values, Object obj) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tint fieldSize = fields.size();\n\t\tfor(int i = 0; i < fieldSize; i++) {\n\t\t\tColumn column = fields.get(i).getAnnotation(Column.class);\n\t\t\tsb.append(getColumnName(column)).append(\"=?\");\n\t\t\tif(i < fieldSize - 1) {\n\t\t\t\tsb.append(\" \").append(logicOperate).append(\" \");\n\t\t\t}\n\t\t\tObject val = DOInfoReader.getValue(fields.get(i), obj);\n\t\t\tif(val != null && column.isJSON()) {\n\t\t\t\tval = NimbleOrmJSON.toJson(val);\n\t\t\t}\n\t\t\tvalues.add(val);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n\t/**\n\t * 拼凑where子句。返回sql【不】包含where关键字\n\t * @param logicOperate 操作符,例如AND\n\t */\n\tprivate static String joinWhere(List<Field> fields, String logicOperate) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tint fieldSize = fields.size();\n\t\tfor(int i = 0; i < fieldSize; i++) {\n\t\t\tColumn column = fields.get(i).getAnnotation(Column.class);\n\t\t\tsb.append(getColumnName(column)).append(\"=?\");\n\t\t\tif(i < fieldSize - 1) {\n\t\t\t\tsb.append(\" \").append(logicOperate).append(\" \");\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n /**\n * 拼凑字段逗号,分隔子句(用于insert),并把参数obj的值放到values中\n * @param isWithNullValue 是否把null值放到values中\n */\n private static String joinAndGetValue(List<Field> fields, String sep,\n List<Object> values, Object obj, boolean isWithNullValue) {\n\t return joinAndGetValueForInsert(fields, sep, null, values, obj, isWithNullValue);\n }\n \n /**\n * 拼凑字段逗号,分隔子句(用于select)。会处理computed的@Column字段\n */\n\tprivate static String joinAndGetValueForSelect(List<Field> fields, String sep, String fieldPrefix,\n\t\t\t\t\t\t\t\t\t\t\t\t Map<FeatureEnum, Boolean> features) {\n fieldPrefix = fieldPrefix == null ? \"\" : fieldPrefix.trim();\n\n \tStringBuilder sb = new StringBuilder();\n \tfor(Field field : fields) {\n \t\tColumn column = field.getAnnotation(Column.class);\n \t\t\n \t\tString computed = column.computed().trim();\n \t\tif(!computed.isEmpty()) {\n \t\t\tsb.append(\"(\").append(SQLUtils.getComputedColumn(column, features)).append(\") AS \");\n \t\t} else {\n \t\t\tsb.append(fieldPrefix); // 计算列不支持默认前缀,当join时,请自行区分计算字段的命名\n \t\t}\n \tsb.append(getColumnName(column)).append(sep);\n \t}\n \tint len = sb.length();\n \treturn len == 0 ? \"\" : sb.substring(0, len - 1);\n\t}\n \n /**\n * 拼凑字段逗号,分隔子句(用于insert),并把参数obj的值放到values中。会排除掉computed的@Column字段\n *\n * @param values 不应该为null\n * @param obj 不应该为null\n * @param isWithNullValue 是否把null值放到values中\n */\n\tprivate static String joinAndGetValueForInsert(List<Field> fields, String sep, String fieldPrefix,\n\t\t\tList<Object> values, Object obj, boolean isWithNullValue) {\n\t\tif(values == null || obj == null) {\n\t\t\tthrow new InvalidParameterException(\"joinAndGetValueForInsert require values and obj\");\n\t\t}\n\t\t\n fieldPrefix = fieldPrefix == null ? \"\" : fieldPrefix.trim();\n\n \tStringBuilder sb = new StringBuilder();\n \tfor(Field field : fields) {\n \t\tColumn column = field.getAnnotation(Column.class);\n \t\tif(!(column.computed().trim().isEmpty())) {\n \t\t\tcontinue; // insert不加入computed字段\n \t\t}\n\n\t\t\tObject value = DOInfoReader.getValue(field, obj);\n\t\t\tif(value != null && column.isJSON()) {\n\t\t\t\tvalue = NimbleOrmJSON.toJson(value);\n\t\t\t}\n\t\t\tif(isWithNullValue) {\n\t\t\t\tvalues.add(value);\n\t\t\t} else {\n\t\t\t\tif(value == null) {\n\t\t\t\t\tcontinue; // 不加入该column\n\t\t\t\t} else {\n\t\t\t\t\tvalues.add(value);\n\t\t\t\t}\n\t\t\t}\n \t\t\n \tsb.append(fieldPrefix).append(getColumnName(column)).append(sep);\n \t}\n \tint len = sb.length();\n \treturn len == 0 ? \"\" : sb.substring(0, len - 1);\n\t}\n\t\n\t/**\n\t * 例如:str=?,times=3,sep=, 返回 ?,?,?\n\t */\n private static String join(String str, int times, String sep) {\n \tStringBuilder sb = new StringBuilder();\n \tfor(int i = 0; i < times; i++) {\n \t\tsb.append(str);\n \t\tif(i < times - 1) {\n \t\t\tsb.append(sep);\n \t\t}\n \t}\n \treturn sb.toString();\n }\n \n\t/**\n\t * 拼凑set子句,将会处理casVersion的字段自动+1\n\t * @param withNull 当为true时,如果field的值为null,也加入\n\t */\n\tprivate static String joinSetAndGetValue(List<Field> fields,\n\t\t\tList<Object> values, Object obj, boolean withNull) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tObject value = DOInfoReader.getValue(field, obj);\n\t\t\tif (column.casVersion()) {\n\t\t\t\tif (value == null) {\n\t\t\t\t\tthrow new CasVersionNotMatchException(\"casVersion column value is null\");\n\t\t\t\t}\n\t\t\t\tlong _v;\n\t\t\t\tif (value instanceof Long) {\n\t\t\t\t\t_v = (Long) value;\n\t\t\t\t} else if (value instanceof Integer) {\n\t\t\t\t\t_v = ((Integer) value).longValue();\n\t\t\t\t} else {\n\t\t\t\t\tthrow new CasVersionNotMatchException(\"casVersion column type must be Integer or Long\");\n\t\t\t\t}\n\t\t\t\tsb.append(getColumnName(column)).append(\"=\").append(_v + 1).append(\",\");\n\t\t\t} else {\n\t\t\t\tif (value != null && column.isJSON()) {\n\t\t\t\t\tvalue = NimbleOrmJSON.toJson(value);\n\t\t\t\t}\n\t\t\t\tif (withNull || value != null) {\n\t\t\t\t\tsb.append(getColumnName(column)).append(\"=?,\");\n\t\t\t\t\tvalues.add(value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn sb.length() == 0 ? \"\" : sb.substring(0, sb.length() - 1);\n\t}\n\n\tprivate static String getTableName(Class<?> clazz) {\n\t\tString tableName = DBHelperContext.getTableName(clazz);\n\t\tif(tableName != null) {\n\t\t\treturn \"`\" + tableName + \"`\";\n\t\t}\n\n\t\tTable table = DOInfoReader.getTable(clazz);\n\t\treturn \"`\" + table.value() + \"`\";\n\t}\n\n\tprivate static String getColumnName(Column column) {\n\t\treturn \"`\" + column.value() + \"`\";\n\t}\n\t\n\t/**\n\t * 输出类似:'2017-05-25 11:22:33'\n\t */\n\tprivate static String getDateString(Date date) {\n\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.SSS\");\n\t\treturn \"'\" + df.format(date) + \"'\";\n\t}\n\n}", "public class DOInfoReader {\n\t\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(DOInfoReader.class);\n\t\n\t/**\n\t * 获取DO的@Table信息,如果子类没有,会往父类查找\n\t *\n\t * @throws NoTableAnnotationException 当clazz没有@Table注解时抛出NoTableAnnotationException\n\t */\n\tpublic static Table getTable(Class<?> clazz) throws NoTableAnnotationException {\n\t\tTable table = getAnnotationClass(clazz, Table.class);\n\t\tif (table != null) {\n\t\t\treturn table;\n\t\t}\n\t\t\n\t\tthrow new NoTableAnnotationException(\"class: \"\n\t\t\t\t+ (clazz == null ? \"null\" : clazz.getName())\n\t\t\t\t+ \" does not have @Table annotation.\");\n\t}\n\t\n\t/**\n\t * 获得clazz上注解的JoinTable,如果没有则返回null\n\t * @return 如果没有则返回null\n\t */\n\tpublic static JoinTable getJoinTable(Class<?> clazz) {\n\t\treturn getAnnotationClass(clazz, JoinTable.class);\n\t}\n\t\n\t/**\n\t * 从db字段名拿字段对象\n\t * @param clazz DO类\n\t * @param dbFieldName 数据库字段名称,多个用逗号隔开\n\t * @return 如果不存在返回空数组,返回的Field的顺序和dbFieldName保持一致;只要有一个dbFieldName找不到,则返回空数组\n\t */\n\tpublic static List<Field> getFieldByDBField(Class<?> clazz, String dbFieldName) {\n\t\tList<String> dbFieldNameList = InnerCommonUtils.split(dbFieldName, \",\");\n\t\tList<Field> fields = getColumns(clazz);\n\t\tList<Field> result = new ArrayList<>();\n\n\t\tfor (String dbField : dbFieldNameList) {\n\t\t\tboolean isFound = false;\n\t\t\tfor(Field field : fields) {\n\t\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\t\tif(column.value().equals(dbField)) {\n\t\t\t\t\tresult.add(field);\n\t\t\t\t\tisFound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!isFound) {\n\t\t\t\tLOGGER.error(\"cannot found db field:{} in class:{}\", dbField, clazz.getName());\n\t\t\t\treturn new ArrayList<>();\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * 获得泛型的class\n\t */\n\tpublic static Class<?> getGenericFieldType(Field field) {\n ParameterizedType stringListType = (ParameterizedType) field.getGenericType();\n\t\treturn (Class<?>) stringListType.getActualTypeArguments()[0];\n\t}\n\t\n\t/**\n\t * 获得所有有@Column注解的列,包括继承的父类中的,顺序父类先\n\t *\n\t * @throws NoColumnAnnotationException 当没有一个@Column注解时抛出\n\t * @return 不会返回null\n\t */\n\tpublic static List<Field> getColumns(Class<?> clazz)\n\t\t\tthrows NoColumnAnnotationException {\n\t\tif(clazz == null) {\n\t\t\tthrow new NoColumnAnnotationException(\"class is null\");\n\t\t}\n\t\t\t\n\t\tList<Field> result = _getAnnotationColumns(clazz, Column.class);\n\t\tif (result.isEmpty()) {\n\t\t\tthrow new NoColumnAnnotationException(\"class \" + clazz.getName()\n\t\t\t\t\t+ \" does not have any @Column fields\");\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * 获得所有有@Column注解的列,包括继承的父类中的,顺序父类先。\n\t * 该方法只用于select读操作。\n\t * @param selectOnlyKey 是否只select主键\n\t * @throws NoColumnAnnotationException 当没有一个@Column注解时抛出\n\t * @return 不会返回null\n\t */\n\tpublic static List<Field> getColumnsForSelect(Class<?> clazz, boolean selectOnlyKey) {\n\t\tif(clazz == null) {\n\t\t\tthrow new NoColumnAnnotationException(\"class is null\");\n\t\t}\n\t\t\n\t\tList<Field> result = _getFieldsForSelect(clazz, selectOnlyKey);\n\t\tif (result.isEmpty()) {\n\t\t\tthrow new NoColumnAnnotationException(\"class \" + clazz.getName()\n\t\t\t\t\t+ \" does not have any @Column fields\");\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * 获得注解了@JoinLeftTable的字段,如果没有注解,抛出NoJoinTableMemberException\n\t */\n\tpublic static Field getJoinLeftTable(Class<?> clazz) {\n\t\treturn getJoinTableField(clazz, JoinLeftTable.class);\n\t}\n\t\n\t/**\n\t * 获得注解了@JoinRightTable的字段,如果没有注解,抛出NoJoinTableMemberException\n\t */\n\tpublic static Field getJoinRightTable(Class<?> clazz) {\n\t\treturn getJoinTableField(clazz, JoinRightTable.class);\n\t}\n\n\t/**\n\t * 用于获取@JoinLeftTable和@JoinRightTable注解的属性Field\n\t */\n\tprivate static Field getJoinTableField(Class<?> clazz,\n\t\t\t\t\t\t\t\t\t\t Class<? extends Annotation> annotationClass) {\n\t\tif (clazz == null) {\n\t\t\tthrow new NoJoinTableMemberException(\"clazz is null\");\n\t\t}\n\n\t\tList<Field> result = _getAnnotationColumns(clazz, annotationClass);\n\t\tif (result.isEmpty()) {\n\t\t\tthrow new NoJoinTableMemberException(\"class \" + clazz.getName()\n\t\t\t\t\t+ \" does not have @\" + annotationClass.getSimpleName() + \" field\");\n\t\t}\n\t\tif (result.size() > 1) {\n\t\t\tLOGGER.error(\"class {} has more than one @{} fields, use first one\",\n\t\t\t\t\tclazz.getName(), annotationClass.getSimpleName());\n\t\t}\n\n\t\treturn result.get(0);\n\t}\n\t\n\t/**\n\t * 获得字段里面的key字段\n\t * @throws NoKeyColumnAnnotationException 如果没有key Column,抛出该异常。\n\t */\n\tpublic static List<Field> getKeyColumns(Class<?> clazz) \n\t throws NoKeyColumnAnnotationException {\n\t\tList<Field> fields = getColumns(clazz);\n\t\tList<Field> keyFields = new ArrayList<>();\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(column.isKey()) {\n\t\t\t\tkeyFields.add(field);\n\t\t\t}\n\t\t}\n\t\tif(keyFields.isEmpty()) {\n\t\t\tthrow new NoKeyColumnAnnotationException();\n\t\t}\n\t\treturn keyFields;\n\t}\n\n\t/**\n\t * 获得一个DO类注解的casVersion字段\n\t * @return 当没有column字段时返回null\n\t * @throws CasVersionNotMatchException 当有2个及2个以上的casVersion字段时抛出该异常\n\t */\n\tpublic static Field getCasVersionColumn(Class<?> clazz) throws CasVersionNotMatchException {\n\t\tList<Field> fields = getColumns(clazz);\n\t\tField casVersionField = null;\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(column.casVersion()) {\n\t\t\t\tif(casVersionField != null) {\n\t\t\t\t\tthrow new CasVersionNotMatchException(\"there are more than one casVersion column in a DO class\");\n\t\t\t\t}\n\t\t\t\tcasVersionField = field;\n\t\t\t}\n\t\t}\n\t\treturn casVersionField;\n\t}\n\t\n\tpublic static Field getOneKeyColumn(Class<?> clazz) throws NotOnlyOneKeyColumnException {\n\t\tList<Field> keyFields = DOInfoReader.getKeyColumns(clazz);\n\n\t\tif (keyFields.size() != 1) {\n\t\t\tthrow new NotOnlyOneKeyColumnException(\n\t\t\t\t\t\"must have only one key column, actually has \"\n\t\t\t\t\t\t\t+ keyFields.size() + \" key columns\");\n\t\t}\n\t\t\n\t\treturn keyFields.get(0);\n\t}\n\t\n\tpublic static Field getAutoIncrementField(Class<?> clazz) {\n\t\t\n\t\tList<Field> fields = getColumns(clazz);\n\t\t\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(column.isAutoIncrement()) {\n\t\t\t\treturn field;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * 获得软删除标记字段,最多只能返回1个。\n\t * @return 如果没有则返回null\n\t */\n\tpublic static Field getSoftDeleteColumn(Class<?> clazz) {\n\n\t\t// 处理turnoff软删除\n\t\tif (DBHelperContext.isTurnOffSoftDelete(clazz)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tList<Field> fields = getColumns(clazz);\n\t\t\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(column.softDelete().length == 2 && !column.softDelete()[0].trim().isEmpty()\n\t\t\t\t\t&& !column.softDelete()[1].trim().isEmpty()) {\n\t\t\t\treturn field;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * 获得字段里面的非key字段\n\t */\n\tpublic static List<Field> getNotKeyColumns(Class<?> clazz) {\n\t\tList<Field> fields = getColumns(clazz);\n\t\t\n\t\tList<Field> keyFields = new ArrayList<>();\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\tif(!column.isKey()) {\n\t\t\t\tkeyFields.add(field);\n\t\t\t}\n\t\t}\n\t\treturn keyFields;\n\t}\n\t\n\t/**\n\t * 获得所有有@RelatedColumn注解的列,包括继承的父类中的,顺序父类先\n\t *\n\t * @return 不会返回null\n\t */\n\tpublic static List<Field> getRelatedColumns(Class<?> clazz) {\n\t\tList<Class<?>> classLink = getClassAndParentClasses(clazz, true);\n\n\t\t// 父类优先\n\t\tList<Field> result = new ArrayList<>();\n\t\tfor (int i = classLink.size() - 1; i >= 0; i--) {\n\t\t\tField[] fields = classLink.get(i).getDeclaredFields();\n\t\t\tfor (Field field : fields) {\n\t\t\t\tif (field.getAnnotation(RelatedColumn.class) != null) {\n\t\t\t\t\tresult.add(field);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * 优先通过getter获得值,如果没有getter,则直接获取\n\t */\n\tpublic static Object getValue(Field field, Object object) {\n\t\tString fieldName = field.getName();\n\t\tString setMethodName = \"get\" + InnerCommonUtils.firstLetterUpperCase(fieldName);\n\t\tMethod method = null;\n\t\ttry {\n\t\t\tmethod = object.getClass().getMethod(setMethodName);\n\t\t} catch (Exception e) {\n\t\t\t// ignore\n\t\t}\n\t\t\n\t\tif(method != null) {\n\t\t\ttry {\n\t\t\t\tmethod.setAccessible(true);\n\t\t\t\treturn method.invoke(object);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"method invoke\", e);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfield.setAccessible(true);\n\t\ttry {\n\t\t\treturn field.get(object);\n\t\t} catch (Exception e) {\n\t\t\tLOGGER.error(\"method invoke\", e);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * 为relatedColumn获得字段的值。这里有特别的逻辑。\n\t * 当fields只有一个时,返回的是对象本身;否则是一个List,里面是按顺序的fields的多个值\n\t * @return 当fields为空,返回null\n\t */\n\tpublic static Object getValueForRelatedColumn(List<Field> fields, Object object) {\n\t\tif (fields == null || fields.isEmpty()) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (fields.size() == 1) {\n\t\t\treturn getValue(fields.get(0), object);\n\t\t}\n\t\tList<Object> result = new ArrayList<>();\n\t\tfor (Field field : fields) {\n\t\t\tresult.add(getValue(field, object));\n\t\t}\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * 先按照setter的约定寻找setter方法(必须严格匹配参数类型或自动转换)<br>\n\t * 如果有则按setter方法,如果没有则直接写入\n\t */\n\tpublic static boolean setValue(Field field, Object object, Object value) {\n\t\tvalue = TypeAutoCast.cast(value, field.getType());\n\t\tMethod method = ClassInfoCache.getFieldMethod(field);\n\t\t\n\t\tif(method != null) {\n\t\t\ttry {\n\t\t\t\tmethod.invoke(object, value);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"method invoke\", e);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tfield.setAccessible(true);\n\t\t\ttry {\n\t\t\t\tfield.set(object, value);\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOGGER.error(\"method invoke\", e);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tprivate static List<Field> _getFieldsForSelect(Class<?> clazz, boolean selectOnlyKey) {\n\t\tList<Class<?>> classLink = getClassAndParentClasses(clazz, true);\n\t\t\n\t\tList<Field> fields = _getFields(classLink, Column.class);\n\t\tif(selectOnlyKey) {\n\t\t\treturn InnerCommonUtils.filter(fields,\n\t\t\t\t\to -> o.getAnnotation(Column.class).isKey());\n\t\t} else {\n\t\t\treturn fields;\n\t\t}\n\t}\n\n\t/**\n\t * 获得clazz类的有annotationClazz注解的字段field(包括clazz类及其父类,父类优先,不处理重名)。\n\t */\n\tprivate static List<Field> _getAnnotationColumns(Class<?> clazz,\n\t\t\t\t\t\t\t\t\t\t\t\t\t Class<? extends Annotation> annotationClazz) {\n\n\t\tList<Class<?>> classLink = getClassAndParentClasses(clazz, false);\n\n\t\treturn _getFields(classLink, annotationClazz);\n\t}\n\n\t/**\n\t * 获得指定类及其父类的列表,子类在前,父类在后\n\t * @param clazz 要查询的类\n\t * @param enableExcludeInheritedColumn 是否受到@ExcludeInheritedColumn注解的约束\n\t */\n\tprivate static List<Class<?>> getClassAndParentClasses(Class<?> clazz, boolean enableExcludeInheritedColumn) {\n\t\tif (clazz == null) {\n\t\t\treturn new ArrayList<>();\n\t\t}\n\n\t\tList<Class<?>> classLink = new ArrayList<>();\n\t\tClass<?> curClass = clazz;\n\t\twhile (curClass != null) {\n\t\t\tclassLink.add(curClass);\n\n\t\t\tif (enableExcludeInheritedColumn) {\n\t\t\t\tExcludeInheritedColumn eic = curClass.getAnnotation(ExcludeInheritedColumn.class);\n\t\t\t\tif(eic != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurClass = curClass.getSuperclass();\n\t\t}\n\n\t\treturn classLink;\n\t}\n\n\t/**\n\t * 从指定类clazz再往其父类查找注解了annotationClass的类,如果已经找到了,就返回对应该注解,不再继续往上找\n\t * @return 找不到返回null\n\t */\n\tprivate static <T extends Annotation> T getAnnotationClass(Class<?> clazz,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t Class<T> annotationClass) {\n\t\tClass<?> curClass = clazz;\n\t\twhile (curClass != null) {\n\t\t\tT annotation = curClass.getAnnotation(annotationClass);\n\t\t\tif(annotation != null) {\n\t\t\t\treturn annotation;\n\t\t\t}\n\t\t\tcurClass = curClass.getSuperclass();\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * 获取classLink多个类中,注解了annotationClazz的Field字段。<br>\n\t * 目前annotationClazz的取值有@Column @JoinLeftTable @JoinRightTable <br>\n\t * 对于Column注解,如果子类和父类字段同名,那么子类将代替父类,父类的Field不会加进来;<br>\n\t * 如果子类出现相同的Field,那么也只拿第一个;一旦出现字段同名,那么进行error log,正常是不建议覆盖和同名操作的,风险很大 <br>\n\t */\n\tprivate static List<Field> _getFields(List<Class<?>> classLink,\n\t\t\tClass<? extends Annotation> annotationClazz) {\n\t\tList<Field> result = new ArrayList<>();\n\t\tif(classLink == null || classLink.isEmpty() || annotationClazz == null) {\n\t\t\treturn result;\n\t\t}\n\n\t\t// 按父类优先的顺序来\n\t\tList<List<Field>> fieldList = new ArrayList<>();\n\t\tfor (int i = classLink.size() - 1; i >= 0; i--) {\n\t\t\tField[] fields = classLink.get(i).getDeclaredFields();\n\t\t\tfieldList.add(InnerCommonUtils.filter(fields, o -> o.getAnnotation(annotationClazz) != null));\n\t\t}\n\n\t\t// @Column注解的字段,需要按value进行去重\n\t\tif (annotationClazz == Column.class) {\n\t\t\tSet<String> columnValues = new HashSet<>();\n\t\t\t// 从子类开始拿\n\t\t\tList<List<Field>> fieldListTmp = new ArrayList<>();\n\t\t\tfor (int i = fieldList.size() - 1; i >= 0; i--) {\n\t\t\t\tList<Field> fields = fieldList.get(i);\n\t\t\t\tList<Field> fieldsTmp = new ArrayList<>();\n\t\t\t\tfor (Field field : fields) {\n\t\t\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\t\t\tif (columnValues.contains(column.value())) {\n\t\t\t\t\t\tLOGGER.error(\"found duplicate field:{} in class(and its parents):{}, this field is ignored\",\n\t\t\t\t\t\t\t\tfield.getName(), classLink.get(0).getName());\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tcolumnValues.add(column.value());\n\n\t\t\t\t\tfieldsTmp.add(field);\n\t\t\t\t}\n\t\t\t\tfieldListTmp.add(0, fieldsTmp);\n\t\t\t}\n\n\t\t\tfor (List<Field> fields : fieldListTmp) {\n\t\t\t\tresult.addAll(fields);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (List<Field> fields : fieldList) {\n\t\t\t\tresult.addAll(fields);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n}", "public class PreHandleObject {\n\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(PreHandleObject.class);\n\n\t/**\n\t * 插入前预处理字段值\n\t */\n\tpublic static <T> void preHandleInsert(T t) {\n\t\tif(t == null) {\n\t\t\treturn;\n\t\t}\n\t\tList<Field> fields = DOInfoReader.getColumns(t.getClass());\n\t\tif(fields.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tfor(Field field : fields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\n\t\t\t// 这个地方不需要处理turnOff软删除,因为它只是写入时设置默认值\n\t\t\tif(column.softDelete().length == 2\n\t\t\t\t\t&& !column.softDelete()[0].trim().isEmpty()\n\t\t\t\t\t&& !column.softDelete()[1].trim().isEmpty()) {\n\t\t\t\tObject delete = DOInfoReader.getValue(field, t);\n\t\t\t\tif(delete == null) {\n\t\t\t\t\tDOInfoReader.setValue(field, t, column.softDelete()[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(column.setTimeWhenInsert() && Date.class.isAssignableFrom(field.getType())) {\n\t\t\t\tif(DOInfoReader.getValue(field, t) == null) {\n\t\t\t\t\tDOInfoReader.setValue(field, t, new Date());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!column.insertDefault().isEmpty()) {\n\t\t\t\tif(DOInfoReader.getValue(field, t) == null) {\n\t\t\t\t\tDOInfoReader.setValue(field, t, column.insertDefault());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(column.setRandomStringWhenInsert()) {\n\t\t\t\tif(DOInfoReader.getValue(field, t) == null) {\n\t\t\t\t\tDOInfoReader.setValue(field, t, \n\t\t\t\t\t\t\tUUID.randomUUID().toString().replace(\"-\", \"\").substring(0, 32));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(column.casVersion()) {\n\t\t\t\tif(DOInfoReader.getValue(field, t) == null) {\n\t\t\t\t\tDOInfoReader.setValue(field, t, 1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tString insertValueScript = column.insertValueScript().trim();\n\t\t\tif(!insertValueScript.isEmpty()) {\n\t\t\t ScriptUtils.setValueFromScript(t, field, column.ignoreScriptError(), insertValueScript);\n\t\t\t}\n\n\t\t\t// truncate string should be last\n\t\t\tif (column.maxStringLength() >= 0) {\n\t\t\t\tif (String.class.equals(field.getType())) {\n\t\t\t\t\tString value = (String) DOInfoReader.getValue(field, t);\n\t\t\t\t\tif (value != null && value.length() > column.maxStringLength()) {\n\t\t\t\t\t\tString newValue = value.substring(0, column.maxStringLength());\n\t\t\t\t\t\tDOInfoReader.setValue(field, t, newValue);\n\t\t\t\t\t\tLOGGER.warn(\"truncate class:{} field:{} value:{} to maxStringLength:{} newValue:{}\",\n\t\t\t\t\t\t\t\tt.getClass().getName(), field.getName(), value, column.maxStringLength(), newValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n public static <T> void preHandleDelete(T t) {\n if(t == null) {\n return;\n }\n\n List<Field> notKeyFields = DOInfoReader.getNotKeyColumns(t.getClass());\n\n for(Field field : notKeyFields) {\n Column column = field.getAnnotation(Column.class);\n\n String deleteValueScript = column.deleteValueScript().trim();\n if(!deleteValueScript.isEmpty()) {\n ScriptUtils.setValueFromScript(t, field, column.ignoreScriptError(), deleteValueScript);\n }\n }\n }\n\t\n\tpublic static <T> void preHandleUpdate(T t) {\n\t\tif(t == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tList<Field> notKeyFields = DOInfoReader.getNotKeyColumns(t.getClass());\n\t\t\n\t\tfor(Field field : notKeyFields) {\n\t\t\tColumn column = field.getAnnotation(Column.class);\n\t\t\t\n\t\t\tif(column.setTimeWhenUpdate() && Date.class.isAssignableFrom(field.getType())) {\n\t\t\t\tDOInfoReader.setValue(field, t, new Date());\n\t\t\t}\n\n\t\t\t// 这个地方不用处理turnOff软删除,因为它只是更新时自动设置软删除的值\n\t\t\tif(column.softDelete().length == 2\n\t\t\t\t\t&& !column.softDelete()[0].trim().isEmpty()\n\t\t\t\t\t&& !column.softDelete()[1].trim().isEmpty()) {\n\t\t\t\tObject delete = DOInfoReader.getValue(field, t);\n\t\t\t\tif(delete == null) {\n\t\t\t\t\tDOInfoReader.setValue(field, t, column.softDelete()[0]);\n\t\t\t\t}\n\t\t\t}\n\n String updateValueScript = column.updateValueScript().trim();\n if(!updateValueScript.isEmpty()) {\n ScriptUtils.setValueFromScript(t, field, column.ignoreScriptError(), updateValueScript);\n }\n\n // truncate string should be last\n\t\t\tif (column.maxStringLength() >= 0) {\n\t\t\t\tif (String.class.equals(field.getType())) {\n\t\t\t\t\tString value = (String) DOInfoReader.getValue(field, t);\n\t\t\t\t\tif (value != null && value.length() > column.maxStringLength()) {\n\t\t\t\t\t\tString newValue = value.substring(0, column.maxStringLength());\n\t\t\t\t\t\tDOInfoReader.setValue(field, t, newValue);\n\t\t\t\t\t\tLOGGER.warn(\"truncate class:{} field:{} value:{} to maxStringLength:{} newValue:{}\",\n\t\t\t\t\t\t\t\tt.getClass().getName(), field.getName(), value, column.maxStringLength(), newValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n}" ]
import com.pugwoo.dbhelper.DBHelperInterceptor; import com.pugwoo.dbhelper.annotation.Column; import com.pugwoo.dbhelper.exception.InvalidParameterException; import com.pugwoo.dbhelper.exception.MustProvideConstructorException; import com.pugwoo.dbhelper.exception.NotAllowQueryException; import com.pugwoo.dbhelper.exception.NullKeyValueException; import com.pugwoo.dbhelper.sql.SQLAssert; import com.pugwoo.dbhelper.sql.SQLUtils; import com.pugwoo.dbhelper.utils.DOInfoReader; import com.pugwoo.dbhelper.utils.PreHandleObject; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.List;
package com.pugwoo.dbhelper.impl.part; public abstract class P5_DeleteOp extends P4_InsertOrUpdateOp { /////// 拦截器 protected void doInterceptBeforeDelete(List<Object> tList) { for (DBHelperInterceptor interceptor : interceptors) { boolean isContinue = interceptor.beforeDelete(tList); if (!isContinue) {
throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
3
mgilangjanuar/GoSCELE
app/src/main/java/com/mgilangjanuar/dev/goscele/modules/forum/list/provider/ForumSearchProvider.java
[ "public abstract class BaseProvider extends AsyncTask<String, Integer, List<Elements>> {\n\n protected Map<String, String> cookies = new HashMap<>();\n\n public BaseProvider() {\n super();\n }\n\n @Override\n @Deprecated\n protected List<Elements> doInBackground(String... params) {\n List<Elements> results = new ArrayList<>();\n int idx = 0;\n try {\n Connection.Response response = Jsoup.connect(url())\n .data(data())\n .method(method())\n .cookies(cookies())\n .execute();\n cookies = response.cookies();\n for (String param : params) {\n if (!TextUtils.isEmpty(param)) {\n results.add(response.parse().select(param));\n }\n publishProgress((int) ((double) (++idx / params.length)) * 100);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return results;\n }\n\n @Override\n @Deprecated\n protected void onProgressUpdate(Integer... values) {\n super.onProgressUpdate(values);\n onProgressUpdate(values[0]);\n }\n\n public abstract void run();\n\n public abstract String url();\n\n public String[] data() {\n return new String[0];\n }\n\n public Connection.Method method() {\n return Connection.Method.GET;\n }\n\n public Map<String, String> cookies() {\n return cookies;\n }\n\n public void onProgressUpdate(Integer value) {\n }\n}", "@Table(name = \"cookie\")\npublic class CookieModel extends BaseModel {\n @Column(name = \"key\")\n public String key;\n\n @Column(name = \"value\")\n public String value;\n\n public static Map<String, String> getCookiesMap() {\n Map<String, String> result = new HashMap<>();\n List<CookieModel> list = new CookieModel().find().execute();\n for (CookieModel cookieModel : list) {\n result.put(cookieModel.key, cookieModel.value);\n }\n return result;\n }\n}", "public class ForumListRecyclerViewAdapter extends BaseRecyclerViewAdapter<ForumListRecyclerViewAdapter.ViewHolder> {\n\n private List<ForumModel> list;\n\n public ForumListRecyclerViewAdapter(List<ForumModel> list) {\n this.list = list;\n }\n\n @Override\n public int findLayout() {\n return R.layout.layout_forum_list;\n }\n\n @Override\n public List<?> findList() {\n return list;\n }\n\n @Override\n public void initialize(final ViewHolder holder, int position) {\n final ForumModel model = list.get(position);\n holder.title.setText(model.title);\n holder.author.setText(model.author);\n holder.lastUpdate.setText(\"Last update: \" + model.lastUpdate);\n holder.layout.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(v.getContext(), ForumDetailActivity.class).putExtra(Constant.URL, model.url);\n v.getContext().startActivity(intent);\n }\n });\n }\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n return new ViewHolder(createView(parent));\n }\n\n public static class ViewHolder extends BaseViewHolder {\n\n @BindView(R.id.title_forum)\n public TextView title;\n\n @BindView(R.id.author_forum)\n public TextView author;\n\n @BindView(R.id.last_update_forum)\n public TextView lastUpdate;\n\n @BindView(R.id.layout_forum)\n public LinearLayout layout;\n\n public ViewHolder(View itemView) {\n super(itemView);\n }\n }\n}", "public interface ForumListListener {\n\n void onRetrieve(ForumListRecyclerViewAdapter adapter);\n\n void onGetTitle(String title);\n\n void onError(String error);\n}", "@Table(name = \"forum\")\npublic class ForumModel extends BaseModel {\n\n @Column(name = \"listUrl\")\n public String listUrl;\n\n @Column(name = \"forumTitle\")\n public String forumTitle;\n\n @Column(name = \"url\")\n public String url;\n\n @Column(name = \"title\")\n public String title;\n\n @Column(name = \"author\")\n public String author;\n\n @Column(name = \"repliesNumber\")\n public String repliesNumber;\n\n @Column(name = \"lastUpdate\")\n public String lastUpdate;\n\n}", "public class Constant {\n // URL and routes\n public static final String BASE_URL = \"https://scele.cs.ui.ac.id/\";\n public static final String BASE_URL_SIAK = \"https://academic.ui.ac.id/main/\";\n\n public static final String ROUTE_LOGIN = \"login/index.php\";\n public static final String ROUTE_LOGIN_SIAK = \"Authentication/Index\";\n public static final String ROUTE_CHANGE_ROLE = \"main/Authentication/ChangeRole\";\n\n // Misc\n public static final String URL = \"url\";\n public static final String USER_AGENT = \"User-Agent\";\n public static final String COOKIE = \"cookie\";\n public static final int ASK_STORAGE_PERMISSION_CODE = 123;\n public static final CharSequence LABEL = \"label\";\n public static final String WIDGET_ACTION_DATA_CHANGE = \"CHECK_LIST\";\n public static final String COURSE_NAME = \"course name\";\n}" ]
import com.mgilangjanuar.dev.goscele.base.BaseProvider; import com.mgilangjanuar.dev.goscele.modules.common.model.CookieModel; import com.mgilangjanuar.dev.goscele.modules.forum.list.adapter.ForumListRecyclerViewAdapter; import com.mgilangjanuar.dev.goscele.modules.forum.list.listener.ForumListListener; import com.mgilangjanuar.dev.goscele.modules.forum.list.model.ForumModel; import com.mgilangjanuar.dev.goscele.utils.Constant; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map;
package com.mgilangjanuar.dev.goscele.modules.forum.list.provider; /** * Created by mgilangjanuar ([email protected]) * * @since 2017 */ public class ForumSearchProvider extends BaseProvider { private ForumListListener listener; private String query; public ForumSearchProvider(ForumListListener listener, String query) { this.listener = listener; this.query = query; } @Override public Map<String, String> cookies() { return CookieModel.getCookiesMap(); } @Override public void run() { execute("#region-main"); } @Override public String url() { try {
return Constant.BASE_URL + "mod/forum/search.php?id=1&perpage=50&search=" + URLEncoder.encode(query, "UTF-8");
5
lijunyandev/MeetMusic
app/src/main/java/com/lijunyan/blackmusic/adapter/PlaylistAdapter.java
[ "public class DBManager {\n\n private static final String TAG = DBManager.class.getName();\n private DatabaseHelper helper;\n private SQLiteDatabase db;\n private static DBManager instance = null;\n\n\n /* 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,mFactory);\n * 需要一个context参数 ,所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里\n */\n public DBManager(Context context) {\n helper = new DatabaseHelper(context);\n db = helper.getWritableDatabase();\n }\n\n public static synchronized DBManager getInstance(Context context) {\n if (instance == null) {\n instance = new DBManager(context);\n }\n return instance;\n }\n\n // 获取音乐表歌曲数量\n public int getMusicCount(int table) {\n int musicCount = 0;\n Cursor cursor = null;\n switch (table) {\n case Constant.LIST_ALLMUSIC:\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, null, null, null, null, null);\n break;\n case Constant.LIST_LASTPLAY:\n cursor = db.query(DatabaseHelper.LAST_PLAY_TABLE, null, null, null, null, null, null);\n break;\n case Constant.LIST_MYLOVE:\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, DatabaseHelper.LOVE_COLUMN + \" = ? \", new String[]{\"\" + 1}, null, null, null);\n break;\n case Constant.LIST_MYPLAY:\n cursor = db.query(DatabaseHelper.PLAY_LIST_TABLE, null, null, null, null, null, null);\n break;\n }\n if (cursor.moveToFirst()) {\n musicCount = cursor.getCount();\n }\n if (cursor != null) {\n cursor.close();\n }\n return musicCount;\n }\n\n public List<MusicInfo> getAllMusicFromMusicTable() {\n Log.d(TAG, \"getAllMusicFromMusicTable: \");\n List<MusicInfo> musicInfoList = new ArrayList<>();\n Cursor cursor = null;\n db.beginTransaction();\n try {\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, null, null, null, null, null);\n musicInfoList = cursorToMusicList(cursor);\n db.setTransactionSuccessful();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n db.endTransaction();\n if (cursor!=null){\n cursor.close();\n }\n }\n return musicInfoList;\n }\n\n public MusicInfo getSingleMusicFromMusicTable(int id) {\n Log.i(TAG, \"getSingleMusicFromMusicTable: \");\n List<MusicInfo> musicInfoList = null;\n MusicInfo musicInfo = null;\n Cursor cursor = null;\n db.beginTransaction();\n try {\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, ID_COLUMN + \" = ?\", new String[]{\"\" + id}, null, null, null);\n musicInfoList = cursorToMusicList(cursor);\n musicInfo = musicInfoList.get(0);\n db.setTransactionSuccessful();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n db.endTransaction();\n if (cursor!=null){\n cursor.close();\n }\n }\n return musicInfo;\n }\n\n\n public List<MusicInfo> getAllMusicFromTable(int playList) {\n Log.d(TAG, \"getAllMusicFromTable: \");\n List<Integer> idList = getMusicList(playList);\n List<MusicInfo> musicList = new ArrayList<>();\n for (int id : idList) {\n musicList.add(getSingleMusicFromMusicTable(id));\n }\n return musicList;\n }\n\n public List<PlayListInfo> getMyPlayList() {\n List<PlayListInfo> playListInfos = new ArrayList<>();\n Cursor cursor = db.query(DatabaseHelper.PLAY_LIST_TABLE, null, null, null, null, null, null);\n Cursor cursorCount = null;\n while (cursor.moveToNext()) {\n PlayListInfo playListInfo = new PlayListInfo();\n int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ID_COLUMN)));\n playListInfo.setId(id);\n playListInfo.setName(cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME_COLUMN)));\n cursorCount = db.query(DatabaseHelper.PLAY_LISY_MUSIC_TABLE,null, ID_COLUMN + \" = ?\", new String[]{\"\" + id}, null,null,null);\n playListInfo.setCount(cursorCount.getCount());\n playListInfos.add(playListInfo);\n }\n if (cursor!=null){\n cursor.close();\n }\n if (cursorCount!=null){\n cursorCount.close();\n }\n return playListInfos;\n }\n\n\n public void createPlaylist(String name) {\n ContentValues values = new ContentValues();\n values.put(DatabaseHelper.NAME_COLUMN, name);\n db.insert(DatabaseHelper.PLAY_LIST_TABLE, null, values);\n }\n\n public List<MusicInfo> getMusicListBySinger(String singer){\n List<MusicInfo> musicInfoList = new ArrayList<>();\n Cursor cursor = null;\n db.beginTransaction();\n try{\n String sql = \"select * from \"+DatabaseHelper.MUSIC_TABLE+\" where \"+ DatabaseHelper.SINGER_COLUMN+\" = ? \";\n cursor = db.rawQuery(sql,new String[]{singer});\n musicInfoList = cursorToMusicList(cursor);\n db.setTransactionSuccessful();\n }catch (Exception e){\n e.printStackTrace();\n }finally {\n db.endTransaction();\n if (cursor !=null)\n cursor.close();\n }\n return musicInfoList;\n }\n\n public List<MusicInfo> getMusicListByAlbum(String album){\n List<MusicInfo> musicInfoList = new ArrayList<>();\n Cursor cursor = null;\n db.beginTransaction();\n try{\n String sql = \"select * from \"+DatabaseHelper.MUSIC_TABLE+\" where \"+ DatabaseHelper.ALBUM_COLUMN+\" = ? \";\n cursor = db.rawQuery(sql,new String[]{album});\n musicInfoList = cursorToMusicList(cursor);\n db.setTransactionSuccessful();\n }catch (Exception e){\n e.printStackTrace();\n }finally {\n db.endTransaction();\n if (cursor !=null)\n cursor.close();\n }\n return musicInfoList;\n }\n\n public List<MusicInfo> getMusicListByFolder(String folder){\n List<MusicInfo> musicInfoList = new ArrayList<>();\n Cursor cursor = null;\n db.beginTransaction();\n try{\n String sql = \"select * from \"+DatabaseHelper.MUSIC_TABLE+\" where \"+ DatabaseHelper.PARENT_PATH_COLUMN+\" = ? \";\n cursor = db.rawQuery(sql,new String[]{folder});\n musicInfoList = cursorToMusicList(cursor);\n db.setTransactionSuccessful();\n }catch (Exception e){\n e.printStackTrace();\n }finally {\n db.endTransaction();\n if (cursor !=null)\n cursor.close();\n }\n return musicInfoList;\n }\n\n public ArrayList<Integer> getMusicIdListByPlaylist(int playlistId){\n Cursor cursor = null;\n db.beginTransaction();\n ArrayList<Integer> list = new ArrayList<Integer>();\n try{\n String sql = \"select * from \"+DatabaseHelper.PLAY_LISY_MUSIC_TABLE+\" where \"+ ID_COLUMN+\" = ? \";\n cursor = db.rawQuery(sql,new String[]{\"\"+playlistId});\n while (cursor.moveToNext()) {\n int musicId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.MUSIC_ID_COLUMN));\n list.add(musicId);\n }\n db.setTransactionSuccessful();\n }catch (Exception e){\n e.printStackTrace();\n }finally {\n db.endTransaction();\n if (cursor !=null)\n cursor.close();\n }\n return list;\n }\n\n public List<MusicInfo> getMusicListByPlaylist(int playlistId){\n List<MusicInfo> musicInfoList = new ArrayList<>();\n Cursor cursor = null;\n int id;\n db.beginTransaction();\n try{\n String sql = \"select * from \"+DatabaseHelper.PLAY_LISY_MUSIC_TABLE+\" where \"+ ID_COLUMN+\" = ? ORDER BY \"+ DatabaseHelper.ID_COLUMN;\n cursor = db.rawQuery(sql,new String[]{\"\"+playlistId});\n while (cursor.moveToNext()){\n MusicInfo musicInfo = new MusicInfo();\n id = cursor.getInt(cursor.getColumnIndex(MUSIC_ID_COLUMN));\n musicInfo = getSingleMusicFromMusicTable(id);\n musicInfoList.add(musicInfo);\n }\n db.setTransactionSuccessful();\n }catch (Exception e){\n e.printStackTrace();\n }finally {\n db.endTransaction();\n if (cursor !=null)\n cursor.close();\n }\n return musicInfoList;\n }\n\n\n\n\n\n public void insertMusicListToMusicTable(List<MusicInfo> musicInfoList) {\n Log.d(TAG, \"insertMusicListToMusicTable: \");\n for (MusicInfo musicInfo : musicInfoList) {\n insertMusicInfoToMusicTable(musicInfo);\n }\n }\n\n\n //添加歌曲到音乐表\n public void insertMusicInfoToMusicTable(MusicInfo musicInfo) {\n ContentValues values;\n Cursor cursor = null;\n int id = 1;\n try {\n values = musicInfoToContentValues(musicInfo);\n String sql = \"select max(id) from \" + DatabaseHelper.MUSIC_TABLE + \";\";\n cursor = db.rawQuery(sql, null);\n if (cursor.moveToFirst()) {\n //设置新添加的ID为最大ID+1\n id = cursor.getInt(0) + 1;\n }\n values.put(ID_COLUMN, id);\n//\t\t\tvalues.put(\"mylove\",0);\n db.insert(DatabaseHelper.MUSIC_TABLE, null, values);\n } catch (Exception e) {\n e.printStackTrace();\n if (cursor!=null){\n cursor.close();\n }\n }\n }\n\n //添加音乐到歌单\n public void addToPlaylist(int playlistId,int musicId){\n ContentValues values = new ContentValues();\n values.put(DatabaseHelper.ID_COLUMN,playlistId);\n values.put(DatabaseHelper.MUSIC_ID_COLUMN,musicId);\n db.insert(DatabaseHelper.PLAY_LISY_MUSIC_TABLE,null,values);\n }\n\n //检索音乐是否已经存在歌单中\n public boolean isExistPlaylist(int playlistId,int musicId){\n boolean result = false;\n Cursor cursor = db.query(DatabaseHelper.PLAY_LISY_MUSIC_TABLE,null,ID_COLUMN + \" = ? and \"+ MUSIC_ID_COLUMN + \" = ? \",\n new String[]{\"\"+playlistId,\"\"+musicId},null,null,null);\n if (cursor.moveToFirst()){\n result= true;\n }\n if (cursor!=null){\n cursor.close();\n }\n return result;\n }\n\n public void updateAllMusic(List<MusicInfo> musicInfoList) {\n db.beginTransaction();\n try {\n deleteAllTable();\n insertMusicListToMusicTable(musicInfoList);\n db.setTransactionSuccessful();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n db.endTransaction();\n }\n }\n\n\n //删除数据库中所有的表\n public void deleteAllTable() {\n db.execSQL(\"PRAGMA foreign_keys=ON\");\n db.delete(DatabaseHelper.MUSIC_TABLE, null, null);\n db.delete(DatabaseHelper.LAST_PLAY_TABLE, null, null);\n db.delete(DatabaseHelper.PLAY_LIST_TABLE, null, null);\n db.delete(DatabaseHelper.PLAY_LISY_MUSIC_TABLE, null, null);\n }\n\n //删除指定音乐\n public void deleteMusic(int id) {\n db.execSQL(\"PRAGMA foreign_keys=ON\");\n db.delete(DatabaseHelper.MUSIC_TABLE, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n db.delete(DatabaseHelper.LAST_PLAY_TABLE, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n }\n\n public void deletePlaylist(int id) {\n db.delete(DatabaseHelper.PLAY_LIST_TABLE, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n }\n\n //根据从哪个activity中发出的移除歌曲指令判断\n public void removeMusic(int id, int witchActivity) {\n db.execSQL(\"PRAGMA foreign_keys=ON\");\n switch (witchActivity) {\n case Constant.ACTIVITY_LOCAL:\n db.delete(DatabaseHelper.MUSIC_TABLE, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n break;\n case Constant.ACTIVITY_RECENTPLAY:\n db.delete(DatabaseHelper.LAST_PLAY_TABLE, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n break;\n case Constant.ACTIVITY_MYLOVE:\n ContentValues values = new ContentValues();\n values.put(DatabaseHelper.LOVE_COLUMN, 0);\n db.update(DatabaseHelper.MUSIC_TABLE, null, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n break;\n }\n }\n\n //根据从哪个activity中发出的移除歌曲指令判断\n public int removeMusicFromPlaylist(int musicId, int playlistId) {\n db.execSQL(\"PRAGMA foreign_keys=ON\");\n int ret = 0;\n try {\n ret = db.delete(DatabaseHelper.PLAY_LISY_MUSIC_TABLE, ID_COLUMN + \" = ? and \" + DatabaseHelper.MUSIC_ID_COLUMN\n + \" = ? \", new String[]{\"\" + playlistId, musicId + \"\"});\n }catch (Exception e){\n e.printStackTrace();\n }\n return ret;\n }\n\n // 获取歌曲路径\n public String getMusicPath(int id) {\n Log.d(TAG, \"getMusicPath id = \" + id);\n if (id == -1) {\n return null;\n }\n String path = null;\n Cursor cursor = null;\n setLastPlay(id); //每次播放一首新歌前都需要获取歌曲路径,所以可以在此设置最近播放\n try {\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, ID_COLUMN + \" = ?\", new String[]{\"\" + id}, null, null, null);\n Log.i(TAG, \"getCount: \" + cursor.getCount());\n if (cursor.moveToFirst()) {\n path = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PATH_COLUMN));\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n return path;\n }\n\n //获取音乐表中的第一首音乐的ID\n public int getFirstId(int listNumber) {\n Cursor cursor = null;\n int id = -1;\n try {\n switch (listNumber) {\n case Constant.LIST_ALLMUSIC:\n cursor = db.rawQuery(\"select min(id) from \" + DatabaseHelper.MUSIC_TABLE, null);\n break;\n default:\n Log.i(TAG, \"getFirstId: default\");\n break;\n }\n if (cursor.moveToFirst()) {\n id = cursor.getInt(0);\n Log.d(TAG, \"getFirstId min id = \" + id);\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n return id;\n }\n\n\n // 获取下一首歌曲(id)\n public int getNextMusic(ArrayList<Integer> musicList, int id, int playMode) {\n if (id == -1) {\n return -1;\n }\n //找到当前id在列表的第几个位置(i+1)\n int index = musicList.indexOf(id);\n if (index == -1) {\n return -1;\n }\n // 如果当前是最后一首\n switch (playMode) {\n case Constant.PLAYMODE_SEQUENCE:\n if ((index + 1) == musicList.size()) {\n id = musicList.get(0);\n } else {\n ++index;\n id = musicList.get(index);\n }\n break;\n case Constant.PLAYMODE_SINGLE_REPEAT:\n break;\n case Constant.PLAYMODE_RANDOM:\n id = getRandomMusic(musicList, id);\n break;\n }\n return id;\n }\n\n // 获取上一首歌曲(id)\n public int getPreMusic(ArrayList<Integer> musicList, int id, int playMode) {\n if (id == -1) {\n return -1;\n }\n //找到当前id在列表的第几个位置(i+1)\n int index = musicList.indexOf(id);\n if (index == -1) {\n return -1;\n }\n // 如果当前是第一首则返回最后一首\n switch (playMode) {\n case Constant.PLAYMODE_SEQUENCE:\n if (index == 0) {\n id = musicList.get(musicList.size() - 1);\n } else {\n --index;\n id = musicList.get(index);\n }\n break;\n case Constant.PLAYMODE_SINGLE_REPEAT:\n break;\n case Constant.PLAYMODE_RANDOM:\n id = getRandomMusic(musicList, id);\n break;\n }\n return id;\n }\n\n // 获取歌单列表\n public ArrayList<Integer> getMusicList(int playList) {\n Cursor cursor = null;\n ArrayList<Integer> list = new ArrayList<Integer>();\n int musicId;\n switch (playList) {\n case Constant.LIST_ALLMUSIC:\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, null, null, null, null, null);\n break;\n case Constant.LIST_LASTPLAY:\n cursor = db.rawQuery(\"select * from \"+DatabaseHelper.LAST_PLAY_TABLE+\" ORDER BY \"+ DatabaseHelper.ID_COLUMN,null);\n break;\n case Constant.LIST_MYLOVE:\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, DatabaseHelper.LOVE_COLUMN + \" = ?\", new String[]{\"\" + 1}, null, null, null);\n break;\n case Constant.LIST_PLAYLIST:\n int listId = MyMusicUtil.getIntShared(Constant.KEY_LIST_ID);\n list = getMusicIdListByPlaylist(listId);\n break;\n default:\n Log.e(TAG, \"getMusicList default\");\n break;\n }\n if (cursor != null) {\n while (cursor.moveToNext()) {\n musicId = cursor.getInt(cursor.getColumnIndex(\"id\"));\n list.add(musicId);\n }\n }\n if (cursor != null) {\n cursor.close();\n }\n return list;\n }\n\n // 获取歌曲详细信息\n public ArrayList<String> getMusicInfo(int id) {\n if (id == -1) {\n return null;\n }\n Cursor cursor = null;\n ArrayList<String> musicInfo = new ArrayList<String>();\n cursor = db.query(DatabaseHelper.MUSIC_TABLE, null, ID_COLUMN + \" = ?\", new String[]{\"\" + id}, null, null, null);\n if (cursor.moveToFirst()) {\n for (int i = 0; i < cursor.getColumnCount(); i++) {\n musicInfo.add(i, cursor.getString(i));\n }\n } else {\n musicInfo.add(\"0\");\n musicInfo.add(\"听听音乐\");\n musicInfo.add(\"好音质\");\n musicInfo.add(\"0\");\n musicInfo.add(\"0\");\n musicInfo.add(\"0\");\n musicInfo.add(\"0\");\n musicInfo.add(\"0\");\n }\n if (cursor != null) {\n cursor.close();\n }\n return musicInfo;\n }\n\n //获取随机歌曲\n public int getRandomMusic(ArrayList<Integer> list, int id) {\n int musicId;\n if (id == -1) {\n return -1;\n }\n if (list.isEmpty()) {\n return -1;\n }\n if (list.size() == 1) {\n return id;\n }\n do {\n int count = (int) (Math.random() * list.size());\n musicId = list.get(count);\n } while (musicId == id);\n\n return musicId;\n\n }\n\n //保留最近的20首\n public void setLastPlay(int id) {\n Log.i(TAG, \"setLastPlay: id = \" + id);\n if (id == -1 || id == 0) {\n return;\n }\n ContentValues values = new ContentValues();\n ArrayList<Integer> lastList = new ArrayList<Integer>();\n Cursor cursor = null;\n lastList.add(id);\n db.beginTransaction();\n try {\n cursor = db.rawQuery(\"select id from \" + DatabaseHelper.LAST_PLAY_TABLE, null);\n while (cursor.moveToNext()) {\n if (cursor.getInt(0) != id) {\n lastList.add(cursor.getInt(0));\n }\n }\n db.delete(DatabaseHelper.LAST_PLAY_TABLE, null, null);\n if (lastList.size() < 20) {\n for (int i = 0; i < lastList.size(); i++) {\n values.put(ID_COLUMN, lastList.get(i));\n db.insert(DatabaseHelper.LAST_PLAY_TABLE, null, values);\n }\n } else {\n for (int i = 0; i < 20; i++) {\n values.put(ID_COLUMN, lastList.get(i));\n db.insert(DatabaseHelper.LAST_PLAY_TABLE, null, values);\n }\n }\n db.setTransactionSuccessful();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n db.endTransaction();\n if (cursor != null) {\n cursor.close();\n }\n }\n }\n\n public void setMyLove(int id) {\n ContentValues values = new ContentValues();\n values.put(DatabaseHelper.LOVE_COLUMN, 1);\n db.update(DatabaseHelper.MUSIC_TABLE, values, ID_COLUMN + \" = ? \", new String[]{\"\" + id});\n }\n\n //把MusicInfo对象转为ContentValues对象\n public ContentValues musicInfoToContentValues(MusicInfo musicInfo) {\n ContentValues values = new ContentValues();\n try {\n// values.put(DatabaseHelper.ID_COLUMN, musicInfo.getId());\n values.put(DatabaseHelper.NAME_COLUMN, musicInfo.getName());\n values.put(DatabaseHelper.SINGER_COLUMN, musicInfo.getSinger());\n values.put(DatabaseHelper.ALBUM_COLUMN, musicInfo.getAlbum());\n values.put(DatabaseHelper.DURATION_COLUMN, musicInfo.getDuration());\n values.put(DatabaseHelper.PATH_COLUMN, musicInfo.getPath());\n values.put(DatabaseHelper.PARENT_PATH_COLUMN, musicInfo.getParentPath());\n values.put(DatabaseHelper.LOVE_COLUMN, musicInfo.getLove());\n values.put(DatabaseHelper.FIRST_LETTER_COLUMN, \"\" + ChineseToEnglish.StringToPinyinSpecial(musicInfo.getName()).toUpperCase().charAt(0));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return values;\n }\n\n //把Cursor对象转为List<MusicInfo>对象\n public List<MusicInfo> cursorToMusicList(Cursor cursor) {\n List<MusicInfo> list = null;\n try {\n if (cursor != null) {\n list = new ArrayList<>();\n while (cursor.moveToNext()) {\n int id = cursor.getInt(cursor.getColumnIndex(ID_COLUMN));\n String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME_COLUMN));\n String singer = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SINGER_COLUMN));\n String album = cursor.getString(cursor.getColumnIndex(DatabaseHelper.ALBUM_COLUMN));\n String duration = cursor.getString(cursor.getColumnIndex(DatabaseHelper.DURATION_COLUMN));\n String path = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PATH_COLUMN));\n String parentPath = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PARENT_PATH_COLUMN));\n int love = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.LOVE_COLUMN));\n String firstLetter = cursor.getString(cursor.getColumnIndex(DatabaseHelper.FIRST_LETTER_COLUMN));\n\n MusicInfo musicInfo = new MusicInfo();\n musicInfo.setId(id);\n musicInfo.setName(name);\n musicInfo.setSinger(singer);\n musicInfo.setAlbum(album);\n musicInfo.setPath(path);\n musicInfo.setParentPath(parentPath);\n musicInfo.setLove(love);\n musicInfo.setDuration(duration);\n musicInfo.setFirstLetter(firstLetter);\n list.add(musicInfo);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return list;\n }\n\n\n}", "public class MusicInfo implements Comparable, Parcelable {\n\n private int id;\n private String name;\n private String singer;\n private String album;\n private String duration;\n private String path;\n private String parentPath; //父目录路径\n private int love; //1设置我喜欢 0未设置\n private String firstLetter;\n\n\n public String getAlbum() {\n return album;\n }\n\n public void setAlbum(String album) {\n this.album = album;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getSinger() {\n return singer;\n }\n\n public void setSinger(String singer) {\n this.singer = singer;\n }\n\n public String getFirstLetter() {\n return firstLetter;\n }\n\n public void setFirstLetter(String firstLetter) {\n this.firstLetter = firstLetter;\n }\n\n public int getLove() {\n return love;\n }\n\n public void setLove(int love) {\n this.love = love;\n }\n\n public String getDuration() {\n return duration;\n }\n\n public void setDuration(String duration) {\n this.duration = duration;\n }\n\n public String getParentPath() {\n return parentPath;\n }\n\n public void setParentPath(String parentPath) {\n this.parentPath = parentPath;\n }\n\n @Override\n public int compareTo(Object o) {\n MusicInfo info = (MusicInfo)o;\n if (info.getFirstLetter().equals(\"#\"))\n return -1;\n if (firstLetter.equals(\"#\"))\n return 1;\n return firstLetter.compareTo(info.getFirstLetter());\n }\n\n @Override\n public String toString() {\n return \"MusicInfo{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", singer='\" + singer + '\\'' +\n \", album='\" + album + '\\'' +\n \", duration='\" + duration + '\\'' +\n \", path='\" + path + '\\'' +\n \", parentPath='\" + parentPath + '\\'' +\n \", love=\" + love +\n \", firstLetter='\" + firstLetter + '\\'' +\n '}';\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(this.id);\n dest.writeString(this.name);\n dest.writeString(this.singer);\n dest.writeString(this.album);\n dest.writeString(this.duration);\n dest.writeString(this.path);\n dest.writeString(this.parentPath);\n dest.writeInt(this.love);\n dest.writeString(this.firstLetter);\n }\n\n public MusicInfo() {\n }\n\n protected MusicInfo(Parcel in) {\n this.id = in.readInt();\n this.name = in.readString();\n this.singer = in.readString();\n this.album = in.readString();\n this.duration = in.readString();\n this.path = in.readString();\n this.parentPath = in.readString();\n this.love = in.readInt();\n this.firstLetter = in.readString();\n }\n\n public static final Parcelable.Creator<MusicInfo> CREATOR = new Parcelable.Creator<MusicInfo>() {\n @Override\n public MusicInfo createFromParcel(Parcel source) {\n return new MusicInfo(source);\n }\n\n @Override\n public MusicInfo[] newArray(int size) {\n return new MusicInfo[size];\n }\n };\n}", "public class PlayListInfo implements Parcelable {\n private int id;\n private String name;\n private int count;\n\n public PlayListInfo() {\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getCount() {\n return count;\n }\n\n public void setCount(int count) {\n this.count = count;\n }\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n \n public static final Creator<PlayListInfo> CREATOR = new Creator<PlayListInfo>() {\n @Override\n public PlayListInfo createFromParcel(Parcel source) {\n return new PlayListInfo(source);\n }\n\n @Override\n public PlayListInfo[] newArray(int size) {\n return new PlayListInfo[size];\n }\n };\n\n\n protected PlayListInfo(Parcel in) {\n this.id = in.readInt();\n this.count = in.readInt();\n this.name = in.readString();\n }\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(this.id);\n dest.writeInt(this.count);\n dest.writeString(this.name);\n }\n}", "public class MusicPlayerService extends Service {\n private static final String TAG = MusicPlayerService.class.getName();\n\n public static final String PLAYER_MANAGER_ACTION = \"com.lijunyan.blackmusic.service.MusicPlayerService.player.action\";\n\n private PlayerManagerReceiver mReceiver;\n\n public MusicPlayerService() {\n }\n\n @Override\n public IBinder onBind(Intent intent) {\n throw new UnsupportedOperationException(\"Not yet implemented\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n Log.e(TAG, \"onCreate: \");\n register();\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n Log.e(TAG, \"onDestroy: \");\n unRegister();\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n Log.e(TAG, \"onStartCommand: \");\n return super.onStartCommand(intent, flags, startId);\n }\n\n\n private void register() {\n mReceiver = new PlayerManagerReceiver(MusicPlayerService.this);\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(PLAYER_MANAGER_ACTION);\n registerReceiver(mReceiver, intentFilter);\n }\n\n private void unRegister() {\n if (mReceiver != null) {\n unregisterReceiver(mReceiver);\n }\n }\n\n}", "public class Constant {\n\n\t//service名\n\tpublic static final String SERVICE_NAME = \"com.example.vinyl.service.MediaPlayerService\";//服务的名称为包名+类名\n\t//播放状态\n\tpublic static final String STATUS = \"status\";\n\n\tpublic static final int STATUS_STOP = 0; //停止状态\n\tpublic static final int STATUS_PLAY = 1; //播放状态\n\tpublic static final int STATUS_PAUSE = 2; //暂停状态\n\tpublic static final int STATUS_RUN = 3; // 状态\n\n\tpublic static final String COMMAND = \"cmd\";\n\n\tpublic static final int COMMAND_INIT = 1; //初始化命令\n\tpublic static final int COMMAND_PLAY = 2; //播放命令\n\tpublic static final int COMMAND_PAUSE = 3; //暂停命令\n\tpublic static final int COMMAND_STOP = 4; //停止命令\n\tpublic static final int COMMAND_PROGRESS = 5; //改变进度命令\n\tpublic static final int COMMAND_RELEASE = 6; //退出程序时释放\n\n\t//播放模式\n\tpublic static final int PLAYMODE_SEQUENCE = -1;\n\tpublic static final int PLAYMODE_SINGLE_REPEAT = 1;\n\tpublic static final int PLAYMODE_RANDOM = 2;\n\n\tpublic static final String PLAYMODE_SEQUENCE_TEXT = \"顺序播放\";\n\tpublic static final String PLAYMODE_RANDOM_TEXT = \"随机播放\";\n\tpublic static final String PLAYMODE_SINGLE_REPEAT_TEXT = \"单曲循环\";\n\n\n\t//Activity label\n\n\tpublic static final String LABEL = \"label\";\n\tpublic static final String LABEL_MYLOVE = \"我喜爱\";\n\tpublic static final String LABEL_LAST = \"最近播放\";\n\tpublic static final String LABEL_LOCAL = \"本地音乐\";\n\n\tpublic static final int ACTIVITY_LOCAL = 20; //我喜爱\n\tpublic static final int ACTIVITY_RECENTPLAY = 21;//最近播放\n\tpublic static final int ACTIVITY_MYLOVE = 22; //我喜爱\n\tpublic static final int ACTIVITY_MYLIST = 24;//我的歌单\n\n\t//fragment_title\n\tpublic static final String FRAGMENT_MYLOVE = \"我喜爱\";\n\tpublic static final String FRAGMENT_DOWNLOAD = \"下载管理\";\n\tpublic static final String FRAGMENT_MYLIST = \"我的歌单\";\n\tpublic static final String FRAGMENT_RECENTPLAY = \"最近播放\";\n\n\t//AlertDialog\n\tpublic static final String DIALOG_TITLE = \"创建歌单\";\n\tpublic static final String DIALOG_OK = \"确定\";\n\tpublic static final String DIALOG_CANCEL = \"取消\";\n\n\t//handle常量\n\tpublic static final int SCAN_ERROR = 0;\n\tpublic static final int SCAN_COMPLETE = 1;\n\tpublic static final int SCAN_UPDATE = 2;\n\tpublic static final int SCAN_NO_MUSIC = 3;\n//\tpublic static final int LOAD_COMPLETE = 4;\n//\tpublic static final int LOAD_PREPARE = 5;\n//\tpublic static final int LOAD_ERROR = 6;\n//\tpublic static final int DOWNLOAD_UPDATE = 14;\n\n\n\t//SharedPreferences key 常量\n\tpublic static final String KEY_ID = \"id\";\n\tpublic static final String KEY_PATH = \"path\";\n\tpublic static final String KEY_MODE = \"mode\";\n\tpublic static final String KEY_LIST = \"list\";\n\tpublic static final String KEY_LIST_ID = \"list_id\";\n\tpublic static final String KEY_CURRENT = \"current\";\n\tpublic static final String KEY_DURATION = \"duration\";\n\n\t//SharedPreferences value 常量 匹配 KEY_LIST\n\tpublic static final int LIST_SINGLE = 101;\t//单曲列表\n//\tpublic static final int LIST_SINGLE = 101;\t//歌手列表\n//\tpublic static final int LIST_SINGLE = 101;\t//专辑列表\n//\tpublic static final int LIST_SINGLE = 101;\t//最近播放列表\n//\tpublic static final int LIST_SINGLE = 101;\t//我喜爱列表\n\n\n\t//歌曲列表常量\n\tpublic static final int LIST_ALLMUSIC = -1;\n\tpublic static final int LIST_MYLOVE = 10000;\n\tpublic static final int LIST_LASTPLAY = 10001;\n\tpublic static final int LIST_DOWNLOAD = 10002;\n\tpublic static final int LIST_MYPLAY = 10003; //我的歌单列表\n\tpublic static final int LIST_PLAYLIST = 10004;\t//歌单音乐列表\n\n\tpublic static final int LIST_SINGER = 10005;\t//歌手\n\tpublic static final int LIST_ALBUM = 10006;\t //专辑\n\tpublic static final int LIST_FOLDER = 10007;\t//文件夹\n\n\n\t//ReceiverForMain.action\n\tpublic static final String UPDATE_MAIN_ACTIVITY =\"MainActivityToReceiver.action\";\n\t//MediaPlayerManager.action\n\tpublic static final String MP_FILTER = \"com.example.vinyl.start_mediaplayer\";\n\t//WidgetUtil.action\n\tpublic static final String UPDATE_WIDGET = \"android.intent.ACTION_WIDGET\";\n\t//UpdateWidget.action\n\tpublic static final String WIDGET_STATUS = \"android.appwidget.action.WIDGET_STATUS\";\n\tpublic static final String WIDGET_SEEK = \"android.appwidget.action.WIDGET_SEEK\";\n\t//\n\tpublic static final String MUSIC_CONTROL = \"kugoumusic.ACTION_CONTROL\";\n\tpublic static final String UPDATE_STATUS = \"kugoumusic.ACTION_STATUS\";\n\n\t//widget播放控制\n\tpublic static final String WIDGET_PLAY=\"android.appwidget.WIDGET_PLAY\";\n\tpublic static final String WIDGET_NEXT=\"android.appwidget.WIDGET_NEXT\";\n\tpublic static final String WIDGET_PREVIOUS=\"android.appwidget.WIDGET_PREVIOUS\";\n\n\n\t//主题\n\tpublic static final String THEME=\"theme\";\n}", "public class MyMusicUtil {\n\n private static final String TAG = MyMusicUtil.class.getName();\n //获取当前播放列表\n public static List<MusicInfo> getCurPlayList(Context context){\n DBManager dbManager = DBManager.getInstance(context);\n int playList = MyMusicUtil.getIntShared(Constant.KEY_LIST);\n List<MusicInfo> musicInfoList = new ArrayList<>();\n switch (playList){\n case Constant.LIST_ALLMUSIC:\n musicInfoList = dbManager.getAllMusicFromMusicTable();\n break;\n case Constant.LIST_MYLOVE:\n musicInfoList = dbManager.getAllMusicFromTable(Constant.LIST_MYLOVE);\n break;\n case Constant.LIST_LASTPLAY:\n musicInfoList = dbManager.getAllMusicFromTable(Constant.LIST_LASTPLAY);\n break;\n case Constant.LIST_PLAYLIST:\n int listId = MyMusicUtil.getIntShared(Constant.KEY_LIST_ID);\n musicInfoList = dbManager.getMusicListByPlaylist(listId);\n break;\n case Constant.LIST_SINGER:\n String singerName = MyMusicUtil.getStringShared(Constant.KEY_LIST_ID);\n if (singerName == null){\n musicInfoList = dbManager.getAllMusicFromMusicTable();\n }else {\n musicInfoList = dbManager.getMusicListBySinger(singerName);\n }\n break;\n case Constant.LIST_ALBUM:\n String albumName = MyMusicUtil.getStringShared(Constant.KEY_LIST_ID);\n if (albumName == null){\n musicInfoList = dbManager.getAllMusicFromMusicTable();\n }else {\n musicInfoList = dbManager.getMusicListByAlbum(albumName);\n }\n break;\n case Constant.LIST_FOLDER:\n String folderName = MyMusicUtil.getStringShared(Constant.KEY_LIST_ID);\n if (folderName == null){\n musicInfoList = dbManager.getAllMusicFromMusicTable();\n }else {\n musicInfoList = dbManager.getMusicListByFolder(folderName);\n }\n break;\n }\n return musicInfoList;\n }\n\n public static void playNextMusic(Context context){\n //获取下一首ID\n DBManager dbManager = DBManager.getInstance(context);\n int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);\n Log.d(TAG,\"next play mode =\"+playMode);\n int musicId = MyMusicUtil.getIntShared(Constant.KEY_ID);\n List<MusicInfo> musicList = getCurPlayList(context);\n ArrayList<Integer> musicIdList =new ArrayList<>();\n for (MusicInfo info : musicList){\n musicIdList.add(info.getId());\n }\n musicId = dbManager.getNextMusic(musicIdList,musicId,playMode);\n MyMusicUtil.setShared(Constant.KEY_ID,musicId);\n if (musicId == -1) {\n Intent intent = new Intent(MusicPlayerService.PLAYER_MANAGER_ACTION);\n intent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);\n context.sendBroadcast(intent);\n Toast.makeText(context, \"歌曲不存在\",Toast.LENGTH_LONG).show();\n return;\n }\n\n //获取播放歌曲路径\n String path = dbManager.getMusicPath(musicId);\n Log.d(TAG,\"next path =\"+path);\n //发送播放请求\n Log.d(TAG,\"next id = \"+musicId+\"path = \"+ path);\n Intent intent = new Intent(MusicPlayerService.PLAYER_MANAGER_ACTION);\n intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);\n intent.putExtra(Constant.KEY_PATH, path);\n context.sendBroadcast(intent);\n }\n\n public static void playPreMusic(Context context){\n //获取下一首ID\n DBManager dbManager = DBManager.getInstance(context);\n int playMode = MyMusicUtil.getIntShared(Constant.KEY_MODE);\n Log.d(TAG,\"pre play mode =\"+playMode);\n int musicId = MyMusicUtil.getIntShared(Constant.KEY_ID);\n List<MusicInfo> musicList = getCurPlayList(context);\n ArrayList<Integer> musicIdList =new ArrayList<>();\n for (MusicInfo info : musicList){\n musicIdList.add(info.getId());\n }\n musicId = dbManager.getPreMusic(musicIdList,musicId,playMode);\n MyMusicUtil.setShared(Constant.KEY_ID,musicId);\n if (musicId == -1) {\n Intent intent = new Intent(MusicPlayerService.PLAYER_MANAGER_ACTION);\n intent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);\n context.sendBroadcast(intent);\n Toast.makeText(context, \"歌曲不存在\",Toast.LENGTH_LONG).show();\n return;\n }\n\n //获取播放歌曲路径\n String path = dbManager.getMusicPath(musicId);\n Log.d(TAG,\"pre path =\"+path);\n //发送播放请求\n Log.d(TAG,\"pre id = \"+musicId+\"path = \"+ path);\n Intent intent = new Intent(MusicPlayerService.PLAYER_MANAGER_ACTION);\n intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);\n intent.putExtra(Constant.KEY_PATH, path);\n context.sendBroadcast(intent);\n }\n\n public static void setMusicMylove(Context context,int musicId){\n if (musicId == -1){\n Toast.makeText(context, \"歌曲不存在\",Toast.LENGTH_LONG).show();\n return;\n }\n DBManager dbManager = DBManager.getInstance(context);\n dbManager.setMyLove(musicId);\n }\n\n //设置--铃声的具体方法\n public static void setMyRingtone(Context context)\n {\n DBManager dbManager = DBManager.getInstance(context);\n int musicId = MyMusicUtil.getIntShared(Constant.KEY_ID);\n String path = dbManager.getMusicPath(musicId);\n File sdfile = new File(path);\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DATA, sdfile.getAbsolutePath());\n values.put(MediaStore.MediaColumns.TITLE, sdfile.getName());\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"audio/*\");\n values.put(MediaStore.Audio.Media.IS_RINGTONE, true);\n values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);\n values.put(MediaStore.Audio.Media.IS_ALARM, false);\n values.put(MediaStore.Audio.Media.IS_MUSIC, false);\n\n Uri uri = MediaStore.Audio.Media.getContentUriForPath(sdfile.getAbsolutePath());\n Uri newUri = context.getContentResolver().insert(uri, values);\n RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);\n Toast.makeText( context,\"设置来电铃声成功!\", Toast.LENGTH_SHORT ).show();\n }\n\n // 设置sharedPreferences\n public static void setShared(String key,int value){\n SharedPreferences pref = MyApplication.getContext().getSharedPreferences(\"music\",MyApplication.getContext().MODE_PRIVATE);\n SharedPreferences.Editor editor = pref.edit();\n editor.putInt(key, value);\n editor.commit();\n }\n\n public static void setShared(String key,String value){\n SharedPreferences pref = MyApplication.getContext().getSharedPreferences(\"music\",MyApplication.getContext().MODE_PRIVATE);\n SharedPreferences.Editor editor = pref.edit();\n editor.putString(key, value);\n editor.commit();\n }\n\n // 获取sharedPreferences\n public static int getIntShared(String key) {\n SharedPreferences pref = MyApplication.getContext().getSharedPreferences(\"music\", MyApplication.getContext().MODE_PRIVATE);\n int value;\n if (key.equals(Constant.KEY_CURRENT)){\n value = pref.getInt(key, 0);\n }else{\n value = pref.getInt(key, -1);\n }\n return value;\n }\n\n public static String getStringShared(String key) {\n SharedPreferences pref = MyApplication.getContext().getSharedPreferences(\"music\", MyApplication.getContext().MODE_PRIVATE);\n String value;\n value = pref.getString(key,null);\n return value;\n }\n\n //按歌手分组\n public static ArrayList<SingerInfo> groupBySinger(ArrayList list) {\n Map<String, List<MusicInfo>> musicMap = new HashMap<>();\n ArrayList<SingerInfo> singerInfoList = new ArrayList<>();\n for (int i = 0; i < list.size(); i++) {\n MusicInfo musicInfo = (MusicInfo) list.get(i);\n if (musicMap.containsKey(musicInfo.getSinger())) {\n ArrayList singerList = (ArrayList) musicMap.get(musicInfo.getSinger());\n singerList.add(musicInfo);\n } else {\n ArrayList temp = new ArrayList();\n temp.add(musicInfo);\n musicMap.put(musicInfo.getSinger(), temp);\n }\n }\n\n for (Map.Entry<String,List<MusicInfo>> entry : musicMap.entrySet()) {\n System.out.println(\"key= \" + entry.getKey() + \" and value= \" + entry.getValue());\n SingerInfo singerInfo = new SingerInfo();\n singerInfo.setName(entry.getKey());\n singerInfo.setCount(entry.getValue().size());\n singerInfoList.add(singerInfo);\n }\n return singerInfoList;\n }\n\n //按专辑分组\n public static ArrayList<AlbumInfo> groupByAlbum(ArrayList list) {\n Map<String, List<MusicInfo>> musicMap = new HashMap<>();\n ArrayList<AlbumInfo> albumInfoList = new ArrayList<>();\n for (int i = 0; i < list.size(); i++) {\n MusicInfo musicInfo = (MusicInfo) list.get(i);\n if (musicMap.containsKey(musicInfo.getAlbum())) {\n ArrayList albumList = (ArrayList) musicMap.get(musicInfo.getAlbum());\n albumList.add(musicInfo);\n } else {\n ArrayList temp = new ArrayList();\n temp.add(musicInfo);\n musicMap.put(musicInfo.getAlbum(), temp);\n }\n }\n\n for (Map.Entry<String,List<MusicInfo>> entry : musicMap.entrySet()) {\n AlbumInfo albumInfo = new AlbumInfo();\n albumInfo.setName(entry.getKey());\n albumInfo.setSinger(entry.getValue().get(0).getSinger());\n albumInfo.setCount(entry.getValue().size());\n albumInfoList.add(albumInfo);\n }\n\n return albumInfoList;\n }\n\n //按文件夹分组\n public static ArrayList<FolderInfo> groupByFolder(ArrayList list) {\n Map<String, List<MusicInfo>> musicMap = new HashMap<>();\n ArrayList<FolderInfo> folderInfoList = new ArrayList<>();\n for (int i = 0; i < list.size(); i++) {\n MusicInfo musicInfo = (MusicInfo) list.get(i);\n if (musicMap.containsKey(musicInfo.getParentPath())) {\n ArrayList folderList = (ArrayList) musicMap.get(musicInfo.getParentPath());\n folderList.add(musicInfo);\n } else {\n ArrayList temp = new ArrayList();\n temp.add(musicInfo);\n musicMap.put(musicInfo.getParentPath(), temp);\n }\n }\n\n for (Map.Entry<String,List<MusicInfo>> entry : musicMap.entrySet()) {\n System.out.println(\"key= \" + entry.getKey() + \" and value= \" + entry.getValue());\n FolderInfo folderInfo = new FolderInfo();\n File file = new File(entry.getKey());\n folderInfo.setName(file.getName());\n folderInfo.setPath(entry.getKey());\n folderInfo.setCount(entry.getValue().size());\n folderInfoList.add(folderInfo);\n }\n\n return folderInfoList;\n }\n\n //设置主题\n public static void setTheme(Context context, int position) {\n int preSelect = getTheme(context);\n SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.THEME, Context.MODE_PRIVATE);\n sharedPreferences.edit().putInt(\"theme_select\", position).commit();\n if (preSelect != ThemeActivity.THEME_SIZE - 1) {\n sharedPreferences.edit().putInt(\"pre_theme_select\", preSelect).commit();\n }\n }\n\n\n //得到主题\n public static int getTheme(Context context) {\n SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.THEME, Context.MODE_PRIVATE);\n return sharedPreferences.getInt(\"theme_select\", 0);\n }\n\n //得到上一次选择的主题,用于取消夜间模式时恢复用\n public static int getPreTheme(Context context) {\n SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.THEME, Context.MODE_PRIVATE);\n return sharedPreferences.getInt(\"pre_theme_select\", 0);\n }\n\n //设置夜间模式\n public static void setNightMode(Context context, boolean mode) {\n if (mode) {\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n } else {\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n }\n SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.THEME, Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.putBoolean(\"night\", mode).commit();\n }\n\n //得到是否夜间模式\n public static boolean getNightMode(Context context) {\n SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.THEME, Context.MODE_PRIVATE);\n return sharedPreferences.getBoolean(\"night\",false);\n }\n\n //得到主题\n public static int getMyThemeStyle(Context context) {\n int themeId = MyMusicUtil.getTheme(context);\n switch (themeId){\n default:\n case 0:\n return R.style.BiLiPinkTheme;\n case 1:\n return R.style.ZhiHuBlueTheme;\n case 2:\n return R.style.KuAnGreenTheme;\n case 3:\n return R.style.CloudRedTheme;\n case 4:\n return R.style.TengLuoPurpleTheme;\n case 5:\n return R.style.SeaBlueTheme;\n case 6:\n return R.style.GrassGreenTheme;\n case 7:\n return R.style.CoffeeBrownTheme;\n case 8:\n return R.style.LemonOrangeTheme;\n case 9:\n return R.style.StartSkyGrayTheme;\n case 10:\n return R.style.NightModeTheme;\n }\n }\n\n // 设置必用图片 sharedPreferences\n public static void setBingShared(String value){\n SharedPreferences pref = MyApplication.getContext().getSharedPreferences(\"bing_pic\",MyApplication.getContext().MODE_PRIVATE);\n SharedPreferences.Editor editor = pref.edit();\n editor.putString(\"pic\", value);\n editor.commit();\n }\n\n // 获取必用图片 sharedPreferences\n public static String getBingShared() {\n SharedPreferences pref = MyApplication.getContext().getSharedPreferences(\"bing_pic\", MyApplication.getContext().MODE_PRIVATE);\n String value = pref.getString(\"pic\",null);\n return value;\n }\n\n\n}" ]
import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.lijunyan.blackmusic.R; import com.lijunyan.blackmusic.database.DBManager; import com.lijunyan.blackmusic.entity.MusicInfo; import com.lijunyan.blackmusic.entity.PlayListInfo; import com.lijunyan.blackmusic.service.MusicPlayerService; import com.lijunyan.blackmusic.util.Constant; import com.lijunyan.blackmusic.util.MyMusicUtil; import java.util.List;
package com.lijunyan.blackmusic.adapter; /** * Created by lijunyan on 2017/3/28. */ public class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.ViewHolder> { private static final String TAG = PlaylistAdapter.class.getName(); private List<MusicInfo> musicInfoList; private Context context; private DBManager dbManager; private PlayListInfo playListInfo; private PlaylistAdapter.OnItemClickListener onItemClickListener ; static class ViewHolder extends RecyclerView.ViewHolder{ View swipeContent; LinearLayout contentLl; TextView musicIndex; TextView musicName; TextView musicSinger; ImageView menuIv; Button deleteBtn; public ViewHolder(View itemView) { super(itemView); this.swipeContent = (View) itemView.findViewById(R.id.swipemenu_layout); this.contentLl = (LinearLayout) itemView.findViewById(R.id.local_music_item_ll); this.musicName = (TextView) itemView.findViewById(R.id.local_music_name); this.musicIndex = (TextView) itemView.findViewById(R.id.local_index); this.musicSinger = (TextView) itemView.findViewById(R.id.local_music_singer); this.menuIv = (ImageView) itemView.findViewById(R.id.local_music_item_never_menu); this.deleteBtn = (Button) itemView.findViewById(R.id.swip_delete_menu_btn); } } public PlaylistAdapter(Context context, PlayListInfo playListInfo,List<MusicInfo> musicInfoList) { this.context = context; this.playListInfo = playListInfo; this.dbManager = DBManager.getInstance(context); this.musicInfoList = musicInfoList; } @Override public int getItemCount() { return musicInfoList.size(); } @Override public PlaylistAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.local_music_item,parent,false); PlaylistAdapter.ViewHolder viewHolder = new PlaylistAdapter.ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(final PlaylistAdapter.ViewHolder holder, final int position) { Log.d(TAG, "onBindViewHolder: position = "+position); final MusicInfo musicInfo = musicInfoList.get(position); holder.musicName.setText(musicInfo.getName()); holder.musicIndex.setText("" + (position + 1)); holder.musicSinger.setText(musicInfo.getSinger());
if (musicInfo.getId() == MyMusicUtil.getIntShared(Constant.KEY_ID)){
4
snowhow/cordova-plugin-gpstrack
src/android/org/java_websocket/WebSocketListener.java
[ "public abstract class Draft {\n\n\t/**\n\t * Enum which represents the states a handshake may be in\n\t */\n\tpublic enum HandshakeState {\n\t\t/** Handshake matched this Draft successfully */\n\t\tMATCHED,\n\t\t/** Handshake is does not match this Draft */\n\t\tNOT_MATCHED\n\t}\n\t/**\n\t * Enum which represents type of handshake is required for a close\n\t */\n\tpublic enum CloseHandshakeType {\n\t\tNONE, ONEWAY, TWOWAY\n\t}\n\n\tpublic static int MAX_FAME_SIZE = 1000;\n\tpublic static int INITIAL_FAMESIZE = 64;\n\n\t/** In some cases the handshake will be parsed different depending on whether */\n\tprotected Role role = null;\n\n\tprotected Opcode continuousFrameType = null;\n\n\tpublic static ByteBuffer readLine( ByteBuffer buf ) {\n\t\tByteBuffer sbuf = ByteBuffer.allocate( buf.remaining() );\n\t\tbyte prev;\n\t\tbyte cur = '0';\n\t\twhile ( buf.hasRemaining() ) {\n\t\t\tprev = cur;\n\t\t\tcur = buf.get();\n\t\t\tsbuf.put( cur );\n\t\t\tif( prev == (byte) '\\r' && cur == (byte) '\\n' ) {\n\t\t\t\tsbuf.limit( sbuf.position() - 2 );\n\t\t\t\tsbuf.position( 0 );\n\t\t\t\treturn sbuf;\n\n\t\t\t}\n\t\t}\n\t\t// ensure that there wont be any bytes skipped\n\t\tbuf.position( buf.position() - sbuf.position() );\n\t\treturn null;\n\t}\n\n\tpublic static String readStringLine( ByteBuffer buf ) {\n\t\tByteBuffer b = readLine( buf );\n\t\treturn b == null ? null : Charsetfunctions.stringAscii( b.array(), 0, b.limit() );\n\t}\n\n\tpublic static HandshakeBuilder translateHandshakeHttp( ByteBuffer buf, Role role ) throws InvalidHandshakeException , IncompleteHandshakeException {\n\t\tHandshakeBuilder handshake;\n\n\t\tString line = readStringLine( buf );\n\t\tif( line == null )\n\t\t\tthrow new IncompleteHandshakeException( buf.capacity() + 128 );\n\n\t\tString[] firstLineTokens = line.split( \" \", 3 );// eg. HTTP/1.1 101 Switching the Protocols\n\t\tif( firstLineTokens.length != 3 ) {\n\t\t\tthrow new InvalidHandshakeException();\n\t\t}\n\n\t\tif( role == Role.CLIENT ) {\n\t\t\t// translating/parsing the response from the SERVER\n\t\t\tif (!\"101\".equals(firstLineTokens[1])) {\n\t\t\t\tthrow new InvalidHandshakeException( \"Invalid status code received: \" + firstLineTokens[1] + \" Status line: \" + line);\n\t\t\t}\n\t\t\tif (!\"HTTP/1.1\".equalsIgnoreCase(firstLineTokens[0])) {\n\t\t\t\tthrow new InvalidHandshakeException( \"Invalid status line received: \" + firstLineTokens[0] + \" Status line: \" + line);\n\t\t\t}\n\n\t\t\thandshake = new HandshakeImpl1Server();\n\t\t\tServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake;\n\t\t\tserverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) );\n\t\t\tserverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] );\n\t\t} else {\n\t\t\t// translating/parsing the request from the CLIENT\n\t\t\tif (!\"GET\".equalsIgnoreCase(firstLineTokens[0])) {\n\t\t\t\tthrow new InvalidHandshakeException( \"Invalid request method received: \" + firstLineTokens[0] + \" Status line: \" + line);\n\t\t\t}\n\t\t\tif (!\"HTTP/1.1\".equalsIgnoreCase(firstLineTokens[2])) {\n\t\t\t\tthrow new InvalidHandshakeException( \"Invalid status line received: \" + firstLineTokens[2] + \" Status line: \" + line);\n\t\t\t}\n\t\t\tClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client();\n\t\t\tclienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] );\n\t\t\thandshake = clienthandshake;\n\t\t}\n\n\t\tline = readStringLine( buf );\n\t\twhile ( line != null && line.length() > 0 ) {\n\t\t\tString[] pair = line.split( \":\", 2 );\n\t\t\tif( pair.length != 2 )\n\t\t\t\tthrow new InvalidHandshakeException( \"not an http header\" );\n\t\t\t// If the handshake contains already a specific key, append the new value\n\t\t\tif ( handshake.hasFieldValue( pair[ 0 ] ) ) {\n\t\t\t\thandshake.put( pair[0], handshake.getFieldValue( pair[ 0 ] ) + \"; \" + pair[1].replaceFirst( \"^ +\", \"\" ) );\n\t\t\t} else {\n\t\t\t\thandshake.put( pair[0], pair[1].replaceFirst( \"^ +\", \"\" ) );\n\t\t\t}\n\t\t\tline = readStringLine( buf );\n\t\t}\n\t\tif( line == null )\n\t\t\tthrow new IncompleteHandshakeException();\n\t\treturn handshake;\n\t}\n\n\tpublic abstract HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHandshake response ) throws InvalidHandshakeException;\n\n\tpublic abstract HandshakeState acceptHandshakeAsServer( ClientHandshake handshakedata ) throws InvalidHandshakeException;\n\n\tprotected boolean basicAccept( Handshakedata handshakedata ) {\n\t\treturn handshakedata.getFieldValue( \"Upgrade\" ).equalsIgnoreCase( \"websocket\" ) && handshakedata.getFieldValue( \"Connection\" ).toLowerCase( Locale.ENGLISH ).contains( \"upgrade\" );\n\t}\n\n\tpublic abstract ByteBuffer createBinaryFrame( Framedata framedata ); // TODO Allow to send data on the base of an Iterator or InputStream\n\n\tpublic abstract List<Framedata> createFrames( ByteBuffer binary, boolean mask );\n\n\tpublic abstract List<Framedata> createFrames( String text, boolean mask );\n\n\n\t/**\n\t * Handle the frame specific to the draft\n\t * @param webSocketImpl the websocketimpl used for this draft\n\t * @param frame the frame which is supposed to be handled\n\t * @throws InvalidDataException will be thrown on invalid data\n\t */\n\tpublic abstract void processFrame( WebSocketImpl webSocketImpl, Framedata frame ) throws InvalidDataException;\n\n\tpublic List<Framedata> continuousFrame( Opcode op, ByteBuffer buffer, boolean fin ) {\n\t\tif(op != Opcode.BINARY && op != Opcode.TEXT) {\n\t\t\tthrow new IllegalArgumentException( \"Only Opcode.BINARY or Opcode.TEXT are allowed\" );\n\t\t}\n\t\tDataFrame bui = null;\n\t\tif( continuousFrameType != null ) {\n\t\t\tbui = new ContinuousFrame();\n\t\t} else {\n\t\t\tcontinuousFrameType = op;\n\t\t\tif (op == Opcode.BINARY) {\n\t\t\t\tbui = new BinaryFrame();\n\t\t\t} else if (op == Opcode.TEXT) {\n\t\t\t\tbui = new TextFrame();\n\t\t\t}\n\t\t}\n\t\tbui.setPayload( buffer );\n\t\tbui.setFin( fin );\n\t\ttry {\n\t\t\tbui.isValid();\n\t\t} catch ( InvalidDataException e ) {\n\t\t\tthrow new IllegalArgumentException( e ); // can only happen when one builds close frames(Opcode.Close)\n\t\t}\n\t\tif( fin ) {\n\t\t\tcontinuousFrameType = null;\n\t\t} else {\n\t\t\tcontinuousFrameType = op;\n\t\t}\n\t\treturn Collections.singletonList( (Framedata) bui );\n\t}\n\n\tpublic abstract void reset();\n\n\tpublic List<ByteBuffer> createHandshake( Handshakedata handshakedata, Role ownrole ) {\n\t\treturn createHandshake( handshakedata, ownrole, true );\n\t}\n\n\tpublic List<ByteBuffer> createHandshake( Handshakedata handshakedata, Role ownrole, boolean withcontent ) {\n\t\tStringBuilder bui = new StringBuilder( 100 );\n\t\tif( handshakedata instanceof ClientHandshake ) {\n\t\t\tbui.append( \"GET \" );\n\t\t\tbui.append( ( (ClientHandshake) handshakedata ).getResourceDescriptor() );\n\t\t\tbui.append( \" HTTP/1.1\" );\n\t\t} else if( handshakedata instanceof ServerHandshake ) {\n\t\t\tbui.append(\"HTTP/1.1 101 \").append(((ServerHandshake) handshakedata).getHttpStatusMessage());\n\t\t} else {\n\t\t\tthrow new IllegalArgumentException( \"unknown role\" );\n\t\t}\n\t\tbui.append( \"\\r\\n\" );\n\t\tIterator<String> it = handshakedata.iterateHttpFields();\n\t\twhile ( it.hasNext() ) {\n\t\t\tString fieldname = it.next();\n\t\t\tString fieldvalue = handshakedata.getFieldValue( fieldname );\n\t\t\tbui.append( fieldname );\n\t\t\tbui.append( \": \" );\n\t\t\tbui.append( fieldvalue );\n\t\t\tbui.append( \"\\r\\n\" );\n\t\t}\n\t\tbui.append( \"\\r\\n\" );\n\t\tbyte[] httpheader = Charsetfunctions.asciiBytes( bui.toString() );\n\n\t\tbyte[] content = withcontent ? handshakedata.getContent() : null;\n\t\tByteBuffer bytebuffer = ByteBuffer.allocate( ( content == null ? 0 : content.length ) + httpheader.length );\n\t\tbytebuffer.put( httpheader );\n\t\tif( content != null )\n\t\t\tbytebuffer.put( content );\n\t\tbytebuffer.flip();\n\t\treturn Collections.singletonList( bytebuffer );\n\t}\n\n\tpublic abstract ClientHandshakeBuilder postProcessHandshakeRequestAsClient( ClientHandshakeBuilder request ) throws InvalidHandshakeException;\n\n\tpublic abstract HandshakeBuilder postProcessHandshakeResponseAsServer( ClientHandshake request, ServerHandshakeBuilder response ) throws InvalidHandshakeException;\n\n\tpublic abstract List<Framedata> translateFrame( ByteBuffer buffer ) throws InvalidDataException;\n\n\tpublic abstract CloseHandshakeType getCloseHandshakeType();\n\n\t/**\n\t * Drafts must only be by one websocket at all. To prevent drafts to be used more than once the Websocket implementation should call this method in order to create a new usable version of a given draft instance.<br>\n\t * The copy can be safely used in conjunction with a new websocket connection.\n\t * @return a copy of the draft\n\t */\n\tpublic abstract Draft copyInstance();\n\n\tpublic Handshakedata translateHandshake( ByteBuffer buf ) throws InvalidHandshakeException {\n\t\treturn translateHandshakeHttp( buf, role );\n\t}\n\n\tpublic int checkAlloc( int bytecount ) throws LimitExedeedException , InvalidDataException {\n\t\tif( bytecount < 0 )\n\t\t\tthrow new InvalidDataException( CloseFrame.PROTOCOL_ERROR, \"Negative count\" );\n\t\treturn bytecount;\n\t}\n\n\tint readVersion( Handshakedata handshakedata ) {\n\t\tString vers = handshakedata.getFieldValue( \"Sec-WebSocket-Version\" );\n\t\tif( vers.length() > 0 ) {\n\t\t\tint v;\n\t\t\ttry {\n\t\t\t\tv = new Integer( vers.trim() );\n\t\t\t\treturn v;\n\t\t\t} catch ( NumberFormatException e ) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic void setParseMode( Role role ) {\n\t\tthis.role = role;\n\t}\n\t\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\tpublic String toString() {\n\t\treturn getClass().getSimpleName();\n\t}\n\n}", "public interface ClientHandshake extends Handshakedata {\n\t/**\n\t * returns the HTTP Request-URI as defined by http://tools.ietf.org/html/rfc2616#section-5.1.2\n\t * @return the HTTP Request-URI\n\t */\n\tString getResourceDescriptor();\n}", "public interface Handshakedata {\n\tIterator<String> iterateHttpFields();\n\tString getFieldValue( String name );\n\tboolean hasFieldValue( String name );\n\tbyte[] getContent();\n}", "public interface ServerHandshake extends Handshakedata {\n\tshort getHttpStatus();\n\tString getHttpStatusMessage();\n}", "public interface ServerHandshakeBuilder extends HandshakeBuilder, ServerHandshake {\n\tvoid setHttpStatus( short status );\n\tvoid setHttpStatusMessage( String message );\n}" ]
import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.handshake.Handshakedata; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.handshake.ServerHandshakeBuilder; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import org.java_websocket.drafts.Draft; import org.java_websocket.exceptions.InvalidDataException;
/* * Copyright (c) 2010-2017 Nathan Rajlich * * 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 org.java_websocket; /** * Implemented by <tt>WebSocketClient</tt> and <tt>WebSocketServer</tt>. * The methods within are called by <tt>WebSocket</tt>. * Almost every method takes a first parameter conn which represents the source of the respective event. */ public interface WebSocketListener { /** * Called on the server side when the socket connection is first established, and the WebSocket * handshake has been received. This method allows to deny connections based on the received handshake.<br> * By default this method only requires protocol compliance. * * @param conn * The WebSocket related to this event * @param draft * The protocol draft the client uses to connect * @param request * The opening http message send by the client. Can be used to access additional fields like cookies. * @return Returns an incomplete handshake containing all optional fields * @throws InvalidDataException * Throwing this exception will cause this handshake to be rejected */ ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer( WebSocket conn, Draft draft, ClientHandshake request ) throws InvalidDataException; /** * Called on the client side when the socket connection is first established, and the WebSocketImpl * handshake response has been received. * * @param conn * The WebSocket related to this event * @param request * The handshake initially send out to the server by this websocket. * @param response * The handshake the server sent in response to the request. * @throws InvalidDataException * Allows the client to reject the connection with the server in respect of its handshake response. */
void onWebsocketHandshakeReceivedAsClient( WebSocket conn, ClientHandshake request, ServerHandshake response ) throws InvalidDataException;
3
gambitproject/gte
lib-algo/src/lse/math/games/matrix/BimatrixSolver.java
[ "public class Rational \r\n{\r\n\tpublic static final Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE);\r\n\tpublic static final Rational ONE = new Rational(BigInteger.ONE, BigInteger.ONE);\r\n\tpublic static final Rational NEGONE = new Rational(BigInteger.ONE.negate(), BigInteger.ONE);\r\n\tpublic BigInteger num;\r\n\tpublic BigInteger den;\r\n\t\r\n\tpublic Rational(BigInteger num, BigInteger den)\r\n\t{\r\n\t\tthis.num = num;\r\n\t\tthis.den = den;\r\n if (zero(den)) {\r\n throw new ArithmeticException(\"Divide by zero\");\r\n } else if (!one(den)) {\r\n \t\treduce();\r\n }\r\n\t}\r\n\t\r\n\tpublic Rational(Rational toCopy)\r\n\t{\r\n\t\tthis.num = toCopy.num;\r\n\t\tthis.den = toCopy.den;\r\n\t}\r\n\t\r\n /* reduces Na Da by gcd(Na,Da) */\r\n private void reduce()\r\n {\r\n \tif (!zero(num)) {\r\n if (negative(den))\r\n {\r\n den = den.negate();\r\n num = num.negate();\r\n }\r\n\t BigInteger gcd = num.gcd(den);\r\n\t if (!one(gcd)) {\r\n\t\t num = num.divide(gcd);\r\n\t\t den = den.divide(gcd);\r\n\t }\r\n \t} else {\r\n \t\tden = BigInteger.ONE;\r\n \t}\r\n }\r\n \r\n public Rational(long numerator, long denominator)\r\n\t{\r\n\t this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));\r\n\t}\r\n\r\n\tprivate void addEq(Rational toAdd)\r\n {\r\n \tif (den.equals(toAdd.den)) {\r\n \t\tnum = num.add(toAdd.num);\r\n \t} else {\r\n\t num = num.multiply(toAdd.den);\r\n\t num = num.add(toAdd.num.multiply(den));\r\n\t den = den.multiply(toAdd.den);\t \r\n \t}\r\n \treduce();\r\n }\r\n \r\n public static Rational valueOf(String s)\r\n throws NumberFormatException\r\n {\r\n \tString[] fraction = s.split(\"/\");\r\n \tif (fraction.length < 1 || fraction.length > 2) \r\n \t\tthrow new NumberFormatException(\"BigIntegerRational not formatted correctly\");\r\n\r\n \tif (fraction.length == 2) {\r\n\t \tBigInteger num = new BigInteger(fraction[0]);\r\n\t \tBigInteger den = new BigInteger(fraction[1]);\r\n\t \treturn new Rational(num, den);\r\n \t} else {\r\n \t\tBigDecimal dec = new BigDecimal(s);\r\n \t\treturn valueOf(dec);\r\n \t}\r\n }\r\n \r\n public static Rational valueOf(double dx)\r\n {\r\n BigDecimal x = BigDecimal.valueOf(dx);\r\n return valueOf(x);\r\n }\r\n \r\n public static Rational valueOf(BigDecimal x)\r\n {\r\n BigInteger num = x.unscaledValue();\r\n BigInteger den = BigInteger.ONE;\r\n \r\n int scale = x.scale();\r\n while (scale > 0) \r\n {\r\n \tden = den.multiply(BigInteger.TEN);\r\n \t--scale;\r\n } \r\n while (scale < 0)\r\n {\r\n \tnum = num.multiply(BigInteger.TEN);\r\n \t++scale;\r\n }\r\n \r\n Rational rv = new Rational(num, den);\r\n rv.reduce();\r\n return rv;\r\n } \r\n \r\n public static Rational valueOf(long value)\r\n {\r\n \tif (value == 0) return ZERO;\r\n \telse if (value == 1) return ONE;\r\n \telse return new Rational(value);\r\n }\r\n \r\n private Rational(long value)\r\n {\r\n this(value, 1);\r\n }\r\n\r\n private void mulEq(Rational other)\r\n {\r\n num = num.multiply(other.num);\r\n den = den.multiply(other.den);\r\n reduce();\r\n }\r\n\r\n //Helper Methods\r\n private void flip() /* aka. Reciprocate */\r\n {\r\n BigInteger x = num;\r\n num = den;\r\n den = x;\r\n } \r\n\r\n public Rational add(Rational b)\r\n\t{\r\n\t\tif (zero(num)) return b;\r\n\t\telse if (zero(b.num))return this; \r\n\t\tRational rv = new Rational(this);\r\n\t rv.addEq(b);\r\n\t return rv;\r\n\t}\r\n\r\n\tpublic Rational add(long b)\r\n {\r\n if (b == 0) return this;\r\n Rational rv = new Rational(b);\r\n rv.addEq(this);\r\n return rv;\r\n }\r\n\r\n public Rational subtract(Rational b)\r\n\t{\r\n\t\tif (zero(b.num))return this; \r\n\t\tRational c = b.negate();\r\n\t if (!zero(num))\r\n\t \tc.addEq(this);\r\n\t return c;\r\n\t}\r\n\r\n\tpublic Rational subtract(long b)\r\n\t{\r\n\t if (b == 0) return this;\r\n\t Rational c = new Rational(-b);\r\n\t c.addEq(this);\r\n\t return c;\r\n\t}\r\n\r\n\tpublic Rational multiply(Rational b)\r\n {\r\n if (zero(num) || zero(b.num)) return ZERO;\r\n Rational rv = new Rational(this);\r\n rv.mulEq(b);\r\n return rv;\r\n }\r\n\r\n public Rational divide(Rational b)\r\n\t{\r\n\t\tRational rv = new Rational(b);\r\n\t\trv.flip();\r\n\t\trv.mulEq(this);\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tpublic Rational negate()\r\n\t{\r\n\t if (zero(num)) return this;\r\n\t return new Rational(num.negate(), den); \r\n\t}\r\n\r\n\tpublic Rational reciprocate()\r\n\t{\r\n\t\tif (zero(num)) throw new ArithmeticException(\"Divide by zero\");\r\n\t\tRational rv = new Rational(this);\r\n\t\trv.flip();\r\n\t\tif (negative(den)) {\r\n\t\t\trv.num = rv.num.negate();\r\n\t\t\trv.den = rv.den.negate();\r\n\t\t}\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tpublic int compareTo(Rational other)\r\n {\r\n if (num.equals(other.num) && den.equals(other.den))\r\n \treturn 0;\r\n \r\n //see if it is a num only compare...\r\n if (den.equals(other.den))\r\n return (greater(other.num, this.num)) ? -1 : 1;\r\n\r\n //check signs...\r\n if ((zero(num) || negative(num)) && positive(other.num)) \r\n \treturn -1;\r\n else if (positive(num) && (zero(other.num) || negative(other.num))) \r\n \treturn 1;\r\n\r\n Rational c = other.negate(); \r\n c.addEq(this);\r\n return (c.isZero() ? 0 : (negative(c.num) ? -1 : 1));\r\n }\r\n\r\n public int compareTo(long other)\r\n {\r\n \tBigInteger othernum = BigInteger.valueOf(other);\r\n if (num.equals(othernum) && one(den)) return 0;\r\n else return compareTo(new Rational(othernum, BigInteger.ONE));\r\n }\r\n\r\n\r\n public double doubleValue()\r\n\t{ \t\r\n \ttry {\r\n \t\treturn (new BigDecimal(num)).divide(new BigDecimal(den)).doubleValue();\r\n \t} catch (ArithmeticException e) {\r\n\t\t\treturn (new BigDecimal(num)).divide(new BigDecimal(den), 32, BigDecimal.ROUND_HALF_UP).doubleValue();\r\n\t\t}\r\n\t}\r\n\r\n\t//Num and Den are only used by Tableau... I'd like to get rid of them, but can't see how\r\n\tpublic boolean isZero() { return zero(num); }\r\n\r\n\tpublic boolean isOne() { return one(num) && one(den); } // should be reduced at all times\r\n\r\n\t//Basic Overrides\r\n @Override\r\n public boolean equals(Object obj)\r\n {\r\n if (obj == null || !(obj instanceof Rational))\r\n return false;\r\n\r\n Rational r = (Rational)obj;\r\n return (compareTo(r) == 0);\r\n }\r\n\r\n @Override\r\n public int hashCode()\r\n {\r\n return (num.multiply(BigInteger.valueOf(7)).intValue() ^ den.multiply(BigInteger.valueOf(17)).intValue());\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n \tStringBuilder sb = new StringBuilder();\r\n \tsb.append(num.toString());\r\n \tif (!one(den) && !zero(num))\r\n \t{\r\n \t\tsb.append(\"/\");\r\n \t\tsb.append(den);\r\n \t}\r\n \treturn sb.toString();\r\n }\r\n\r\n\tpublic static Rational sum(Iterable<Rational> list)\r\n\t{\r\n\t Rational sum = ZERO;\r\n\t for (Rational rat : list) {\r\n\t sum.addEq(rat); \r\n\t }\r\n\t return sum;\r\n\t}\r\n\r\n\t// TODO: why is this here?\r\n\tpublic static long gcd(long a, long b)\r\n\t{\r\n\t long c;\r\n\t if (a < 0L) {\r\n\t \ta = -a;\r\n\t }\r\n\t if (b < 0L) {\r\n\t \tb = -b;\r\n\t }\r\n\t if (a < b) { \r\n\t \tc = a; \r\n\t \ta = b; \r\n\t \tb = c; \r\n\t }\r\n\t while (b != 0L) {\r\n\t c = a % b;\r\n\t a = b;\r\n\t b = c;\r\n\t }\r\n\t return a;\r\n\t}\r\n\t\r\n\tpublic static Rational[] probVector(int length, Random prng)\r\n\t{\r\n\t\tif (length == 0) return new Rational[] {};\r\n\t\telse if (length == 1) return new Rational[] { Rational.ONE };\r\n\t\t\r\n\t\tdouble dProb = prng.nextDouble();\r\n\t\tRational probA = Rational.valueOf(dProb);\r\n\t\tRational probB = Rational.valueOf(1 - dProb);\r\n\t\tif (length == 2) {\r\n\t\t\treturn new Rational[] { probA, probB };\r\n\t\t} else {\r\n\t\t\tRational[] a = probVector(length / 2, prng);\r\n\t\t\tRational[] b = probVector((length + 1) / 2, prng);\r\n\t\t\tRational[] c = new Rational[a.length + b.length];\r\n\t\t\tfor (int i = 0; i < a.length; ++i) {\r\n\t\t\t\tc[i] = a[i].multiply(probA);\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < b.length; ++i) {\r\n\t\t\t\tc[a.length + i] = b[i].multiply(probB);\r\n\t\t\t}\r\n\t\t\treturn c;\r\n\t\t}\t\t\r\n\t}\r\n\t\r\n\t// TODO: put this somewhere else...\r\n\tpublic static void printRow(String name, Rational value, ColumnTextWriter colpp, boolean excludeZero)\r\n\t{\t\t\t\t\t\r\n\t\tif (!value.isZero() || !excludeZero) {\r\n\t\t\tcolpp.writeCol(name);\r\n\t\t\tcolpp.writeCol(value.toString());\r\n\t\t\t\t\t\r\n\t\t\tif (!BigIntegerUtils.one(value.den)) {\r\n\t\t\t\tcolpp.writeCol(String.format(\"%.3f\", value.doubleValue()));\t\r\n\t\t\t}\r\n\t\t\tcolpp.endRow();\r\n\t\t}\t\t\r\n\t}\r\n}\r", "public interface Lrs {\r\n\tVPolygon run(HPolygon in);\r\n}\r", "public class HPolygon {\r\n\tpublic boolean nonnegative = true;\r\n\tpublic boolean incidence = true; // for recording the full cobasis at lexmin points\r\n\tpublic boolean printcobasis = true; //incidence implies printcobasis\r\n\t//hull = false\r\n\tpublic int[] linearities = new int[0];\r\n\t\r\n\tprivate int n;\r\n\tprivate int m;\r\n\tprivate int d;\r\n\t\r\n\tpublic Rational[][] matrix;\r\n\t\t\r\n\tpublic HPolygon(Rational[][] matrix, boolean nonnegative)\r\n\t{\r\n\t\tthis.matrix = matrix;\r\n\t\tm = matrix.length;\r\n\t\tn = m > 0 ? matrix[0].length : 0;\r\n\t\td = n - 1;\r\n\t\t\r\n\t\tthis.nonnegative = nonnegative;\r\n\t}\r\n\t\r\n\t\r\n\tpublic int getNumRows() { return m; }\t\r\n\tpublic int getNumCols() { return n; }\t\r\n\tpublic int getDimension() { return d; }\r\n\t\r\n\t\r\n\tpublic void setIncidence(boolean value)\r\n\t{\r\n\t\tincidence = value;\r\n\t\tif (value && !printcobasis)\r\n\t\t\tprintcobasis = true;\r\n\t}\r\n\t\r\n\t/* for H-rep, are zero in column 0 */\r\n\tpublic boolean homogeneous() {\r\n\t\tboolean ishomo = true;\r\n\t\tfor (Rational[] row : matrix) {\r\n\t\t\tif (row.length < 1 || !row[0].isZero()) {\r\n\t\t\t\tishomo = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ishomo;\t\t\r\n\t}\r\n}\r", "public class VPolygon {\r\n\tpublic List<Rational[]> vertices = new ArrayList<Rational[]>(); // may also contain rays\r\n\tpublic List<Integer[]> cobasis = new ArrayList<Integer[]>();\r\n\t//boolean hull = true; //when is this false? I should try to set this as an output param as well\r\n\t//boolean voronoi = false; //(if true, then poly is false)\r\n\t\r\n\t/* all rows must have a one in column one */\r\n\tpublic boolean polytope() {\r\n\t\tboolean ispoly = true;\r\n\t\tfor (Rational[] row : vertices) {\r\n\t\t\tif (row.length < 1 || !row[0].isOne()) {\r\n\t\t\t\tispoly = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ispoly;\r\n\t}\r\n\t\r\n\t/* for V-rep, all zero in column 1 */\r\n\tpublic boolean homogeneous() {\r\n\t\tboolean ishomo = true;\r\n\t\tfor (Rational[] row : vertices) {\r\n\t\t\tif (row.length < 2 || !row[1].isZero()) {\r\n\t\t\t\tishomo = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ishomo;\t\t\r\n\t}\r\n}\r", "public class LCP {\r\n\tprivate static int MAXLCPDIM = 2000; /* max LCP dimension */ //MKE: Why do we need a max?\r\n\r\n // M and q define the LCP\r\n Rational[][] M;\r\n Rational[] q;\r\n \r\n // d vector for Lemke algo\r\n Rational[] d;\r\n\r\n /* allocate and initialize with zero entries an LCP of dimension n\r\n * this is the only method changing lcpdim \r\n * exit with error if fails, e.g. if n not sensible\r\n */\r\n public LCP(int dimension)\r\n {\r\n if (dimension < 1 || dimension > MAXLCPDIM) {\r\n throw new RuntimeException(String.format( //TODO: RuntimeException not the cleanest thing to do here\r\n \"Problem dimension n=%d not allowed. Minimum n is 1, maximum %d.\", \r\n dimension, MAXLCPDIM));\r\n } \r\n \r\n M = new Rational[dimension][dimension];\r\n q = new Rational[dimension];\r\n d = new Rational[dimension];\r\n \r\n for (int i = 0; i < M.length; i++) {\r\n for (int j = 0; j < M[i].length; j++) {\r\n M[i][j] = Rational.ZERO;\r\n }\r\n q[i] = Rational.ZERO;\r\n d[i] = Rational.ZERO;\r\n }\r\n }\r\n\r\n public boolean isTrivial()\r\n {\r\n boolean isQPos = true;\r\n for (int i = 0, len = q.length; i < len; ++i) {\r\n if (q[i].compareTo(0) < 0) {\r\n isQPos = false;\r\n }\r\n }\r\n return isQPos;\r\n }\r\n\r\n //when is negate false?\r\n // TODO: how do I consolidate the code in these two methods elegantly... delegate?\r\n // TODO: These methods do not really have anything to do with LCP...\r\n public void payratmatcpy(Rational[][] frommatr, boolean bnegate,\r\n boolean btranspfrommatr, int nfromrows, int nfromcols,\r\n int targrowoffset, int targcoloffset)\r\n {\r\n for (int i = 0; i < nfromrows; i++) {\r\n for (int j = 0; j < nfromcols; j++) { \r\n Rational value = (frommatr[i][j].isZero()) ? ZERO : (bnegate ? frommatr[i][j].negate() : frommatr[i][j]);\r\n SetMEntry(btranspfrommatr, targrowoffset, targcoloffset, i, j, value);\r\n }\r\n }\r\n }\r\n\r\n //integer to rational matrix copy\r\n public void intratmatcpy(int[][] frommatr, boolean bnegate,\r\n boolean btranspfrommatr, int nfromrows, int nfromcols,\r\n int targrowoffset, int targcoloffset)\r\n {\r\n for (int i = 0; i < nfromrows; i++) {\r\n for (int j = 0; j < nfromcols; j++) {\r\n Rational value = (frommatr[i][j] == 0) ? ZERO : (bnegate ? Rational.valueOf(-frommatr[i][j]) : Rational.valueOf(frommatr[i][j]));\r\n SetMEntry(btranspfrommatr, targrowoffset, targcoloffset, i, j, value);\r\n }\r\n }\r\n }\r\n\r\n private void SetMEntry(boolean btranspfrommatr, int targrowoffset, int targcoloffset, int i, int j, Rational value)\r\n {\r\n if (btranspfrommatr) {\r\n M[j + targrowoffset][i + targcoloffset] = value;\r\n } else {\r\n M[i + targrowoffset][j + targcoloffset] = value;\r\n }\r\n }\r\n\r\n public Rational[][] M() { return M; }\r\n public Rational M(int row, int col) { return M[row][col]; }\r\n public void setM(int row, int col, Rational value) { M[row][col] = value; }\r\n \r\n public Rational[] q() { return q; }\r\n public Rational q(int row) { return q[row]; }\r\n public void setq(int row, Rational value) { q[row] = value; }\r\n \r\n public Rational[] d() { return d; }\r\n public Rational d(int row) { return d[row]; }\r\n public void setd(int row, Rational value) { d[row] = value; }\r\n \r\n public int size() { return d.length; }\r\n \r\n @Override\r\n public String toString()\r\n { \t\r\n \tfinal ColumnTextWriter colpp = new ColumnTextWriter(); \t\r\n \tcolpp.writeCol(\"M\");\r\n \tfor (int i = 1; i < size(); ++i) {\r\n \t\tcolpp.writeCol(\"\"); \r\n \t}\r\n \tcolpp.writeCol(\"d\");\r\n \tcolpp.writeCol(\"q\");\r\n \tcolpp.endRow();\r\n \t\r\n\t\tfor (int i = 0; i < size(); ++i)\r\n { \t \t \r\n for (int j = 0; j < M[i].length; j++)\r\n {\r\n //if (j > 0) output.append(\", \"); \t\r\n colpp.writeCol(M[i][j] == Rational.ZERO ? \".\" : M[i][j].toString());\r\n } \r\n colpp.writeCol(d[i].toString()); \r\n colpp.writeCol(q[i].toString()); \r\n colpp.endRow();\r\n }\r\n \treturn colpp.toString(); \t\r\n }\r\n}\r", "public class LemkeAlgorithm \r\n{\r\n\tprivate static final Logger log = Logger.getLogger(LemkeAlgorithm.class.getName());\r\n\t\r\n\t//region State\r\n private int pivotcount;\r\n private int record_size = 0; /* MP digit record */ //MKE: TODO\r\n private long duration;\r\n\r\n private boolean z0leave;\r\n \r\n public long getDuration() { return duration; }\r\n public int getPivotCount() { return pivotcount; } /* no. of Lemke pivot iterations, including the first to pivot z0 in */\r\n public int getRecordDigits() { return record_size; } \r\n public Tableau A;\r\n public LexicographicMethod lex; // Performs MinRatio Test\r\n private LCP origLCP;\r\n\r\n //region Event Callbacks\r\n public LeavingVariableDelegate leavingVarHandler; //interactivevar OR lexminvar\r\n public OnCompleteDelegate onComplete; //chain: binitabl (secondcall), boutsol, blexstats\r\n public OnInitDelegate onInit; //binitabl (first call)\r\n public OnPivotDelegate onPivot; //bdocupivot\r\n public OnTableauChangeDelegate onTableauChange; //bouttabl\r\n public OnLexCompleteDelegate onLexComplete; //blexstats\r\n public OnLexRayTerminationDelegate onLexRayTermination;\r\n\r\n\r\n private void init(LCP lcp)\r\n \tthrows InvalidLCPException, TrivialSolutionException\r\n {\r\n checkInputs(lcp.q(), lcp.d());\r\n\torigLCP = lcp;\r\n A = new Tableau(lcp.d().length);\r\n A.fill(lcp.M(), lcp.q(), lcp.d());\r\n if (onInit != null)\r\n \tonInit.onInit(\"After filltableau\", A);\r\n lex = new LexicographicMethod(A.vars().size(), lcp);\r\n\r\n this.leavingVarHandler = new LeavingVariableDelegate() {\r\n\t\t\tpublic int getLeavingVar(int enter) throws RayTerminationException {\r\n\t\t\t\treturn lex.lexminratio(A, enter);\r\n\t\t\t}\r\n\t\t\tpublic boolean canZ0Leave() {\r\n\t\t\t\treturn lex.z0leave();\r\n\t\t\t}\r\n };\r\n }\r\n\r\n /** \r\n * asserts that d >= 0 and not q >= 0 (o/w trivial sol) \r\n * and that q[i] < 0 implies d[i] > 0\r\n */\r\n public void checkInputs(Rational[] rhsq, Rational[] vecd)\r\n \tthrows InvalidLCPException, TrivialSolutionException\r\n {\r\n boolean isQPos = true;\r\n for (int i = 0, len = rhsq.length; i < len; ++i) {\r\n if (vecd[i].compareTo(0) < 0) {\r\n throw new InvalidLCPException(String.format(\"Covering vector d[%d] = %s negative. Cannot start Lemke.\", i + 1, vecd[i].toString()));\r\n } else if (rhsq[i].compareTo(0) < 0) {\r\n isQPos = false;\r\n if (vecd[i].isZero()) {\r\n \tthrow new InvalidLCPException(String.format(\"Covering vector d[%d] = 0 where q[%d] = %s is negative. Cannot start Lemke.\", i + 1, i + 1, rhsq[i].toString()));\r\n }\r\n }\r\n }\r\n if (isQPos) {\r\n throw new TrivialSolutionException(\"No need to start Lemke since q>=0. Trivial solution z=0.\");\r\n }\r\n } \r\n \r\n private boolean complementaryPivot(int enter, int leave)\r\n {\r\n if (onPivot != null)\r\n onPivot.onPivot(leave, enter, A.vars());\r\n\r\n A.pivot(leave, enter);\r\n return z0leave;\r\n }\r\n\r\n /**\r\n * solve LCP via Lemke's algorithm,\r\n * solution in solz [0..lcpdim-1]\r\n * exit with error if ray termination\r\n */\r\n public Rational[] run(LCP lcp) \r\n \tthrows RayTerminationException, InvalidLCPException, TrivialSolutionException \r\n\t{ \r\n \treturn run(lcp, 0); \r\n\t}\r\n \r\n public Rational[] run(LCP lcp, int maxcount)\r\n \tthrows RayTerminationException, InvalidLCPException, TrivialSolutionException\r\n {\r\n \tinit(lcp);\r\n\r\n z0leave = false; \r\n int enter = A.vars().z(0); /* z0 enters the basis to obtain lex-feasible solution */\r\n int leave = nextLeavingVar(enter);\r\n\r\n A.negCol(A.RHS()); /* now give the entering q-col its correct sign */\r\n if (onTableauChange != null) { \r\n onTableauChange.onTableauChange(\"After negcol\", A);\r\n }\r\n\r\n pivotcount = 1;\r\n long before = System.currentTimeMillis();\r\n while (true) {\r\n if (complementaryPivot(enter, leave)) {\r\n \tbreak; // z0 will have a value of zero but may still be basic... amend?\r\n } \r\n \r\n if (onTableauChange != null)\r\n \tonTableauChange.onTableauChange(\"\", A); //TODO: Is there a constant for the empty string? \r\n\r\n // selectpivot\r\n enter = A.vars().complement(leave);\r\n leave = nextLeavingVar(enter);\r\n\r\n if (pivotcount++ == maxcount) /* maxcount == 0 is equivalent to infinity since pivotcount starts at 1 */\r\n {\r\n log.warning(String.format(\"------- stop after %d pivoting steps --------\", maxcount));\r\n break;\r\n }\r\n }\r\n duration = System.currentTimeMillis() - before;\r\n\r\n if (onComplete != null)\r\n \tonComplete.onComplete(\"Final tableau\", A); // hook up two tabl output functions to a chain delegate where the flags are analyzzed\r\n\r\n if (onLexComplete != null)\r\n \tonLexComplete.onLexComplete(lex);\r\n\r\n return getLCPSolution(); // LCP solution z vector \r\n }\r\n\r\n /**\r\n * LCP result\r\n * current basic solution turned into solz [0..n-1]\r\n * note that Z(1)..Z(n) become indices 0..n-1\r\n * gives a warning if conversion to ordinary rational fails\r\n * and returns 1, otherwise 0\r\n */\r\n private Rational[] getLCPSolution()\r\n {\r\n Rational[] z = new Rational[A.vars().size()];\r\n for (int i = 1; i <= z.length; i++)\r\n {\r\n int var = A.vars().z(i);\r\n z[i - 1] = A.result(var); \r\n }\r\n return z;\r\n }\r\n\r\n private int nextLeavingVar(int enter)\r\n \tthrows RayTerminationException\r\n {\r\n try {\r\n int rv = leavingVarHandler.getLeavingVar(enter);\r\n z0leave = leavingVarHandler.canZ0Leave();\r\n return rv;\r\n } catch (RayTerminationException ex) {\r\n if (onLexRayTermination != null) {\r\n onLexRayTermination.onLexRayTermination(enter, A, origLCP);\r\n\t }\r\n throw ex;\r\n }\r\n }\r\n \r\n //delegates\r\n public interface LeavingVariableDelegate { \r\n \tpublic int getLeavingVar(int enter) throws RayTerminationException; \r\n \tpublic boolean canZ0Leave();\r\n\t}\r\n public interface OnInitDelegate { public void onInit(String message, Tableau A); }\r\n public interface OnCompleteDelegate { public void onComplete(String message, Tableau A); }\r\n public interface OnPivotDelegate { public void onPivot(int leave, int enter, TableauVariables vars); }\r\n public interface OnTableauChangeDelegate { public void onTableauChange(String message, Tableau A); }\r\n public interface OnLexCompleteDelegate { public void onLexComplete(LexicographicMethod lex); }\r\n public interface OnLexRayTerminationDelegate { \r\n public void onLexRayTermination(int enter, Tableau end, LCP start); \r\n }\r\n \r\n @SuppressWarnings(\"serial\")\r\n public static class LemkeException extends Exception { \t\r\n\t\tpublic LemkeException(String message) {\r\n \t\tsuper(message);\r\n \t}\r\n }\r\n \r\n @SuppressWarnings(\"serial\")\r\n public static class InvalidLCPException extends LemkeException {\r\n\t\tpublic InvalidLCPException(String message) {\r\n \t\tsuper(message);\r\n \t}\r\n }\r\n \r\n @SuppressWarnings(\"serial\")\r\n\tpublic static class TrivialSolutionException extends LemkeException \r\n { \t\t\t\r\n\t\tpublic TrivialSolutionException(String message) {\r\n \t\tsuper(message);\r\n \t}\r\n }\r\n \r\n @SuppressWarnings(\"serial\")\r\n public static class RayTerminationException extends LemkeException {\r\n\t\tpublic Tableau A;\r\n\t\tpublic LCP start;\r\n\r\n\t\tpublic RayTerminationException(String error, Tableau A, LCP start) \r\n\t\t{ \r\n\t\t\tsuper(error);\r\n\t\t\tthis.A = A;\r\n\t\t\tthis.start = start;\r\n\t\t}\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic String getMessage()\r\n\t\t{\r\n\t\t\tStringBuilder sb = new StringBuilder()\r\n\t\t\t\t.append(super.getMessage())\r\n\t\t\t\t.append(System.getProperty(\"line.separator\"))\r\n\t\t\t\t.append(start != null ? start.toString() : \"LCP is null\")\r\n\t\t\t\t.append(System.getProperty(\"line.separator\"))\r\n\t\t\t\t.append(A.toString());\r\n\t\t\treturn sb.toString();\r\n\t\t}\r\n }\r\n}\r", " @SuppressWarnings(\"serial\")\r\n public static class LemkeException extends Exception { \t\r\npublic LemkeException(String message) {\r\n \t\tsuper(message);\r\n \t}\r\n }\r" ]
import java.io.PrintWriter; import java.util.List; import java.util.Random; import java.util.logging.Logger; import lse.math.games.Rational; import lse.math.games.lrs.Lrs; import lse.math.games.lrs.HPolygon; import lse.math.games.lrs.VPolygon; import lse.math.games.lcp.LCP; import lse.math.games.lcp.LemkeAlgorithm; import lse.math.games.lcp.LemkeAlgorithm.LemkeException;
package lse.math.games.matrix; public class BimatrixSolver { private static final Logger log = Logger.getLogger(BimatrixSolver.class.getName()); public Rational[] computePriorBeliefs(int size, Random prng) { Rational[] priors = null; if (prng != null) { priors = Rational.probVector(size, prng); } else { priors = new Rational[size]; Rational prob = Rational.ONE.divide(Rational.valueOf(size)); for (int i = 0; i < size; ++i) { priors[i] = prob; } } return priors; } public Equilibrium findOneEquilibrium(LemkeAlgorithm lemke, Rational[][] a, Rational[][] b, Rational[] xPriors, Rational[] yPriors, PrintWriter out) throws LemkeException { // 1. Adjust the payoffs to be strictly negative (max = -1) Rational payCorrectA = BimatrixSolver.correctPaymentsNeg(a); Rational payCorrectB = BimatrixSolver.correctPaymentsNeg(b); // 2. Generate the LCP from the two payoff matrices and the priors
LCP lcp = BimatrixSolver.generateLCP(a, b, xPriors, yPriors);
4
jramoyo/quickfix-messenger
src/main/java/com/jramoyo/qfixmessenger/ui/ProjectDialog.java
[ "public class ProjectTreeCellEditor extends DefaultTreeCellEditor\r\n{\r\n\tpublic ProjectTreeCellEditor(JTree tree)\r\n\t{\r\n\t\tsuper(tree, null);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isCellEditable(EventObject event)\r\n\t{\r\n\t\tif (super.isCellEditable(event))\r\n\t\t{\r\n\t\t\tObject value = tree.getLastSelectedPathComponent();\r\n\t\t\tif (value instanceof String)\r\n\t\t\t{\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n}\r", "public class ProjectTreeMouseListener extends MouseAdapter\r\n{\r\n\tprivate final QFixMessengerFrame frame;\r\n\r\n\tprivate final JTree projectTree;\r\n\r\n\tpublic ProjectTreeMouseListener(QFixMessengerFrame frame, JTree projectTree)\r\n\t{\r\n\t\tthis.frame = frame;\r\n\t\tthis.projectTree = projectTree;\r\n\t}\r\n\r\n\tpublic void mouseClicked(MouseEvent event)\r\n\t{\r\n\t\tif (event.getButton() == MouseEvent.BUTTON3)\r\n\t\t{\r\n\t\t\tJPopupMenu popUpMenu = new JPopupMenu();\r\n\r\n\t\t\tJMenuItem sendAllMenuItem = new JMenuItem(\"Send All Messages\");\r\n\t\t\tsendAllMenuItem.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t.getConfig(), IconBuilder.SEND_ALL_ICON));\r\n\t\t\tsendAllMenuItem.addActionListener(new ActionListener()\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (MessageType xmlMessageType : frame\r\n\t\t\t\t\t\t\t.getActiveXmlProject().getMessages().getMessage())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttry\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tframe.getMessenger().sendXmlMessage(xmlMessageType);\r\n\t\t\t\t\t\t} catch (QFixMessengerException ex)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tJOptionPane.showMessageDialog(\r\n\t\t\t\t\t\t\t\t\tframe.getProjectFrame(),\r\n\t\t\t\t\t\t\t\t\t\"Unable to send message:\\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t+ ex.getMessage(), \"Error\",\r\n\t\t\t\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\tJMenuItem collapseAllMenuItem = new JMenuItem(\"Collapse All\");\r\n\t\t\tcollapseAllMenuItem.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t.getConfig(), IconBuilder.COLLAPSE_ICON));\r\n\t\t\tcollapseAllMenuItem.addActionListener(new ActionListener()\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t{\r\n\t\t\t\t\tsynchronized (projectTree)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tint row = projectTree.getRowCount() - 1;\r\n\t\t\t\t\t\twhile (row > 1)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tprojectTree.collapseRow(row);\r\n\t\t\t\t\t\t\trow--;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\tJMenuItem expandAllMenuItem = new JMenuItem(\"Expand All\");\r\n\t\t\texpandAllMenuItem.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t.getConfig(), IconBuilder.EXPAND_ICON));\r\n\t\t\texpandAllMenuItem.addActionListener(new ActionListener()\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t{\r\n\t\t\t\t\tsynchronized (projectTree)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tint row = 0;\r\n\t\t\t\t\t\twhile (row < projectTree.getRowCount())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tprojectTree.expandRow(row);\r\n\t\t\t\t\t\t\trow++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\tif (projectTree.getLastSelectedPathComponent() != null\r\n\t\t\t\t\t&& projectTree.getLastSelectedPathComponent() instanceof MessageType)\r\n\t\t\t{\r\n\t\t\t\tJMenuItem loadMessageMenuItem = new JMenuItem(\"Load Message\");\r\n\t\t\t\tloadMessageMenuItem.setIcon(IconBuilder.build(frame\r\n\t\t\t\t\t\t.getMessenger().getConfig(), IconBuilder.LOAD_ICON));\r\n\t\t\t\tloadMessageMenuItem.addActionListener(new ActionListener()\r\n\t\t\t\t{\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMessageType xmlMessageType = (MessageType) projectTree\r\n\t\t\t\t\t\t\t\t.getLastSelectedPathComponent();\r\n\t\t\t\t\t\tframe.loadXmlMessage(xmlMessageType);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\tJMenuItem sendMenuItem = new JMenuItem(\"Send Message\");\r\n\t\t\t\tsendMenuItem.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.SEND_SMALL_ICON));\r\n\t\t\t\tsendMenuItem.addActionListener(new ActionListener()\r\n\t\t\t\t{\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMessageType xmlMessageType = (MessageType) projectTree\r\n\t\t\t\t\t\t\t\t.getLastSelectedPathComponent();\r\n\t\t\t\t\t\ttry\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tframe.getMessenger().sendXmlMessage(xmlMessageType);\r\n\t\t\t\t\t\t} catch (QFixMessengerException ex)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tJOptionPane.showMessageDialog(\r\n\t\t\t\t\t\t\t\t\tframe.getProjectFrame(),\r\n\t\t\t\t\t\t\t\t\t\"Unable to send message:\\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t+ ex.getMessage(), \"Error\",\r\n\t\t\t\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\tJMenuItem exportMenuItem = new JMenuItem(\"Export Message\");\r\n\t\t\t\texportMenuItem.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.EXPORT_ICON));\r\n\t\t\t\texportMenuItem.addActionListener(new ActionListener()\r\n\t\t\t\t{\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMessageType xmlMessageType = (MessageType) projectTree\r\n\t\t\t\t\t\t\t\t.getLastSelectedPathComponent();\r\n\t\t\t\t\t\tframe.marshallXmlMessage(xmlMessageType);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\tJMenuItem deleteMessageMenuItem = new JMenuItem(\r\n\t\t\t\t\t\t\"Delete Message\");\r\n\t\t\t\tdeleteMessageMenuItem.setIcon(IconBuilder.build(frame\r\n\t\t\t\t\t\t.getMessenger().getConfig(), IconBuilder.DELETE_ICON));\r\n\t\t\t\tdeleteMessageMenuItem.addActionListener(new ActionListener()\r\n\t\t\t\t{\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMessageType xmlMessageType = (MessageType) projectTree\r\n\t\t\t\t\t\t\t\t.getLastSelectedPathComponent();\r\n\r\n\t\t\t\t\t\tint choice = JOptionPane.showConfirmDialog(\r\n\t\t\t\t\t\t\t\tframe.getProjectFrame(), \"Delete \\\"\"\r\n\t\t\t\t\t\t\t\t\t\t+ xmlMessageType.getName() + \"\\\"?\",\r\n\t\t\t\t\t\t\t\t\"Delete Message\", JOptionPane.YES_NO_OPTION);\r\n\t\t\t\t\t\tif (choice == JOptionPane.YES_OPTION)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tProjectTreeModel projectTreeModel = (ProjectTreeModel) projectTree\r\n\t\t\t\t\t\t\t\t\t.getModel();\r\n\t\t\t\t\t\t\tProjectType xmlProjectType = (ProjectType) projectTreeModel\r\n\t\t\t\t\t\t\t\t\t.getRoot();\r\n\t\t\t\t\t\t\tint index = 0;\r\n\t\t\t\t\t\t\tfor (MessageType currentXmlMessageType : xmlProjectType\r\n\t\t\t\t\t\t\t\t\t.getMessages().getMessage())\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tif (currentXmlMessageType\r\n\t\t\t\t\t\t\t\t\t\t.equals(xmlMessageType))\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tindex++;\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\txmlProjectType.getMessages().getMessage()\r\n\t\t\t\t\t\t\t\t\t.remove(index);\r\n\t\t\t\t\t\t\tprojectTreeModel.updateMessageRemoved(\r\n\t\t\t\t\t\t\t\t\txmlMessageType, index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\tpopUpMenu.add(loadMessageMenuItem);\r\n\t\t\t\tpopUpMenu.add(sendMenuItem);\r\n\t\t\t\tpopUpMenu.add(exportMenuItem);\r\n\t\t\t\tpopUpMenu.add(deleteMessageMenuItem);\r\n\t\t\t\tpopUpMenu.addSeparator();\r\n\t\t\t\tpopUpMenu.add(sendAllMenuItem);\r\n\t\t\t\tpopUpMenu.addSeparator();\r\n\t\t\t\tpopUpMenu.add(collapseAllMenuItem);\r\n\t\t\t\tpopUpMenu.add(expandAllMenuItem);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tpopUpMenu.add(sendAllMenuItem);\r\n\t\t\t\tpopUpMenu.addSeparator();\r\n\t\t\t\tpopUpMenu.add(collapseAllMenuItem);\r\n\t\t\t\tpopUpMenu.add(expandAllMenuItem);\r\n\t\t\t}\r\n\r\n\t\t\tpopUpMenu.show(projectTree, event.getX(), event.getY());\r\n\t\t}\r\n\t}\r\n}\r", "public class ProjectTreeModel implements TreeModel\r\n{\r\n\tprivate ProjectType xmlProjectType;\r\n\r\n\tprivate EventListenerList eventListenerList;\r\n\r\n\tpublic ProjectTreeModel(ProjectType xmlProjectType)\r\n\t{\r\n\t\tthis.xmlProjectType = xmlProjectType;\r\n\t\teventListenerList = new EventListenerList();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void addTreeModelListener(TreeModelListener listener)\r\n\t{\r\n\t\teventListenerList.add(TreeModelListener.class, listener);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Object getChild(Object parent, int index)\r\n\t{\r\n\t\tif (parent instanceof ProjectType)\r\n\t\t{\r\n\t\t\tif (index == 0)\r\n\t\t\t{\r\n\t\t\t\treturn ((ProjectType) parent).getMessages();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof MessagesType)\r\n\t\t{\r\n\t\t\treturn ((MessagesType) parent).getMessage().get(index);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof MessageType)\r\n\t\t{\r\n\t\t\tMessageType xmlMessageType = (MessageType) parent;\r\n\t\t\tswitch (index)\r\n\t\t\t{\r\n\t\t\tcase 0:\r\n\t\t\t\treturn xmlMessageType.getSession();\r\n\t\t\tcase 1:\r\n\t\t\t\tif (xmlMessageType.getHeader() != null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn xmlMessageType.getHeader();\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\treturn xmlMessageType.getBody();\r\n\t\t\t\t}\r\n\t\t\tcase 2:\r\n\t\t\t\tif (xmlMessageType.getHeader() != null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn xmlMessageType.getBody();\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\treturn xmlMessageType.getTrailer();\r\n\t\t\t\t}\r\n\t\t\tcase 3:\r\n\t\t\t\treturn xmlMessageType.getTrailer();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof SessionType)\r\n\t\t{\r\n\t\t\tSessionType xmlSessionType = (SessionType) parent;\r\n\t\t\tswitch (index)\r\n\t\t\t{\r\n\t\t\tcase 0:\r\n\t\t\t\treturn xmlSessionType.getName();\r\n\t\t\tcase 1:\r\n\t\t\t\treturn xmlSessionType.getAppVersionId();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof HeaderType)\r\n\t\t{\r\n\t\t\treturn ((HeaderType) parent).getField().get(index);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof BodyType)\r\n\t\t{\r\n\t\t\treturn ((BodyType) parent).getFieldOrGroupsOrComponent().get(index);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof TrailerType)\r\n\t\t{\r\n\t\t\treturn ((TrailerType) parent).getField().get(index);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof GroupsType)\r\n\t\t{\r\n\t\t\treturn ((GroupsType) parent).getGroup().get(index);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof GroupType)\r\n\t\t{\r\n\t\t\treturn ((GroupType) parent).getFieldOrGroupsOrComponent()\r\n\t\t\t\t\t.get(index);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof ComponentType)\r\n\t\t{\r\n\t\t\treturn ((ComponentType) parent).getFieldOrGroupsOrComponent().get(\r\n\t\t\t\t\tindex);\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof FieldType)\r\n\t\t{\r\n\t\t\tif (index == 0)\r\n\t\t\t{\r\n\t\t\t\treturn ((FieldType) parent).getValue();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getChildCount(Object parent)\r\n\t{\r\n\t\tif (parent instanceof ProjectType)\r\n\t\t{\r\n\t\t\tProjectType xmlProjectType = (ProjectType) parent;\r\n\t\t\tif (xmlProjectType.getMessages() != null)\r\n\t\t\t{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof MessagesType)\r\n\t\t{\r\n\t\t\tMessagesType xmlMessagesType = (MessagesType) parent;\r\n\t\t\treturn xmlMessagesType.getMessage().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof MessageType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\r\n\t\t\tMessageType xmlMessageType = (MessageType) parent;\r\n\t\t\tif (xmlMessageType.getSession() != null)\r\n\t\t\t{\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\tif (xmlMessageType.getHeader() != null)\r\n\t\t\t{\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\tif (xmlMessageType.getBody() != null)\r\n\t\t\t{\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\tif (xmlMessageType.getTrailer() != null)\r\n\t\t\t{\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\treturn i;\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof SessionType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\r\n\t\t\tSessionType xmlSessionType = (SessionType) parent;\r\n\t\t\tif (xmlSessionType.getName() != null)\r\n\t\t\t{\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\tif (xmlSessionType.getAppVersionId() != null)\r\n\t\t\t{\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\r\n\t\t\treturn i;\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof HeaderType)\r\n\t\t{\r\n\t\t\tHeaderType xmlHeaderType = (HeaderType) parent;\r\n\t\t\treturn xmlHeaderType.getField().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof BodyType)\r\n\t\t{\r\n\t\t\tBodyType xmlBodyType = (BodyType) parent;\r\n\t\t\treturn xmlBodyType.getFieldOrGroupsOrComponent().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof TrailerType)\r\n\t\t{\r\n\t\t\tTrailerType xmlTrailerType = (TrailerType) parent;\r\n\t\t\treturn xmlTrailerType.getField().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof GroupsType)\r\n\t\t{\r\n\t\t\tGroupsType groupsType = (GroupsType) parent;\r\n\t\t\treturn groupsType.getGroup().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof GroupType)\r\n\t\t{\r\n\t\t\tGroupType xmlGroupType = (GroupType) parent;\r\n\t\t\treturn xmlGroupType.getFieldOrGroupsOrComponent().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof ComponentType)\r\n\t\t{\r\n\t\t\tComponentType xmlComponentType = (ComponentType) parent;\r\n\t\t\treturn xmlComponentType.getFieldOrGroupsOrComponent().size();\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof FieldType)\r\n\t\t{\r\n\t\t\tFieldType xmlFieldType = (FieldType) parent;\r\n\t\t\tif (xmlFieldType.getValue() != null)\r\n\t\t\t{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int getIndexOfChild(Object parent, Object child)\r\n\t{\r\n\t\tif (parent instanceof ProjectType)\r\n\t\t{\r\n\t\t\tProjectType xmlProjectType = (ProjectType) parent;\r\n\t\t\tif (child.equals(xmlProjectType.getMessages()))\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof MessagesType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tMessagesType xmlMessagesType = (MessagesType) parent;\r\n\t\t\tfor (MessageType xmlMessageType : xmlMessagesType.getMessage())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlMessageType))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof MessageType)\r\n\t\t{\r\n\t\t\tMessageType xmlMessageType = (MessageType) parent;\r\n\t\t\tif (child.equals(xmlMessageType.getSession()))\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\r\n\t\t\tif (child.equals(xmlMessageType.getHeader()))\r\n\t\t\t{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\r\n\t\t\tif (child.equals(xmlMessageType.getBody()))\r\n\t\t\t{\r\n\t\t\t\tif (xmlMessageType.getHeader() != null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn 2;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (child.equals(xmlMessageType.getTrailer()))\r\n\t\t\t{\r\n\t\t\t\tif (xmlMessageType.getHeader() != null)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn 3;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\treturn 2;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof SessionType)\r\n\t\t{\r\n\t\t\tSessionType xmlSessionType = (SessionType) parent;\r\n\t\t\tif (child.equals(xmlSessionType.getName()))\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\r\n\t\t\tif (child.equals(xmlSessionType.getAppVersionId()))\r\n\t\t\t{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof HeaderType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tHeaderType xmlHeaderType = (HeaderType) parent;\r\n\t\t\tfor (FieldType xmlFieldType : xmlHeaderType.getField())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlFieldType))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof BodyType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tBodyType xmlBodyType = (BodyType) parent;\r\n\t\t\tfor (Object xmlObject : xmlBodyType.getFieldOrGroupsOrComponent())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlObject))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof TrailerType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tTrailerType xmlTrailerType = (TrailerType) parent;\r\n\t\t\tfor (FieldType xmlFieldType : xmlTrailerType.getField())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlFieldType))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof GroupsType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tGroupsType groupsType = (GroupsType) parent;\r\n\t\t\tfor (GroupType xmlGroupType : groupsType.getGroup())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlGroupType))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof GroupType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tGroupType xmlGroupType = (GroupType) parent;\r\n\t\t\tfor (Object xmlObject : xmlGroupType.getFieldOrGroupsOrComponent())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlObject))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof ComponentType)\r\n\t\t{\r\n\t\t\tint i = 0;\r\n\t\t\tComponentType xmlComponentType = (ComponentType) parent;\r\n\t\t\tfor (Object xmlObject : xmlComponentType\r\n\t\t\t\t\t.getFieldOrGroupsOrComponent())\r\n\t\t\t{\r\n\t\t\t\tif (child.equals(xmlObject))\r\n\t\t\t\t{\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (parent instanceof FieldType)\r\n\t\t{\r\n\t\t\tFieldType xmlFieldType = (FieldType) parent;\r\n\t\t\tif (child.equals(xmlFieldType.getValue()))\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn -1;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Object getRoot()\r\n\t{\r\n\t\treturn xmlProjectType;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the listeners to this tree model\r\n\t * \r\n\t * @return the listeners to this tree model\r\n\t */\r\n\tpublic TreeModelListener[] getTreeModelListeners()\r\n\t{\r\n\t\treturn (TreeModelListener[]) eventListenerList\r\n\t\t\t\t.getListeners(TreeModelListener.class);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isLeaf(Object node)\r\n\t{\r\n\t\tif (node instanceof String)\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t} else\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void removeTreeModelListener(TreeModelListener listener)\r\n\t{\r\n\t\teventListenerList.remove(TreeModelListener.class, listener);\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the entire tree model\r\n\t */\r\n\tpublic void update()\r\n\t{\r\n\t\tint n = getChildCount(xmlProjectType);\r\n\t\tint[] childIdx = new int[n];\r\n\t\tObject[] children = new Object[n];\r\n\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t{\r\n\t\t\tchildIdx[i] = i;\r\n\t\t\tchildren[i] = getChild(xmlProjectType, i);\r\n\t\t}\r\n\r\n\t\tfireTreeStructureChanged(this, new Object[] { xmlProjectType },\r\n\t\t\t\tchildIdx, children);\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tree model that a message has been added to the project\r\n\t * \r\n\t * @param xmlMessageType\r\n\t * the added XML MessageType\r\n\t */\r\n\tpublic void updateMessageAdded(MessageType xmlMessageType)\r\n\t{\r\n\t\tObject[] path = { xmlProjectType, xmlProjectType.getMessages() };\r\n\t\tint[] childIndices = { getIndexOfChild(xmlProjectType.getMessages(),\r\n\t\t\t\txmlMessageType) };\r\n\t\tObject[] children = { xmlMessageType };\r\n\t\tfireTreeNodesInserted(this, path, childIndices, children);\r\n\t}\r\n\r\n\t/**\r\n\t * Updates the tree model that a message has been removed from the project\r\n\t * \r\n\t * @param xmlMessageType\r\n\t * the removed XML MessageType\r\n\t */\r\n\tpublic void updateMessageRemoved(MessageType xmlMessageType, int index)\r\n\t{\r\n\t\tObject[] path = { xmlProjectType, xmlProjectType.getMessages() };\r\n\t\tint[] childIndices = { index };\r\n\t\tObject[] children = { xmlMessageType };\r\n\t\tfireTreeNodesRemoved(this, path, childIndices, children);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void valueForPathChanged(TreePath treePath, Object newValue)\r\n\t{\r\n\t\tObject[] path;\r\n\t\tint[] childIndices = null;\r\n\t\tObject[] children = null;\r\n\t\tif (treePath.getPathCount() > 1)\r\n\t\t{\r\n\t\t\tObject parent = treePath.getParentPath().getLastPathComponent();\r\n\t\t\tif (parent instanceof FieldType)\r\n\t\t\t{\r\n\t\t\t\t((FieldType) parent).setValue((String) newValue);\r\n\t\t\t\tchildIndices = new int[] { 0 };\r\n\t\t\t}\r\n\r\n\t\t\telse if (parent instanceof SessionType)\r\n\t\t\t{\r\n\t\t\t\t/*\r\n\t\t\t\t * TODO Find a better way to know whether the new value is a\r\n\t\t\t\t * session name or an application version\r\n\t\t\t\t */\r\n\t\t\t\tString newString = (String) newValue;\r\n\t\t\t\tif ((newString.contains(\"FIX.\") || (newString.contains(\"FIXT.\")))\r\n\t\t\t\t\t\t&& newString.contains(\">\"))\r\n\t\t\t\t{\r\n\t\t\t\t\t((SessionType) parent).setName(newString);\r\n\t\t\t\t\tchildIndices = new int[] { 0 };\r\n\t\t\t\t} else if (newString.contains(\"FIX.\"))\r\n\t\t\t\t{\r\n\t\t\t\t\t((SessionType) parent).setAppVersionId(newString);\r\n\t\t\t\t\tchildIndices = new int[] { 1 };\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttreePath = treePath.getParentPath().pathByAddingChild(newValue);\r\n\t\t\tpath = treePath.getParentPath().getPath();\r\n\t\t\tchildren = new Object[] { newValue };\r\n\t\t} else\r\n\t\t{\r\n\t\t\tpath = treePath.getPath();\r\n\t\t}\r\n\r\n\t\tfireTreeNodesChanged(this, path, childIndices, children);\r\n\t}\r\n\r\n\tprotected void fireTreeNodesChanged(Object source, Object[] path,\r\n\t\t\tint[] childIndices, Object[] children)\r\n\t{\r\n\t\tTreeModelEvent event = new TreeModelEvent(source, path, childIndices,\r\n\t\t\t\tchildren);\r\n\t\tfor (TreeModelListener listener : getTreeModelListeners())\r\n\t\t{\r\n\t\t\tlistener.treeNodesChanged(event);\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void fireTreeNodesInserted(Object source, Object[] path,\r\n\t\t\tint[] childIndices, Object[] children)\r\n\t{\r\n\t\tTreeModelEvent event = new TreeModelEvent(source, path, childIndices,\r\n\t\t\t\tchildren);\r\n\t\tfor (TreeModelListener listener : getTreeModelListeners())\r\n\t\t{\r\n\t\t\tlistener.treeNodesInserted(event);\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void fireTreeNodesRemoved(Object source, Object[] path,\r\n\t\t\tint[] childIndices, Object[] children)\r\n\t{\r\n\t\tTreeModelEvent event = new TreeModelEvent(source, path, childIndices,\r\n\t\t\t\tchildren);\r\n\t\tfor (TreeModelListener listener : getTreeModelListeners())\r\n\t\t{\r\n\t\t\tlistener.treeNodesRemoved(event);\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void fireTreeStructureChanged(Object source, Object[] path,\r\n\t\t\tint[] childIndices, Object[] children)\r\n\t{\r\n\t\tTreeModelEvent event = new TreeModelEvent(source, path, childIndices,\r\n\t\t\t\tchildren);\r\n\t\tfor (TreeModelListener listener : getTreeModelListeners())\r\n\t\t{\r\n\t\t\tlistener.treeStructureChanged(event);\r\n\t\t}\r\n\t}\r\n}\r", "public class ProjectTreeCellRenderer extends DefaultTreeCellRenderer\r\n{\r\n\tprivate static final long serialVersionUID = -435212244413010769L;\r\n\r\n\tprivate final QFixMessengerFrame frame;\r\n\r\n\tpublic ProjectTreeCellRenderer(QFixMessengerFrame frame)\r\n\t{\r\n\t\tthis.frame = frame;\r\n\t}\r\n\r\n\tpublic Component getTreeCellRendererComponent(JTree tree, Object value,\r\n\t\t\tboolean sel, boolean expanded, boolean leaf, int row,\r\n\t\t\tboolean hasFocus)\r\n\t{\r\n\t\tJLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value,\r\n\t\t\t\tsel, expanded, leaf, row, hasFocus);\r\n\r\n\t\tif (value instanceof ProjectType)\r\n\t\t{\r\n\t\t\tProjectType xmlProjectType = (ProjectType) value;\r\n\t\t\tlabel.setText(xmlProjectType.getName());\r\n\t\t\tif (expanded)\r\n\t\t\t{\r\n\t\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.PROJECT_OPEN_ICON));\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.PROJECT_ICON));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (value instanceof MessagesType)\r\n\t\t{\r\n\t\t\tlabel.setText(\"Messages\");\r\n\t\t\tif (expanded)\r\n\t\t\t{\r\n\t\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.MESSAGES_OPEN_ICON));\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.MESSAGES_ICON));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (value instanceof MessageType)\r\n\t\t{\r\n\t\t\tMessageType xmlMessageType = (MessageType) value;\r\n\t\t\tlabel.setText(xmlMessageType.getName() + \" (\"\r\n\t\t\t\t\t+ xmlMessageType.getMsgType() + \")\");\r\n\t\t\tif (expanded)\r\n\t\t\t{\r\n\t\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.MESSAGE_OPEN_ICON));\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.MESSAGE_ICON));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (value instanceof SessionType)\r\n\t\t{\r\n\t\t\tlabel.setText(\"Session\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.SESSION_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof HeaderType)\r\n\t\t{\r\n\t\t\tlabel.setText(\"Header\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.COMPONENT_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof BodyType)\r\n\t\t{\r\n\t\t\tlabel.setText(\"Body\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.COMPONENT_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof TrailerType)\r\n\t\t{\r\n\t\t\tlabel.setText(\"Trailer\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.COMPONENT_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof GroupsType)\r\n\t\t{\r\n\t\t\tGroupsType xmlGroupsType = (GroupsType) value;\r\n\t\t\tlabel.setText(xmlGroupsType.getName() + \" (\"\r\n\t\t\t\t\t+ xmlGroupsType.getId() + \")\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.GROUPS_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof GroupType)\r\n\t\t{\r\n\t\t\tlabel.setText(\"Group\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.GROUP_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof ComponentType)\r\n\t\t{\r\n\t\t\tComponentType xmlComponentType = (ComponentType) value;\r\n\t\t\tlabel.setText(xmlComponentType.getName());\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.COMPONENT_ICON));\r\n\t\t}\r\n\r\n\t\telse if (value instanceof FieldType)\r\n\t\t{\r\n\t\t\tFieldType xmlFieldType = (FieldType) value;\r\n\t\t\tlabel.setText(xmlFieldType.getName() + \" (\" + xmlFieldType.getId()\r\n\t\t\t\t\t+ \")\");\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.FIELD_ICON));\r\n\t\t}\r\n\r\n\t\telse\r\n\t\t{\r\n\t\t\tlabel.setIcon(IconBuilder.build(frame.getMessenger().getConfig(),\r\n\t\t\t\t\tIconBuilder.TEXT_ICON));\r\n\t\t}\r\n\r\n\t\treturn label;\r\n\t}\r\n}\r", "public final class IconBuilder\n{\n\tpublic static String APP_ICON = \"app.png\";\n\n\tpublic static String ADD_ICON = \"add.png\";\n\tpublic static String SEND_ICON = \"send.png\";\n\tpublic static String DESTROY_ICON = \"destroy.png\";\n\n\tpublic static String NEW_ICON = \"new.png\";\n\tpublic static String OPEN_ICON = \"open.png\";\n\tpublic static String SAVE_ICON = \"save.png\";\n\tpublic static String CLOSE_ICON = \"close.png\";\n\tpublic static String IMPORT_ICON = \"import.png\";\n\n\tpublic static String EXPORT_ICON = \"export.png\";\n\tpublic static String EXIT_ICON = \"exit.png\";\n\n\tpublic static String LOGON_ICON = \"logon.png\";\n\n\tpublic static String LOGOFF_ICON = \"logoff.png\";\n\tpublic static String RESET_ICON = \"reset.png\";\n\tpublic static String HELP_ICON = \"help.png\";\n\n\tpublic static String WINDOW_ICON = \"window.png\";\n\n\tpublic static String LOAD_ICON = \"load.png\";\n\n\tpublic static String DELETE_ICON = \"delete.png\";\n\tpublic static String SEND_SMALL_ICON = \"send-small.png\";\n\tpublic static String SEND_ALL_ICON = \"send-all.png\";\n\tpublic static String COLLAPSE_ICON = \"collapse.png\";\n\tpublic static String EXPAND_ICON = \"expand.png\";\n\tpublic static String PROJECT_ICON = \"project.png\";\n\n\tpublic static String PROJECT_OPEN_ICON = \"project-open.png\";\n\tpublic static String MESSAGES_ICON = \"messages.png\";\n\tpublic static String MESSAGES_OPEN_ICON = \"messages-open.png\";\n\tpublic static String MESSAGE_ICON = \"message.png\";\n\tpublic static String MESSAGE_OPEN_ICON = \"message-open.png\";\n\tpublic static String SESSION_ICON = \"session.png\";\n\tpublic static String COMPONENT_ICON = \"component.png\";\n\tpublic static String GROUP_ICON = \"group.png\";\n\tpublic static String GROUPS_ICON = \"groups.png\";\n\tpublic static String FIELD_ICON = \"field.png\";\n\tpublic static String TEXT_ICON = \"text.png\";\n\n\tpublic static String CLEAR_ALL_ICON = \"clear-all.png\";\n\tpublic static String INVALID_FIELD = \"invalid-field.png\";\n\n\tpublic static ImageIcon build(QFixMessengerConfig config, String path)\n\t{\n\t\tString res = String.format(\"%s/%s\", config.getIconsLocation(), path);\n\t\treturn new ImageIcon(IconBuilder.class.getResource(res));\n\t}\n}" ]
import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.BoxLayout; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.TreeSelectionModel; import com.jramoyo.fix.xml.MessageType; import com.jramoyo.fix.xml.ProjectType; import com.jramoyo.qfixmessenger.ui.editors.ProjectTreeCellEditor; import com.jramoyo.qfixmessenger.ui.listeners.ProjectTreeMouseListener; import com.jramoyo.qfixmessenger.ui.models.ProjectTreeModel; import com.jramoyo.qfixmessenger.ui.renderers.ProjectTreeCellRenderer; import com.jramoyo.qfixmessenger.ui.util.IconBuilder;
/* * Copyright (c) 2011, Jan Amoyo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * ProjectDialog.java * Sep 23, 2012 */ package com.jramoyo.qfixmessenger.ui; /** * ProjectDialog * * @author jramoyo */ public class ProjectDialog extends JDialog { private static final long serialVersionUID = -1653220967743151936L; private final QFixMessengerFrame frame; private final ProjectType xmlProjectType; private JPanel mainPanel; private JTree projectTree; public ProjectDialog(QFixMessengerFrame frame, ProjectType xmlProjectType) { this.frame = frame; this.xmlProjectType = xmlProjectType; } /** * Launches the frame */ public void launch() { initDialog(); initComponents(); positionFrame(); setVisible(true); } /** * Reloads the project tree */ public void reload() {
((ProjectTreeModel) projectTree.getModel()).update();
2
OasisDigital/nges
src/test/java/com/oasisdigital/nges/event/EventStoreITest.java
[ "public interface MessageGroup {\n\n /**\n * Publish a message to the group.\n */\n public abstract void publish(Object message);\n\n /**\n * Register a subscriber for messages from the group. See documentation for a particular implementation to\n * learn more about its specifics.\n */\n public abstract void registerSubscriber(Object subscriber);\n\n /**\n * Unregister a subscriber from the group.\n */\n public abstract void unregisterSubscriber(Object subscriber);\n\n}", "public class EventStoreConflict extends EventStoreException {\n private static final long serialVersionUID = 1L;\n\n public EventStoreConflict() {\n super();\n }\n\n public EventStoreConflict(String message, Throwable cause, boolean enableSuppression,\n boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n\n public EventStoreConflict(String message, Throwable cause) {\n super(message, cause);\n }\n\n public EventStoreConflict(String message) {\n super(message);\n }\n\n public EventStoreConflict(Throwable cause) {\n super(cause);\n }\n\n}", "public class EventStream {\n private UUID streamId;\n private String streamType;\n private Long lastEventId;\n private OffsetDateTime lastTransactionTime;\n private Long lastSeqNo;\n\n public UUID getStreamId() {\n return streamId;\n }\n\n public void setStreamId(UUID streamId) {\n this.streamId = streamId;\n }\n\n public String getStreamType() {\n return streamType;\n }\n\n public void setStreamType(String streamType) {\n this.streamType = streamType;\n }\n\n public Long getLastEventId() {\n return lastEventId;\n }\n\n public void setLastEventId(Long lastEventId) {\n this.lastEventId = lastEventId;\n }\n\n public OffsetDateTime getLastTransactionTime() {\n return lastTransactionTime;\n }\n\n public void setLastTransactionTime(OffsetDateTime lastTransactionTime) {\n this.lastTransactionTime = lastTransactionTime;\n }\n\n public Long getLastSeqNo() {\n return lastSeqNo;\n }\n\n public void setLastSeqNo(Long lastSeqNo) {\n this.lastSeqNo = lastSeqNo;\n }\n\n}", "public class Lease {\n private String leaseKey;\n private String ownerKey;\n private OffsetDateTime expirationDate;\n\n public String getLeaseKey() {\n return leaseKey;\n }\n\n public void setLeaseKey(String leaseKey) {\n this.leaseKey = leaseKey;\n }\n\n public String getOwnerKey() {\n return ownerKey;\n }\n\n public void setOwnerKey(String ownerKey) {\n this.ownerKey = ownerKey;\n }\n\n public OffsetDateTime getExpirationDate() {\n return expirationDate;\n }\n\n public void setExpirationDate(OffsetDateTime expirationDate) {\n this.expirationDate = expirationDate;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((expirationDate == null) ? 0 : expirationDate.hashCode());\n result = prime * result + ((leaseKey == null) ? 0 : leaseKey.hashCode());\n result = prime * result + ((ownerKey == null) ? 0 : ownerKey.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Lease other = (Lease) obj;\n if (expirationDate == null) {\n if (other.expirationDate != null)\n return false;\n } else if (!expirationDate.equals(other.expirationDate))\n return false;\n if (leaseKey == null) {\n if (other.leaseKey != null)\n return false;\n } else if (!leaseKey.equals(other.leaseKey))\n return false;\n if (ownerKey == null) {\n if (other.ownerKey != null)\n return false;\n } else if (!ownerKey.equals(other.ownerKey))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return leaseKey + \":\" + ownerKey + \":\" + expirationDate;\n }\n\n public boolean isOwnedBy(String owner) {\n return getOwnerKey().equals(owner);\n }\n}", "public class Event implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * <p>\n * Number assigned from a globally increasing sequence. Might contain holes, i.e. it is possible for\n * events with IDs 100 and 102 to exist without an event with ID 101. Event with ID N+1 must have been\n * saved after the event with ID N.\n * </p>\n * <p>\n * Automatically populated by the system on save, never empty.\n * </p>\n */\n private long eventId;\n\n /**\n * ID of a stream of events, for example identifying a DDD aggregeate or another kind of entity. Populated\n * by the caller on save, mandatory.\n */\n private UUID streamId;\n\n /**\n * Type of the event, useful for interpreting the payload etc. Populated by the caller on save.\n */\n private String type;\n\n /**\n * Correlation ID. Populated by the caller on save, mandatory.\n */\n private UUID correlationId;\n\n /**\n * Sequence number within this particular stream. Events within a stream are automatically assigned\n * consecutive numbers starting with 1, without gaps. Never empry.\n */\n private long sequence;\n\n /**\n * Time when the event was saved. Events saved in one transaction are assigned the exact same timestamp.\n * Automatically populated by the system on save, never empty.\n */\n private OffsetDateTime transactionTime;\n\n /**\n * JSON payload.\n */\n private String payload;\n\n public Event() {\n }\n\n public Event(UUID streamId, String type, UUID correlationId, String payload) {\n this.streamId = streamId;\n this.type = type;\n this.correlationId = correlationId;\n this.payload = payload;\n }\n\n public void setEventId(long eventId) {\n this.eventId = eventId;\n }\n\n public void setStreamId(UUID streamId) {\n this.streamId = streamId;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public void setTransactionTime(OffsetDateTime transactionTime) {\n this.transactionTime = transactionTime;\n }\n\n public void setPayload(String payload) {\n this.payload = payload;\n }\n\n public void setCorrelationId(UUID correlationId) {\n this.correlationId = correlationId;\n }\n\n public long getEventId() {\n return eventId;\n }\n\n public UUID getStreamId() {\n return streamId;\n }\n\n public String getType() {\n return type;\n }\n\n public OffsetDateTime getTransactionTime() {\n return transactionTime;\n }\n\n public String getPayload() {\n return payload;\n }\n\n public UUID getCorrelationId() {\n return correlationId;\n }\n\n public long getSequence() {\n return sequence;\n }\n\n public void setSequence(long sequence) {\n this.sequence = sequence;\n }\n\n}", "public interface EventStore extends LeaseManager {\n\n /**\n * <p>\n * Use as lastSequence for {@link #save(List, String, long)}.\n * </p>\n *\n * <p>\n * Create the stream if it doesn't exist yet. Auto-generate the sequence number for new events. Fail on\n * concurrent update. A call to save with this value cannot perform optimistic concurrency control.\n * </p>\n */\n public static final long AUTO_GENERATE_SEQUENCE = -1;\n\n /**\n * <p>\n * Use as lastSequence for {@link #save(List, String, long)}.\n * </p>\n *\n * <p>\n * Create new stream. Fail if it already exists.\n * </p>\n */\n // This value is intentionally 0, so that the first inserted sequence is 1.\n public static final long NEW_STREAM = 0;\n\n /**\n * Append events to the event log.\n *\n * @param events\n * New events to append to the log.\n * @param streamType\n * Name of the stream type, used for bookkeeping and preventing concurrent creation of another\n * stream type with the same ID.\n * @param lastSequence\n * <p>\n * The expected sequence number of the last event within the stream, or one of\n * {@link #AUTO_GENERATE_SEQUENCE} or {@link #NEW_STREAM}. If the value is different from\n * {@link #AUTO_GENERATE_SEQUENCE}, the number is used for optimistic concurrency control and\n * this method will throw an exception if it does not match the current value in database.\n * </p>\n * <p>\n * The way to use it is: Query the event store to reconstruct state, remembering the sequence\n * number of the last event. Calculate the new state (i.e. new events to append to the store)\n * and pass the remembered sequence number for saving. The store will use that number to detect\n * concurrent modification of the stream and throw {@link EventStoreConflict}.\n * </p>\n * @return IDs of the newly saved events, in the same order as the input list.\n * @throws EventStoreConflict\n */\n List<Long> save(List<Event> events, String streamType, long lastSequence) throws EventStoreException;\n\n /**\n * Like {@link #save(List, String, long)}, but it only saves the events if all of the given lease keys are\n * owned by the given owner. If any of the leases is missing, no events are saved and this method returns\n * an empty list.\n *\n * @see #lease(String, String, long)\n */\n List<Long> save(List<Event> events, String streamType, long lastSequence, Collection<String> leaseKeys,\n String leaseOwnerKey) throws EventStoreException;\n\n /**\n * Get a single event by ID. Throws {@link EventStoreException} if the event does not exist.\n */\n Event getEvent(long eventId) throws EventStoreException;\n\n /**\n * Get a number of most recent events.\n */\n List<Event> getLatestEvents(int limit) throws EventStoreException;\n\n /**\n * Get a number of events after given event ID, sorted by event ID.\n */\n List<Event> getEventsForAllStreams(long afterEventId, int limit) throws EventStoreException;\n\n /**\n * Get a number of events for particular stream after given sequence number.\n */\n List<Event> getEventsForStream(UUID streamId, long afterSequenceId, int limit) throws EventStoreException;\n\n /**\n * Get the ID of the most recent event.\n */\n Optional<Long> getLastEventId() throws EventStoreException;\n\n /**\n * Get the last sequence number for a stream.\n */\n Optional<Long> getLastSequence(UUID streamId) throws EventStoreException;\n\n /**\n * Get the number of event streams in the store.\n */\n long getStreamCount(String streamType) throws EventStoreException;\n\n /**\n * Get information about a particular stream. Throws {@link EventStoreException} if the stream does not\n * exist.\n */\n EventStream findByStreamId(UUID id) throws EventStoreException;\n}", "public class EventStoreException extends RuntimeException {\n\n private static final long serialVersionUID = -1237680703226042282L;\n\n public EventStoreException() {\n super();\n }\n\n public EventStoreException(String message, Throwable cause, boolean enableSuppression,\n boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n\n public EventStoreException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public EventStoreException(String message) {\n super(message);\n }\n\n public EventStoreException(Throwable cause) {\n super(cause);\n }\n}", "public class EventStoreContext {\n public static final String DEFAULT_JGROUPS_CLUSTER_NAME = \"EventStore\";\n public static final int DEFAULT_JGROUPS_PORT = 47123;\n public static final long DEFAULT_HEARTBEAT_DELAY = 0;\n public static final long DEFAULT_HEARTBEAT_INTERVAL = 5000;\n\n private final JGroupsMessageGroup messageGroup;\n private final JdbcEventStore eventStore;\n private final EventStoreStatusPublisher statusPublisher;\n private final EventStoreStatusHeartbeat heartbeat;\n private final EventStoreStatus jmx;\n\n public EventStoreContext(DataSource dataSource) {\n this.messageGroup = new JGroupsMessageGroup();\n this.statusPublisher = new EventStoreStatusPublisher(messageGroup);\n this.eventStore = new JdbcEventStore(dataSource, statusPublisher);\n this.heartbeat = new EventStoreStatusHeartbeat(eventStore, statusPublisher);\n this.jmx = new EventStoreStatus(eventStore);\n\n configureMessageGroup(DEFAULT_JGROUPS_CLUSTER_NAME, DEFAULT_JGROUPS_PORT);\n configureHeartbeat(DEFAULT_HEARTBEAT_DELAY, DEFAULT_HEARTBEAT_INTERVAL);\n }\n\n /**\n * Must not be called after {@link #initialize()}.\n */\n public void configureMessageGroup(String jgroupsClusterName, int jgroupsMulticastPort) {\n this.messageGroup.setClusterName(jgroupsClusterName);\n this.messageGroup.setMulticastPort(jgroupsMulticastPort);\n }\n\n /**\n * Must not be called after {@link #initialize()}.\n *\n * @param defaultHeartbeatDelay\n * delay (in milliseconds) before querying the event store and publishing its status for the\n * first time\n * @param defaultHeartbeatInterval\n * interval (in milliseconds) of polling the event store and publishing its status\n */\n public void configureHeartbeat(long initialDelayMs, long pollingIntervalMs) {\n this.heartbeat.setInitialDelayMs(initialDelayMs);\n this.heartbeat.setPollingIntervalMs(pollingIntervalMs);\n }\n\n /**\n * <p>\n * Creates thread pools for message group and heartbeat. Initializes JGroups cluster. Registers JMX MBean\n * for event store status.\n * </p>\n *\n * <p>\n * It is mandatory to call this method prior to using the event store.\n * </p>\n *\n * <p>\n * This method may take a while. For example JGroups initialization may take a few seconds. It may be a\n * good idea to run it in a background thread to speed up application start.\n * </p>\n */\n public void initialize() {\n try {\n messageGroup.initialize();\n heartbeat.initialize();\n jmx.registerMBean();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Shut down JGroups cluster and thread pools, unregister JMX MBean.\n */\n public void destroy() {\n try {\n messageGroup.destroy();\n heartbeat.destroy();\n jmx.unregisterMBean();\n } catch (Exception e) {\n throw new RuntimeException();\n }\n }\n\n public MessageGroup getMessageGroup() {\n return messageGroup;\n }\n\n public EventStore getEventStore() {\n return eventStore;\n }\n}", "abstract public class BaseITest {\n protected static DataSource dataSource;\n\n @BeforeClass(alwaysRun = true)\n static public void setUpDataSource() throws Exception {\n File propertiesFile = new File(\"config/application.properties\");\n if (!propertiesFile.exists()) {\n throw new IllegalStateException(\n \"Missing configuration file, please create config/application.properties based on sample.\");\n }\n Properties props = new Properties();\n try (FileInputStream fis = new FileInputStream(propertiesFile)) {\n props.load(fis);\n }\n\n PGPoolingDataSource dataSource = new PGPoolingDataSource();\n dataSource.setServerName(props.getProperty(\"db.server\"));\n dataSource.setDatabaseName(props.getProperty(\"db.database\"));\n dataSource.setUser(props.getProperty(\"db.user\"));\n dataSource.setPassword(props.getProperty(\"db.password\"));\n dataSource.setPortNumber(Integer.parseInt(props.getProperty(\"db.port\")));\n BaseITest.dataSource = dataSource;\n }\n}" ]
import static com.jayway.awaitility.Awaitility.await; import static com.oasisdigital.nges.event.EventStore.AUTO_GENERATE_SEQUENCE; import static com.oasisdigital.nges.event.EventStore.NEW_STREAM; import static java.util.Arrays.asList; import static java.util.UUID.randomUUID; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import java.time.OffsetDateTime; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import java.util.stream.Stream; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.oasisdigital.nges.cluster.MessageGroup; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.Lease; import com.oasisdigital.nges.event.Event; import com.oasisdigital.nges.event.EventStore; import com.oasisdigital.nges.event.EventStoreException; import com.oasisdigital.nges.event.config.EventStoreContext; import com.oasisdigital.nges.event.jdbc.BaseITest;
IntStream.range(0, 10).parallel().forEach(i -> { try { save(textAppended(String.valueOf(i)), AUTO_GENERATE_SEQUENCE); } catch (Exception e) { throw new RuntimeException(e); } }); // Then expect it to write them all successfully List<Event> events = eventStore.getEventsForStream(streamId, 0, 100); assertThat(events.size(), is(10)); } @Test public void shouldSerializeConcurrentBatchAppendingToDifferentStreams() throws Exception { List<UUID> streamIds = Stream.generate(() -> UUID.randomUUID()).limit(10).collect(toList()); // Initialize some streams streamIds.forEach(streamId -> save(textAppended(streamId, "-"))); long lastEventId = eventStore.getLastEventId().orElse(0L); // Append to them in parallel - this is a separate call, so that we don't interfere with stream // initialization (which may involve locking). The goal of the test is to verify that just appending // to existing stream yields consistent blocks. // @formatter:off streamIds.stream() .parallel() .forEach(streamId -> save(asList(textAppended(streamId, "a"), textAppended(streamId, "b"), textAppended(streamId, "c")), 1)); // @formatter:on0 List<Event> events = eventStore.getEventsForAllStreams(lastEventId, 100); assertThat(events.size(), is(30)); List<UUID> savedStreamIdsInOrder = events.stream().map(e -> e.getStreamId()).collect(toList()); assertThat(savedStreamIdsInOrder, consistsOfConsistentBlocks(10, 3)); } // // LEASE // @Test public void shouldPreventLeaseToAnotherOwner() { String leaseKey = randomKey("Lease"); String ownerKey1 = randomKey("Owner1"); String ownerKey2 = randomKey("Owner2"); assertThat(eventStore.lease(leaseKey, ownerKey1, 2000).getOwnerKey(), is(ownerKey1)); assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey1)); } @Test public void shouldRenewLeaseToCurrentOwnerWithLease() { String leaseKey = randomKey("Lease"); String ownerKey = randomKey("Owner"); Lease first = eventStore.lease(leaseKey, ownerKey, 2000); Lease second = eventStore.lease(leaseKey, ownerKey, 2000); assertThat(second.getOwnerKey(), is(ownerKey)); assertThat(second.getExpirationDate(), is(after(first.getExpirationDate()))); } @Test public void shouldLeaseToAnotherOwnerAfterOwnerReleases() { String leaseKey = randomKey("Lease"); String ownerKey1 = randomKey("Owner1"); String ownerKey2 = randomKey("Owner2"); assertThat(eventStore.lease(leaseKey, ownerKey1, 2000).getOwnerKey(), is(ownerKey1)); eventStore.release(leaseKey, ownerKey1); assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey2)); } @Test public void shouldIgnoreReleaseFromNonOwner() { String leaseKey = randomKey("Lease"); String ownerKey1 = randomKey("Owner1"); String ownerKey2 = randomKey("Owner2"); assertThat(eventStore.lease(leaseKey, ownerKey1, 2000).getOwnerKey(), is(ownerKey1)); eventStore.release(leaseKey, ownerKey2); assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey1)); } @Test public void shouldLeaseDifferentKeysToDifferentProcesses() { String leaseKey1 = randomKey("Lease1"); String leaseKey2 = randomKey("Lease2"); String ownerKey1 = randomKey("Owner1"); String ownerKey2 = randomKey("Owner2"); assertThat(eventStore.lease(leaseKey1, ownerKey1, 2000).getOwnerKey(), is(ownerKey1)); assertThat(eventStore.lease(leaseKey2, ownerKey2, 2000).getOwnerKey(), is(ownerKey2)); } @Test public void shouldLeaseMultipleKeysToOneOwner() { String leaseKey1 = randomKey("Lease1"); String leaseKey2 = randomKey("Lease2"); String ownerKey = randomKey("Owner"); assertThat(eventStore.lease(leaseKey1, ownerKey, 2000).getOwnerKey(), is(ownerKey)); assertThat(eventStore.lease(leaseKey2, ownerKey, 2000).getOwnerKey(), is(ownerKey)); } @Test public void shouldLeaseToAnotherOwnerAfterExpiration() throws Exception { String leaseKey = randomKey("Lease"); String ownerKey1 = randomKey("Owner1"); String ownerKey2 = randomKey("Owner2"); eventStore.lease(leaseKey, ownerKey1, 150); Thread.sleep(151); assertThat(eventStore.lease(leaseKey, ownerKey2, 2000).getOwnerKey(), is(ownerKey2)); }
@Test(expectedExceptions = EventStoreException.class)
6
UweTrottmann/MovieTracker
SeriesGuideMovies/src/com/uwetrottmann/movies/util/TraktCredentialsDialogFragment.java
[ "public class ServiceManager {\n /** API key. */\n private String apiKeyValue;\n /** User email. */\n private String username;\n /** User password. */\n private String password_sha;\n /** Connection timeout (in milliseconds). */\n private Integer connectionTimeout;\n /** Read timeout (in milliseconds). */\n private Integer readTimeout;\n /** Plugin version debug string. */\n private String pluginVersion;\n /** Media center version debug string. */\n private String mediaCenterVersion;\n /** Media center build date debug string. */\n private String mediaCenterDate;\n /** Whether or not to use SSL API endpoint. */\n private boolean useSsl;\n\n\n /** Create a new manager instance. */\n public ServiceManager() {}\n\n\n /**\n * Set default authentication credentials.\n *\n * @param username Username.\n * @param password_sha SHA1 of user password.\n * @return Current instance for builder pattern.\n */\n public ServiceManager setAuthentication(String username, String password_sha) {\n this.username = username;\n this.password_sha = password_sha;\n return this;\n }\n\n /**\n * Set default API key.\n *\n * @param value API key value.\n * @return Current instance for builder pattern.\n */\n public ServiceManager setApiKey(String value) {\n this.apiKeyValue = value;\n return this;\n }\n\n /**\n * Set default connection timeout.\n *\n * @param connectionTimeout Timeout (in milliseconds).\n * @return Current instance for builder pattern.\n */\n public ServiceManager setConnectionTimeout(int connectionTimeout) {\n this.connectionTimeout = connectionTimeout;\n return this;\n }\n\n /**\n * Set default read timeout.\n *\n * @param readTimeout Timeout (in milliseconds).\n * @return Current instance for builder pattern.\n */\n public ServiceManager setReadTimeout(int readTimeout) {\n this.readTimeout = readTimeout;\n return this;\n }\n\n /**\n * Set default debug information when using a developer method.\n *\n * @param pluginVersion Internal version of your plugin. Make sure to\n * increment this for each plugin update.\n * @param mediaCenterVersion Version number of the media center, be as\n * specific as you can including nightly build number, etc.\n * @param mediaCenterDate Build date of the media center.\n * @return Current instance for builder pattern.\n */\n public ServiceManager setDebugInfo(String pluginVersion, String mediaCenterVersion, String mediaCenterDate) {\n this.pluginVersion = pluginVersion;\n this.mediaCenterVersion = mediaCenterVersion;\n this.mediaCenterDate = mediaCenterDate;\n return this;\n }\n\n /**\n * Set whether or not to use SSL API endpoint.\n *\n * @param useSsl Value.\n * @return Current instance for builder pattern.\n */\n public ServiceManager setUseSsl(boolean useSsl) {\n this.useSsl = useSsl;\n return this;\n }\n\n /**\n * Set up a new service with the defaults.\n *\n * @param service Service to set up.\n */\n private void setupService(TraktApiService service) {\n if (this.apiKeyValue != null) {\n service.setApiKey(this.apiKeyValue);\n }\n if ((this.username != null) && (this.password_sha != null)) {\n service.setAuthentication(this.username, this.password_sha);\n }\n if (this.connectionTimeout != null) {\n service.setConnectTimeout(this.connectionTimeout);\n }\n if (this.readTimeout != null) {\n service.setReadTimeout(this.readTimeout);\n }\n if (this.pluginVersion != null) {\n service.setPluginVersion(this.pluginVersion);\n }\n if (this.mediaCenterVersion != null) {\n service.setMediaCenterVersion(this.mediaCenterVersion);\n }\n if (this.mediaCenterDate != null) {\n service.setMediaCenterDate(this.mediaCenterDate);\n }\n service.setUseSsl(this.useSsl);\n }\n\n public AccountService accountService() {\n AccountService service = ServiceManager.createAccountService();\n this.setupService(service);\n return service;\n }\n\n public ActivityService activityService() {\n ActivityService service = ServiceManager.createActivityService();\n this.setupService(service);\n return service;\n }\n\n public CalendarService calendarService() {\n CalendarService service = ServiceManager.createCalendarService();\n this.setupService(service);\n return service;\n }\n\n public FriendsService friendsService() {\n FriendsService service = ServiceManager.createFriendsService();\n this.setupService(service);\n return service;\n }\n\n public GenreService genreService() {\n GenreService service = ServiceManager.createGenreService();\n this.setupService(service);\n return service;\n }\n\n public ListService listService() {\n ListService service = ServiceManager.createListService();\n this.setupService(service);\n return service;\n }\n\n public MovieService movieService() {\n MovieService service = ServiceManager.createMovieService();\n this.setupService(service);\n return service;\n }\n\n public RateService rateService() {\n RateService service = ServiceManager.createRateService();\n this.setupService(service);\n return service;\n }\n\n public RecommendationsService recommendationsService() {\n RecommendationsService service = ServiceManager.createRecommendationsService();\n this.setupService(service);\n return service;\n }\n\n public SearchService searchService() {\n SearchService service = ServiceManager.createSearchService();\n this.setupService(service);\n return service;\n }\n\n public ShoutService shoutService() {\n ShoutService service = ServiceManager.createShoutService();\n this.setupService(service);\n return service;\n }\n\n public ShowService showService() {\n ShowService service = ServiceManager.createShowService();\n this.setupService(service);\n return service;\n }\n\n public UserService userService() {\n UserService service = ServiceManager.createUserService();\n this.setupService(service);\n return service;\n }\n\n public static final AccountService createAccountService() {\n return new AccountService();\n }\n\n public static final ActivityService createActivityService() {\n return new ActivityService();\n }\n\n public static final CalendarService createCalendarService() {\n return new CalendarService();\n }\n\n public static final FriendsService createFriendsService() {\n return new FriendsService();\n }\n\n public static final GenreService createGenreService() {\n return new GenreService();\n }\n\n public static final ListService createListService() {\n return new ListService();\n }\n\n public static final MovieService createMovieService() {\n return new MovieService();\n }\n\n public static final RateService createRateService() {\n return new RateService();\n }\n\n public static final RecommendationsService createRecommendationsService() {\n return new RecommendationsService();\n }\n\n public static final SearchService createSearchService() {\n return new SearchService();\n }\n\n public static final ShoutService createShoutService() {\n return new ShoutService();\n }\n\n public static final ShowService createShowService() {\n return new ShowService();\n }\n\n public static final UserService createUserService() {\n return new UserService();\n }\n}", "public final class TraktException extends RuntimeException {\n private static final long serialVersionUID = 6158978902757706299L;\n\n private final String url;\n private final JsonObject postBody;\n private final Response response;\n\n public TraktException(String url, ApiException cause) {\n this(url, null, cause);\n }\n public TraktException(String url, JsonObject postBody, ApiException cause) {\n super(cause);\n this.url = url;\n this.postBody = postBody;\n this.response = null;\n }\n public TraktException(String url, JsonObject postBody, ApiException cause, Response response) {\n super(response.error, cause);\n this.url = url;\n this.postBody = postBody;\n this.response = response;\n }\n\n public String getUrl() {\n return this.url;\n }\n public JsonObject getPostBody() {\n return this.postBody;\n }\n public Response getResponse() {\n return this.response;\n }\n}", "public class Response implements TraktEntity {\n private static final long serialVersionUID = 5921890886906816035L;\n\n public String status; //TODO: enum\n public String message;\n public String error;\n public int wait;\n\n /** @deprecated Use {@link #status} */\n @Deprecated\n public String getStatus() {\n return this.status;\n }\n /** @deprecated Use {@link #message} */\n @Deprecated\n public String getMessage() {\n return this.message;\n }\n /** @deprecated Use {@link #error} */\n @Deprecated\n public String getError() {\n return this.error;\n }\n}", "public class AndroidUtils {\n\n private static final int DEFAULT_BUFFER_SIZE = 8192;\n\n public static boolean isJellyBeanOrHigher() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n }\n\n public static boolean isICSOrHigher() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;\n }\n\n public static boolean isHoneycombOrHigher() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;\n }\n\n public static boolean isGingerbreadOrHigher() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;\n }\n\n public static boolean isFroyoOrHigher() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;\n }\n\n /**\n * Checks if {@link Environment}.MEDIA_MOUNTED is returned by\n * {@code getExternalStorageState()} and therefore external storage is read-\n * and writeable.\n * \n * @return\n */\n public static boolean isExtStorageAvailable() {\n return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());\n }\n\n /**\n * Whether there is any network with a usable connection.\n * \n * @param context\n * @return\n */\n public static boolean isNetworkConnected(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\n if (activeNetworkInfo != null) {\n return activeNetworkInfo.isConnected();\n }\n return false;\n }\n\n /**\n * Whether WiFi has an active, usable connection.\n * \n * @param context\n * @return\n */\n public static boolean isWifiConnected(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo wifiNetworkInfo = connectivityManager\n .getNetworkInfo(ConnectivityManager.TYPE_WIFI);\n if (wifiNetworkInfo != null) {\n return wifiNetworkInfo.isConnected();\n }\n return false;\n }\n\n /**\n * Copies the contents of one file to the other using {@link FileChannel}s.\n * \n * @param src source {@link File}\n * @param dst destination {@link File}\n * @throws IOException\n */\n public static void copyFile(File src, File dst) throws IOException {\n FileInputStream in = new FileInputStream(src);\n FileOutputStream out = new FileOutputStream(dst);\n FileChannel inChannel = in.getChannel();\n FileChannel outChannel = out.getChannel();\n\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } finally {\n if (inChannel != null) {\n inChannel.close();\n }\n if (outChannel != null) {\n outChannel.close();\n }\n }\n\n in.close();\n out.close();\n }\n\n /**\n * Copies data from one input stream to the other using a buffer of 8\n * kilobyte in size.\n * \n * @param input {@link InputStream}\n * @param output {@link OutputStream}\n * @return\n * @throws IOException\n */\n public static int copy(InputStream input, OutputStream output) throws IOException {\n byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];\n int count = 0;\n int n = 0;\n while (-1 != (n = input.read(buffer))) {\n output.write(buffer, 0, n);\n count += n;\n }\n return count;\n }\n\n /**\n * Execute an {@link AsyncTask} on a thread pool.\n * \n * @param task Task to execute.\n * @param args Optional arguments to pass to\n * {@link AsyncTask#execute(Object[])}.\n * @param <T> Task argument type.\n */\n @TargetApi(11)\n public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... args) {\n // TODO figure out how to subclass abstract and generalized AsyncTask,\n // then put this there\n if (AndroidUtils.isHoneycombOrHigher()) {\n task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args);\n } else {\n task.execute(args);\n }\n }\n\n /**\n * Returns an {@link InputStream} using {@link HttpURLConnection} to connect\n * to the given URL.\n */\n public static InputStream downloadUrl(String urlString) throws IOException {\n HttpURLConnection conn = buildHttpUrlConnection(urlString);\n conn.connect();\n\n InputStream stream = conn.getInputStream();\n return stream;\n }\n\n /**\n * Returns an {@link HttpURLConnection} using sensible default settings for\n * mobile and taking care of buggy behavior prior to Froyo.\n */\n public static HttpURLConnection buildHttpUrlConnection(String urlString)\n throws MalformedURLException, IOException {\n AndroidUtils.disableConnectionReuseIfNecessary();\n\n URL url = new URL(urlString);\n\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setReadTimeout(10000 /* milliseconds */);\n conn.setConnectTimeout(15000 /* milliseconds */);\n conn.setDoInput(true);\n conn.setRequestMethod(\"GET\");\n return conn;\n }\n\n /**\n * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some\n * frustrating bugs. In particular, calling close() on a readable\n * InputStream could poison the connection pool. Work around this by\n * disabling connection pooling.\n */\n public static void disableConnectionReuseIfNecessary() {\n // HTTP connection reuse which was buggy pre-froyo\n if (!isFroyoOrHigher()) {\n System.setProperty(\"http.keepAlive\", \"false\");\n }\n }\n}", "public interface TraktStatus {\n String SUCCESS = \"success\";\n\n String FAILURE = \"failure\";\n}", "public class AppPreferences {\n\n public static final String KEY_TRAKTUSER = \"com.uwetrottmann.movies.trakt.username\";\n\n public static final String KEY_TRAKTPWD = \"com.uwetrottmann.movies.trakt.password\";\n\n public static final String KEY_RANDOM = \"com.uwetrottmann.movies.random\";\n\n public static final String KEY_ENABLEANALYTICS = \"com.uwetrottmann.movies.analytics\";\n\n public static final String KEY_SHAREWITHGETGLUE = \"com.uwetrottmann.movies.share.getglue\";\n\n public static final String KEY_SHAREWITHTRAKT = \"com.uwetrottmann.movies.share.trakt\";\n\n public static final String KEY_NAVSELECTION = \"com.uwetrottmann.movies.navselections\";\n\n}" ]
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.TextView; import com.actionbarsherlock.app.SherlockDialogFragment; import com.jakewharton.apibuilder.ApiException; import com.jakewharton.trakt.ServiceManager; import com.jakewharton.trakt.TraktException; import com.jakewharton.trakt.entities.Response; import com.uwetrottmann.androidutils.AndroidUtils; import com.uwetrottmann.movies.R; import com.uwetrottmann.movies.entities.TraktStatus; import com.uwetrottmann.movies.ui.AppPreferences;
/* * Copyright 2012 Uwe Trottmann * * 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 com.uwetrottmann.movies.util; /** * Dialog to gather and verify as well as clear trakt.tv credentials. * * @author Uwe Trottmann */ public class TraktCredentialsDialogFragment extends SherlockDialogFragment { public static TraktCredentialsDialogFragment newInstance() { TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment(); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().setTitle(R.string.pref_traktcredentials); final Context context = getActivity().getApplicationContext(); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, null); // restore the username from settings final String username = Utils.getTraktUsername(context); ((EditText) layout.findViewById(R.id.username)).setText(username); // new account toggle final View mailviews = layout.findViewById(R.id.mailviews); mailviews.setVisibility(View.GONE); ((CheckBox) layout.findViewById(R.id.checkNewAccount)) .setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mailviews.setVisibility(View.VISIBLE); } else { mailviews.setVisibility(View.GONE); } } }); // status strip final TextView status = (TextView) layout.findViewById(R.id.status); final View progressbar = layout.findViewById(R.id.progressbar); final View progress = layout.findViewById(R.id.progress); progress.setVisibility(View.GONE); final Button connectbtn = (Button) layout.findViewById(R.id.connectbutton); final Button disconnectbtn = (Button) layout.findViewById(R.id.disconnectbutton); // disable disconnect button if there are no saved credentials if (username.length() == 0) { disconnectbtn.setEnabled(false); } connectbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // prevent multiple instances connectbtn.setEnabled(false); disconnectbtn.setEnabled(false); final String username = ((EditText) layout.findViewById(R.id.username)).getText() .toString(); final String passwordHash = Utils.toSHA1(((EditText) layout .findViewById(R.id.password)).getText().toString().getBytes()); final String email = ((EditText) layout.findViewById(R.id.email)).getText() .toString(); final boolean isNewAccount = ((CheckBox) layout.findViewById(R.id.checkNewAccount)) .isChecked(); final String traktApiKey = getResources().getString(R.string.trakt_apikey); AsyncTask<String, Void, Response> accountValidatorTask = new AsyncTask<String, Void, Response>() { @Override protected void onPreExecute() { progress.setVisibility(View.VISIBLE); progressbar.setVisibility(View.VISIBLE); status.setText(R.string.waitplease); } @Override protected Response doInBackground(String... params) { // check if we have any usable data if (username.length() == 0 || passwordHash == null) { return null; } // check for connectivity if (!AndroidUtils.isNetworkConnected(context)) { Response r = new Response(); r.status = TraktStatus.FAILURE; r.error = context.getString(R.string.offline); return r; } // use a separate ServiceManager here to avoid // setting wrong credentials
final ServiceManager manager = new ServiceManager();
0
kihira/Tails
src/main/java/uk/kihira/tails/client/render/FallbackRenderHandler.java
[ "public class Model implements IDisposable\n{\n private final ArrayList<Node> allNodes;\n private final ArrayList<Node> rootNodes;\n private final HashMap<String, Animation> animations;\n private final ArrayList<ResourceLocation> textures;\n\n public Model(ArrayList<Node> allNodes, ArrayList<Node> rootNodes, HashMap<String, Animation> animations, ArrayList<ResourceLocation> textures) {\n this.allNodes = allNodes;\n this.rootNodes = rootNodes;\n this.animations = animations;\n this.textures = textures;\n }\n\n public void render(MatrixStack matrixStack)\n {\n for (Node node : rootNodes)\n {\n node.render(matrixStack);\n }\n }\n\n public void dispose()\n {\n allNodes.forEach(Node::dispose);\n\n // Textures\n textures.forEach(texture -> Minecraft.getInstance().getTextureManager().deleteTexture(texture));\n textures.clear();\n }\n}", "public enum MountPoint {\n HEAD,\n CHEST,\n RIGHT_ARM,\n LEFT_ARM,\n RIGHT_LEG,\n LEFT_LEG\n}", "public class OutfitPart {\n public final UUID basePart;\n public MountPoint mountPoint;\n public float[] mountOffset; // [x,y,z]\n public float[] rotation; // [x,y,z]\n public float[] scale; // [x,y,z]\n public float[][] tint; // [[r,g,b],[r,g,b]]\n public UUID texture;\n\n // Client only fields\n private transient Part part;\n public transient ResourceLocation textureLoc;\n\n public OutfitPart(Part part) {\n this.basePart = part.id;\n this.mountPoint = part.mountPoint;\n this.mountOffset = part.mountOffset;\n this.rotation = part.rotation;\n this.scale = part.scale;\n this.tint = part.tint;\n this.texture = part.textures[0];\n\n this.textureLoc = new ResourceLocation(Tails.MOD_ID, this.texture.toString());\n }\n\n /**\n * Gets the {@link Part} that has the ID for {@link #basePart}\n * @return The part\n */\n @Nullable\n public Part getPart() \n {\n if (part == null) \n {\n part = PartRegistry.getPart(basePart).orElse(null);\n }\n return part;\n }\n}", "public final class PartRegistry\n{\n private static final Logger LOGGER = LogManager.getFormatterLogger();\n private static final String MODEL_CACHE_FOLDER = \"tails/cache/model\";\n private static final String PARTS_CACHE_FOLDER = \"tails/cache/part\";\n\n private static final LazyLoadAssetRegistry<UUID, Part> parts = new LazyLoadAssetRegistry<>(LOGGER, PartRegistry::loadPart, null, null);\n private static final LazyLoadAssetRegistry<UUID, Model> models = new LazyLoadAssetRegistry<>(LOGGER, PartRegistry::loadModel, null, null);\n\n /**\n * Loads the cache from disk locally \n * @throws IOException\n */\n public static void loadAllPartsFromCache() throws IOException\n {\n Path cachePath = Paths.get(Minecraft.getInstance().gameDir.getPath(), PARTS_CACHE_FOLDER);\n try (Stream<Path> paths = Files.walk(cachePath))\n {\n paths.filter(Files::isRegularFile).forEach(path ->\n {\n try (FileReader reader = new FileReader(path.toFile()))\n {\n addPart(Tails.GSON.fromJson(reader, Part.class));\n }\n catch (IOException e)\n {\n e.printStackTrace();\n }\n });\n }\n }\n\n private static void initCache()\n {\n String gameDir = Minecraft.getInstance().gameDir.getPath();\n Path partCachePath = Paths.get(gameDir, PARTS_CACHE_FOLDER);\n Path modelCachePath = Paths.get(gameDir, MODEL_CACHE_FOLDER);\n\n try\n {\n if (!Files.exists(partCachePath))\n {\n Files.createDirectories(partCachePath);\n }\n if (!Files.exists(modelCachePath))\n {\n Files.createDirectories(modelCachePath);\n }\n }\n catch (IOException e)\n {\n LOGGER.error(\"Failed to create cache directories\", e);\n }\n }\n\n /**\n * Gets the {@link Part} for the associated ID, or loads it if it is not yet created.\n * <p>\n * A step-by-step procedure is followed to attempt to load the part as outlined:\n * - If the part has been loaded already, this is returned from {@link PartRegistry#parts}\n * - If the part does not exist in there, it will attempt to load it from the cache directory. This method will\n * return an empty optional until it is loaded.\n * - If it does not exist in the cache directory, it will attempt to download it from API server. This will return\n * an empty optional until it is loaded\n *\n * @param uuid The ID of the part\n * @return The part if loaded, or empty Optional\n */\n public static Optional<Part> getPart(final UUID uuid)\n {\n return parts.get(uuid);\n }\n\n private static CompletableFuture<Part> loadPart(final UUID partId)\n {\n return loadPartFromCache(partId)\n .thenCompose(part -> part\n .map(CompletableFuture::completedFuture)\n .orElseGet(() -> loadPartFromApiAndSaveToCache(partId)))\n .exceptionally(ex ->\n {\n LOGGER.error(\"Failed to load part \" + partId.toString(), ex);\n return null;\n });\n }\n\n private static CompletableFuture<Part> loadPartFromApiAndSaveToCache(final UUID partId)\n {\n // TODO Implement call to API\n return CompletableFuture.completedFuture(Optional.empty())\n .thenApply(optionalPart ->\n {\n if (optionalPart.isPresent())\n {\n savePartToCache((Part) optionalPart.get());\n return (Part) optionalPart.get();\n }\n return null;\n });\n }\n\n /**\n * Asynchronously loads a part from the cache if it exists, and populates an Optional object with it\n * If it does not exist or it fails to load, returns an empty Optional.\n * @param partId The ID of the part to load\n * @return A CompletableFuture that provides the part\n */\n private static CompletableFuture<Optional<Part>> loadPartFromCache(final UUID partId)\n {\n return CompletableFuture.supplyAsync(() ->\n {\n Path path = Paths.get(Minecraft.getInstance().gameDir.getPath(), PARTS_CACHE_FOLDER, partId.toString() + \".json\");\n\n if (Files.exists(path))\n {\n try (FileReader reader = new FileReader(path.toFile()))\n {\n return Optional.ofNullable(Tails.GSON.fromJson(reader, Part.class));\n }\n catch (IOException e)\n {\n LOGGER.error(\"Failed to load part \" + partId + \" from cache\", e);\n }\n }\n return Optional.empty();\n });\n }\n\n /**\n * Saves a {@link Part} to the cache folder\n * @param part The part to save\n */\n private static void savePartToCache(@Nonnull Part part)\n {\n Path path = Paths.get(Minecraft.getInstance().gameDir.getPath(), PARTS_CACHE_FOLDER, part.id.toString() + \".json\");\n try (FileWriter writer = new FileWriter(path.toFile()))\n {\n IOUtils.write(Tails.GSON.toJson(part), writer);\n }\n catch (IOException e)\n {\n LOGGER.error(String.format(\"Failed to save part %s (%s) to cache\", part.name, part.id), e);\n }\n }\n\n /**\n * Gets a {@link Stream} of Parts whose {@link Part#mountPoint} equals the specified {@link MountPoint}\n *\n * @param mountPoint The mount point to filter by\n * @return A stream of parts\n */\n public static Stream<Part> getPartsByMountPoint(MountPoint mountPoint) {\n return parts.values().stream().filter(part -> part.mountPoint == mountPoint);\n }\n\n /**\n * Gets the {@link Model} for the associated ID, or loads it if it is not yet created.\n * <p>\n * A step-by-step procedure is followed to attempt to load the model as outlined:\n * - If the model has been loaded already, this is returned from {@link PartRegistry#models}\n * - If the model does not exist in there, it will attempt to load it from the cache directory. This method will\n * return null until it is loaded.\n * - If it does not exist in the cache directory, it will attempt to download it from API server. This will return\n * null until it is loaded\n *\n * @param uuid The ID of the model\n * @return The model if loaded, or null if not\n */\n public static Optional<Model> getModel(final UUID uuid)\n {\n return models.get(uuid);\n }\n\n private static CompletableFuture<Model> loadModel(final UUID uuid)\n {\n return CompletableFuture.supplyAsync(() ->\n {\n Path path = Paths.get(Minecraft.getInstance().gameDir.getPath(), MODEL_CACHE_FOLDER, uuid.toString() + \".glb\");\n\n if (Files.exists(path))\n {\n try {\n // todo seperate loading and OpenGL calls\n return GltfLoader.LoadGlbFile(path.toFile());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else\n {\n // todo download from API server. also track if download from API server failed and don't retry\n return null;\n }\n return null;\n })\n .exceptionally(ex ->\n {\n LOGGER.error(\"Failed to load model \" + uuid.toString(), ex);\n return null;\n });\n }\n\n /**\n * Loads all parts from the resources directory into the cache and memory\n */\n public static void loadAllPartsFromResources()\n {\n ResourceLocation resLoc = new ResourceLocation(Tails.MOD_ID, \"parts.json\");\n try (InputStream is = Minecraft.getInstance().getResourceManager().getResource(resLoc).getInputStream())\n {\n InputStreamReader reader = new InputStreamReader(is);\n List<UUID> parts = Tails.GSON.fromJson(reader, new TypeToken<List<UUID>>(){}.getType());\n\n CompletableFuture.allOf(parts.stream()\n .map(uuid -> CompletableFuture.runAsync(() -> PartRegistry.loadPartFromResources(uuid)))\n .toArray(CompletableFuture[]::new))\n .thenRun(() -> LOGGER.info(\"Loaded %d parts from resources\", parts.size()));\n }\n catch (IOException e)\n {\n Tails.LOGGER.error(\"Cannot load parts list\", e);\n }\n }\n\n /**\n * Loads a part from the resources folder and copies it model\n *\n * @param uuid Part ID\n */\n private static void loadPartFromResources(final UUID uuid)\n {\n IResourceManager resourceManager = Minecraft.getInstance().getResourceManager();\n ResourceLocation resLoc = new ResourceLocation(Tails.MOD_ID, \"part/\" + uuid + \".json\");\n try (InputStream is = resourceManager.getResource(resLoc).getInputStream())\n {\n InputStreamReader reader = new InputStreamReader(is);\n addPart(Tails.GSON.fromJson(reader, Part.class));\n\n // Copy model to cache\n ResourceLocation modelResLoc = new ResourceLocation(Tails.MOD_ID, \"model/\" + uuid + \".glb\");\n Path path = Paths.get(Minecraft.getInstance().gameDir.getPath(), MODEL_CACHE_FOLDER, uuid.toString() + \".glb\");\n try (InputStream modelStream = resourceManager.getResource(modelResLoc).getInputStream();\n FileOutputStream outputStream = new FileOutputStream(path.toFile()))\n {\n IOUtils.copy(modelStream, outputStream);\n }\n }\n catch (IOException e)\n {\n LOGGER.error(\"Failed to load part: \" + uuid, e);\n }\n }\n\n private static void addPart(Part part)\n {\n parts.put(part.id, part);\n }\n}", "public final class Outfit\n{\n public final UUID id;\n public String name;\n public String description;\n public ArrayList<OutfitPart> parts;\n\n public Outfit()\n {\n id = UUID.randomUUID();\n parts = new ArrayList<>();\n }\n\n // todo make a client only multimap of mountpoint <-> outfitpart?\n}", "@Mod(Tails.MOD_ID)\npublic class Tails \n{\n public static final String MOD_ID = \"tails\";\n public static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n public static final Gson GSON = new GsonBuilder().create();\n public static final boolean DEBUG = true;\n\n public static boolean hasRemote;\n\n public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new);\n\n public Tails()\n {\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange);\n MinecraftForge.EVENT_BUS.addListener(this::addReloadListener);\n }\n\n private void setup(final FMLCommonSetupEvent event)\n {\n proxy.preInit();\n Config.loadConfig();\n\n PartRegistry.loadAllPartsFromResources();\n }\n\n private void addReloadListener(final AddReloadListenerEvent event)\n {\n event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) ->\n CompletableFuture.runAsync(() -> proxy.onResourceManagerReload()));\n }\n\n public void onConfigChange(final ModConfigEvent event)\n {\n if (event.getConfig().getModId().equals(Tails.MOD_ID)) \n {\n Config.loadConfig();\n }\n }\n\n public static void setLocalOutfit(final Outfit outfit)\n {\n Config.localOutfit.set(outfit);\n Config.configuration.save();\n }\n}" ]
import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.renderer.model.ModelRenderer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.RenderPlayerEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import uk.kihira.gltf.Model; import uk.kihira.tails.client.MountPoint; import uk.kihira.tails.client.outfit.OutfitPart; import uk.kihira.tails.client.PartRegistry; import uk.kihira.tails.client.outfit.Outfit; import uk.kihira.tails.common.Tails; import java.util.Optional; import java.util.UUID; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder;
package uk.kihira.tails.client.render; /** * Legacy renderer that uses the player render event. * This is used for compatibility with certain mods */ public class FallbackRenderHandler { private static RenderPlayerEvent.Pre currentEvent = null; private static Outfit currentOutfit = null; private static ResourceLocation currentPlayerTexture = null; @SubscribeEvent(priority = EventPriority.LOWEST) public void onPlayerRenderTick(RenderPlayerEvent.Pre e) { UUID uuid = e.getPlayer().getGameProfile().getId(); if (Tails.proxy.hasActiveOutfit(uuid) && !e.getPlayer().isInvisible()) { currentOutfit = Tails.proxy.getActiveOutfit(uuid); currentPlayerTexture = ((ClientPlayerEntity) e.getPlayer()).getLocationSkin(); currentEvent = e; } } @SubscribeEvent() public void onPlayerRenderTickPost(RenderPlayerEvent.Post e) { //Reset to null after rendering the current tail currentOutfit = null; currentPlayerTexture = null; currentEvent = null; } public static class ModelRendererWrapper extends ModelRenderer { private final MountPoint mountPoint; public ModelRendererWrapper(net.minecraft.client.renderer.model.Model model, MountPoint mountPoint) { super(model); this.mountPoint = mountPoint; addBox(0, 0, 0, 0, 0, 0); //Adds in a blank box as it's required in certain cases such as rendering arrows in entities } @Override public void render(MatrixStack matrixStackIn, IVertexBuilder bufferIn, int packedLightIn, int packedOverlayIn) { if (currentEvent != null && currentOutfit != null && currentPlayerTexture != null) {
for (OutfitPart part : currentOutfit.parts)
2
ppicas/android-clean-architecture-mvp
app/src/main/java/cat/ppicas/cleanarch/ui/presenter/CityListItemPresenter.java
[ "public class City {\n\n private String mId;\n private String mName;\n private String mCountry;\n private CurrentWeatherPreview mCurrentWeatherPreview;\n\n public City(String id, String name, String country) {\n mId = id;\n mName = name;\n mCountry = country;\n }\n\n public City(String id, String name, String country,\n CurrentWeatherPreview currentWeatherPreview) {\n mId = id;\n mName = name;\n mCountry = country;\n mCurrentWeatherPreview = currentWeatherPreview;\n }\n\n public String getId() {\n return mId;\n }\n\n public String getName() {\n return mName;\n }\n\n public String getCountry() {\n return mCountry;\n }\n\n public CurrentWeatherPreview getCurrentWeatherPreview() {\n return mCurrentWeatherPreview;\n }\n}", "public class GetElevationTask implements Task<Integer, NoException> {\n\n @SuppressWarnings(\"FieldCanBeLocal\")\n private City mCity;\n\n private volatile boolean mCanceled;\n\n public GetElevationTask(City city) {\n mCity = city;\n }\n\n @Override\n public TaskResult<Integer, NoException> execute() {\n try {\n // Here we simulate an external call to some service\n for (int i = 0; i < 15 && !mCanceled; i++) {\n Thread.sleep(100);\n }\n } catch (InterruptedException ignored) {}\n\n if (!mCanceled) {\n int result = (int) (Math.random() * 1500);\n return TaskResult.newSuccessResult(result);\n } else {\n return TaskResult.newCanceledResult();\n }\n }\n\n public void cancel() {\n mCanceled = true;\n }\n}", "public final class NumberFormat {\n\n private static final java.text.NumberFormat DECIMAL_FORMATTER\n = java.text.NumberFormat.getInstance();\n\n static {\n DECIMAL_FORMATTER.setMaximumFractionDigits(2);\n }\n\n private NumberFormat() {\n throw new RuntimeException(\"Instances are not allowed for this class\");\n }\n\n public static String formatDecimal(double num) {\n return DECIMAL_FORMATTER.format(num);\n }\n\n public static String formatTemperature(double temp) {\n return DECIMAL_FORMATTER.format(temp) + \"º\";\n }\n\n public static String formatHumidity(double humidity) {\n return Math.round(humidity) + \"%\";\n }\n\n public static String formatWindSpeed(double windSpeed) {\n return DECIMAL_FORMATTER.format(windSpeed) + \" m/s\";\n }\n\n public static String formatElevation(int elevation) {\n return elevation + \"m\";\n }\n}", "public interface CityListItemVista extends Vista {\n\n void setCityName(String name);\n\n void setCountry(String country);\n\n void setCurrentTemp(String temp);\n\n void setLoadingElevation(boolean loading);\n\n void setElevation(int elevation);\n\n}", "public abstract class SuccessTaskCallback<R> implements TaskCallback<R, NoException> {\n\n @Override\n public void onError(NoException error) {\n throw error;\n }\n}", "public interface TaskExecutor {\n\n <R, E extends Exception> void execute(Task<R, E> task, TaskCallback<R, E> callback);\n\n boolean isRunning(Task<?, ?> task);\n\n}", "public abstract class Presenter<T extends Vista> {\n\n private T mVista;\n\n /**\n * Returns the current bound {@link Vista} if any.\n *\n * @return The bound {@code Vista} or {@code null}.\n */\n @Nullable\n public T getVista() {\n return mVista;\n }\n\n /**\n * Must be called to bind the {@link Vista} and let the {@link Presenter} know that can start\n * {@code Vista} updates. Normally this method will be called from {@link Activity#onStart()}\n * or from {@link Fragment#onStart()}.\n *\n * @param vista A {@code Vista} instance to bind.\n */\n public final void start(T vista) {\n mVista = vista;\n onStart(vista);\n }\n\n /**\n * Must be called un unbind the {@link Vista} and let the {@link Presenter} know that must\n * stop updating the {@code Vista}. Normally this method will be called from\n * {@link Activity#onStop()} or from {@link Fragment#onStop()}.\n */\n public final void stop() {\n mVista = null;\n onStop();\n }\n\n /**\n * Called when the {@link Presenter} can start {@link Vista} updates.\n *\n * @param vista The bound {@code Vista}.\n */\n public abstract void onStart(T vista);\n\n /**\n * Called when the {@link Presenter} must stop {@link Vista} updates. The extending\n * {@code Presenter} can override this method to provide some custom logic.\n */\n public void onStop() {\n }\n\n /**\n * Called to ask the {@link Presenter} to save its current dynamic state, so it\n * can later be reconstructed in a new instance of its process is\n * restarted.\n *\n * @param state Bundle in which to place your saved state.\n * @see Activity#onSaveInstanceState(Bundle)\n */\n public void saveState(Bundle state) {\n }\n\n /**\n * Called to ask the {@link Presenter} to restore the previous saved state.\n *\n * @param state The data most recently supplied in {@link #saveState}.\n * @see Activity#onRestoreInstanceState(Bundle)\n */\n public void restoreState(Bundle state) {\n }\n\n /**\n * Called when this {@link Presenter} is going to be destroyed, so it has a chance to\n * release resources. The extending {@code Presenter} can override this method to provide some\n * custom logic.\n */\n public void onDestroy() {\n }\n}" ]
import cat.ppicas.cleanarch.model.City; import cat.ppicas.cleanarch.task.GetElevationTask; import cat.ppicas.cleanarch.text.NumberFormat; import cat.ppicas.cleanarch.ui.vista.CityListItemVista; import cat.ppicas.framework.task.SuccessTaskCallback; import cat.ppicas.framework.task.TaskExecutor; import cat.ppicas.framework.ui.Presenter;
/* * Copyright (C) 2015 Pau Picas Sans <[email protected]> * * 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 cat.ppicas.cleanarch.ui.presenter; public class CityListItemPresenter extends Presenter<CityListItemVista> { private TaskExecutor mTaskExecutor; private City mCity; private int mElevation = -1; private GetElevationTask mGetElevationTask; public CityListItemPresenter(TaskExecutor taskExecutor, City city) { mTaskExecutor = taskExecutor; mCity = city; } @Override public void onStart(CityListItemVista vista) { updateVista(); if (mElevation > -1) { vista.setLoadingElevation(false); vista.setElevation(mElevation); } else { vista.setLoadingElevation(true); if (!mTaskExecutor.isRunning(mGetElevationTask)) { mGetElevationTask = new GetElevationTask(mCity); mTaskExecutor.execute(mGetElevationTask, new GetElevationTaskCallback()); } } } @Override public void onDestroy() { if (mTaskExecutor.isRunning(mGetElevationTask)) { mGetElevationTask.cancel(); } } public void setCity(City city) { if (mCity.getId().equals(city.getId()) && mCity.getName().equals(city.getName())) { return; } mCity = city; updateVista(); if (mTaskExecutor.isRunning(mGetElevationTask)) { mGetElevationTask.cancel(); } if (getVista() != null) { getVista().setLoadingElevation(true); } mElevation = -1; mGetElevationTask = new GetElevationTask(city); mTaskExecutor.execute(mGetElevationTask, new GetElevationTaskCallback()); } private void updateVista() { CityListItemVista vista = getVista(); if (vista == null) { return; } vista.setCityName(mCity.getName()); vista.setCountry(mCity.getCountry()); double temp = mCity.getCurrentWeatherPreview().getCurrentTemp();
vista.setCurrentTemp(NumberFormat.formatTemperature(temp));
2
irengrig/fossil4idea
src/org/github/irengrig/fossil4idea/checkin/CheckinUtil.java
[ "public class FossilConfigurable implements Configurable {\n private final Project myProject;\n private JPanel myPanel;\n private TextFieldWithBrowseButton myCommandLine;\n\n public FossilConfigurable(final Project project) {\n myProject = project;\n createUI();\n }\n\n private void createUI() {\n myPanel = new JPanel(new BorderLayout());\n\n final JLabel label = new JLabel(\"Fossil command line client: \");\n final JPanel wrapper = new JPanel();\n final BoxLayout boxLayout = new BoxLayout(wrapper, BoxLayout.X_AXIS);\n wrapper.setLayout(boxLayout);\n wrapper.add(label);\n myCommandLine = new TextFieldWithBrowseButton();\n myCommandLine.addBrowseFolderListener(\"Point to Fossil command line\", null, myProject,\n new FileChooserDescriptor(true, false, false, false, false, false));\n wrapper.add(myCommandLine);\n myPanel.add(wrapper, BorderLayout.NORTH);\n }\n\n @Nls\n public String getDisplayName() {\n return FossilVcs.DISPLAY_NAME;\n }\n\n @Nullable\n public String getHelpTopic() {\n return null;\n }\n\n @Nullable\n public JComponent createComponent() {\n return myPanel;\n }\n\n public boolean isModified() {\n return ! Comparing.equal(FossilConfiguration.getInstance(myProject).FOSSIL_PATH, myCommandLine.getText().trim());\n }\n\n public void apply() throws ConfigurationException {\n FossilConfiguration.getInstance(myProject).FOSSIL_PATH = myCommandLine.getText().trim();\n }\n\n public void reset() {\n myCommandLine.setText(FossilConfiguration.getInstance(myProject).FOSSIL_PATH);\n }\n\n public void disposeUIResources() {\n }\n}", "@State(\n name = \"FossilConfiguration\",\n storages = {\n @Storage(file = StoragePathMacros.WORKSPACE_FILE)\n }\n)\npublic class FossilConfiguration implements PersistentStateComponent<Element> {\n public String FOSSIL_PATH = \"\";\n private final Map<File, String> myRemoteUrls = new HashMap<File, String>();\n\n @Nullable\n public Element getState() {\n Element element = new Element(\"state\");\n element.setAttribute(\"FOSSIL_PATH\", FOSSIL_PATH);\n return element;\n }\n\n public void loadState(Element element) {\n final Attribute fossilPath = element.getAttribute(\"FOSSIL_PATH\");\n if (fossilPath != null) {\n FOSSIL_PATH = fossilPath.getValue();\n }\n }\n\n public static FossilConfiguration getInstance(final Project project) {\n return ServiceManager.getService(project, FossilConfiguration.class);\n }\n\n public void setRemoteUrls(final Map<File, String> urls) {\n myRemoteUrls.clear();\n myRemoteUrls.putAll(urls);\n }\n\n public Map<File, String> getRemoteUrls() {\n return myRemoteUrls;\n }\n}", "public class FossilVcs extends AbstractVcs {\n public static String NAME = \"fossil\";\n public static String DISPLAY_NAME = \"Fossil\";\n private FossilChangeProvider myChangeProvider;\n private static final VcsKey ourKey = createKey(NAME);\n private FossilVfsListener myVfsListener;\n private UiManager uiManager;\n private FossilCheckinEnvironment fossilCheckinEnvironment;\n\n public FossilVcs(Project project) {\n super(project, NAME);\n }\n\n @Override\n public String getDisplayName() {\n return DISPLAY_NAME;\n }\n\n @Override\n public Configurable getConfigurable() {\n return new FossilConfigurable(myProject);\n }\n\n @Override\n protected void activate() {\n myVfsListener = new FossilVfsListener(myProject);\n uiManager = new UiManager(myProject);\n }\n\n @Override\n protected void deactivate() {\n if (myVfsListener != null) {\n Disposer.dispose(myVfsListener);\n myVfsListener = null;\n uiManager.stop();\n }\n }\n\n public UiManager getUiManager() {\n return uiManager;\n }\n\n @Nullable\n @Override\n public ChangeProvider getChangeProvider() {\n if (myChangeProvider == null) {\n myChangeProvider = new FossilChangeProvider(myProject);\n }\n return myChangeProvider;\n }\n\n @Nullable\n @Override\n protected CheckinEnvironment createCheckinEnvironment() {\n if (fossilCheckinEnvironment == null) {\n fossilCheckinEnvironment = new FossilCheckinEnvironment(this);\n }\n return fossilCheckinEnvironment;\n }\n\n @Nullable\n @Override\n protected RollbackEnvironment createRollbackEnvironment() {\n return new FossilRollbackEnvironment(this);\n }\n\n @Nullable\n @Override\n public VcsHistoryProvider getVcsHistoryProvider() {\n return new FossilHistoryProvider(this);\n }\n\n @Nullable\n @Override\n protected UpdateEnvironment createUpdateEnvironment() {\n return new FossilUpdateEnvironment(this);\n }\n\n @Override\n public List<CommitExecutor> getCommitExecutors() {\n return Collections.<CommitExecutor>singletonList(new FossilCommitAndPushExecutor(myProject));\n }\n\n public void checkVersion() {\n //todo\n }\n\n @Nullable\n @Override\n public DiffProvider getDiffProvider() {\n return new FossilDiffProvider(this);\n }\n\n public static FossilVcs getInstance(final Project project) {\n return (FossilVcs) ProjectLevelVcsManager.getInstance(project).findVcsByName(NAME);\n }\n\n public static VcsKey getVcsKey() {\n return ourKey;\n }\n\n @Nullable\n @Override\n public AnnotationProvider getAnnotationProvider() {\n return new FossilAnnotationProvider(this);\n }\n}", "public enum FCommandName {\n add(\"add\"),\n addremove(\"addremove\"),\n all_(\"all\"),\n annotate(\"annotate\"),\n artifact(\"artifact\"),\n bisect(\"bisect\"),\n branch(\"branch\"),\n cgi(\"cgi\"),\n changes(\"changes\"),\n checkout(\"checkout\"),\n ci(\"ci\"),\n clean(\"clean\"),\n clone(\"clone\"),\n close(\"close\"),\n co(\"co\"),\n commit(\"commit\"),\n configuration(\"configuration\"),\n deconstruct(\"deconstruct\"),\n delete(\"delete\"),\n descendants(\"descendants\"),\n diff(\"diff\"),\n export(\"export\"),\n extras(\"extras\"),\n finfo(\"finfo\"),\n gdiff(\"gdiff\"),\n http_(\"http\"),\n import_(\"import\"),\n info(\"info\"),\n init(\"init\"),\n leaves(\"leaves\"),\n ls(\"ls\"),\n md5sum(\"md5sum\"),\n merge(\"merge\"),\n mv(\"mv\"),\n new_(\"new\"),\n open(\"open\"),\n pull(\"pull\"),\n push(\"push\"),\n rebuild(\"rebuild\"),\n reconstruct(\"reconstruct\"),\n redo(\"redo\"),\n remote_url(\"remote-url\"),\n rename(\"rename\"),\n revert(\"revert\"),\n rm(\"rm\"),\n scrub(\"scrub\"),\n search(\"search\"),\n server(\"server\"),\n settings(\"settings\"),\n sha1sum(\"sha1sum\"),\n sqlite3(\"sqlite3\"),\n stash(\"stash\"),\n status(\"status\"),\n synch(\"synch\"),\n tag(\"tag\"),\n tarball(\"tarball\"),\n ticket(\"ticket\"),\n timeline(\"timeline\"),\n ui(\"ui\"),\n undo(\"undo\"),\n unset(\"unset\"),\n update(\"update\"),\n user(\"user\"),\n version(\"version\"),\n whatis(\"whatis\"),\n wiki(\"wiki\"),\n winsrv(\"winsrv\"),\n zip(\"zip\");\n\n private final String myName;\n\n private FCommandName(String name) {\n myName = name;\n }\n\n public String getName() {\n return myName;\n }\n}", "public class FossilSimpleCommand extends FossilTextCommand {\n private static final Logger LOG = Logger.getInstance(\"#FossilSimpleCommand\");\n private final StringBuilder myStderr;\n private final StringBuilder myStdout;\n private final Set<String> myStartBreakSequence;\n private final Set<String> mySkipErrors;\n private final Set<String> myAnswerYesLines;\n\n public FossilSimpleCommand(Project project, File workingDirectory, @NotNull FCommandName commandName) {\n this(project, workingDirectory, commandName, null);\n }\n\n public FossilSimpleCommand(Project project, File workingDirectory, @NotNull FCommandName commandName,\n final String breakSequence) {\n super(project, workingDirectory, commandName);\n\n myStderr = new StringBuilder();\n myStdout = new StringBuilder();\n myStartBreakSequence = new HashSet<String>();\n if (breakSequence != null) {\n myStartBreakSequence.add(breakSequence);\n }\n mySkipErrors = new HashSet<String>();\n myAnswerYesLines = new HashSet<String>();\n addUsualSequences();\n }\n\n private void addUsualSequences() {\n myStartBreakSequence.add(\"If you have recently updated your fossil executable, you might\\n\" +\n \"need to run \\\"fossil all rebuild\\\" to bring the repository\\n\" +\n \"schemas up to date.\");\n myStartBreakSequence.add(\"database is locked\");\n }\n\n public void addBreakSequence(final String s) {\n myStartBreakSequence.add(s);\n }\n\n public void addSkipError(final String s) {\n mySkipErrors.add(s);\n }\n\n public void addAnswerYes(final String s) {\n myAnswerYesLines.add(s);\n }\n\n @Override\n protected void processTerminated(int exitCode) {\n //\n }\n\n @Override\n protected void onTextAvailable(String text, Key outputType) {\n if (tryToInteractivelyCommunicate(text)) {\n return;\n }\n\n if (ProcessOutputTypes.STDOUT.equals(outputType)) {\n if (isInBreakSequence(text)) {\n myStdout.append(text);\n destroyProcess();\n return;\n }\n myStdout.append(text);\n } else if (ProcessOutputTypes.STDERR.equals(outputType)) {\n if (myStderr.length() == 0 && isInBreakSequence(text)) {\n myStderr.append(text);\n destroyProcess();\n return;\n }\n myStderr.append(text);\n }\n }\n\n // we use --no-warnings instead\n private boolean tryToInteractivelyCommunicate(final String s) {\n if (s == null || s.isEmpty()) return false;\n for (String error : myAnswerYesLines) {\n if (s.contains(error) || s.toLowerCase().contains(error.toLowerCase())) {\n final OutputStream outputStream = myProcess.getOutputStream();\n try {\n outputStream.write(\"y\\n\".getBytes());\n outputStream.flush();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return true;\n }\n }\n return false;\n }\n\n private boolean isInBreakSequence(final String text) {\n for (String s : myStartBreakSequence) {\n if (text.contains(s)) return true;\n }\n return false;\n }\n\n public StringBuilder getStderr() {\n return myStderr;\n }\n\n public StringBuilder getStdout() {\n return myStdout;\n }\n\n public String run() throws VcsException {\n final VcsException[] ex = new VcsException[1];\n final String[] result = new String[1];\n addListener(new ProcessEventListener() {\n @Override\n public void processTerminated(int exitCode) {\n try {\n if (exitCode == 0 || skipError(getStderr().toString())) {\n result[0] = getStdout().toString();\n LOG.info(myCommandLine.getCommandLineString() + \" >>\\n\" + result[0]);\n System.out.println(myCommandLine.getCommandLineString() + \" >>\\n\" + result[0]);\n }\n else {\n String msg = getStderr().toString();\n if (msg.length() == 0) {\n msg = getStdout().toString();\n }\n if (msg.length() == 0) {\n msg = \"Fossil process exited with error code: \" + exitCode;\n }\n LOG.info(myCommandLine.getCommandLineString() + \" >>\\n\" + msg);\n System.out.println(myCommandLine.getCommandLineString() + \" >>\\n\" + msg);\n ex[0] = new VcsException(msg);\n }\n }\n catch (Throwable t) {\n ex[0] = new VcsException(t.toString(), t);\n }\n }\n\n private boolean skipError(String s) {\n if (s == null || s.isEmpty()) return false;\n for (String error : mySkipErrors) {\n if (s.contains(error) || s.toLowerCase().contains(error.toLowerCase())) return true;\n }\n return false;\n }\n\n @Override\n public void startFailed(Throwable exception) {\n ex[0] = new VcsException(\"Process failed to start (\" + myCommandLine.getCommandLineString() + \"): \" + exception.toString(), exception);\n }\n });\n start();\n if (myProcess != null) {\n waitFor();\n }\n if (ex[0] != null) {\n FossilVcs.getInstance(myProject).checkVersion();\n throw ex[0];\n }\n if (result[0] == null) {\n throw new VcsException(\"Svn command returned null: \" + myCommandLine.getCommandLineString());\n }\n return result[0];\n }\n}", "public class MoveWorker {\n private final Project myProject;\n\n public MoveWorker(final Project project) {\n myProject = project;\n }\n\n public void doRename(final File oldPath, final File newPath) throws VcsException {\n final FossilSimpleCommand command = new FossilSimpleCommand(myProject, findParent(oldPath), FCommandName.rename);\n command.addParameters(oldPath.getPath());\n command.addParameters(newPath.getName());\n command.run();\n }\n\n public void doMove(final File oldPath, final File targetDir) throws VcsException {\n final FossilSimpleCommand command = new FossilSimpleCommand(myProject, findParent(oldPath), FCommandName.rename);\n command.addParameters(oldPath.getPath());\n command.addParameters(targetDir.getPath());\n command.run();\n }\n\n public static File findParent(final File oldPath) throws FossilException {\n File current = oldPath;\n while (current != null) {\n if (current.exists() && current.isDirectory()) return current;\n current = current.getParentFile();\n }\n throw new FossilException(\"Can not find existing parent directory for file: \" + oldPath.getPath());\n }\n}", "public class FossilException extends VcsException {\n public FossilException(final String message) {\n super(message);\n }\n\n public FossilException(final Throwable throwable, final boolean isWarning) {\n super(throwable, isWarning);\n }\n\n public FossilException(final Throwable throwable) {\n super(throwable);\n }\n\n public FossilException(final String message, final Throwable cause) {\n super(message, cause);\n }\n\n public FossilException(final String message, final boolean isWarning) {\n super(message, isWarning);\n }\n\n public FossilException(final Collection<String> messages) {\n super(messages);\n }\n}", "public class FossilUpdateConfigurable implements Configurable {\n private final Project myProject;\n private final Collection<FilePath> myRoots;\n private final Map<File, String> myCheckoutURLs;\n private final String myWarning;\n private final Map<File, JBTextField> myFields;\n\n public FossilUpdateConfigurable(final Project project, final Collection<FilePath> roots, Map<File, String> checkoutURLs, String warning) {\n myProject = project;\n myRoots = roots;\n myCheckoutURLs = checkoutURLs;\n myWarning = warning;\n myFields = new HashMap<File, JBTextField>();\n }\n\n @Nls\n @Override\n public String getDisplayName() {\n return \"Fossil Update Settings\";\n }\n\n @Nullable\n @Override\n public String getHelpTopic() {\n return null;\n }\n\n @Nullable\n @Override\n public JComponent createComponent() {\n final JBPanel panel = new JBPanel(new GridBagLayout());\n if (myRoots.size() > 1) {\n buildForMultiple(panel);\n } else {\n buildForOne(panel, myRoots.iterator().next());\n }\n return panel;\n }\n\n private void buildForOne(JBPanel panel, final FilePath root) {\n final GridBagConstraints c = new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST,\n GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0);\n c.fill = GridBagConstraints.HORIZONTAL;\n c.gridwidth = 2;\n final JBLabel comp = new JBLabel(\"Please select remote URL:\");\n comp.setFont(comp.getFont().deriveFont(Font.BOLD));\n panel.add(comp, c);\n final JBTextField value = new JBTextField();\n value.setColumns(100);\n final String preset = myCheckoutURLs.get(root.getIOFile());\n if (preset != null) {\n value.setText(preset);\n }\n myFields.put(root.getIOFile(), value);\n ++ c.gridy;\n panel.add(value, c);\n addWarning(panel, c);\n }\n\n private void buildForMultiple(JBPanel panel) {\n final GridBagConstraints c = new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(1, 1, 1, 1), 0, 0);\n c.gridwidth = 2;\n c.fill = GridBagConstraints.HORIZONTAL;\n final JBLabel comp = new JBLabel(\"Please select remote URLs for roots:\");\n comp.setFont(comp.getFont().deriveFont(Font.BOLD));\n panel.add(comp, c);\n c.gridwidth = 1;\n\n for (FilePath root : myRoots) {\n c.weighty = 0;\n c.gridx = 0;\n ++ c.gridy;\n c.fill = GridBagConstraints.NONE;\n panel.add(new JBLabel(root.getName() + \" (\" + root.getParentPath() + \")\"), c);\n ++ c.gridx;\n c.fill = GridBagConstraints.HORIZONTAL;\n c.weighty = 1;\n final JBTextField field = new JBTextField();\n panel.add(field, c);\n myFields.put(root.getIOFile(), field);\n final String preset = myCheckoutURLs.get(root.getIOFile());\n if (preset != null) {\n field.setText(preset);\n }\n }\n addWarning(panel, c);\n }\n\n private void addWarning(JBPanel panel, GridBagConstraints c) {\n if (myWarning != null && myWarning.length() > 0) {\n ++ c.gridy;\n c.gridx = 0;\n c.gridwidth = 2;\n c.fill = GridBagConstraints.HORIZONTAL;\n final JLabel label = new JLabel(new TextUtil().insertLineCuts(\"Warning: \" + myWarning));\n label.setUI(new MultiLineLabelUI());\n label.setForeground(SimpleTextAttributes.ERROR_ATTRIBUTES.getFgColor());\n panel.add(label, c);\n }\n }\n\n @Override\n public boolean isModified() {\n return false;\n }\n\n @Override\n public void apply() throws ConfigurationException {\n FossilConfiguration configuration = FossilConfiguration.getInstance(myProject);\n\n final Map<File, String> urls = new HashMap<File, String>(configuration.getRemoteUrls());\n for (Map.Entry<File, JBTextField> entry : myFields.entrySet()) {\n final String text = entry.getValue().getText();\n if (text.trim().equals(myCheckoutURLs.get(entry.getKey())) || text.trim().length() == 0) {\n // remove override from map\n urls.remove(entry.getKey());\n } else {\n urls.put(entry.getKey(), text.trim());\n }\n }\n configuration.setRemoteUrls(urls);\n }\n\n @Override\n public void reset() {\n }\n\n @Override\n public void disposeUIResources() {\n }\n}" ]
import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ObjectsConvertor; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.actions.VcsQuickListPopupAction; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ui.UIUtil; import org.github.irengrig.fossil4idea.FossilConfigurable; import org.github.irengrig.fossil4idea.FossilConfiguration; import org.github.irengrig.fossil4idea.FossilVcs; import org.github.irengrig.fossil4idea.commandLine.FCommandName; import org.github.irengrig.fossil4idea.commandLine.FossilSimpleCommand; import org.github.irengrig.fossil4idea.local.MoveWorker; import org.github.irengrig.fossil4idea.FossilException; import org.github.irengrig.fossil4idea.pull.FossilUpdateConfigurable; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.File; import java.util.*;
package org.github.irengrig.fossil4idea.checkin; /** * Created with IntelliJ IDEA. * User: Irina.Chernushina * Date: 2/24/13 * Time: 2:59 PM */ public class CheckinUtil { public static final String QUESTION = "Commit anyhow (a=all/c=convert/y/N)?"; public static final String BREAK_SEQUENCE = "contains CR/NL line endings"; public static final String PUSH_TO = "Push to"; private final Project myProject; public static final String PREFIX = "New_Version: "; public CheckinUtil(final Project project) { myProject = project; } public void push() { final FossilVcs fossil = FossilVcs.getInstance(myProject); final VirtualFile[] roots = ProjectLevelVcsManager.getInstance(myProject).getRootsUnderVcs(fossil); if (roots.length == 0) { // PopupUtil.showBalloonForActiveComponent("Error occurred while pushing: No roots under Fossil found.", MessageType.ERROR); return; } UIUtil.invokeAndWaitIfNeeded(new Runnable() { @Override public void run() { final List<FilePath> filePaths = ObjectsConvertor.vf2fp(Arrays.asList(roots));
final FossilUpdateConfigurable configurable = (FossilUpdateConfigurable) fossil.getUpdateEnvironment().createConfigurable(filePaths);
7
lukas-krecan/JsonUnit
json-unit-json-path/src/main/java/net/javacrumbs/jsonunit/jsonpath/JsonPathAdapter.java
[ "public static Object jsonSource(Object json, String pathPrefix) {\n return jsonSource(json, pathPrefix, emptyList());\n}", "public static Object missingNode() {\n return Node.MISSING_NODE;\n}", "public static Node wrapDeserializedObject(Object source) {\n return GenericNodeBuilder.wrapDeserializedObject(source);\n}", "static String fromBracketNotation(String path) {\n return path\n .replace(\"['\", \".\")\n .replace(\"']\", \"\");\n}", "static <T> T readValue(com.jayway.jsonpath.Configuration conf, Object json, String path) {\n if (json instanceof String) {\n return using(conf).parse((String) json).read(path);\n } else {\n return using(conf).parse(JsonUtils.convertToJson(json, \"actual\").getValue()).read(path);\n }\n}" ]
import com.jayway.jsonpath.EvaluationListener; import com.jayway.jsonpath.PathNotFoundException; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.Configuration.defaultConfiguration; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.jsonSource; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.missingNode; import static net.javacrumbs.jsonunit.core.internal.JsonUtils.wrapDeserializedObject; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.fromBracketNotation; import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.readValue;
/** * Copyright 2009-2019 the original author or authors. * * 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 net.javacrumbs.jsonunit.jsonpath; /** * Adapts json-path to json-unit. */ public final class JsonPathAdapter { private JsonPathAdapter() { } public static Object inPath(@NotNull Object json, @NotNull String path) { String normalizedPath = fromBracketNotation(path); try { MatchRecordingListener recordingListener = new MatchRecordingListener(); Object value = readValue(defaultConfiguration().addEvaluationListeners(recordingListener), json, path); return jsonSource(wrapDeserializedObject(value), normalizedPath, recordingListener.getMatchingPaths()); } catch (PathNotFoundException e) {
return jsonSource(missingNode(), normalizedPath);
1
onyxbits/TradeTrax
src/main/java/de/onyxbits/tradetrax/pages/edit/NameEditor.java
[ "@Entity\n@Table(name = \"bookmarks\")\npublic class Bookmark implements Serializable{\n\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Reference to {@link Stock} id.\n\t */\n\t@Id\n\t@Column(name = \"id\", unique = true)\n\tprivate long id;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n}", "@Entity\n@Table(name = \"name\")\npublic class Name implements Serializable{\n\t\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Row index\n\t */\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private long id;\n \n /**\n * Human readable value.\n */\n @Column(name = \"label\", unique=true)\n private String label;\n \n\t/**\n\t * @return the id\n\t */\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id the id to set\n\t */\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the value\n\t */\n\tpublic String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * @param value the value to set\n\t */\n\tpublic void setLabel(String label) {\n\t\tthis.label = label;\n\t}\n}", "@Entity\n@Table(name = \"stock\")\npublic class Stock implements Serializable {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Row index\n\t */\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate long id;\n\n\t/**\n\t * Optional storage location identifier (free form text)\n\t */\n\t@Column(name = \"location\")\n\tprivate String location;\n\n\t/**\n\t * Optional comment (free form text).\n\t */\n\t@Column(name = \"comment\")\n\tprivate String comment;\n\n\t/**\n\t * How much a single unit cost when buying it\n\t */\n\t@Column(name = \"buyprice\")\n\tprivate long buyPrice;\n\n\t/**\n\t * How much a single unit return when selling it.\n\t */\n\t@Column(name = \"sellprice\")\n\tprivate long sellPrice;\n\n\t/**\n\t * How many individual items are in this stack? Stacks may only be sold as a\n\t * whole. In case a partial amount is to be sold, the Asset must be split into\n\t * smaller stacks first.\n\t * <p>\n\t * Any integer number is valid. A value of zero might mean the user is\n\t * tracking stock in refillable bins, a negative value might represent stock\n\t * that was bought on margins.\n\t */\n\t@Column(name = \"stacksize\")\n\tprivate int unitCount = 1;\n\n\t/**\n\t * Human readable name of the asset\n\t */\n\t@ManyToOne(cascade = { CascadeType.ALL })\n\tprivate Name name;\n\n\t/**\n\t * Subtype (e.g. if the asset is available in multiple colors).\n\t */\n\t@ManyToOne(cascade = CascadeType.ALL)\n\tprivate Variant variant;\n\n\t/**\n\t * Timestamp: when the asset was bought.\n\t */\n\t@Column\n\t@Type(type = \"timestamp\")\n\tprivate Date acquired;\n\n\t/**\n\t * Timestamp: when the asset was sold\n\t */\n\t@Column\n\t@Type(type = \"timestamp\")\n\tprivate Date liquidated;\n\n\tpublic Stock() {\n\t}\n\n\t/**\n\t * Create a stock using a template\n\t */\n\tpublic Stock(Stock template) {\n\t\tacquired = template.acquired;\n\t\tbuyPrice = template.buyPrice;\n\t\tcomment = template.comment;\n\t\tid = template.id;\n\t\tliquidated = template.liquidated;\n\t\tif (template.name != null) {\n\t\t\tname = new Name();\n\t\t\tname.setId(template.name.getId());\n\t\t\tname.setLabel(template.name.getLabel());\n\t\t}\n\t\tsellPrice = template.sellPrice;\n\t\tunitCount = template.unitCount;\n\t\tlocation = template.location;\n\t\tif (template.variant != null) {\n\t\t\tvariant = new Variant();\n\t\t\tvariant.setId(template.variant.getId());\n\t\t\tvariant.setLabel(template.variant.getLabel());\n\t\t}\n\t}\n\n\t/**\n\t * Split a new Stock off from this one.\n\t * \n\t * @param amount\n\t * number of units to transfer to the split off stock\n\t * @return a new instance with the specified number of units.\n\t */\n\tpublic Stock splitStock(int amount) {\n\t\tStock ret = new Stock();\n\t\tif (acquired != null) {\n\t\t\tret.acquired = (Date) acquired.clone();\n\t\t}\n\t\tret.buyPrice = buyPrice;\n\n\t\tif (liquidated != null) {\n\t\t\tret.liquidated = (Date) liquidated.clone();\n\t\t}\n\t\tret.name = name;\n\t\tret.sellPrice = sellPrice;\n\t\tret.variant = variant;\n\t\tret.unitCount = amount;\n\t\tunitCount -= amount;\n\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Create the criteria for finding other stock items that are allowed to merge\n\t * with this one. Two items may merge if they only differ in comment,\n\t * unitcount and acquisition/liquidation date (but they need to be in the same\n\t * state of acquisition/liquidation).\n\t * \n\t * @return Hibernate criterias\n\t */\n\tpublic List<Criterion> allowedToMergeWith() {\n\t\tVector<Criterion> ret = new Vector<Criterion>();\n\t\tret.add(Restrictions.ne(\"id\", id));\n\t\tret.add(Restrictions.eq(\"buyPrice\", buyPrice));\n\t\tret.add(Restrictions.eq(\"sellPrice\", sellPrice));\n\n\t\tif (name == null) {\n\t\t\t// This should never happen\n\t\t\tret.add(Restrictions.isNull(\"name\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.eq(\"name.id\", name.getId()));\n\t\t}\n\t\tif (variant == null) {\n\t\t\tret.add(Restrictions.isNull(\"variant\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.eq(\"variant.id\", variant.getId()));\n\t\t}\n\t\tif (acquired == null) {\n\t\t\tret.add(Restrictions.isNull(\"acquired\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.isNotNull(\"acquired\"));\n\t\t}\n\t\tif (liquidated == null) {\n\t\t\tret.add(Restrictions.isNull(\"liquidated\"));\n\t\t}\n\t\telse {\n\t\t\tret.add(Restrictions.isNotNull(\"liquidated\"));\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\t/**\n\t * Calculate the profit, disregarding of whether the asset has been acquired\n\t * and liquidated.\n\t * \n\t * @return the profit in database format.\n\t */\n\tpublic long calcProfit() {\n\t\treturn (sellPrice - buyPrice) * unitCount;\n\t}\n\n\t/**\n\t * Calculate the total aquisition cost, disregarding whether or not the asset\n\t * has been acquired.\n\t * \n\t * @return buyprice times unitcount\n\t */\n\tpublic long calcTotalCost() {\n\t\treturn buyPrice * unitCount;\n\t}\n\n\t/**\n\t * Calculate the total returns, disregarding whetehr or not the asset has been\n\t * liquidated.\n\t * \n\t * @return sellprice times unit\n\t */\n\tpublic long calcTotalReturns() {\n\t\treturn sellPrice * unitCount;\n\t}\n\n\t/**\n\t * Calculate the financial impact of the stock in its current state on the\n\t * owner's wallet.\n\t * \n\t * @return the balance in database format.\n\t */\n\tpublic long calcBalance() {\n\t\tlong bal = 0;\n\t\tif (liquidated != null) {\n\t\t\tbal = sellPrice * unitCount;\n\t\t}\n\t\tif (acquired != null) {\n\t\t\tbal -= buyPrice * unitCount;\n\t\t}\n\t\treturn bal;\n\t}\n\n\t/**\n\t * @return the comment\n\t */\n\tpublic String getComment() {\n\t\treturn comment;\n\t}\n\n\t/**\n\t * @param comment\n\t * the comment to set\n\t */\n\tpublic void setComment(String comment) {\n\t\tthis.comment = comment;\n\t}\n\n\t/**\n\t * @return the id\n\t */\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id\n\t * the id to set\n\t */\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the buyPrice\n\t */\n\tpublic long getBuyPrice() {\n\t\treturn buyPrice;\n\t}\n\n\t/**\n\t * @param buyPrice\n\t * the buyPrice to set\n\t */\n\tpublic void setBuyPrice(long buyPrice) {\n\t\tthis.buyPrice = buyPrice;\n\t}\n\n\t/**\n\t * @return the sellPrice\n\t */\n\tpublic long getSellPrice() {\n\t\treturn sellPrice;\n\t}\n\n\t/**\n\t * @param sellPrice\n\t * the sellPrice to set\n\t */\n\tpublic void setSellPrice(long sellPrice) {\n\t\tthis.sellPrice = sellPrice;\n\t}\n\n\t/**\n\t * @return the unitCount\n\t */\n\tpublic int getUnitCount() {\n\t\treturn unitCount;\n\t}\n\n\t/**\n\t * @param unitCount\n\t * the unitCount to set\n\t */\n\tpublic void setUnitCount(int unitCount) {\n\t\tthis.unitCount = unitCount;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic Name getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name\n\t * the name to set\n\t */\n\tpublic void setName(Name name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * @return the variant\n\t */\n\tpublic Variant getVariant() {\n\t\treturn variant;\n\t}\n\n\t/**\n\t * @param variant\n\t * the variant to set\n\t */\n\tpublic void setVariant(Variant variant) {\n\t\tthis.variant = variant;\n\t}\n\n\t/**\n\t * @return the aquired\n\t */\n\tpublic Date getAcquired() {\n\t\treturn acquired;\n\t}\n\n\t/**\n\t * @param aquired\n\t * the aquired to set\n\t */\n\tpublic void setAcquired(Date aquired) {\n\t\tthis.acquired = aquired;\n\t}\n\n\t/**\n\t * @return the liquidated\n\t */\n\tpublic Date getLiquidated() {\n\t\treturn liquidated;\n\t}\n\n\t/**\n\t * @param liquidated\n\t * the liquidated to set\n\t */\n\tpublic void setLiquidated(Date liquidated) {\n\t\tthis.liquidated = liquidated;\n\t}\n\n\t/**\n\t * @return the location\n\t */\n\tpublic String getLocation() {\n\t\treturn location;\n\t}\n\n\t/**\n\t * @param location\n\t * the location to set\n\t */\n\tpublic void setLocation(String location) {\n\t\tthis.location = location;\n\t}\n}", "@Import(library = \"context:js/mousetrap.min.js\")\npublic class Index {\n\n\t@SessionAttribute(Layout.FOCUSID)\n\tprivate long focusedStockId;\n\n\t@Property\n\tprivate DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);\n\n\t@Inject\n\tprivate Session session;\n\n\t@Inject\n\tprivate Messages messages;\n\n\t@Inject\n\tprivate BeanModelSource ledgerSource;\n\n\t@Property\n\t@Validate(\"required,minlength=3\")\n\tprivate String buyName;\n\n\t@Property\n\tprivate String buyVariant;\n\n\t@Property\n\tprivate String buyCost;\n\n\t@Property\n\tprivate String buyReturns;\n\n\t@Property\n\tprivate String buyLocation;\n\n\t@Property\n\tprivate int buyAmount = 1;\n\n\t@Property\n\tprivate StockPagedGridDataSource stocks;\n\n\t@Property\n\tprivate Stock row;\n\n\t@Component(id = \"buyform\")\n\tprivate Form buyForm;\n\n\t@Component(id = \"buyName\")\n\tprivate TextField buyNameField;\n\n\t@Component(id = \"buyVariant\")\n\tprivate TextField buyVariantField;\n\n\t@Component(id = \"buyAmount\")\n\tprivate TextField buyAmountField;\n\n\t@Component(id = \"buyCost\")\n\tprivate TextField buyCostField;\n\n\t@Component(id = \"buyReturns\")\n\tprivate TextField buyReturnsField;\n\n\t@Component(id = \"buyLocation\")\n\tprivate TextField buyLocationFiels;\n\n\t@Component(id = \"ledger\")\n\tprivate Grid ledger;\n\n\t@Component(id = \"filterForm\")\n\tprivate Form filterForm;\n\n\t@Component(id = \"reset\")\n\tprivate Submit reset;\n\n\t@Persist\n\t@Property\n\tprivate String filterName;\n\n\t@Persist\n\t@Property\n\tprivate String filterLocation;\n\n\t@Component(id = \"filterLocation\")\n\tprivate TextField filterLocationField;\n\n\t@Persist\n\t@Property\n\tprivate String filterComment;\n\n\t@Component(id = \"filterComment\")\n\tprivate TextField filterCommentField;\n\n\t@Component(id = \"filterName\")\n\tprivate TextField filterNameField;\n\n\t@Persist\n\t@Property\n\tprivate String filterVariant;\n\n\t@Component(id = \"filterVariant\")\n\tprivate TextField filterVariantField;\n\n\t@Persist\n\t@Property\n\tprivate StockState filterState;\n\n\t@Component(id = \"filterState\")\n\tprivate Select filterStateField;\n\n\t@Persist\n\t@Property\n\tprivate Date filterAcquisition;\n\n\t@Component(id = \"filterAcquisition\")\n\tprivate DateField filterAcquisitionField;\n\n\t@Persist\n\t@Validate(\"required\")\n\t@Property\n\tprivate TimeSpan filterAcquisitionSpan;\n\n\t@Component(id = \"filterAcquisitionSpan\")\n\tprivate Select filterAcquisitionSpanField;\n\n\t@Persist\n\t@Property\n\tprivate Date filterLiquidation;\n\n\t@Component(id = \"filterLiquidation\")\n\tprivate DateField filterLiquidationField;\n\n\t@Persist\n\t@Validate(\"required\")\n\t@Property\n\tprivate TimeSpan filterLiquidationSpan;\n\n\t@Component(id = \"filterLiquidationSpan\")\n\tprivate Select filterLiquidationSpanField;\n\n\t@Inject\n\tprivate SettingsStore settingsStore;\n\n\t@Inject\n\tprivate EventLogger eventLogger;\n\n\t@Inject\n\tprivate MoneyRepresentation moneyRepresentation;\n\n\t@Property\n\tprivate String matches;\n\n\t@Inject\n\tprivate Block acquisitionblock;\n\n\t@Inject\n\tprivate Block filterblock;\n\n\t@InjectComponent\n\tprivate Zone flipview;\n\n\t@Property\n\t@Persist\n\tprivate boolean showFilterForm;\n\n\t@Property\n\tprivate long matchingItemCount;\n\n\t@Property\n\t@Persist\n\tprivate boolean autofocusBuyForm;\n\n\t@Property\n\tprivate int matchingAssetCount;\n\n\t@Inject\n\tprivate JavaScriptSupport javaScriptSupport;\n\n\tpublic String styleFor(String tag) {\n\t\tString tmp = settingsStore.get(SettingsStore.TCACFIELDS, AcquisitionFields.DEFAULT);\n\t\tif (!tmp.contains(tag)) {\n\t\t\treturn \"display:none;\";\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic Block getActiveForm() {\n\t\tif (showFilterForm) {\n\t\t\treturn filterblock;\n\t\t}\n\t\telse {\n\t\t\treturn acquisitionblock;\n\t\t}\n\t}\n\n\tpublic void setupRender() {\n\t\tstocks = new StockPagedGridDataSource(session).withName(filterName).withVariant(filterVariant)\n\t\t\t\t.withState(filterState).withLocation(filterLocation).withComment(filterComment)\n\t\t\t\t.withAcquisition(filterAcquisition, filterAcquisitionSpan)\n\t\t\t\t.withLiquidation(filterLiquidation, filterLiquidationSpan);\n\t\tmatchingAssetCount = stocks.getAvailableRows();\n\t\tmatchingItemCount = stocks.getItemCount();\n\t}\n\n\tpublic void afterRender() {\n\t\tautofocusBuyForm = false;\n\n\t\t// Let the Escape key toggle the forms. It is slightly messy to do it this\n\t\t// way. Using getElementById() would be preferable, but the id is assigned\n\t\t// dynamically.\n\t\tjavaScriptSupport\n\t\t\t\t.addScript(\"Mousetrap.prototype.stopCallback = function(e, element) {return false;};\");\n\t\tjavaScriptSupport\n\t\t\t\t.addScript(\"Mousetrap.bind('esc', function() {document.getElementsByClassName('formtoggler')[0].click();});\");\n\t}\n\n\tpublic BeanModel<Object> getLedgerModel() {\n\t\tBeanModel<Object> model = ledgerSource.createDisplayModel(Object.class, messages);\n\t\tList<LedgerColumns> tmp = LedgerColumns.fromCsv(settingsStore.get(SettingsStore.TCLCOLUMNS,\n\t\t\t\tLedgerColumns.DEFAULT));\n\t\tfor (LedgerColumns col : tmp) {\n\t\t\tmodel.addEmpty(col.getName()).sortable(\n\t\t\t\t\tLedgerColumns.BUYPRICE.getName().equals(col.getName())\n\t\t\t\t\t\t\t|| LedgerColumns.SELLPRICE.getName().equals(col.getName())\n\t\t\t\t\t\t\t|| LedgerColumns.LIQUIDATED.getName().equals(col.getName())\n\t\t\t\t\t\t\t|| LedgerColumns.ACQUIRED.getName().equals(col.getName()));\n\t\t}\n\t\treturn model;\n\t}\n\n\tpublic List<String> onProvideCompletionsFromBuyVariant(String partial) {\n\t\treturn IdentUtil.suggestVariants(session, partial);\n\t}\n\n\tpublic List<String> onProvideCompletionsFromBuyName(String partial) {\n\t\treturn IdentUtil.suggestNames(session, partial);\n\t}\n\n\tpublic void onValidateFromBuyForm() {\n\t\ttry {\n\t\t\tmoneyRepresentation.userToDatabase(buyCost, 1);\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\tbuyForm.recordError(buyCostField, messages.get(\"invalid-numberformat\"));\n\t\t}\n\t\ttry {\n\t\t\tmoneyRepresentation.userToDatabase(buyReturns, 1);\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\tbuyForm.recordError(buyReturnsField, messages.get(\"invalid-numberformat\"));\n\t\t}\n\t}\n\n\tpublic Object onToggleForm() {\n\t\tshowFilterForm = !showFilterForm;\n\t\treturn flipview;\n\t}\n\n\t@CommitAfter\n\tpublic Object onSuccessFromBuyForm() {\n\t\tStock item = new Stock();\n\n\t\titem.setName(IdentUtil.findName(session, buyName));\n\t\titem.setVariant(IdentUtil.findVariant(session, buyVariant));\n\t\ttry {\n\t\t\titem.setBuyPrice(moneyRepresentation.userToDatabase(buyCost, 1));\n\t\t\titem.setSellPrice(moneyRepresentation.userToDatabase(buyReturns, 1));\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\t// We already validated this\n\t\t}\n\t\tCalendar now = Calendar.getInstance();\n\t\tnow.set(Calendar.MILLISECOND, 0);\n\t\tnow.set(Calendar.SECOND, 0);\n\t\tnow.set(Calendar.MINUTE, 0);\n\t\tnow.set(Calendar.HOUR_OF_DAY, 0);\n\n\t\titem.setLocation(buyLocation);\n\t\titem.setUnitCount(buyAmount);\n\t\titem.setAcquired(now.getTime());\n\t\tsession.persist(item);\n\t\tfocusedStockId = item.getId();\n\t\teventLogger.acquired(item);\n\t\twithNoFilters();\n\t\tledger.reset();\n\t\tautofocusBuyForm = true;\n\t\treturn Index.class;\n\t}\n\n\tpublic void onSelectedFromReset() {\n\t\t// Reset button event -> return all values to their defaults...\n\t\tfilterName = null;\n\t\tfilterState = null;\n\t\tfilterVariant = null;\n\t\tfilterAcquisition = null;\n\t\tfilterLiquidation = null;\n\t\tfilterLocation = null;\n\t\tfilterComment = null;\n\t\tledger.reset();\n\t\t// ... then just fall through to the success action.\n\t}\n\n\tpublic Object onSuccessFromFilterForm() {\n\t\treturn Index.class;\n\t}\n\n\tpublic Index withNoFilters() {\n\t\tfilterName = null;\n\t\tfilterState = null;\n\t\tfilterVariant = null;\n\t\tfilterAcquisition = null;\n\t\tfilterLiquidation = null;\n\t\tfilterLocation = null;\n\t\tfilterComment = null;\n\t\tshowFilterForm = false;\n\t\treturn this;\n\t}\n\n\tpublic Index withFilterName(String name) {\n\t\tthis.filterName = name;\n\t\tshowFilterForm = true;\n\t\treturn this;\n\t}\n\n\tpublic Index withFilterVariant(String name) {\n\t\tthis.filterVariant = name;\n\t\tshowFilterForm = true;\n\t\treturn this;\n\t}\n\n\tpublic String hasFilterName() {\n\t\treturn filterName;\n\t}\n\n\tpublic String hasFilterVariant() {\n\t\treturn filterVariant;\n\t}\n\n}", "public class LabelManager {\n\n\t@Inject\n\tprivate Session session;\n\t\n\t@Inject\n\tprivate AlertManager alertManager;\n\t\n\t@Inject\n\tprivate Messages messages;\n\n\t@Inject\n\tprivate EventLogger eventLogger;\n\n\t@Property\n\tprivate Name name;\n\n\t@Property\n\tprivate Variant variant;\n\n\t@Property\n\tprivate LabelActions actions;\n\n\t@Property\n\tprivate boolean applyToNames;\n\n\t@Property\n\tprivate boolean applyToVariants;\n\n\t@Component(id = \"applyToNames\")\n\tprivate Checkbox applyToNamesField;\n\n\t@Component(id = \"applyToVariants\")\n\tprivate Checkbox applyToVariantsField;\n\n\t@Component(id = \"actionForm\")\n\tprivate Form actionForm;\n\n\t@Property\n\tprivate int affected;\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Name> getNames() {\n\t\treturn session.createCriteria(Name.class).addOrder(Order.asc(\"label\")).list();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Variant> getVariants() {\n\t\treturn session.createCriteria(Variant.class).addOrder(Order.asc(\"label\")).list();\n\t}\n\n\tpublic void setupRender() {\n\t\taffected=0;\n\t}\n\n\t@CommitAfter\n\tpublic LabelManager onSuccessFromActionForm() {\n\t\tif (actions == LabelActions.TRIM) {\n\t\t\ttrimLabels();\n\t\t\talertManager.alert(Duration.SINGLE,Severity.INFO,messages.format(\"deleted\",affected));\n\t\t}\n\t\telse {\n\t\t\tsanitizeLabels();\n\t\t\talertManager.alert(Duration.SINGLE,Severity.INFO,messages.format(\"updated\",affected));\n\t\t}\n\t\treturn this;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void sanitizeLabels() {\n\t\tif (applyToNames) {\n\t\t\tList<Name> lst = session.createCriteria(Name.class).list();\n\t\t\tfor (Name n : lst) {\n\t\t\t\tswitch (actions) {\n\t\t\t\t\tcase UPPERCASE: {\n\t\t\t\t\t\tString s = n.getLabel().toUpperCase().trim();\n\t\t\t\t\t\tif (!s.equals(n.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(n.getLabel(), s);\n\t\t\t\t\t\t\tn.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase LOWERCASE: {\n\t\t\t\t\t\tString s = n.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (!s.equals(n.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(n.getLabel(), s);\n\t\t\t\t\t\t\tn.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase CAPITALIZE: {\n\t\t\t\t\t\tString s = n.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (s.length() >= 1) {\n\t\t\t\t\t\t\ts = Character.toUpperCase(s.charAt(0)) + s.substring(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!s.equals(n.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(n.getLabel(), s);\n\t\t\t\t\t\t\tn.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsession.update(n);\n\t\t\t}\n\t\t}\n\t\tif (applyToVariants) {\n\t\t\tList<Variant> lst = session.createCriteria(Variant.class).list();\n\t\t\tfor (Variant v : lst) {\n\t\t\t\tswitch (actions) {\n\t\t\t\t\tcase UPPERCASE: {\n\t\t\t\t\t\tString s = v.getLabel().toUpperCase().trim();\n\t\t\t\t\t\tif (!s.equals(v.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(v.getLabel(), s);\n\t\t\t\t\t\t\tv.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase LOWERCASE: {\n\t\t\t\t\t\tString s = v.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (!s.equals(v.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(v.getLabel(), s);\n\t\t\t\t\t\t\tv.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase CAPITALIZE: {\n\t\t\t\t\t\tString s = v.getLabel().toLowerCase().trim();\n\t\t\t\t\t\tif (s.length() >= 1) {\n\t\t\t\t\t\t\ts = Character.toUpperCase(s.charAt(0)) + s.substring(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!s.equals(v.getLabel())) {\n\t\t\t\t\t\t\teventLogger.rename(v.getLabel(), s);\n\t\t\t\t\t\t\tv.setLabel(s);\n\t\t\t\t\t\t\taffected++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsession.update(v);\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void trimLabels() {\n\t\t// Yes, this is super inefficient, but these tables are not that big\n\t\tif (applyToNames) {\n\t\t\tList<Name> lst = session.createCriteria(Name.class).list();\n\t\t\tfor (Name n : lst) {\n\t\t\t\tlong count = (Long) session.createCriteria(Stock.class)\n\t\t\t\t\t\t.add(Restrictions.eq(\"name.id\", n.getId())).setProjection(Projections.rowCount())\n\t\t\t\t\t\t.uniqueResult();\n\t\t\t\tif (count < 1) {\n\t\t\t\t\tsession.delete(n);\n\t\t\t\t\teventLogger.deleted(n.getLabel());\n\t\t\t\t\taffected++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (applyToVariants) {\n\t\t\tList<Variant> lst = session.createCriteria(Variant.class).list();\n\t\t\tfor (Variant v : lst) {\n\t\t\t\tlong count = (Long) session.createCriteria(Stock.class)\n\t\t\t\t\t\t.add(Restrictions.eq(\"variant.id\", v.getId())).setProjection(Projections.rowCount())\n\t\t\t\t\t\t.uniqueResult();\n\t\t\t\tif (count < 1) {\n\t\t\t\t\tsession.delete(v);\n\t\t\t\t\teventLogger.deleted(v.getLabel());\n\t\t\t\t\taffected++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "public interface EventLogger {\n\n\t/**\n\t * Call this after selling off an asset.\n\t * \n\t * @param stock\n\t * the stock after saving it to the database.\n\t */\n\tpublic void liquidated(Stock stock);\n\n\t/**\n\t * Call this after acquiring an asset.\n\t * \n\t * @param stock\n\t * the stock after saving it to the database\n\t */\n\tpublic void acquired(Stock stock);\n\n\t/**\n\t * Call this after splitting a stock in two.\n\t * \n\t * @param parent\n\t * the stock from which units were split off (after saving it to the\n\t * database)\n\t * @param offspring\n\t * the newly created stock (after saving it to the database).\n\t */\n\tpublic void split(Stock parent, Stock offspring);\n\n\t/**\n\t * Call this after merging two assets\n\t * \n\t * @param accumulator\n\t * the stock into which was merged ( after being saved to the\n\t * database).\n\t * @param collected\n\t * the stock that was assimilated (after being saved to the\n\t * database).\n\t */\n\tpublic void merged(Stock accumulator, Stock collected);\n\n\t/**\n\t * Call this after a deleting a stock from the ledger\n\t * \n\t * @param stock\n\t * the stock after it has been deleted.\n\t */\n\tpublic void deleted(Stock stock);\n\n\t/**\n\t * Call this after the user edited a stock\n\t * \n\t * @param orig\n\t * the original state of the stock.\n\t */\n\tpublic void modified(Stock orig);\n\n\t/**\n\t * Rename a label\n\t * \n\t * @param orig\n\t * old name\n\t * @param now\n\t * new name\n\t */\n\tpublic void rename(String orig, String now);\n\n\t/**\n\t * Delete a label\n\t * \n\t * @param name\n\t * the label to delete\n\t */\n\tpublic void deleted(String name);\n\n\t/**\n\t * Create a filter expression for finding log entries that concern a specific\n\t * stock item.\n\t * \n\t * @param stock\n\t * the stock to search the log for\n\t * @return a string for grepping in the details messages.\n\t */\n\tpublic String grep(Stock stock);\n\n}" ]
import java.util.List; import org.apache.tapestry5.alerts.AlertManager; import org.apache.tapestry5.alerts.Duration; import org.apache.tapestry5.alerts.Severity; import org.apache.tapestry5.annotations.Component; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.annotations.InjectPage; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.beaneditor.Validate; import org.apache.tapestry5.corelib.components.EventLink; import org.apache.tapestry5.corelib.components.Form; import org.apache.tapestry5.corelib.components.TextField; import org.apache.tapestry5.hibernate.annotations.CommitAfter; import org.apache.tapestry5.ioc.Messages; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.javascript.JavaScriptSupport; import org.hibernate.Session; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import de.onyxbits.tradetrax.entities.Bookmark; import de.onyxbits.tradetrax.entities.Name; import de.onyxbits.tradetrax.entities.Stock; import de.onyxbits.tradetrax.pages.Index; import de.onyxbits.tradetrax.pages.tools.LabelManager; import de.onyxbits.tradetrax.services.EventLogger;
package de.onyxbits.tradetrax.pages.edit; /** * A simple editor page for changing or deleting a {@link Name} object and * returning to the main page afterwards. * * @author patrick * */ @Import(library = "context:js/mousetrap.min.js") public class NameEditor { @Property private long nameId; @Property @Validate("required,minlength=3") private String name; @Property private String status; @Component(id = "nameField") private TextField nameField; @Component(id = "editForm") private Form form; @Inject private Session session; @Inject private AlertManager alertManager; @Inject private Messages messages; @Inject private EventLogger eventLogger; @InjectPage private Index index; private boolean eventDelete; @Component(id = "show") private EventLink show; @Inject private JavaScriptSupport javaScriptSupport; protected Object onShow() { Name n = (Name) session.get(Name.class, nameId); if (n != null) { index.withNoFilters().withFilterName(n.getLabel()); } return index; } protected void onActivate(Long nameId) { this.nameId = nameId; } protected void setupRender() { Name n = (Name) session.get(Name.class, nameId); if (n != null) { name = n.getLabel(); status = messages.format("status-count", session.createCriteria(Stock.class).add(Restrictions.eq("name.id", this.nameId)) .setProjection(Projections.rowCount()).uniqueResult()); } } protected Long onPassivate() { return nameId; } public void onValidateFromEditForm() { if (name == null) { form.recordError(messages.get("validate-not-empty")); } else { if (name.trim().length() < name.length()) { form.recordError(messages.get("validate-not-trimmed")); } } } public void onSelectedFromDelete() { eventDelete = true; } public void onSelectedFromSave() { eventDelete = false; } @CommitAfter public Object onSuccess() { if (eventDelete) { doDelete(); } else { doSave(); } return LabelManager.class; } private void doSave() { try { Name n = (Name) session.load(Name.class, nameId); String s = n.getLabel(); n.setLabel(name); session.update(n); alertManager.alert(Duration.SINGLE, Severity.INFO, messages.format("renamed", s, name)); eventLogger.rename(s, name); } catch (Exception e) { // TODO: Figure out how we got here and give the user better feedback alertManager.alert(Duration.SINGLE, Severity.WARN, messages.format("exception", e)); } } private void doDelete() { try { Name bye = (Name) session.load(Name.class, nameId); @SuppressWarnings("unchecked") List<Stock> lst = session.createCriteria(Stock.class).add(Restrictions.eq("name", bye)) .list(); for (Stock s : lst) {
Bookmark bm = (Bookmark) session.get(Bookmark.class, s.getId());
0
GlitchCog/ChatGameFontificator
src/main/java/com/glitchcog/fontificator/gui/emoji/EmojiLoadProgressPanel.java
[ "public class ConfigEmoji extends Config\n{\n private static final Logger logger = Logger.getLogger(ConfigEmoji.class);\n\n public static final int MIN_SCALE = 10;\n public static final int MAX_SCALE = 500;\n\n public static final int MIN_BADGE_OFFSET = -32;\n public static final int MAX_BADGE_OFFSET = 64;\n\n /**\n * The green of moderator badges, used for FrankerFaceZ badge coloration\n */\n public static final Color MOD_BADGE_COLOR = new Color(0x34AE0A);\n\n /**\n * Whether all emoji are enabled or not\n */\n private Boolean emojiEnabled;\n\n /**\n * Whether emoji that have animations should display animated\n */\n private Boolean animationEnabled;\n\n /**\n * Whether Twitch badges are enabled or not\n */\n private Boolean twitchBadgesEnabled;\n\n /**\n * Whether FrankerFaceZ badges are enabled or not\n */\n private Boolean ffzBadgesEnabled;\n\n /**\n * Whether the emoji scale value is used to modify the size of the emoji relative to the line height, or the\n * original emoji image size\n */\n private Boolean emojiScaleToLine;\n\n /**\n * Whether the badge scale value is used to modify the size of the badge relative to the line height, or the\n * original badge image size\n */\n private Boolean badgeScaleToLine;\n\n /**\n * This is the number of pixels to offset the badges vertically to accommodate the fact that sprite fonts don't have\n * a baseline to determine where the vertical center of the text is appropriately\n */\n private Integer badgeHeightOffset;\n\n /**\n * The scale value to be applied to the emoji\n */\n private Integer emojiScale;\n\n /**\n * The scale value to be applied to the badge\n */\n private Integer badgeScale;\n\n /**\n * The strategy for drawing an emoji when the emoji key word and image URL are loaded, but the image itself is not\n */\n private EmojiLoadingDisplayStragegy displayStrategy;\n\n /**\n * Whether Twitch emotes are enabled or not\n */\n private Boolean twitchEnabled;\n\n /**\n * Whether Twitch global emotes are to be cached or not\n */\n private Boolean twitchCacheEnabled;\n\n /**\n * Whether FrankerFaceZ emotes are enabled or not\n */\n private Boolean ffzEnabled;\n\n /**\n * Whether FrankerFaceZ emotes are to be cached or not\n */\n private Boolean ffzCacheEnabled;\n\n /**\n * The loaded Twitch badges channel, or null if none is loaded\n */\n private String twitchBadgesLoadedChannel;\n\n /**\n * The loaded FrankerFaceZ badges channel, or null if none is loaded\n */\n private String ffzBadgesLoadedChannel;\n\n /**\n * Whether the Twitch emotes have been loaded\n */\n private Boolean twitchLoaded;\n\n /**\n * Whether Twitch global emotes are cached or not\n */\n private Boolean twitchCached;\n\n /**\n * The loaded FrankerFaceZ channel, or null if none is loaded\n */\n private String ffzLoadedChannel;\n\n /**\n * Whether the FrankerFaceZ global emotes are loaded\n */\n private Boolean ffzGlobalLoaded;\n\n /**\n * Whether FrankerFaceZ global and channel specific emotes have been cached\n */\n private Boolean ffzCached;\n\n /**\n * Whether BetterTTV emotes are enabled or not\n */\n private Boolean bttvEnabled;\n\n /**\n * Whether BetterTTV emotes are to be cached or not\n */\n private Boolean bttvCacheEnabled;\n\n /**\n * The loaded BetterTTV channel, or null if none is loaded\n */\n private String bttvLoadedChannel;\n\n /**\n * Whether the BetterTTV global emotes are loaded\n */\n private Boolean bttvGlobalLoaded;\n\n /**\n * Whether BetterTTV global and channel specific emotes have been cached\n */\n private Boolean bttvCached;\n\n /**\n * Whether to use Twitter emoji images rather than the system font\n */\n private Boolean twitterEnabled;\n\n public ConfigEmoji()\n {\n resetWorkCompleted();\n }\n\n @Override\n public void reset()\n {\n emojiEnabled = null;\n animationEnabled = null;\n twitchBadgesEnabled = null;\n ffzBadgesEnabled = null;\n emojiScaleToLine = null;\n badgeScaleToLine = null;\n badgeHeightOffset = null;\n emojiScale = null;\n badgeScale = null;\n displayStrategy = null;\n twitchEnabled = null;\n twitchCacheEnabled = null;\n ffzEnabled = null;\n ffzCacheEnabled = null;\n bttvEnabled = null;\n bttvCacheEnabled = null;\n bttvLoadedChannel = null;\n bttvGlobalLoaded = null;\n bttvCached = null;\n twitterEnabled = null;\n }\n\n public boolean isEmojiEnabled()\n {\n return emojiEnabled != null && emojiEnabled;\n }\n\n public void setEmojiEnabled(Boolean emojiEnabled)\n {\n this.emojiEnabled = emojiEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_ENABLED, Boolean.toString(emojiEnabled));\n }\n\n public boolean isAnimationEnabled()\n {\n return animationEnabled != null && animationEnabled;\n }\n\n public void setAnimationEnabled(Boolean animationEnabled)\n {\n this.animationEnabled = animationEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_ANIMATION, Boolean.toString(animationEnabled));\n }\n\n public boolean isTwitchBadgesEnabled()\n {\n return twitchBadgesEnabled != null && twitchBadgesEnabled;\n }\n\n public void setTwitchBadgesEnabled(Boolean twitchBadgesEnabled)\n {\n this.twitchBadgesEnabled = twitchBadgesEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_TWITCH_BADGES, Boolean.toString(twitchBadgesEnabled));\n }\n\n public boolean isFfzBadgesEnabled()\n {\n return ffzBadgesEnabled != null && ffzBadgesEnabled;\n }\n\n public void setFfzBadgesEnabled(Boolean ffzBadgesEnabled)\n {\n this.ffzBadgesEnabled = ffzBadgesEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_FFZ_BADGES, Boolean.toString(ffzBadgesEnabled));\n }\n\n /**\n * Get whether badges of any type enabled\n * \n * @return ffz or twitch badges enabled\n */\n public boolean isAnyBadgesEnabled()\n {\n return isFfzBadgesEnabled() || isTwitchBadgesEnabled();\n }\n\n public boolean isEmojiScaleToLine()\n {\n return emojiScaleToLine != null && emojiScaleToLine;\n }\n\n public void setEmojiScaleToLine(Boolean emojiScaleToLine)\n {\n this.emojiScaleToLine = emojiScaleToLine;\n props.setProperty(FontificatorProperties.KEY_EMOJI_SCALE_TO_LINE, Boolean.toString(emojiScaleToLine));\n }\n\n public boolean isBadgeScaleToLine()\n {\n return badgeScaleToLine != null && badgeScaleToLine;\n }\n\n public void setBadgeScaleToLine(Boolean badgeScaleToLine)\n {\n this.badgeScaleToLine = badgeScaleToLine;\n props.setProperty(FontificatorProperties.KEY_EMOJI_BADGE_SCALE_TO_LINE, Boolean.toString(badgeScaleToLine));\n }\n\n public int getBadgeHeightOffset()\n {\n return badgeHeightOffset;\n }\n\n public void setBadgeHeightOffset(int badgeHeightOffset)\n {\n this.badgeHeightOffset = badgeHeightOffset;\n props.setProperty(FontificatorProperties.KEY_EMOJI_BADGE_HEIGHT_OFFSET, Integer.toString(badgeHeightOffset));\n }\n\n public Integer getEmojiScale()\n {\n return emojiScale;\n }\n\n public void setEmojiScale(Integer emojiScale)\n {\n this.emojiScale = emojiScale;\n props.setProperty(FontificatorProperties.KEY_EMOJI_SCALE, Integer.toString(emojiScale));\n }\n\n public Integer getBadgeScale()\n {\n return badgeScale;\n }\n\n public void setBadgeScale(Integer badgeScale)\n {\n this.badgeScale = badgeScale;\n props.setProperty(FontificatorProperties.KEY_EMOJI_BADGE_SCALE, Integer.toString(badgeScale));\n }\n\n public EmojiLoadingDisplayStragegy getDisplayStrategy()\n {\n return displayStrategy;\n }\n\n public void setDisplayStrategy(EmojiLoadingDisplayStragegy displayStrategy)\n {\n this.displayStrategy = displayStrategy;\n props.setProperty(FontificatorProperties.KEY_EMOJI_DISPLAY_STRAT, displayStrategy.name());\n }\n\n public boolean isTwitchEnabled()\n {\n return twitchEnabled != null && twitchEnabled;\n }\n\n public void setTwitchEnabled(Boolean twitchEnabled)\n {\n this.twitchEnabled = twitchEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_TWITCH_ENABLE, Boolean.toString(twitchEnabled));\n }\n\n public boolean isTwitchCacheEnabled()\n {\n return twitchCacheEnabled != null && twitchCacheEnabled;\n }\n\n public void setTwitchCacheEnabled(Boolean twitchCacheEnabled)\n {\n this.twitchCacheEnabled = twitchCacheEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_TWITCH_CACHE, Boolean.toString(twitchCacheEnabled));\n }\n\n public boolean isFfzEnabled()\n {\n return ffzEnabled != null && ffzEnabled;\n }\n\n public void setFfzEnabled(Boolean ffzEnabled)\n {\n this.ffzEnabled = ffzEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_FFZ_ENABLE, Boolean.toString(ffzEnabled));\n }\n\n public boolean isFfzCacheEnabled()\n {\n return ffzCacheEnabled != null && ffzCacheEnabled;\n }\n\n public void setFfzCacheEnabled(Boolean ffzCacheEnabled)\n {\n this.ffzCacheEnabled = ffzCacheEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_FFZ_CACHE, Boolean.toString(ffzCacheEnabled));\n }\n\n public Boolean isBttvEnabled()\n {\n return bttvEnabled != null && bttvEnabled;\n }\n\n public Boolean isBttvCacheEnabled()\n {\n return bttvCacheEnabled != null && bttvCacheEnabled;\n }\n\n public void setBttvCacheEnabled(Boolean bttvCacheEnabled)\n {\n this.bttvCacheEnabled = bttvCacheEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_BTTV_CACHE, Boolean.toString(bttvCacheEnabled));\n }\n\n /**\n * Get whether the type of emoji is enabled and loaded\n * \n * @param type\n * @return enabled\n */\n public boolean isTypeEnabledAndLoaded(EmojiType type)\n {\n if (type == null)\n {\n return false;\n }\n else\n {\n switch (type)\n {\n case FRANKERFACEZ_CHANNEL:\n return ffzEnabled != null && ffzEnabled && ffzLoadedChannel != null;\n case FRANKERFACEZ_GLOBAL:\n return ffzEnabled != null && ffzEnabled && ffzGlobalLoaded != null && ffzGlobalLoaded;\n case FRANKERFACEZ_BADGE:\n return ffzBadgesEnabled != null && ffzBadgesEnabled && ffzBadgesLoadedChannel != null;\n case BETTER_TTV_CHANNEL:\n return bttvEnabled != null && bttvEnabled && bttvLoadedChannel != null;\n case BETTER_TTV_GLOBAL:\n return bttvEnabled != null && bttvEnabled && bttvGlobalLoaded != null && bttvGlobalLoaded;\n // case TWITCH_V2:\n // case TWITCH_V3:\n // // Only V2 and V3. Chat V1 doesn't use the normal EmojiTypeMap, so it doesn't need to be checked. They're loaded on the fly.\n // return ControlPanelEmoji.TWITCH_EMOTE_VERSION.equals(type) && twitchEnabled != null && twitchEnabled && twitchLoaded != null && twitchLoaded;\n case TWITCH_BADGE:\n return twitchBadgesEnabled != null && twitchBadgesEnabled && twitchBadgesLoadedChannel != null;\n case TWITTER_EMOJI:\n return twitterEnabled;\n default:\n // If it doesn't have a coded EmojiType, then we don't know it\n return false;\n }\n }\n }\n\n public LoadConfigReport validateStrings(LoadConfigReport report, String enabledBool, String aniBool, String badgeTwitchBool, String badgeFfzBool, String scaleEnabledBool, String scaleBadgeEnabledBool, String badgeHeightOffsetStr, String scale, String scaleBadge, String displayStrat, String twitchBool, String twitchCacheBool, String ffzBool, String ffzCacheBool, String bttvBool, String bttvCacheBool, String twitterBool)\n {\n validateBooleanStrings(report, enabledBool, aniBool, badgeTwitchBool, badgeFfzBool, scaleEnabledBool, scaleBadgeEnabledBool, twitchBool, twitchCacheBool, ffzBool, ffzCacheBool, bttvBool, bttvCacheBool);\n validateIntegerWithLimitString(FontificatorProperties.KEY_EMOJI_SCALE, scale, MIN_SCALE, MAX_SCALE, report);\n validateIntegerWithLimitString(FontificatorProperties.KEY_EMOJI_BADGE_SCALE, scaleBadge, MIN_SCALE, MAX_SCALE, report);\n validateIntegerWithLimitString(FontificatorProperties.KEY_EMOJI_BADGE_HEIGHT_OFFSET, badgeHeightOffsetStr, MIN_BADGE_OFFSET, MAX_BADGE_OFFSET, report);\n return report;\n }\n\n @Override\n public LoadConfigReport load(Properties props, LoadConfigReport report)\n {\n this.props = props;\n\n reset();\n\n // Check that the values exist\n baseValidation(props, FontificatorProperties.EMOJI_KEYS, report);\n\n if (report.isErrorFree())\n {\n final String enabledStr = props.getProperty(FontificatorProperties.KEY_EMOJI_ENABLED);\n final String aniStr = props.getProperty(FontificatorProperties.KEY_EMOJI_ANIMATION);\n\n final String twitchBadgeStr = props.getProperty(FontificatorProperties.KEY_EMOJI_TWITCH_BADGES);\n final String ffzBadgeStr = props.getProperty(FontificatorProperties.KEY_EMOJI_FFZ_BADGES);\n\n final String scaleEnabledStr = props.getProperty(FontificatorProperties.KEY_EMOJI_SCALE_TO_LINE);\n final String scaleBadgeEnabledStr = props.getProperty(FontificatorProperties.KEY_EMOJI_BADGE_SCALE_TO_LINE);\n final String badgeHeightOffsetStr = props.getProperty(FontificatorProperties.KEY_EMOJI_BADGE_HEIGHT_OFFSET);\n final String scaleStr = props.getProperty(FontificatorProperties.KEY_EMOJI_SCALE);\n final String scaleBadgeStr = props.getProperty(FontificatorProperties.KEY_EMOJI_BADGE_SCALE);\n final String displayStratStr = props.getProperty(FontificatorProperties.KEY_EMOJI_DISPLAY_STRAT);\n\n final String twitchEnabledStr = props.getProperty(FontificatorProperties.KEY_EMOJI_TWITCH_ENABLE);\n final String twitchCacheStr = props.getProperty(FontificatorProperties.KEY_EMOJI_TWITCH_CACHE);\n\n final String ffzEnabledStr = props.getProperty(FontificatorProperties.KEY_EMOJI_FFZ_ENABLE);\n final String ffzCacheStr = props.getProperty(FontificatorProperties.KEY_EMOJI_FFZ_CACHE);\n\n final String bttvEnabledStr = props.getProperty(FontificatorProperties.KEY_EMOJI_BTTV_ENABLE);\n final String bttvCacheStr = props.getProperty(FontificatorProperties.KEY_EMOJI_BTTV_CACHE);\n\n final String twitterStr = props.getProperty(FontificatorProperties.KEY_EMOJI_TWITTER_ENABLE);\n\n // Check that the values are valid\n validateStrings(report, enabledStr, aniStr, twitchBadgeStr, ffzBadgeStr, scaleEnabledStr, scaleBadgeEnabledStr, badgeHeightOffsetStr, scaleStr, scaleBadgeStr, displayStratStr, twitchEnabledStr, twitchCacheStr, ffzEnabledStr, ffzCacheStr, bttvEnabledStr, bttvCacheStr, twitterStr);\n\n // Fill the values\n if (report.isErrorFree())\n {\n emojiEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_ENABLED, report);\n animationEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_ANIMATION, report);\n twitchBadgesEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_TWITCH_BADGES, report);\n ffzBadgesEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_FFZ_BADGES, report);\n emojiScaleToLine = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_SCALE_TO_LINE, report);\n badgeScaleToLine = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_BADGE_SCALE_TO_LINE, report);\n badgeHeightOffset = evaluateIntegerString(props, FontificatorProperties.KEY_EMOJI_BADGE_HEIGHT_OFFSET, report);\n emojiScale = evaluateIntegerString(props, FontificatorProperties.KEY_EMOJI_SCALE, report);\n badgeScale = evaluateIntegerString(props, FontificatorProperties.KEY_EMOJI_BADGE_SCALE, report);\n displayStrategy = EmojiLoadingDisplayStragegy.valueOf(displayStratStr);\n twitchEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_TWITCH_ENABLE, report);\n twitchCacheEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_TWITCH_CACHE, report);\n ffzEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_FFZ_ENABLE, report);\n ffzCacheEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_FFZ_CACHE, report);\n bttvEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_BTTV_ENABLE, report);\n bttvCacheEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_BTTV_CACHE, report);\n twitterEnabled = evaluateBooleanString(props, FontificatorProperties.KEY_EMOJI_TWITTER_ENABLE, report);\n }\n }\n\n return report;\n }\n\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((displayStrategy == null) ? 0 : displayStrategy.hashCode());\n result = prime * result + ((emojiEnabled == null) ? 0 : emojiEnabled.hashCode());\n result = prime * result + ((animationEnabled == null) ? 0 : animationEnabled.hashCode());\n result = prime * result + ((twitchBadgesEnabled == null) ? 0 : twitchBadgesEnabled.hashCode());\n result = prime * result + ((ffzBadgesEnabled == null) ? 0 : ffzBadgesEnabled.hashCode());\n result = prime * result + ((ffzEnabled == null) ? 0 : ffzEnabled.hashCode());\n result = prime * result + ((ffzLoadedChannel == null) ? 0 : ffzLoadedChannel.hashCode());\n result = prime * result + ((ffzGlobalLoaded == null) ? 0 : ffzGlobalLoaded.hashCode());\n result = prime * result + ((bttvEnabled == null) ? 0 : bttvEnabled.hashCode());\n result = prime * result + ((bttvLoadedChannel == null) ? 0 : bttvLoadedChannel.hashCode());\n result = prime * result + ((bttvGlobalLoaded == null) ? 0 : bttvGlobalLoaded.hashCode());\n result = prime * result + ((emojiScale == null) ? 0 : emojiScale.hashCode());\n result = prime * result + ((emojiScaleToLine == null) ? 0 : emojiScaleToLine.hashCode());\n result = prime * result + ((badgeScale == null) ? 0 : badgeScale.hashCode());\n result = prime * result + ((badgeScaleToLine == null) ? 0 : badgeScaleToLine.hashCode());\n result = prime * result + ((badgeHeightOffset == null) ? 0 : badgeHeightOffset.hashCode());\n result = prime * result + ((twitchEnabled == null) ? 0 : twitchEnabled.hashCode());\n result = prime * result + ((twitchLoaded == null) ? 0 : twitchLoaded.hashCode());\n result = prime * result + ((twitchBadgesLoadedChannel == null) ? 0 : twitchBadgesLoadedChannel.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n {\n return true;\n }\n if (obj == null)\n {\n return false;\n }\n if (getClass() != obj.getClass())\n {\n return false;\n }\n ConfigEmoji other = (ConfigEmoji) obj;\n if (displayStrategy != other.displayStrategy)\n {\n return false;\n }\n if (emojiEnabled == null)\n {\n if (other.emojiEnabled != null)\n {\n return false;\n }\n }\n else if (!emojiEnabled.equals(other.emojiEnabled))\n {\n return false;\n }\n if (twitchBadgesEnabled == null)\n {\n if (other.twitchBadgesEnabled != null)\n {\n return false;\n }\n }\n else if (!twitchBadgesEnabled.equals(other.twitchBadgesEnabled))\n {\n return false;\n }\n if (ffzBadgesEnabled == null)\n {\n if (other.ffzBadgesEnabled != null)\n {\n return false;\n }\n }\n else if (!ffzBadgesEnabled.equals(other.ffzBadgesEnabled))\n {\n return false;\n }\n if (ffzEnabled == null)\n {\n if (other.ffzEnabled != null)\n {\n return false;\n }\n }\n else if (!ffzEnabled.equals(other.ffzEnabled))\n {\n return false;\n }\n if (ffzLoadedChannel == null)\n {\n if (other.ffzLoadedChannel != null)\n {\n return false;\n }\n }\n else if (!ffzLoadedChannel.equals(other.ffzLoadedChannel))\n {\n return false;\n }\n if (ffzGlobalLoaded == null)\n {\n if (other.ffzGlobalLoaded != null)\n {\n return false;\n }\n }\n else if (!ffzGlobalLoaded.equals(other.ffzGlobalLoaded))\n {\n return false;\n }\n if (bttvEnabled == null)\n {\n if (other.bttvEnabled != null)\n {\n return false;\n }\n }\n else if (!bttvEnabled.equals(other.bttvEnabled))\n {\n return false;\n }\n if (bttvLoadedChannel == null)\n {\n if (other.bttvLoadedChannel != null)\n {\n return false;\n }\n }\n else if (!bttvLoadedChannel.equals(other.bttvLoadedChannel))\n {\n return false;\n }\n if (bttvGlobalLoaded == null)\n {\n if (other.bttvGlobalLoaded != null)\n {\n return false;\n }\n }\n else if (!bttvGlobalLoaded.equals(other.bttvGlobalLoaded))\n {\n return false;\n }\n if (emojiScale == null)\n {\n if (other.emojiScale != null)\n {\n return false;\n }\n }\n else if (!emojiScale.equals(other.emojiScale))\n {\n return false;\n }\n if (badgeScale == null)\n {\n if (other.badgeScale != null)\n {\n return false;\n }\n }\n else if (!badgeScale.equals(other.badgeScale))\n {\n return false;\n }\n if (emojiScaleToLine == null)\n {\n if (other.emojiScaleToLine != null)\n {\n return false;\n }\n }\n else if (!emojiScaleToLine.equals(other.emojiScaleToLine))\n {\n return false;\n }\n if (badgeScaleToLine == null)\n {\n if (other.badgeScaleToLine != null)\n {\n return false;\n }\n }\n else if (!badgeScaleToLine.equals(other.badgeScaleToLine))\n {\n return false;\n }\n if (badgeHeightOffset == null)\n {\n if (other.badgeHeightOffset != null)\n {\n return false;\n }\n }\n else if (!badgeHeightOffset.equals(other.badgeHeightOffset))\n {\n return false;\n }\n if (twitchEnabled == null)\n {\n if (other.twitchEnabled != null)\n {\n return false;\n }\n }\n else if (!twitchEnabled.equals(other.twitchEnabled))\n {\n return false;\n }\n if (twitchLoaded == null)\n {\n if (other.twitchLoaded != null)\n {\n return false;\n }\n }\n else if (!twitchLoaded.equals(other.twitchLoaded))\n {\n return false;\n }\n if (twitchBadgesLoadedChannel == null)\n {\n if (other.twitchBadgesLoadedChannel != null)\n {\n return false;\n }\n }\n else if (!twitchBadgesLoadedChannel.equals(other.twitchBadgesLoadedChannel))\n {\n return false;\n }\n if (twitterEnabled == null)\n {\n if (other.twitterEnabled != null)\n {\n return false;\n }\n }\n else if (!twitterEnabled.equals(other.twitterEnabled))\n {\n return false;\n }\n return true;\n }\n\n /**\n * Perform a deep copy of the emoji config, used to compare against the previous one used to generated the string of\n * characters and emojis that are stored in a Message object\n * \n * @param copy\n */\n public void deepCopy(ConfigEmoji copy)\n {\n this.emojiEnabled = copy.emojiEnabled;\n this.twitchBadgesEnabled = copy.twitchBadgesEnabled;\n this.ffzBadgesEnabled = copy.ffzBadgesEnabled;\n this.emojiScaleToLine = copy.emojiScaleToLine;\n this.emojiScale = copy.emojiScale;\n this.badgeScaleToLine = copy.badgeScaleToLine;\n this.badgeHeightOffset = copy.badgeHeightOffset;\n this.badgeScale = copy.badgeScale;\n this.displayStrategy = copy.displayStrategy;\n this.twitchEnabled = copy.twitchEnabled;\n this.ffzEnabled = copy.ffzEnabled;\n this.twitchLoaded = copy.twitchLoaded;\n this.twitchBadgesLoadedChannel = copy.twitchBadgesLoadedChannel;\n this.ffzLoadedChannel = copy.ffzLoadedChannel;\n this.ffzGlobalLoaded = copy.ffzGlobalLoaded;\n this.bttvEnabled = copy.bttvEnabled;\n this.bttvCacheEnabled = copy.bttvCacheEnabled;\n this.bttvLoadedChannel = copy.bttvLoadedChannel;\n this.bttvGlobalLoaded = copy.bttvGlobalLoaded;\n this.bttvCached = copy.bttvCached;\n this.twitterEnabled = copy.twitterEnabled;\n }\n\n /**\n * Get whether the Twitch emotes have been loaded\n * \n * @return twitchLoaded\n */\n public Boolean isTwitchLoaded()\n {\n return twitchLoaded != null && twitchLoaded;\n }\n\n /**\n * Set whether the Twitch emotes have been loaded\n * \n * @param twitchLoaded\n */\n public void setTwitchLoaded(Boolean twitchLoaded)\n {\n this.twitchLoaded = twitchLoaded;\n }\n\n /**\n * Get whether the global Twitch emotes have been cached\n * \n * @return twitchCached\n */\n public Boolean isTwitchCached()\n {\n return twitchCached != null && twitchCached;\n }\n\n /**\n * Set whether the global Twitch emotes have been cached\n * \n * @param twitchCached\n */\n public void setTwitchCached(Boolean twitchCached)\n {\n this.twitchCached = twitchCached;\n }\n\n /**\n * Get whether the Twitch badges have been loaded for the specified channel\n * \n * @return loaded\n */\n public boolean isTwitchBadgesLoaded(String testChannel)\n {\n return twitchBadgesLoadedChannel != null && twitchBadgesLoadedChannel.equals(testChannel);\n }\n\n /**\n * Get whether the FrankerFaceZ badges have been loaded for the specified channel\n * \n * @return loaded\n */\n public boolean isFfzBadgesLoaded(String testChannel)\n {\n return ffzBadgesLoadedChannel != null && ffzBadgesLoadedChannel.equals(testChannel);\n }\n\n /**\n * Set whether the Twitch badges have been loaded\n * \n * @param twitchLoadedChannel\n * from which the Twitch emotes are loaded\n */\n public void setTwitchBadgesLoaded(String twitchBadgesLoadedChannel)\n {\n this.twitchBadgesLoadedChannel = twitchBadgesLoadedChannel;\n }\n\n /**\n * Set whether the FrankerFaceZ badges have been loaded\n * \n * @param ffzLoadedChannel\n * from which the FrankerFaceZ emotes are loaded\n */\n public void setFfzBadgesLoaded(String ffzBadgesLoadedChannel)\n {\n this.ffzBadgesLoadedChannel = ffzBadgesLoadedChannel;\n }\n\n /**\n * Get whether the FrankerFaceZ emotes have been loaded for the specified channel\n * \n * @return loaded\n */\n public boolean isFfzLoaded(String testChannel)\n {\n return ffzLoadedChannel != null && ffzLoadedChannel.equals(testChannel);\n }\n\n /**\n * Set whether the FrankerFaceZ emotes have been loaded\n * \n * @param ffzLoadedChannel\n * from which the FrankerFaceZ emotes are loaded\n */\n public void setFfzLoaded(String ffzLoadedChannel)\n {\n this.ffzLoadedChannel = ffzLoadedChannel;\n }\n\n /**\n * Get whether the global FrankerFaceZ emotes have been loaded\n * \n * @return ffzGlobalLoaded\n */\n public Boolean isFfzGlobalLoaded()\n {\n return ffzGlobalLoaded != null && ffzGlobalLoaded;\n }\n\n /**\n * Set whether the global FrankerFaceZ emotes have been loaded\n * \n * @param ffzGlobalLoaded\n */\n public void setFfzGlobalLoaded(Boolean ffzGlobalLoaded)\n {\n this.ffzGlobalLoaded = ffzGlobalLoaded;\n }\n\n /**\n * Get whether the FrankerFaceZ emotes have been cached\n * \n * @return ffzCached\n */\n public boolean isFfzCached()\n {\n return ffzCached != null && ffzCached;\n }\n\n /**\n * Set whether the FrankerFaceZ emotes have been cached\n * \n * @param ffzCached\n */\n public void setFfzCached(Boolean ffzCached)\n {\n this.ffzCached = ffzCached;\n }\n\n public void setBttvEnabled(Boolean bttvEnabled)\n {\n this.bttvEnabled = bttvEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_BTTV_ENABLE, Boolean.toString(bttvEnabled));\n }\n\n public String getBttvLoadedChannel()\n {\n return bttvLoadedChannel;\n }\n\n public void setBttvLoadedChannel(String bttvLoadedChannel)\n {\n this.bttvLoadedChannel = bttvLoadedChannel;\n }\n\n public void setBttvGlobalLoaded(Boolean bttvGlobalLoaded)\n {\n this.bttvGlobalLoaded = bttvGlobalLoaded;\n }\n\n public boolean isBttvLoaded(String testChannel)\n {\n return bttvLoadedChannel != null && bttvLoadedChannel.equals(testChannel);\n }\n\n public void setBttfLoaded(String bttvLoadedChannel)\n {\n this.bttvLoadedChannel = bttvLoadedChannel;\n }\n\n public Boolean isBttvGlobalLoaded()\n {\n return bttvGlobalLoaded != null && bttvGlobalLoaded;\n }\n\n public void setBttfGlobalLoaded(Boolean bttvGlobalLoaded)\n {\n this.bttvGlobalLoaded = bttvGlobalLoaded;\n }\n\n public boolean isBttvCached()\n {\n return bttvCached != null && bttvCached;\n }\n\n public void setBttvCached(Boolean bttvCached)\n {\n this.bttvCached = bttvCached;\n }\n\n public boolean isTwitterEnabled()\n {\n return twitterEnabled;\n }\n\n public void setTwitterEnabled(Boolean twitterEnabled)\n {\n this.twitterEnabled = twitterEnabled;\n props.setProperty(FontificatorProperties.KEY_EMOJI_TWITTER_ENABLE, Boolean.toString(twitterEnabled));\n }\n\n /**\n * Mark work as being completed by setting the loaded and cached member variables of this emoji config\n * \n * @param job\n * Contains the type, op, and channel of the job completed\n */\n public void setWorkCompleted(EmojiJob job)\n {\n logger.trace(job.toString() + \" completed\");\n\n final EmojiType emojiType = job.getType();\n final EmojiOperation emojiOp = job.getOp();\n\n if (EmojiType.TWITCH_BADGE.equals(emojiType))\n {\n this.twitchBadgesLoadedChannel = job.getChannel();\n }\n else if (EmojiType.FRANKERFACEZ_BADGE.equals(emojiType))\n {\n this.ffzBadgesLoadedChannel = job.getChannel();\n }\n else if (emojiType.isTwitchEmote()) // This would also include TWITCH_BADGE, but it's already checked above\n {\n if (EmojiOperation.LOAD == emojiOp)\n {\n this.twitchLoaded = true;\n }\n else if (EmojiOperation.CACHE == emojiOp)\n {\n this.twitchCached = true;\n }\n }\n else if (emojiType.isFrankerFaceZEmote())\n {\n if (EmojiOperation.LOAD == emojiOp)\n {\n if (emojiType == EmojiType.FRANKERFACEZ_CHANNEL)\n {\n this.ffzLoadedChannel = job.getChannel();\n }\n else if (emojiType == EmojiType.FRANKERFACEZ_GLOBAL)\n {\n this.ffzGlobalLoaded = true;\n }\n }\n else if (EmojiOperation.CACHE == emojiOp)\n {\n this.ffzCached = true;\n }\n }\n else if (emojiType.isBetterTtvEmote())\n {\n if (EmojiOperation.LOAD == emojiOp)\n {\n if (emojiType == EmojiType.BETTER_TTV_CHANNEL)\n {\n this.bttvLoadedChannel = job.getChannel();\n }\n else if (emojiType == EmojiType.BETTER_TTV_GLOBAL)\n {\n this.bttvGlobalLoaded = true;\n }\n }\n else if (EmojiOperation.CACHE == emojiOp)\n {\n this.bttvCached = true;\n }\n }\n }\n\n /**\n * Reset the flags indicating any completed work. This enables a reloading of everything. It does not clear out the\n * previously loaded or cached data, just enables the system to reload or recache it.\n */\n public void resetWorkCompleted()\n {\n this.twitchLoaded = false;\n this.twitchCached = false;\n this.twitchBadgesLoadedChannel = null;\n this.ffzBadgesLoadedChannel = null;\n this.ffzLoadedChannel = null;\n this.ffzGlobalLoaded = false;\n this.ffzCached = null;\n this.bttvLoadedChannel = null;\n this.bttvGlobalLoaded = false;\n this.bttvCached = null;\n }\n\n /**\n * Get whether any work been done to load or cache any emoji or badges\n * \n * @return whether work was done\n */\n public boolean isAnyWorkDone()\n {\n // @formatter:off\n return twitchBadgesLoadedChannel != null || isTwitchLoaded() || isTwitchCached() || \n ffzBadgesLoadedChannel != null || ffzLoadedChannel != null || isFfzGlobalLoaded() || isFfzCached() || \n bttvLoadedChannel != null || isBttvGlobalLoaded() || isBttvCached();\n // @formatter:on\n }\n\n}", "public class EmojiJob\n{\n private final EmojiType type;\n\n private final EmojiOperation op;\n\n private final String oauth;\n\n /**\n * Can be null if no channel is required\n */\n private final String channel;\n\n public EmojiJob(String oauth, EmojiType type, EmojiOperation op)\n {\n this(oauth, type, op, null);\n }\n\n public EmojiJob(String oauth, EmojiType type, EmojiOperation op, String channel)\n {\n this.type = type;\n this.op = op;\n this.oauth = oauth;\n this.channel = channel;\n }\n\n public String getOauth()\n {\n return oauth;\n }\n\n public EmojiType getType()\n {\n return type;\n }\n\n public EmojiOperation getOp()\n {\n return op;\n }\n\n public String getChannel()\n {\n return channel;\n }\n\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((channel == null) ? 0 : channel.hashCode());\n result = prime * result + ((op == null) ? 0 : op.hashCode());\n result = prime * result + ((type == null) ? 0 : type.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n EmojiJob other = (EmojiJob) obj;\n if (channel == null)\n {\n if (other.channel != null)\n return false;\n }\n else if (!channel.equals(other.channel))\n return false;\n if (op != other.op)\n return false;\n if (type != other.type)\n return false;\n return true;\n }\n\n @Override\n public String toString()\n {\n return op.getDescription().substring(0, 1).toUpperCase() + op.getDescription().substring(1) + \" \" + type.getDescription() + (channel != null ? \" for \" + channel : \"\");\n }\n\n}", "public enum EmojiOperation\n{\n LOAD(\"load\"), CACHE(\"cache\");\n\n private final String description;\n\n private EmojiOperation(String description)\n {\n this.description = description;\n }\n\n public String getDescription()\n {\n return description;\n }\n}", "public class ChatPanel extends JPanel implements MouseWheelListener\n{\n private static final Logger logger = Logger.getLogger(ChatPanel.class);\n\n private static final long serialVersionUID = 1L;\n\n /**\n * The cache of messages to be displayed\n */\n private ConcurrentLinkedQueue<Message> messages;\n\n private MessageCensorPanel censor;\n\n /**\n * Contains the timed task and a reference to this chat to be used to progress rolling out new messages at the\n * appropriate speed\n */\n private MessageProgressor messageProgressor;\n\n /**\n * Contains the timed task and a reference to this chat to be used to refresh periodically in case any messages have\n * been expired\n */\n private MessageExpirer messageExpirer;\n\n /**\n * The sprite used to draw the border around the chat, to be displayed if the border scale is greater than zero\n */\n private Sprite border;\n\n /**\n * The number of lines for all the messages in the chat buffer. This is not the number of messages, but the number\n * of lines the messages will take up once drawn.\n */\n private int lineCount;\n\n /**\n * The number of lines that fit on the screen between the top border and bottom border.\n */\n private int onScreenLineCount;\n\n /**\n * Configuration for the font and the border\n */\n private ConfigFont fontConfig;\n\n /**\n * Configuration for the chat, meaning whether scrolling is enabled and whether and how to draw the chroma key\n * border\n */\n private ConfigChat chatConfig;\n\n /**\n * Configuration for which colors to use to draw the chat\n */\n private ConfigColor colorConfig;\n\n /**\n * Configuration for how to draw the messages, what parts of the messages to display, the rate to display new\n * messages, the format for the timestamps, and the queue size\n */\n private ConfigMessage messageConfig;\n\n /**\n * Configuration for whether to include emoji in the messages\n */\n private ConfigEmoji emojiConfig;\n\n /**\n * Configuration for how to censor messages\n */\n private ConfigCensor censorConfig;\n\n /**\n * The control panel for the debug options. They aren't saved, so a reference to the control panel itself is\n * sufficient\n */\n private ControlPanelDebug debugSettings;\n\n /**\n * The font used to draw the chat messages\n */\n private SpriteFont font;\n\n /**\n * This indicates whether the configuration has been loaded. Before this is true, no call to any methods that draw\n * should be called because they all rely on the configuration. Once it is set to true, it will remain true- it is\n * only on the initial setup that configuration might be null\n */\n private boolean loaded;\n\n /**\n * Manages emoji loading, caching, and access\n */\n private EmojiManager emojiManager;\n\n /**\n * Construct the ChatPanel, which contains the entire visualization of the chat\n * \n * @param censor\n * The message popup dialog from the Control Window to be updated when a message is posted so the censor\n * list is current\n * @throws IOException\n */\n public ChatPanel() throws IOException\n {\n loaded = false;\n lineCount = Integer.MAX_VALUE;\n onScreenLineCount = 0;\n messages = new ConcurrentLinkedQueue<Message>();\n\n emojiManager = new EmojiManager();\n messageProgressor = new MessageProgressor(this);\n messageExpirer = new MessageExpirer(this);\n }\n\n /**\n * Get whether the configuration and message dialog have been loaded. Before this is true, no call to any methods\n * that draw should be called because they all rely on the configuration and the link to the message dialog to be\n * updated so censorship rules can be assessed. Once it returns true, it will remain true- it is only on the initial\n * setup that configuration and the message dialog might be null.\n * \n * @return loaded\n */\n public boolean isLoaded()\n {\n return loaded && censor != null;\n }\n\n /**\n * Set the configuration references from the properties object. This method instantiates the font and border. Once\n * this method is complete, loaded is set to true.\n * \n * @param fProps\n * The properties from which to get the configuration references\n * @throws IOException\n * If there are any issues loading the files specified for the font and border\n */\n public void setConfig(FontificatorProperties fProps) throws IOException\n {\n logger.trace(\"Setting chat panel config via fontificator properties object\");\n this.fontConfig = fProps.getFontConfig();\n this.chatConfig = fProps.getChatConfig();\n this.colorConfig = fProps.getColorConfig();\n this.messageConfig = fProps.getMessageConfig();\n this.emojiConfig = fProps.getEmojiConfig();\n this.censorConfig = fProps.getCensorConfig();\n\n font = new SpriteFont(fontConfig);\n reloadFontFromConfig();\n // This initializes the border\n reloadBorderFromConfig();\n\n // This indicates that the chat panel is ready to be drawn\n loaded = true;\n }\n\n /**\n * Set the Control Panel for debugging on this chat panel\n * \n * @param debugSettings\n * The control panel for debug settings\n */\n public void setDebugSettings(ControlPanelDebug debugSettings)\n {\n this.debugSettings = debugSettings;\n }\n\n public void setMessageCensor(MessageCensorPanel censor)\n {\n this.censor = censor;\n }\n\n @Override\n public void paint(Graphics g)\n {\n if (!isLoaded())\n {\n return;\n }\n\n Graphics2D g2d = (Graphics2D) g;\n\n if (chatConfig.isAntiAlias())\n {\n g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);\n }\n\n // Fits in the line height.\n boolean stillFits = true;\n int fontSize = 0;\n while (stillFits)\n {\n fontSize++;\n g2d.setFont(new Font(g2d.getFont().getName(), Font.PLAIN, fontSize));\n stillFits = (font.getFontHeight() - fontConfig.getBaselineOffset()) * fontConfig.getFontScale() > g2d.getFontMetrics().getStringBounds(\"A\", 0, 1, g2d).getHeight();\n }\n\n logger.trace(\"Calulated font size: \" + fontSize);\n\n List<Message> drawMessages = new ArrayList<Message>();\n\n // Make a copy of the actual cache that only includes the messages that are completely drawn and possibly the\n // one message currently being drawn\n long drawTime = System.currentTimeMillis();\n for (Message msg : messages)\n {\n final boolean censored = censorConfig.isCensorshipEnabled() && msg.isCensored();\n final boolean expired = messageConfig.isMessageExpirable() && msg.getAge(drawTime) > messageConfig.getExpirationTime();\n if (!censored && !expired)\n {\n drawMessages.add(msg);\n }\n if (!censored && !expired && !msg.isCompletelyDrawn())\n {\n // No need to check any further messages because this is the one currently being rolled out\n break;\n }\n }\n\n // Draws the background color and the chroma key border\n if (messageConfig.isHideEmptyBackground() && drawMessages.isEmpty())\n {\n // If the messages are empty and the background should be hidden, draw the chroma color regardless of whether it's enabled\n g2d.setColor(colorConfig.getChromaColor());\n g2d.fillRect(0, 0, getWidth(), getHeight());\n }\n else\n {\n drawBackgroundAndChroma(g2d);\n }\n\n // This offset represents how far inward in the x and y directions the messages should be drawn\n Point offset = new Point();\n\n // If border scale is zero, just skip this. The drawBorder method won't draw a zero scale border, but if these\n // calculations are attempted with a zero scale it will throw a divide by zero exception\n // Also check if no messages are visible whether the border should be hidden\n if (fontConfig.getBorderScale() > 0.0f && !(messageConfig.isHideEmptyBorder() && drawMessages.isEmpty()))\n {\n final int gridWidth = getWidth() / border.getSpriteDrawWidth(fontConfig.getBorderScale());\n final int gridHeight = getHeight() / border.getSpriteDrawHeight(fontConfig.getBorderScale());\n\n final int leftOffset = (getWidth() - gridWidth * border.getSpriteDrawWidth(fontConfig.getBorderScale())) / 2;\n final int topOffset = (getHeight() - gridHeight * border.getSpriteDrawHeight(fontConfig.getBorderScale())) / 2;\n\n offset = new Point(leftOffset, topOffset);\n\n drawBorder(g2d, gridWidth, gridHeight, offset, colorConfig.getBorderColor(), debugSettings.isDrawBorderGrid(), debugSettings.getBorderGridColor());\n }\n\n drawChat(g2d, drawMessages, offset, debugSettings.isDrawTextGrid(), debugSettings.getTextGridColor());\n }\n\n /**\n * Draws a test grid for debugging purposes\n * \n * @param g\n * @param one\n * @param two\n * @param x\n * @param y\n * @param width\n * @param height\n * @param squareSize\n */\n protected void drawGrid(Graphics g, Color one, Color two, int x, int y, int width, int height, int squareSize)\n {\n for (int r = 0; r < height / squareSize + 1; r++)\n {\n for (int c = 0; c < width / squareSize + 1; c++)\n {\n boolean colorOne = r % 2 == 1 && c % 2 == 0 || r % 2 == 0 && c % 2 == 1;\n g.setColor(colorOne ? one : two);\n g.fillRect(x + c * squareSize, y + r * squareSize, squareSize, squareSize);\n }\n }\n }\n\n /**\n * Draw the background and the chroma key border\n * \n * @param g2d\n */\n private void drawBackgroundAndChroma(Graphics2D g2d)\n {\n if (chatConfig.isChromaEnabled())\n {\n g2d.setColor(chatConfig.isChromaInvert() ? colorConfig.getBgColor() : colorConfig.getChromaColor());\n g2d.fillRect(0, 0, getWidth(), getHeight());\n g2d.setColor(chatConfig.isChromaInvert() ? colorConfig.getChromaColor() : colorConfig.getBgColor());\n Rectangle border = chatConfig.getChromaBorder();\n g2d.fillRoundRect(Math.min(getWidth(), border.x), Math.min(getHeight(), border.y), Math.max(0, getWidth() - border.width - border.x), Math.max(0, getHeight() - border.height - border.y), chatConfig.getChromaCornerRadius(), chatConfig.getChromaCornerRadius());\n }\n else\n {\n // Just draw the background\n g2d.setColor(colorConfig.getBgColor());\n g2d.fillRect(0, 0, getWidth(), getHeight());\n }\n }\n\n /**\n * Draw the words in the messages in the chat\n * \n * @param g2d\n * @param messages\n * @param offset\n */\n private void drawChat(Graphics2D g2d, List<Message> drawMessages, Point offset, boolean debug, Color debugColor)\n {\n final int lineWrapLength = (border == null || fontConfig.getBorderScale() <= 0.0f ? getWidth() : border.getSpriteDrawWidth(fontConfig.getBorderScale()) * (getWidth() / border.getSpriteDrawWidth(fontConfig.getBorderScale()) - 2)) - fontConfig.getBorderInsetX() * 2;\n final int leftEdge = offset.x + (border == null || fontConfig.getBorderScale() <= 0.0f ? 0 : border.getSpriteDrawWidth(fontConfig.getBorderScale())) + fontConfig.getBorderInsetX();\n\n // totalHeight is the height of all the messages\n int totalHeight = 0;\n for (int i = 0; i < drawMessages.size(); i++)\n {\n Message msg = drawMessages.get(i);\n final boolean lastMessage = i >= drawMessages.size() - 1;\n Dimension dim = font.getMessageDimensions(msg, g2d.getFontMetrics(), messageConfig, emojiConfig, emojiManager, lineWrapLength, lastMessage);\n totalHeight += dim.getHeight();\n }\n\n // Used for scrolling\n int lineHeight = font.getLineHeightScaled();\n if (lineHeight == 0)\n {\n lineHeight = 1;\n }\n lineCount = lineHeight == 0 ? 0 : totalHeight / lineHeight;\n\n // borderEdgeThickness is the y-inset on the top plus the height of the top part of the border\n final int borderEdgeThickness = offset.y + (border == null || fontConfig.getBorderScale() < ConfigFont.FONT_BORDER_SCALE_GRANULARITY ? 0 : border.getSpriteDrawHeight(fontConfig.getBorderScale())) + fontConfig.getBorderInsetY();\n\n final int drawableVerticalRange = getHeight() - borderEdgeThickness * 2;\n\n // Used for scrolling when chat scrolls normally and starts from the top, or when chat scrolls reverse and starts from the bottom\n onScreenLineCount = drawableVerticalRange / lineHeight;\n\n // y is where the drawing begins\n int y;\n if (chatConfig.isChatFromBottom())\n {\n if (chatConfig.isReverseScrolling())\n {\n if (totalHeight > drawableVerticalRange)\n {\n y = borderEdgeThickness;\n }\n else\n {\n y = getHeight() - totalHeight - borderEdgeThickness;\n }\n }\n else\n {\n y = getHeight() - totalHeight - borderEdgeThickness;\n }\n }\n // else chat from top\n else\n {\n if (chatConfig.isReverseScrolling())\n {\n y = borderEdgeThickness;\n }\n else\n {\n if (totalHeight > drawableVerticalRange)\n {\n // Not all the messages fit in the given space range, so start drawing up out of bounds at a negative y. This uses just the top borderEdgeThickness's height, not both top and bottom\n y = (getHeight() - borderEdgeThickness) - totalHeight;\n }\n // If the total height of all the messages is less than or equal to the total height\n else\n {\n // Just set the y to start drawing to the borderEdgeThickness because it should be fixed to the top when there's enough room for everything\n y = borderEdgeThickness;\n }\n }\n }\n\n final int botLimit;\n if (chatConfig.isReverseScrolling() && totalHeight > drawableVerticalRange)\n {\n botLimit = getHeight() - borderEdgeThickness - font.getLineHeightScaled();\n }\n else\n {\n botLimit = getHeight() - borderEdgeThickness;\n }\n\n // Draw each message in the drawMessages copy of the cache\n for (int i = 0; i < drawMessages.size(); i++)\n {\n int msgIndex = chatConfig.isReverseScrolling() ? drawMessages.size() - i - 1 : i;\n Message msg = drawMessages.get(msgIndex);\n Color col = getUsernameColor(colorConfig, msg);\n final boolean lastMessage = i >= drawMessages.size() - 1;\n // The call to drawMessage in SpriteFont will determine whether to draw each character based on whether it is located at a position appropriate to be drawn on\n Dimension dim = font.drawMessage(g2d, g2d.getFontMetrics(), msg, col, colorConfig, messageConfig, emojiConfig, emojiManager, leftEdge, y, borderEdgeThickness, botLimit, lineWrapLength, debug, debugColor, this, lastMessage);\n y += dim.getHeight();\n }\n }\n\n private static Color getUsernameColor(ConfigColor colorConfig, Message msg)\n {\n Color col;\n if (msg.isJoinType())\n {\n col = colorConfig.getHighlight();\n }\n else if (colorConfig.isUseTwitchColors() && msg.getPrivmsg().getColor() != null)\n {\n col = msg.getPrivmsg().getColor();\n }\n else\n {\n col = colorConfig.getPalette().isEmpty() ? colorConfig.getHighlight() : colorConfig.getPalette().get(Math.abs(msg.getUsername().toLowerCase().hashCode()) % colorConfig.getPalette().size());\n }\n return col;\n }\n\n /**\n * Draw the border\n * \n * @param g2d\n * @param gridWidth\n * @param gridHeight\n * @param offset\n * @param color\n */\n private void drawBorder(Graphics2D g2d, int gridWidth, int gridHeight, Point offset, Color color, boolean debug, Color debugColor)\n {\n final float scale = fontConfig.getBorderScale();\n\n if (scale <= 0.0f)\n {\n return;\n }\n\n if (debug)\n {\n g2d.setColor(debugColor);\n }\n\n for (int r = 0; r < gridHeight; r++)\n {\n for (int c = 0; c < gridWidth; c++)\n {\n int pixelX = c * border.getSpriteDrawWidth(scale) + offset.x;\n int pixelY = r * border.getSpriteDrawHeight(scale) + offset.y;\n\n if (r == 0) // Top row\n {\n if (c == 0) // Top left\n {\n border.draw(g2d, pixelX, pixelY, 0, scale, color);\n }\n else if (c == gridWidth - 1) // Top right\n {\n border.draw(g2d, pixelX, pixelY, 2, scale, color);\n }\n else\n // Top middle\n {\n border.draw(g2d, pixelX, pixelY, 1, scale, color);\n }\n }\n else if (r == gridHeight - 1) // Bottom row\n {\n if (c == 0) // Bottom left\n {\n border.draw(g2d, pixelX, pixelY, 6, scale, color);\n }\n else if (c == gridWidth - 1) // Bottom right\n {\n border.draw(g2d, pixelX, pixelY, 8, scale, color);\n }\n else\n // Bottom middle\n {\n border.draw(g2d, pixelX, pixelY, 7, scale, color);\n }\n }\n else\n // Middle\n {\n if (c == 0) // Middle left\n {\n border.draw(g2d, pixelX, pixelY, 3, scale, color);\n }\n else if (c == gridWidth - 1) // Middle right\n {\n border.draw(g2d, pixelX, pixelY, 5, scale, color);\n }\n else\n // Middle middle\n {\n border.draw(g2d, pixelX, pixelY, 4, scale, color);\n }\n }\n if (debug)\n {\n g2d.drawRect(pixelX, pixelY, (int) (border.getSpriteWidth() * scale), (int) (border.getSpriteHeight() * scale));\n }\n }\n }\n }\n\n /**\n * Add a message to the cache, and call method to process any censorship\n * \n * @param addition\n */\n synchronized public void addMessage(Message addition)\n {\n if (addition.isJoinType() && !messageConfig.showJoinMessages())\n {\n return;\n }\n\n censor.checkCensor(addition);\n\n // Note that for a moment here, the size of messages can exceed the specified queueSize in the message config,\n // so if another thread is accessing this, be sure to take that into consideration\n messages.add(addition);\n int remCount = Math.max(0, messages.size() - messageConfig.getQueueSize());\n\n Iterator<Message> iter = messages.iterator();\n while (iter.hasNext() && remCount > 0)\n {\n iter.next();\n iter.remove();\n remCount--;\n }\n\n initMessageRollout();\n if (censor.isVisible())\n {\n censor.updateManualTable();\n }\n\n repaint();\n }\n\n /**\n * Delete all messages from the queue to clear the chat\n */\n synchronized public void clearChat()\n {\n messages.clear();\n repaint();\n }\n\n /**\n * Reset the scroll offset to zero\n */\n public void resetScrollOffset()\n {\n if (isLoaded())\n {\n font.setLineScrollOffset(0);\n }\n }\n\n /**\n * Refresh the scroll offset in case of resize (only needed when chat starts at top)\n * \n * @param positiveDirection\n * Whether the direction is up or down\n * @param lines\n * how many lines to scroll\n */\n public void incrementScrollOffset(boolean positiveDirection, int lines)\n {\n if (isLoaded())\n {\n final int dir = positiveDirection ? lines : -lines;\n if (chatConfig.isChatFromBottom())\n {\n font.incrementLineScrollOffset(dir, 0, lineCount);\n }\n else\n {\n final boolean screenIsOverflowing = lineCount >= onScreenLineCount;\n if (screenIsOverflowing)\n {\n font.incrementLineScrollOffset(dir, -onScreenLineCount + 1, lineCount - onScreenLineCount + 1);\n }\n else\n {\n font.incrementLineScrollOffset(dir, lineCount == 0 ? 0 : -lineCount + 1, 1);\n }\n }\n repaint();\n }\n }\n\n /**\n * This is added to the window above\n */\n @Override\n public void mouseWheelMoved(MouseWheelEvent e)\n {\n if (isLoaded() && chatConfig.isScrollable())\n {\n incrementScrollOffset(e.getWheelRotation() < 0, 1);\n }\n }\n\n /**\n * Get the message cache. This is used by the timer task that resides in the MessageProgressor object to increment\n * the drawing of the messages\n * \n * @return messages\n */\n synchronized public Message[] getMessages()\n {\n return messages.toArray(new Message[messages.size()]);\n }\n\n /**\n * Get the actual queue of messages\n * \n * @return messages\n */\n public ConcurrentLinkedQueue<Message> getMessageQueue()\n {\n return messages;\n }\n\n /**\n * Updates the font when there are changes to the configuration\n * \n * @throws IOException\n * If there is a problem using a file\n */\n public void reloadFontFromConfig() throws IOException\n {\n font.updateForConfigChange();\n }\n\n /**\n * Updates the border when there are changes to the configuration\n * \n * @throws IOException\n */\n public void reloadBorderFromConfig() throws IOException\n {\n try\n {\n border = new Sprite(fontConfig.getBorderFilename(), 3, 3);\n }\n catch (Exception e)\n {\n final String errorMessage = \"Unable to load border sprite \" + (fontConfig == null ? \"for null font configuration\" : \"for border filename \" + fontConfig.getBorderFilename());\n logger.error(errorMessage, e);\n border = new Sprite();\n }\n }\n\n /**\n * Used for getting the message configuration for formatting the message and timing the message progression\n * \n * @return message config\n */\n public ConfigMessage getMessageConfig()\n {\n return messageConfig;\n }\n\n /**\n * Used for getting the emoji configuration for formatting the message\n * \n * @return emoji config\n */\n public ConfigEmoji getEmojiConfig()\n {\n return emojiConfig;\n }\n\n /**\n * Get the message progressor\n * \n * @return messageProgressor\n */\n public MessageProgressor getMessageProgressor()\n {\n return messageProgressor;\n }\n\n public MessageExpirer getMessageExpirer()\n {\n return messageExpirer;\n }\n\n public void banUser(String bannedUser)\n {\n censor.addBan(bannedUser);\n repaint();\n }\n\n public void unbanUser(String bannedUser)\n {\n censor.removeBan(bannedUser);\n repaint();\n }\n\n public EmojiManager getEmojiManager()\n {\n return emojiManager;\n }\n\n public void initExpirationTimer()\n {\n if (messageConfig.isMessageExpirable())\n {\n messageExpirer.startClock();\n }\n }\n\n /**\n * Attempt to restart the message rollout, called whenever some messages might be reintroduced to the drawMessage\n * after the message rollout is completed, by being uncensored for example. This call relies on the fact that the\n * messageProgression will halt again if all the messages are complete already.\n */\n public void initMessageRollout()\n {\n messageProgressor.startClock(messageConfig.getMessageDelay());\n }\n\n public boolean isCensorshipEnabled()\n {\n return censorConfig.isCensorshipEnabled();\n }\n\n /**\n * Used to purge messages from chat whenever a user is timed-out or banned by a Twitch moderator\n * \n * @param username\n * @param reason\n */\n public void purgeMessagesForUser(final String username, final String reason)\n {\n censor.purgeMessagesForUser(username, reason);\n }\n\n public String getFontGameName()\n {\n return ControlPanelFont.getFontGameName(fontConfig.getFontFilename());\n }\n\n public String getBorderGameName()\n {\n return ControlPanelFont.getBorderGameName(fontConfig.getBorderFilename());\n }\n}", "public abstract class ControlPanelBase extends JPanel\n{\n private static final long serialVersionUID = 1L;\n\n /**\n * The human-readable name of the control panel\n */\n protected String label;\n\n /**\n * Used where ever default insets are required for a GridBagConstraints object\n */\n protected final static Insets DEFAULT_INSETS = new Insets(2, 4, 2, 4);\n\n /**\n * Used where ever no insets are required for a GridBagConstraints object\n */\n protected final static Insets NO_INSETS = new Insets(0, 0, 0, 0);\n\n /**\n * Reference to the ChatWindow, needed for some functions on the Chat control panel\n */\n protected final ChatWindow chatWindow;\n\n /**\n * Reference to the ChatPanel, needed to affect the chat by all the control panels\n */\n protected final ChatPanel chat;\n\n /**\n * Used to lay out the control panel, instantiated in a default way here to avoid having to set all its bits in\n * every class extended from this\n */\n protected GridBagConstraints gbc;\n\n /**\n * Reference to the properties, needed to load and save any modifications made by the control panels\n */\n protected FontificatorProperties fProps;\n\n /**\n * The member baseBorder to be used on the control panels\n */\n protected Border baseBorder;\n\n /**\n * The box displayed on the IRC connection tab that displays the log of the program and the chat. This reference is\n * stored here so any of the control panels can append logs to it.\n */\n protected LogBox logBox;\n\n /**\n * A single source for a newly instantiated base border to be used in the control panels\n * \n * @return baseBorder\n */\n public static Border getBaseBorder()\n {\n return BorderFactory.createLineBorder(Color.GRAY);\n }\n\n /**\n * A newly instantiated grid bag constraints model, anchored in the the northwest corner with fill set to none,\n * xweight set to 0 and yweight set to 1\n * \n * @return gbc\n */\n public static GridBagConstraints getGbc()\n {\n return new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, DEFAULT_INSETS, 0, 0);\n }\n\n /**\n * Sets the grid bag constraints layout, calls build(), and calls fill()\n * \n * @param label\n * The label that will display on the tab for this control panel\n * @param fProps\n * The reference to the properties that define the all the configurable parts of the viewer via the\n * control panels\n * @param chatWindow\n * The window that contains the chat view\n * @param logBox\n * The box displayed on the IRC connection tab that displays the log of the program and the chat\n */\n public ControlPanelBase(String label, FontificatorProperties fProps, ChatWindow chatWindow, LogBox logBox)\n {\n this.fProps = fProps;\n this.logBox = logBox;\n this.label = label;\n this.chatWindow = chatWindow;\n this.chat = chatWindow.getChatPanel();\n setLayout(new GridBagLayout());\n this.gbc = getGbc();\n this.baseBorder = getBaseBorder();\n build();\n fillInputFromProperties(fProps);\n }\n\n /**\n * Get the human readable label of the control panel. Used to log errors in ControlTabs.\n * \n * @return label\n */\n public String getLabel()\n {\n return label;\n }\n\n /**\n * Builds the panel by constructing and adding all the components. Called by the base constructor.\n */\n protected abstract void build();\n\n /**\n * Sets the config from the properties file, then calls fillUiFromConfig\n */\n protected abstract void fillInputFromProperties(FontificatorProperties fProps);\n\n /**\n * Fills all the input fields with the configuration. Called by the base constructor. Typically fill is where the\n * specialized config for the extension of this base class should be set if it is to be kept as a member variable\n */\n protected abstract void fillInputFromConfig();\n\n /**\n * Validates UI input and updates config objects\n */\n public void update()\n {\n LoadConfigReport report = validateInput();\n if (report.isErrorFree())\n {\n try\n {\n fillConfigFromInput();\n chat.repaint();\n }\n catch (Exception ex)\n {\n ChatWindow.popup.handleProblem(\"Unexpected Error: \" + ex.toString(), ex);\n }\n }\n else\n {\n ChatWindow.popup.handleProblem(report);\n }\n }\n\n /**\n * Must return an error report if any input field value is invalid for storing on the config object or in the final\n * properties destination should it be saved\n * \n * @return report\n */\n protected abstract LoadConfigReport validateInput();\n\n /**\n * Takes user data and parses it into config file objects. Because a successful report was returned by validateInput\n * when this is run, it should be safe from Exceptions\n */\n protected abstract void fillConfigFromInput() throws Exception;\n\n}", "public class ControlPanelEmoji extends ControlPanelBase\n{\n private static final long serialVersionUID = 1L;\n\n /**\n * The bar to indicate progress as emotes load from the APIs\n */\n private EmojiLoadProgressPanel progressPanel;\n\n /**\n * Whether to use any emoji at all\n */\n private JCheckBox enableAll;\n\n /**\n * Whether to display animation in emoji\n */\n private JCheckBox enableAnimation;\n\n /**\n * Whether to display Twitch user badges\n */\n private JCheckBox enableTwitchBadges;\n\n /**\n * Whether to display FrankerFaceZ badges\n */\n private JCheckBox enableFfzBadges;\n\n /**\n * Whether emoji should be scaled to match line height or just scaled against their actual size\n */\n private JCheckBox emojiScaleToLineHeight;\n\n /**\n * How much to scale the emoji\n */\n private LabeledSlider emojiScale;\n\n /**\n * Whether badges should be scaled to match line height or just scaled against their actual size\n */\n private JCheckBox badgeScaleToLineHeight;\n\n /**\n * How much to scale the badges\n */\n private LabeledSlider badgeScale;\n\n /**\n * How much to offset the badge vertically, needed because the middle line of a font image is much lower than the\n * middle line calculated from the font baseline to the top\n */\n private LabeledSlider badgeHeightOffset;\n\n /**\n * Label for menu for how to deal with emote images that are not yet loaded\n */\n private JLabel emojiLoadingDisplayStratLabel;\n\n /**\n * Specifies how to deal with emote images that are not yet loaded\n */\n private JComboBox<EmojiLoadingDisplayStragegy> emojiLoadingDisplayStrat;\n\n /**\n * Whether to enabled the Twitter emoji in place of the default font's extended unicode support\n */\n private JCheckBox enableTwitterEmoji;\n\n /**\n * Whether to enable Twitch emotes\n */\n private JCheckBox enableTwitch;\n\n /**\n * Whether to cache global Twitch emotes\n */\n private JCheckBox cacheTwitch;\n\n /**\n * Whether to enable FrankerFaceZ emotes\n */\n private JCheckBox enableFrankerFaceZ;\n\n /**\n * Whether to cache global and channel specific FrankerFazeZ emotes\n */\n private JCheckBox cacheFrankerFaceZ;\n\n /**\n * Whether to enable BetterTTV emotes\n */\n private JCheckBox enableBetterTtv;\n\n /**\n * Whether to cache global and channel specific BetterTTV emotes\n */\n private JCheckBox cacheBetterTtv;\n\n /**\n * The emoji config object that bridges the UI to the properties file\n */\n private ConfigEmoji config;\n\n /**\n * Panel to house general emoji options\n */\n private JPanel scaleAndDisplayPanel;\n\n /**\n * Panel to house Twitch emote options\n */\n private JPanel twitchPanel;\n\n /**\n * Panel to house FrankerFaceZ options\n */\n private JPanel frankerPanel;\n\n /**\n * Panel to house BetterTTV options\n */\n private JPanel betterPanel;\n\n /**\n * A reference to the IRC bot to check whether the user is already connected when they check to load or cache an\n * emote type\n */\n private final ChatViewerBot bot;\n\n /**\n * Construct an emoji control panel\n * \n * @param fProps\n * @param chatWindow\n * @param bot\n * @param logBox\n */\n public ControlPanelEmoji(FontificatorProperties fProps, ChatWindow chatWindow, ChatViewerBot bot, LogBox logBox)\n {\n super(\"Emoji\", fProps, chatWindow, logBox);\n this.progressPanel.setEmojiConfig(config);\n this.bot = bot;\n }\n\n private void resolveEnables()\n {\n final boolean all = enableAll.isSelected();\n final boolean badges = enableTwitchBadges.isSelected() || enableFfzBadges.isSelected();\n\n scaleAndDisplayPanel.setEnabled(all || badges);\n emojiScaleToLineHeight.setEnabled(all);\n badgeScaleToLineHeight.setEnabled(badges);\n emojiScale.setEnabled(all);\n badgeScale.setEnabled(badges);\n badgeHeightOffset.setEnabled(badges);\n emojiLoadingDisplayStratLabel.setEnabled(all || badges);\n emojiLoadingDisplayStrat.setEnabled(all || badges);\n enableTwitterEmoji.setEnabled(all);\n\n twitchPanel.setEnabled(all);\n enableTwitch.setEnabled(all);\n cacheTwitch.setEnabled(all && enableTwitch.isSelected());\n\n frankerPanel.setEnabled(all);\n enableFrankerFaceZ.setEnabled(all);\n cacheFrankerFaceZ.setEnabled(all && enableFrankerFaceZ.isSelected());\n\n betterPanel.setEnabled(all);\n enableBetterTtv.setEnabled(all);\n cacheBetterTtv.setEnabled(all && enableBetterTtv.isSelected());\n\n progressPanel.handleButtonEnables();\n }\n\n @Override\n protected void build()\n {\n enableAll = new JCheckBox(\"Enable Emoji\");\n enableAnimation = new JCheckBox(\"Enable Animation\");\n enableTwitchBadges = new JCheckBox(\"Enable Twitch Badges\");\n enableFfzBadges = new JCheckBox(\"Enable FrankerFaceZ Badges\");\n\n progressPanel = new EmojiLoadProgressPanel(chat, this);\n\n emojiScaleToLineHeight = new JCheckBox(\"Relative to Line Height\");\n emojiScale = new LabeledSlider(\"Emoji Scale\", \"%\", ConfigEmoji.MIN_SCALE, ConfigEmoji.MAX_SCALE, 100, 3);\n\n badgeScaleToLineHeight = new JCheckBox(\"Relative to Line Height\");\n badgeScale = new LabeledSlider(\"Badge Scale\", \"%\", ConfigEmoji.MIN_SCALE, ConfigEmoji.MAX_SCALE, 100, 3);\n badgeHeightOffset = new LabeledSlider(\"Badge Height Offset\", \"pixels\", ConfigEmoji.MIN_BADGE_OFFSET, ConfigEmoji.MAX_BADGE_OFFSET, 0, 3);\n\n emojiLoadingDisplayStratLabel = new JLabel(\"Loading Display Strategy:\");\n emojiLoadingDisplayStrat = new JComboBox<EmojiLoadingDisplayStragegy>(EmojiLoadingDisplayStragegy.values());\n\n enableTwitterEmoji = new JCheckBox(\"Enable Twitter Emoji\");\n enableTwitterEmoji.setToolTipText(\"Use Twitter emoji for extended character emoji instead of the local default font\");\n\n enableTwitch = new JCheckBox(\"Enable Twitch Emotes\");\n cacheTwitch = new JCheckBox(\"Cache Global Twitch Emotes\");\n\n enableFrankerFaceZ = new JCheckBox(\"Enable FrankerFaceZ Emotes\");\n cacheFrankerFaceZ = new JCheckBox(\"Cache FrankerFaceZ Emotes\");\n\n enableBetterTtv = new JCheckBox(\"Enable BetterTTV Emotes\");\n cacheBetterTtv = new JCheckBox(\"Cache BetterTTV Emotes\");\n\n emojiScale.addChangeListener(new ChangeListener()\n {\n @Override\n public void stateChanged(ChangeEvent e)\n {\n config.setEmojiScale(emojiScale.getValue());\n chat.repaint();\n }\n });\n\n badgeScale.addChangeListener(new ChangeListener()\n {\n @Override\n public void stateChanged(ChangeEvent e)\n {\n config.setBadgeScale(badgeScale.getValue());\n chat.repaint();\n }\n });\n\n badgeHeightOffset.addChangeListener(new ChangeListener()\n {\n @Override\n public void stateChanged(ChangeEvent e)\n {\n config.setBadgeHeightOffset(badgeHeightOffset.getValue());\n chat.repaint();\n }\n });\n\n emojiLoadingDisplayStrat.addActionListener(new ActionListener()\n {\n @Override\n public void actionPerformed(ActionEvent e)\n {\n config.setDisplayStrategy((EmojiLoadingDisplayStragegy) emojiLoadingDisplayStrat.getSelectedItem());\n chat.repaint();\n }\n });\n\n enableTwitterEmoji.addActionListener(new ActionListener()\n {\n @Override\n public void actionPerformed(ActionEvent e)\n {\n config.setTwitterEnabled(enableTwitterEmoji.isSelected());\n chat.repaint();\n }\n });\n\n // This action listener is for loading emotes and badges whenever a checkbox is checked while connected\n ActionListener cbal = new ActionListener()\n {\n @Override\n public void actionPerformed(ActionEvent e)\n {\n JCheckBox source = (JCheckBox) e.getSource();\n if (bot.isConnected())\n {\n Set<EmojiJob> jobsToRun = new HashSet<EmojiJob>();\n Set<EmojiJob> jobsToCancel = new HashSet<EmojiJob>();\n\n final boolean clickAll = enableAll.equals(source);\n final boolean clickFfzLoad = clickAll || enableFrankerFaceZ.equals(source);\n final boolean clickFfzCache = clickAll || cacheFrankerFaceZ.equals(source);\n final boolean clickBttvLoad = clickAll || enableBetterTtv.equals(source);\n final boolean clickBttvCache = clickAll || cacheBetterTtv.equals(source);\n\n // Badges is independent of enableAll\n final boolean clickTwitchBadges = !config.isTwitchBadgesLoaded(getConnectChannel()) && enableTwitchBadges.equals(source);\n final boolean clickFfzBadges = !config.isFfzBadgesLoaded(getConnectChannel()) && enableFfzBadges.equals(source);\n\n final String oauth = fProps.getProperty(FontificatorProperties.KEY_IRC_AUTH);\n\n if (clickFfzLoad && !config.isFfzLoaded(getConnectChannel()))\n {\n EmojiJob jobA = new EmojiJob(oauth, EmojiType.FRANKERFACEZ_CHANNEL, EmojiOperation.LOAD, getConnectChannel());\n EmojiJob jobB = new EmojiJob(oauth, EmojiType.FRANKERFACEZ_GLOBAL, EmojiOperation.LOAD);\n\n if (enableAll.isSelected() && enableFrankerFaceZ.isSelected())\n {\n jobsToRun.add(jobA);\n jobsToRun.add(jobB);\n }\n else\n {\n jobsToCancel.add(jobA);\n jobsToCancel.add(jobB);\n }\n }\n\n if (clickBttvLoad && !config.isBttvLoaded(getConnectChannel()))\n {\n EmojiJob jobA = new EmojiJob(oauth, EmojiType.BETTER_TTV_CHANNEL, EmojiOperation.LOAD, getConnectChannel());\n EmojiJob jobB = new EmojiJob(oauth, EmojiType.BETTER_TTV_GLOBAL, EmojiOperation.LOAD);\n\n if (enableAll.isSelected() && enableBetterTtv.isSelected())\n {\n jobsToRun.add(jobA);\n jobsToRun.add(jobB);\n }\n else\n {\n jobsToCancel.add(jobA);\n jobsToCancel.add(jobB);\n }\n }\n\n if (clickFfzCache && !config.isFfzCached())\n {\n EmojiJob jobA = new EmojiJob(oauth, EmojiType.FRANKERFACEZ_CHANNEL, EmojiOperation.CACHE);\n EmojiJob jobB = new EmojiJob(oauth, EmojiType.FRANKERFACEZ_GLOBAL, EmojiOperation.CACHE);\n if (enableAll.isSelected() && cacheFrankerFaceZ.isSelected())\n {\n jobsToRun.add(jobA);\n jobsToRun.add(jobB);\n }\n else\n {\n jobsToCancel.add(jobA);\n jobsToCancel.add(jobB);\n }\n }\n\n if (clickBttvCache && !config.isBttvCached())\n {\n EmojiJob jobA = new EmojiJob(oauth, EmojiType.BETTER_TTV_CHANNEL, EmojiOperation.CACHE);\n EmojiJob jobB = new EmojiJob(oauth, EmojiType.BETTER_TTV_GLOBAL, EmojiOperation.CACHE);\n if (enableAll.isSelected() && cacheBetterTtv.isSelected())\n {\n jobsToRun.add(jobA);\n jobsToRun.add(jobB);\n }\n else\n {\n jobsToCancel.add(jobA);\n jobsToCancel.add(jobB);\n }\n }\n\n if (clickTwitchBadges && !config.isTwitchBadgesLoaded(getConnectChannel()))\n {\n EmojiJob job = new EmojiJob(oauth, EmojiType.TWITCH_BADGE, EmojiOperation.LOAD, getConnectChannel());\n // No check for enable all here, because badges are independent of the emoji enableAll toggle\n if (enableTwitchBadges.isSelected())\n {\n jobsToRun.add(job);\n }\n else\n {\n jobsToCancel.add(job);\n }\n }\n\n if (clickFfzBadges && !config.isFfzBadgesLoaded(getConnectChannel()))\n {\n EmojiJob job = new EmojiJob(oauth, EmojiType.FRANKERFACEZ_BADGE, EmojiOperation.LOAD, getConnectChannel());\n // No check for enable all here, because badges are independent of the emoji enableAll toggle\n if (enableFfzBadges.isSelected())\n {\n jobsToRun.add(job);\n }\n else\n {\n jobsToCancel.add(job);\n }\n }\n\n loadEmojiWork(jobsToRun);\n\n cancelEmojiWork(jobsToCancel);\n\n if (!jobsToRun.isEmpty() && !progressPanel.isCurrentlyRunning())\n {\n runEmojiWork();\n }\n }\n\n // These are only the checkboxes handled in fillConfigFromInput()\n config.setEmojiEnabled(enableAll.isSelected());\n config.setAnimationEnabled(enableAnimation.isSelected());\n config.setTwitchBadgesEnabled(enableTwitchBadges.isSelected());\n config.setFfzBadgesEnabled(enableFfzBadges.isSelected());\n config.setTwitchEnabled(enableTwitch.isSelected());\n config.setTwitchCacheEnabled(cacheTwitch.isSelected());\n config.setFfzEnabled(enableFrankerFaceZ.isSelected());\n config.setFfzCacheEnabled(cacheFrankerFaceZ.isSelected());\n config.setBttvEnabled(enableBetterTtv.isSelected());\n config.setBttvCacheEnabled(cacheBetterTtv.isSelected());\n config.setEmojiScaleToLine(emojiScaleToLineHeight.isSelected());\n config.setBadgeScaleToLine(badgeScaleToLineHeight.isSelected());\n config.setTwitterEnabled(enableTwitterEmoji.isSelected());\n resolveEnables();\n\n chat.repaint();\n }\n };\n\n enableAll.addActionListener(cbal);\n enableAnimation.addActionListener(cbal);\n enableTwitchBadges.addActionListener(cbal);\n enableFfzBadges.addActionListener(cbal);\n emojiScaleToLineHeight.addActionListener(cbal);\n badgeScaleToLineHeight.addActionListener(cbal);\n enableTwitch.addActionListener(cbal);\n cacheTwitch.addActionListener(cbal);\n enableFrankerFaceZ.addActionListener(cbal);\n cacheFrankerFaceZ.addActionListener(cbal);\n enableBetterTtv.addActionListener(cbal);\n cacheBetterTtv.addActionListener(cbal);\n\n // Top row containing emoji toggle, animation, and badge toggles\n JPanel allEnabledPanel = new JPanel(new GridBagLayout());\n GridBagConstraints allGbc = getGbc();\n allGbc.weighty = 1.0;\n allGbc.fill = GridBagConstraints.NONE;\n allGbc.anchor = GridBagConstraints.WEST;\n allGbc.weightx = 0.25;\n allEnabledPanel.add(enableAll, allGbc);\n allGbc.gridx++;\n allEnabledPanel.add(enableAnimation, allGbc);\n allGbc.gridx++;\n allGbc.anchor = GridBagConstraints.EAST;\n allEnabledPanel.add(enableTwitchBadges, allGbc);\n allGbc.gridx++;\n allEnabledPanel.add(enableFfzBadges, allGbc);\n allGbc.gridx++;\n\n scaleAndDisplayPanel = new JPanel(new GridBagLayout());\n scaleAndDisplayPanel.setBorder(baseBorder);\n GridBagConstraints scaleAndDisplayGbc = getGbc();\n\n // Emoji scaling\n scaleAndDisplayGbc.anchor = GridBagConstraints.CENTER;\n scaleAndDisplayGbc.fill = GridBagConstraints.HORIZONTAL;\n scaleAndDisplayGbc.weightx = 1.0;\n scaleAndDisplayPanel.add(emojiScale, scaleAndDisplayGbc);\n scaleAndDisplayGbc.gridx++;\n scaleAndDisplayGbc.fill = GridBagConstraints.NONE;\n scaleAndDisplayGbc.weightx = 0.0;\n scaleAndDisplayPanel.add(emojiScaleToLineHeight, scaleAndDisplayGbc);\n scaleAndDisplayGbc.gridx = 0;\n scaleAndDisplayGbc.gridy++;\n\n // Badge scaling\n scaleAndDisplayGbc.anchor = GridBagConstraints.CENTER;\n scaleAndDisplayGbc.fill = GridBagConstraints.HORIZONTAL;\n scaleAndDisplayGbc.weightx = 1.0;\n scaleAndDisplayPanel.add(badgeScale, scaleAndDisplayGbc);\n scaleAndDisplayGbc.gridx++;\n scaleAndDisplayGbc.fill = GridBagConstraints.NONE;\n scaleAndDisplayGbc.weightx = 0.0;\n scaleAndDisplayPanel.add(badgeScaleToLineHeight, scaleAndDisplayGbc);\n scaleAndDisplayGbc.gridx = 0;\n scaleAndDisplayGbc.gridy++;\n scaleAndDisplayGbc.fill = GridBagConstraints.HORIZONTAL;\n scaleAndDisplayGbc.gridwidth = 2;\n scaleAndDisplayPanel.add(badgeHeightOffset, scaleAndDisplayGbc);\n scaleAndDisplayGbc.gridy++;\n\n scaleAndDisplayGbc.gridwidth = 2;\n scaleAndDisplayGbc.weightx = 1.0;\n scaleAndDisplayGbc.fill = GridBagConstraints.HORIZONTAL;\n scaleAndDisplayPanel.add(new JSeparator(SwingConstants.HORIZONTAL), scaleAndDisplayGbc);\n scaleAndDisplayGbc.gridy++;\n JPanel bottomOfScaleDisplayPanel = new JPanel(new GridBagLayout());\n GridBagConstraints bosdpGbc = getGbc();\n bottomOfScaleDisplayPanel.add(emojiLoadingDisplayStratLabel, bosdpGbc);\n bosdpGbc.gridx++;\n bottomOfScaleDisplayPanel.add(emojiLoadingDisplayStrat, bosdpGbc);\n bosdpGbc.gridx++;\n bottomOfScaleDisplayPanel.add(enableTwitterEmoji, bosdpGbc);\n scaleAndDisplayPanel.add(bottomOfScaleDisplayPanel, scaleAndDisplayGbc);\n\n twitchPanel = new JPanel(new GridBagLayout());\n twitchPanel.setBorder(BorderFactory.createTitledBorder(baseBorder, \"Twitch Emotes\"));\n GridBagConstraints twitchGbc = getGbc();\n twitchPanel.add(enableTwitch, twitchGbc);\n twitchGbc.gridy++;\n twitchPanel.add(cacheTwitch, twitchGbc);\n twitchGbc.gridy++;\n\n frankerPanel = new JPanel(new GridBagLayout());\n frankerPanel.setBorder(BorderFactory.createTitledBorder(baseBorder, \"FrankerFaceZ Emotes\"));\n GridBagConstraints frankerGbc = getGbc();\n frankerPanel.add(enableFrankerFaceZ, frankerGbc);\n frankerGbc.gridy++;\n frankerPanel.add(cacheFrankerFaceZ, frankerGbc);\n frankerGbc.gridy++;\n\n betterPanel = new JPanel(new GridBagLayout());\n betterPanel.setBorder(BorderFactory.createTitledBorder(baseBorder, \"BetterTTV Emotes\"));\n GridBagConstraints betterGbc = getGbc();\n betterPanel.add(enableBetterTtv, betterGbc);\n betterGbc.gridy++;\n betterPanel.add(cacheBetterTtv, betterGbc);\n betterGbc.gridy++;\n\n gbc.anchor = GridBagConstraints.NORTH;\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.weightx = 1.0;\n gbc.weighty = 0.0;\n\n gbc.gridwidth = 3;\n add(allEnabledPanel, gbc);\n gbc.gridy++;\n\n gbc.gridwidth = 1;\n add(twitchPanel, gbc);\n gbc.gridx++;\n\n add(frankerPanel, gbc);\n gbc.gridx++;\n\n add(betterPanel, gbc);\n gbc.gridx++;\n gbc.gridx = 0;\n gbc.gridy++;\n\n gbc.gridwidth = 3;\n add(scaleAndDisplayPanel, gbc);\n gbc.gridy++;\n\n gbc.gridy++;\n gbc.anchor = GridBagConstraints.SOUTH;\n gbc.weighty = 1.0;\n gbc.weightx = 1.0;\n gbc.gridwidth = 3;\n gbc.fill = GridBagConstraints.BOTH;\n add(progressPanel, gbc);\n gbc.gridy++;\n }\n\n private String getConnectChannel()\n {\n return fProps.getIrcConfig().getChannelNoHash();\n }\n\n /**\n * Load emoji based on what's already happened and what is checked. This is called by the IRC control panel when a\n * connection is first made to the IRC channel or by the manual load button on the progress panel at the bottom of\n * the Emoji tab of the Control Window.\n */\n public void loadAndRunEmojiWork()\n {\n boolean atLeastOneBadgeSelected = enableTwitchBadges.isSelected() || enableFfzBadges.isSelected();\n if (enableAll.isSelected() || atLeastOneBadgeSelected)\n {\n Set<EmojiJob> jobs = collectJobs();\n\n if (jobs.isEmpty())\n {\n progressPanel.log(\"No new work found.\");\n }\n else\n {\n loadEmojiWork(jobs);\n }\n runEmojiWork();\n }\n progressPanel.handleButtonEnables();\n }\n\n public int countJobs()\n {\n int count = 0;\n if (config == null)\n {\n return count;\n }\n\n final String channel = getConnectChannel();\n\n if (enableAll.isSelected())\n {\n final boolean workTwitchLoad = !config.isTwitchLoaded() && enableTwitch.isSelected();\n final boolean workTwitchCache = !config.isTwitchCached() && cacheTwitch.isSelected();\n final boolean workFfzLoad = !config.isFfzLoaded(channel) && enableFrankerFaceZ.isSelected();\n final boolean workFfzGlobalLoad = !config.isFfzGlobalLoaded() && enableFrankerFaceZ.isSelected();\n final boolean workFfzCache = !config.isFfzCached() && cacheFrankerFaceZ.isSelected();\n final boolean workBttvLoad = !config.isBttvLoaded(channel) && enableBetterTtv.isSelected();\n final boolean workBttvGlobalLoad = !config.isBttvGlobalLoaded() && enableBetterTtv.isSelected();\n final boolean workBttvCache = !config.isBttvCached() && cacheBetterTtv.isSelected();\n\n count += countBooleans(workTwitchLoad, workTwitchCache, workFfzLoad, workFfzGlobalLoad, workFfzCache, workBttvLoad, workBttvGlobalLoad, workBttvCache);\n }\n\n final boolean workTwitchBadges = enableTwitchBadges.isSelected() && !config.isTwitchBadgesLoaded(channel);\n final boolean workFfzBadges = enableFfzBadges.isSelected() && !config.isFfzBadgesLoaded(channel);\n\n count += countBooleans(workTwitchBadges, workFfzBadges);\n\n return count;\n }\n\n private static int countBooleans(boolean... bools)\n {\n int count = 0;\n for (int i = 0; i < bools.length; i++)\n {\n if (bools[i])\n {\n count++;\n }\n }\n return count;\n }\n\n /**\n * Parse through the selected UI options to determine what jobs need to be done. This will return an empty job list\n * if any of the jobs specified by the UI require a channel and no channel is provided on the Connection tab. A\n * popup will present this information to the user.\n * \n * @return jobs\n */\n public Set<EmojiJob> collectJobs()\n {\n Set<EmojiJob> jobs = new HashSet<EmojiJob>();\n\n if (config == null)\n {\n return jobs;\n }\n\n final String channel = getConnectChannel();\n final String oauth = fProps.getProperty(FontificatorProperties.KEY_IRC_AUTH);\n\n if (enableAll.isSelected())\n {\n final boolean workFfzLoad = !config.isFfzLoaded(channel) && enableFrankerFaceZ.isSelected();\n final boolean workFfzGlobalLoad = !config.isFfzGlobalLoaded() && enableFrankerFaceZ.isSelected();\n final boolean workFfzCache = !config.isFfzCached() && cacheFrankerFaceZ.isSelected();\n final boolean workBttvLoad = !config.isBttvLoaded(channel) && enableBetterTtv.isSelected();\n final boolean workBttvGlobalLoad = !config.isBttvGlobalLoaded() && enableBetterTtv.isSelected();\n final boolean workBttvCache = !config.isBttvCached() && cacheBetterTtv.isSelected();\n\n if (workFfzLoad)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.FRANKERFACEZ_CHANNEL, EmojiOperation.LOAD, channel));\n if (channel == null)\n {\n ChatWindow.popup.handleProblem(\"Please specify a channel on the Connection tab to load emoji\");\n jobs.clear();\n return jobs;\n }\n }\n\n if (workFfzGlobalLoad)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.FRANKERFACEZ_GLOBAL, EmojiOperation.LOAD));\n }\n\n if (workFfzCache)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.FRANKERFACEZ_CHANNEL, EmojiOperation.CACHE));\n jobs.add(new EmojiJob(oauth, EmojiType.FRANKERFACEZ_GLOBAL, EmojiOperation.CACHE));\n }\n\n if (workBttvLoad)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.BETTER_TTV_CHANNEL, EmojiOperation.LOAD, channel));\n if (channel == null)\n {\n ChatWindow.popup.handleProblem(\"Please specify a channel on the Connection tab to load emoji\");\n jobs.clear();\n return jobs;\n }\n }\n\n if (workBttvGlobalLoad)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.BETTER_TTV_GLOBAL, EmojiOperation.LOAD));\n }\n\n if (workBttvCache)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.BETTER_TTV_CHANNEL, EmojiOperation.CACHE));\n jobs.add(new EmojiJob(oauth, EmojiType.BETTER_TTV_GLOBAL, EmojiOperation.CACHE));\n }\n }\n\n final boolean workTwitchBadges = enableTwitchBadges.isSelected() && !config.isTwitchBadgesLoaded(channel);\n final boolean workFfzBadges = enableFfzBadges.isSelected() && !config.isFfzBadgesLoaded(channel);\n\n if (workTwitchBadges)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.TWITCH_BADGE, EmojiOperation.LOAD, channel));\n if (channel == null)\n {\n ChatWindow.popup.handleProblem(\"Please specify a channel on the Connection tab to load badges\");\n jobs.clear();\n return jobs;\n }\n }\n\n if (workFfzBadges)\n {\n jobs.add(new EmojiJob(oauth, EmojiType.FRANKERFACEZ_BADGE, EmojiOperation.LOAD, channel));\n if (channel == null)\n {\n ChatWindow.popup.handleProblem(\"Please specify a channel on the Connection tab to load badges\");\n jobs.clear();\n return jobs;\n }\n }\n\n return jobs;\n }\n\n /**\n * Queue the work of a specified operation (load or cache) on a specified type of emote (Twitch or FrankerFaceZ).\n * Call runEmoteWork to run the loaded work in series.\n * \n * @param types\n * @param ops\n */\n private void loadEmojiWork(Collection<EmojiJob> jobs)\n {\n for (EmojiJob job : jobs)\n {\n EmojiWorkerReport initialReport = new EmojiWorkerReport(job.toString(), 0);\n\n // A SwingWorkers can only be run once because... reasons. So each call to do work must be on a freshly\n // instantiated worker object.\n EmojiWorker worker = new EmojiWorker(chat.getEmojiManager(), progressPanel, job, logBox, initialReport);\n\n progressPanel.addWorkToQueue(worker);\n }\n }\n\n /**\n * Cancel\n * \n * @param typesToCancel\n * @param opsToCancel\n */\n private void cancelEmojiWork(Collection<EmojiJob> jobs)\n {\n for (EmojiJob job : jobs)\n {\n progressPanel.removeWorkFromQueue(job);\n }\n }\n\n /**\n * To be called after loadEmoteWork has set up the tasks\n */\n private void runEmojiWork()\n {\n progressPanel.initiateWork();\n }\n\n @Override\n protected void fillInputFromProperties(FontificatorProperties fProps)\n {\n config = fProps.getEmojiConfig();\n fillInputFromConfig();\n }\n\n @Override\n protected void fillInputFromConfig()\n {\n this.enableAll.setSelected(config.isEmojiEnabled());\n this.enableAnimation.setSelected(config.isAnimationEnabled());\n this.enableTwitchBadges.setSelected(config.isTwitchBadgesEnabled());\n this.enableFfzBadges.setSelected(config.isFfzBadgesEnabled());\n this.emojiScaleToLineHeight.setSelected(config.isEmojiScaleToLine());\n this.badgeScaleToLineHeight.setSelected(config.isBadgeScaleToLine());\n this.emojiScale.setValue(config.getEmojiScale());\n this.badgeScale.setValue(config.getBadgeScale());\n this.emojiLoadingDisplayStrat.setSelectedItem(config.getDisplayStrategy());\n this.enableTwitch.setSelected(config.isTwitchEnabled());\n this.cacheTwitch.setSelected(config.isTwitchCacheEnabled());\n this.enableFrankerFaceZ.setSelected(config.isFfzEnabled());\n this.cacheFrankerFaceZ.setSelected(config.isFfzCacheEnabled());\n this.enableBetterTtv.setSelected(config.isBttvEnabled());\n this.cacheBetterTtv.setSelected(config.isBttvCacheEnabled());\n this.enableAnimation.setSelected(config.isAnimationEnabled());\n this.enableTwitterEmoji.setSelected(config.isTwitterEnabled());\n\n resolveEnables();\n }\n\n @Override\n protected LoadConfigReport validateInput()\n {\n return new LoadConfigReport();\n }\n\n @Override\n protected void fillConfigFromInput() throws Exception\n {\n config.setEmojiEnabled(enableAll.isSelected());\n config.setAnimationEnabled(enableAnimation.isSelected());\n config.setTwitchBadgesEnabled(enableTwitchBadges.isSelected());\n config.setFfzBadgesEnabled(enableFfzBadges.isSelected());\n config.setEmojiScaleToLine(emojiScaleToLineHeight.isSelected());\n config.setBadgeScaleToLine(badgeScaleToLineHeight.isSelected());\n config.setEmojiScale(emojiScale.getValue());\n config.setBadgeScale(badgeScale.getValue());\n config.setDisplayStrategy((EmojiLoadingDisplayStragegy) emojiLoadingDisplayStrat.getSelectedItem());\n config.setTwitchEnabled(enableTwitch.isSelected());\n config.setTwitchCacheEnabled(cacheTwitch.isSelected());\n config.setFfzEnabled(enableFrankerFaceZ.isSelected());\n config.setFfzCacheEnabled(cacheFrankerFaceZ.isSelected());\n config.setBttvEnabled(enableBetterTtv.isSelected());\n config.setBttvCacheEnabled(cacheBetterTtv.isSelected());\n config.setAnimationEnabled(enableAnimation.isSelected());\n config.setTwitterEnabled(enableTwitterEmoji.isSelected());\n }\n\n}", "public class LogBox extends JScrollPane\n{\n private static final long serialVersionUID = 1L;\n\n private JTextArea output;\n\n private String authCode;\n\n public LogBox()\n {\n super(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);\n\n this.authCode = null;\n\n output = new JTextArea();\n output.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));\n output.setWrapStyleWord(true);\n output.setLineWrap(true);\n output.setEditable(false);\n output.setBackground(getBackground());\n\n super.setViewportView(output);\n }\n\n public void setAuthCode(String authCode)\n {\n this.authCode = authCode;\n }\n\n public void log(LoadConfigReport report)\n {\n for (String msg : report.getMessages())\n {\n log(msg);\n }\n }\n\n public void log(String line)\n {\n if (authCode != null && line.contains(authCode))\n {\n String blocks = \"\";\n for (int i = 0; i < authCode.length(); i++)\n {\n blocks += \"*\";\n }\n // Blank out any time the oauth key is logged- this output might accidentally wind up in a video stream\n line = line.replaceAll(authCode, blocks);\n }\n if (line.endsWith(\"\\n\"))\n {\n line = line.substring(0, line.length() - 1);\n }\n output.append((output.getText().isEmpty() ? \"\" : \"\\n\") + line);\n output.setCaretPosition(output.getDocument().getLength());\n }\n\n public void clear()\n {\n output.setText(\"\");\n }\n\n}" ]
import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ConcurrentLinkedQueue; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import org.apache.log4j.Logger; import com.glitchcog.fontificator.config.ConfigEmoji; import com.glitchcog.fontificator.emoji.EmojiJob; import com.glitchcog.fontificator.emoji.EmojiOperation; import com.glitchcog.fontificator.gui.chat.ChatPanel; import com.glitchcog.fontificator.gui.controls.panel.ControlPanelBase; import com.glitchcog.fontificator.gui.controls.panel.ControlPanelEmoji; import com.glitchcog.fontificator.gui.controls.panel.LogBox;
blankAllValues(); reset(); handleButtonEnables(); } else if (report.isError()) { emojiLogBox.log(report.getMessage()); blankAllValues(); if (currentWorker != null) { currentWorker.haltCurrentJob(); } currentWorker = null; initiateNextWork(); } else { bar.setValue(report.getPercentComplete()); percentValue.setText(report.getPercentText()); if (report.isComplete()) { emojiLogBox.log(report.getMessage()); if (currentWorker != null) { emojiConfig.setWorkCompleted(currentWorker.getEmojiJob()); } initiateNextWork(); } } repaint(); } /** * Reverts the panel to its ready state */ synchronized private void reset() { cancelButton.setEnabled(false); blankAllValues(); workerTaskListLoad.clear(); workerTaskListCache.clear(); currentWorker = null; } /** * Removes all labels and values from the display */ synchronized private void blankAllValues() { percentValue.setText(EMPTY_VALUE_TEXT); bar.setValue(0); } /** * Call to add work * * @param label * @param emojiWorker * @param initialReport */ synchronized public void addWorkToQueue(EmojiWorker emojiWorker) { ConcurrentLinkedQueue<EmojiWorker> taskList = getTaskList(emojiWorker.getEmojiJob()); for (EmojiWorker worker : taskList) { if (!worker.isCancelled() && worker.getEmojiJob().equals(emojiWorker.getEmojiJob())) { // Already exists in a non-canceled way, so don't add it return; } } taskList.add(emojiWorker); } /** * Call to initiate work */ synchronized public void initiateWork() { ConcurrentLinkedQueue<EmojiWorker> taskList = getTaskList(); if (!taskList.isEmpty()) { currentWorker = taskList.poll(); setLocation(getParent().getLocation().x + (getParent().getWidth() - getWidth()) / 2, getParent().getLocation().y + (getParent().getHeight() - getHeight()) / 2); cancelButton.setEnabled(true); update(currentWorker.getInitialReport()); currentWorker.execute(); } } /** * Kick off the next worker when the current worker is done */ synchronized private void initiateNextWork() { this.percentValue.setText(EMPTY_VALUE_TEXT); ConcurrentLinkedQueue<EmojiWorker> taskList = getTaskList(); this.currentWorker = taskList.poll(); chat.repaint(); if (currentWorker == null) { reset(); handleButtonEnables(); } else { currentWorker.execute(); } } /** * Take any worker containing a job that matches the specified job off the queue of workers to be executed. Also * cancels the currently running worker if it matches. * * @param job */
synchronized public void removeWorkFromQueue(EmojiJob job)
1
bitkylin/BitkyShop
Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/UserFragment.java
[ "public class KyUser extends BmobUser {\n private String pwdResumeQuestion;\n private String pwdResumeAnswer;\n private Boolean haveDetailInfo;\n\n public Boolean getHaveDetailInfo() {\n return haveDetailInfo;\n }\n\n public void setHaveDetailInfo(Boolean haveDetailInfo) {\n this.haveDetailInfo = haveDetailInfo;\n }\n\n public String getPwdResumeQuestion() {\n return pwdResumeQuestion;\n }\n\n public void setPwdResumeQuestion(String pwdResumeQuestion) {\n this.pwdResumeQuestion = pwdResumeQuestion;\n }\n\n public String getPwdResumeAnswer() {\n return pwdResumeAnswer;\n }\n\n public void setPwdResumeAnswer(String pwdResumeAnswer) {\n this.pwdResumeAnswer = pwdResumeAnswer;\n }\n}", "public class AddressOptionActivity extends AppCompatActivity implements View.OnClickListener {\n\n private AddressOptionPresenter presenter;\n private ToastUtil toastUtil;\n private KyBaseRecyclerAdapter<ReceiveAddress> recyclerAdapter;\n private String objectId;\n private String username;\n\n @Override protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_address_option);\n presenter = new AddressOptionPresenter(this);\n toastUtil = new ToastUtil(this);\n\n //初始化Toolbar\n KyToolBar kyToolBar = (KyToolBar) findViewById(R.id.addressOptionActivity_kyToolbar);\n kyToolBar.setNavigationOnClickListener(this);\n kyToolBar.setRightButtonOnClickListener(this);\n\n initRecyclerView();\n\n //由订单确认页面进入时的初始化\n int requestCode = getIntent().getIntExtra(\"requestCode\", -1);\n if (requestCode == KySet.CART_REQUEST_SELECT_RECEIVE_ADDRESS) {\n kyToolBar.setTitle(\"点击选择收货地址\");\n recyclerAdapter.setOnClickListener(\n new KyBaseRecyclerAdapter.KyRecyclerViewItemOnClickListener<ReceiveAddress>() {\n @Override public void Onclick(View v, int adapterPosition, ReceiveAddress data) {\n Intent intent = getIntent();\n intent.putExtra(\"address\", data);\n setResult(KySet.CART_RESULT_SELECT_RECEIVE_ADDRESS, intent);\n finish();\n }\n });\n }\n\n //初始化本地User对象并获取远端ReceivedAddress\n String objectId = getIntent().getStringExtra(\"objectId\");\n String username = getIntent().getStringExtra(\"userName\");\n if (objectId != null && username != null) {\n this.objectId = objectId;\n this.username = username;\n presenter.getCurrentUserAddress(objectId);\n } else {\n KLog.d(\"未知错误\");\n toastUtil.show(\"未知错误\");\n finish();\n }\n }\n\n private void initRecyclerView() {\n RecyclerView recyclerView =\n (RecyclerView) findViewById(R.id.addressOptionActivity_RecyclerView);\n if (recyclerAdapter == null) {\n initRecyclerViewData(new ArrayList<ReceiveAddress>());\n }\n recyclerView.setLayoutManager(new LinearLayoutManager(this));\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n //recyclerView.addItemDecoration(\n // new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));\n recyclerView.setAdapter(recyclerAdapter);\n }\n\n public void initRecyclerViewData(List<ReceiveAddress> list) {\n recyclerAdapter = new KyBaseRecyclerAdapter<ReceiveAddress>(list,\n R.layout.recycler_userfragment_receive_address) {\n\n @Override\n public void setDataToViewHolder(final ReceiveAddress dataItem, KyBaseViewHolder holder) {\n holder.getTextView(R.id.recycler_userfragment_receiveAddress_name)\n .setText(dataItem.getName());\n holder.getTextView(R.id.recycler_userfragment_receiveAddress_phone)\n .setText(dataItem.getPhone());\n holder.getTextView(R.id.recycler_userfragment_receiveAddress_address)\n .setText(dataItem.getAddress());\n holder.getCheckBox(R.id.recycler_userfragment_receiveAddress_is_default)\n .setChecked(dataItem.getDefault());\n holder.getCheckBox(R.id.recycler_userfragment_receiveAddress_is_default)\n .setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n updateCheckedStatus((CheckBox) v, dataItem);\n }\n });\n holder.getTextView(R.id.recycler_userfragment_receiveAddress_delete)\n .setOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n deleteItem(dataItem);\n }\n });\n }\n };\n }\n\n /**\n * 删除指定的Item\n *\n * @param dataItem 指定的Item\n */\n private void deleteItem(ReceiveAddress dataItem) {\n if (dataItem.getDefault()) {\n showMessage(\"不能删除默认地址\", null);\n } else {\n presenter.deleteUserAddress(dataItem.getObjectId());\n }\n }\n\n /**\n * 升级地址列表的\"被设为默认的\"状态\n *\n * @param c 当前被点击的 Checkbox\n * @param dataItem 被点击的view所对应的Item\n */\n private void updateCheckedStatus(CheckBox c, ReceiveAddress dataItem) {\n if (!c.isChecked()) {\n c.setChecked(true);\n } else {\n for (ReceiveAddress receiveAddress : recyclerAdapter.getDataItems()) {\n if (receiveAddress.getDefault()) {\n receiveAddress.setDefault(false);\n presenter.updateUserAddressDefault(receiveAddress.getObjectId(), false);\n }\n }\n\n dataItem.setDefault(true);\n presenter.updateUserAddressDefault(dataItem.getObjectId(), true);\n recyclerAdapter.notifyDataSetChanged();\n }\n }\n\n @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n switch (resultCode) {\n case KySet.USER_RESULT_CREATE_ADDRESS:\n String name = data.getStringExtra(\"name\");\n String phone = data.getStringExtra(\"phone\");\n String address = data.getStringExtra(\"address\");\n\n if (name != null && phone != null && address != null) {\n ReceiveAddress createdAddress =\n new ReceiveAddress(objectId, username, name, phone, address);\n if (recyclerAdapter.getDataItems().size() == 0) createdAddress.setDefault(true);\n List<ReceiveAddress> receiveAddresses = new ArrayList<ReceiveAddress>();\n receiveAddresses.add(createdAddress);\n recyclerAdapter.loadMoreData(receiveAddresses);\n presenter.insertUserAddress(createdAddress);\n }\n }\n }\n\n @Override public void onClick(View v) {\n switch (v.getId()) {\n case R.id.kytoolbar_navigation:\n finish();\n break;\n case R.id.kytoolbar_rightButton:\n Intent intent = new Intent(this, CreateAddressActivity.class);\n startActivityForResult(intent, KySet.USER_REQUEST_CREATE_ADDRESS);\n break;\n }\n }\n\n /**\n * 从云端读入的数据\n *\n * @param receiveList 完全正确的数据\n */\n public void initReceiveAddress(List<ReceiveAddress> receiveList) {\n if (receiveList != null && receiveList.size() > 0) {\n KLog.d(\"reloadData\");\n recyclerAdapter.reloadData(receiveList);\n }\n }\n\n public void showMessage(String message, Type type) {\n if (type != null) {\n switch (type) {\n case deleteAddressSuccess:\n //本地删除被选定的Item\n Iterator<ReceiveAddress> iterator = recyclerAdapter.getDataItems().iterator();\n while (iterator.hasNext()) {\n ReceiveAddress address = iterator.next();\n if (address.getObjectId().equals(message)) {\n int index = recyclerAdapter.getDataItems().indexOf(address);\n iterator.remove();\n recyclerAdapter.notifyItemRemoved(index);\n }\n }\n break;\n }\n return;\n }\n if (message != null) {\n toastUtil.show(message);\n }\n }\n}", "public class LoginActivity extends AppCompatActivity implements ILoginActivity {\n ToastUtil toastUtil;\n\n @Override protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_login);\n toastUtil = new ToastUtil(this);\n KyToolBar kyToolBar = (KyToolBar) findViewById(R.id.loginActivity_toolbar);\n kyToolBar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n finish();\n }\n });\n\n setTabLayout();\n }\n\n void setTabLayout() {\n TabLayout tabLayout = (TabLayout) findViewById(R.id.loginActivity_tabLayout);\n ViewPager viewPager = (ViewPager) findViewById(R.id.loginActivity_viewPager);\n //初始化各fragment\n LoginPhoneFragment loginPhoneFragment = new LoginPhoneFragment();\n // LoginLegacyFragment loginLegacyFragment = new LoginLegacyFragment();\n // loginLegacyFragment.setActivity(this);\n loginPhoneFragment.setActivity(this);\n //将fragment装进列表中\n List<Fragment> fragmentList = new ArrayList<>();\n fragmentList.add(loginPhoneFragment);\n // fragmentList.add(loginLegacyFragment);\n //将名称加载tab名字列表,正常情况下,我们应该在values/arrays.xml中进行定义然后调用\n List<String> titleList = new ArrayList<>();\n titleList.add(\"手机号一键登录\");\n // titleList.add(\"传统登录\");\n //设置TabLayout的模式\n tabLayout.setTabMode(TabLayout.MODE_FIXED);\n //为TabLayout添加tab名称\n tabLayout.addTab(tabLayout.newTab().setText(titleList.get(0)));\n // tabLayout.addTab(tabLayout.newTab().setText(titleList.get(1)));\n FragmentManager fragmentManager = getSupportFragmentManager();\n FragmentPagerAdapter fAdapter = new FindTabAdapter(fragmentManager, fragmentList, titleList);\n //viewpager加载adapter\n viewPager.setAdapter(fAdapter);\n //TabLayout加载viewpager\n tabLayout.setupWithViewPager(viewPager);\n }\n\n @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n switch (resultCode) {\n case KySet.USER_RESULT_SIGN_UP:\n Bundle bundle = data.getBundleExtra(\"bundle\");\n String objectId = bundle.getString(\"objectId\");\n String username = bundle.getString(\"username\");\n String password = bundle.getString(\"password\");\n if (objectId != null && username != null && password != null) {\n userLoginByLegacy(username, password);\n }\n break;\n case KySet.USER_RESULT_PHONE_SIGNUP_OR_LOGIN:\n String userObjectIdGet = data.getStringExtra(\"userObjectId\");\n String usernameGet = data.getStringExtra(\"username\");\n String phoneGet = data.getStringExtra(\"phone\");\n Boolean haveDetailInfoGet = data.getBooleanExtra(\"haveDetailInfo\", true);\n Intent intent = new Intent();\n setResult(KySet.USER_RESULT_LOG_IN, intent);\n finish();\n break;\n }\n }\n\n @Override public void userLoginByLegacy(String userName, String password) {\n if (userName.length() == 0 || password.length() == 0) {\n toastUtil.show(\"请输入用户名和密码\");\n return;\n }\n //验证语法规则\n if (!KyPattern.checkUserName(userName)) {\n toastUtil.show(\"用户名只能使用中文、英文和数字\");\n return;\n }\n if (!KyPattern.checkNumStr(password)) {\n toastUtil.show(\"密码只能使用英文和数字\");\n return;\n }\n\n KyUser kyUser = new KyUser();\n kyUser.setUsername(userName);\n kyUser.setPassword(password);\n kyUser.loginObservable(KyUser.class).subscribe(new Subscriber<KyUser>() {\n @Override public void onCompleted() {\n toastUtil.show(\"onCompleted\");\n }\n\n @Override public void onError(Throwable throwable) {\n toastUtil.show(throwable.getMessage());\n }\n\n @Override public void onNext(KyUser kyUser) {\n Intent intent = new Intent();\n Bundle bundle = new Bundle();\n bundle.putString(\"objectId\", kyUser.getObjectId());\n bundle.putString(\"username\", kyUser.getUsername());\n intent.putExtra(\"bundle\", bundle);\n setResult(KySet.USER_RESULT_LOG_IN, intent);\n finish();\n }\n });\n }\n\n @Override public void userLoginByPhone(final String phone) {\n if (!KyPattern.checkPhoneNumber(phone)) {\n toastUtil.show(\"请输入正确的手机号码\");\n return;\n }\n\n final Intent intent = new Intent(this, RequestSMSCodeActivity.class);\n intent.putExtra(\"phone\", phone);\n\n BmobSMS.requestSMSCode(phone, \"生活服务超市模板\", new QueryListener<Integer>() {\n\n @Override public void done(Integer smsId, BmobException ex) {\n if (ex != null) {\n toastUtil.show(\"出现未知错误,请重启该应用\");\n KLog.d(ex.getErrorCode() + \":\" + ex.getMessage());\n return;\n }\n startActivityForResult(intent, KySet.USER_REQUEST_PHONE_SIGNUP_OR_LOGIN);\n }\n });\n }\n\n @Override public void signUp() {\n Intent intent = new Intent(this, SignupActivity.class);\n startActivityForResult(intent, KySet.USER_REQUEST_SIGN_UP);\n }\n}", "public class OrderManagerActivity extends AppCompatActivity {\n Context mContext;\n private ToastUtil toastUtil;\n private OrderManagerRecyclerAdapter recyclerAdapter;\n private OrderManagerPresenter presenter;\n private String objectId;\n private String username;\n private MaterialRefreshLayout swipeRefreshLayout;\n private RecyclerView recyclerView;\n\n @Override protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_order_manager);\n mContext = this;\n toastUtil = new ToastUtil(mContext);\n presenter = new OrderManagerPresenter(this);\n KyToolBar kyToolBar = (KyToolBar) findViewById(R.id.orderManagerActivity_kyToolbar);\n kyToolBar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override public void onClick(View v) {\n finish();\n }\n });\n initSwipeRefreshLayout();\n initRecyclerView(new ArrayList<Order>());\n\n //初始化本地User对象并获取远端Order\n String objectId = getIntent().getStringExtra(\"objectId\");\n String username = getIntent().getStringExtra(\"userName\");\n if (objectId != null && username != null) {\n this.objectId = objectId;\n this.username = username;\n presenter.queryOrderFormBmob(objectId, Order.NONE);\n } else {\n KLog.d(\"未知错误\");\n toastUtil.show(\"未知错误\");\n finish();\n }\n }\n\n private void initSwipeRefreshLayout() {\n swipeRefreshLayout =\n (MaterialRefreshLayout) findViewById(R.id.orderManagerActivity_swiperefreshlayout);\n swipeRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {\n @Override public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {\n presenter.refreshRecyclerAdapterData(RefreshType.Refresh);\n }\n\n @Override public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {\n super.onRefreshLoadMore(materialRefreshLayout);\n presenter.refreshRecyclerAdapterData(RefreshType.LoadMore);\n }\n });\n }\n\n public void refleshRecyclerViewData(List<Order> list, RefreshType type) {\n switch (type) {\n case Refresh:\n swipeRefreshLayout.finishRefresh();\n if (recyclerAdapter != null) recyclerAdapter.reloadData(list);\n recyclerView.scrollToPosition(0);\n break;\n\n case LoadMore:\n swipeRefreshLayout.finishRefreshLoadMore();\n if (recyclerAdapter != null) recyclerAdapter.loadMoreData(list);\n break;\n }\n }\n\n public void CanNotRefreshData(RefreshType type) {\n toastUtil.show(\"没有更多的订单了!\");\n swipeRefreshLayout.finishRefreshLoadMore();\n }\n\n private void initRecyclerView(List<Order> list) {\n recyclerView = (RecyclerView) findViewById(R.id.orderManagerActivity_recycler_All);\n if (recyclerAdapter == null) {\n recyclerAdapter = new OrderManagerRecyclerAdapter(list, mContext);\n recyclerAdapter.setOnClickListener(\n new KyBaseRecyclerAdapter.KyRecyclerViewItemOnClickListener<Order>() {\n @Override public void Onclick(View v, int adapterPosition, Order data) {\n Bundle bundle = new Bundle();\n bundle.putSerializable(\"order\", data);\n Intent intent = new Intent(mContext, OrderActivity.class);\n intent.putExtra(\"bundle\", bundle);\n intent.putExtra(\"requestCode\", KySet.USER_REQUEST_HISTORY_ORDER);\n startActivityForResult(intent, KySet.USER_REQUEST_HISTORY_ORDER);\n }\n });\n recyclerAdapter.setCompletedClickListener(\n new OrderManagerRecyclerAdapter.OnButtonCompletedClickListener() {\n @Override public void onClick(Order order) {\n presenter.updateOrderStatus(order, Order.COMPLETED);\n }\n });\n recyclerAdapter.setCancelledClickListener(\n new OrderManagerRecyclerAdapter.OnButtonCancelledClickListener() {\n @Override public void onClick(Order order) {\n presenter.updateOrderStatus(order, Order.CANCELLED);\n }\n });\n }\n recyclerView.setLayoutManager(new LinearLayoutManager(this));\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n recyclerView.setAdapter(recyclerAdapter);\n }\n\n @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (resultCode == KySet.USER_RESULT_REFRESH_ORDER) {\n presenter.queryOrderFormBmob(objectId, Order.NONE);\n }\n }\n\n public void showMessage(String message) {\n toastUtil.show(message);\n }\n\n public void initCloudOrder(List<Order> list) {\n recyclerAdapter.reloadData(list);\n }\n}", "public class KyBmobHelper {\n\n /**\n * 获取本地保存的当前用户\n */\n public static KyUser getCurrentUser() {\n return BmobUser.getCurrentUser(KyUser.class);\n }\n\n\n}", "public class KyPattern {\n /**\n * 验证手机号码\n *\n * @param phoneNumber 手机号码\n * @return boolean\n */\n public static boolean checkPhoneNumber(String phoneNumber) {\n Pattern pattern = Pattern.compile(\"^1[0-9]{10}$\");\n Matcher matcher = pattern.matcher(phoneNumber);\n return matcher.matches();\n }\n\n /**\n * 验证数字字母和中文字符\n *\n * @param phoneNumber 用户名\n * @return boolean\n */\n public static boolean checkUserName(String phoneNumber) {\n Pattern pattern = Pattern.compile(\"([a-zA-Z0-9\\\\u4e00-\\\\u9fa5]{2,24})\");\n Matcher matcher = pattern.matcher(phoneNumber);\n return matcher.matches();\n }\n\n /**\n * 验证数字字母\n *\n * @param phoneNumber 密码\n * @return boolean\n */\n public static boolean checkNumStr(String phoneNumber) {\n Pattern pattern = Pattern.compile(\"([a-zA-Z0-9]{2,24})\");\n Matcher matcher = pattern.matcher(phoneNumber);\n return matcher.matches();\n }\n}", "public class KySet {\n //请求\n public static final int USER_REQUEST_SIGN_UP = 11;\n public static final int USER_REQUEST_LOG_IN = 12;\n public static final int CART_REQUEST_SUBMIT_ORDER = 13;\n public static final int USER_REQUEST_CREATE_ADDRESS = 14;\n public static final int CART_REQUEST_SELECT_RECEIVE_ADDRESS = 15;\n public static final int USER_REQUEST_HISTORY_ORDER = 16;\n public static final int USER_REQUEST_PHONE_SIGNUP_OR_LOGIN = 18;\n\n //返回结果\n public static final int USER_RESULT_SIGN_UP = 21;\n public static final int USER_RESULT_LOG_IN = 22;\n public static final int CART_RESULT_SUBMIT_ORDER = 23;\n public static final int USER_RESULT_CREATE_ADDRESS = 24;\n public static final int CART_RESULT_SELECT_RECEIVE_ADDRESS = 25;\n public static final int USER_RESULT_REFRESH_ORDER = 27;\n public static final int USER_RESULT_PHONE_SIGNUP_OR_LOGIN = 28;\n\n public static final int RESULT_ERROR = -21;\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import cc.bitky.bitkyshop.R; import cc.bitky.bitkyshop.bean.cart.KyUser; import cc.bitky.bitkyshop.fragment.userfragment.addressactivity.AddressOptionActivity; import cc.bitky.bitkyshop.fragment.userfragment.loginfragment.LoginActivity; import cc.bitky.bitkyshop.fragment.userfragment.orderactivity.OrderManagerActivity; import cc.bitky.bitkyshop.utils.tools.KyBmobHelper; import cc.bitky.bitkyshop.utils.tools.KyPattern; import cc.bitky.bitkyshop.utils.tools.KySet; import cn.bmob.v3.BmobUser;
package cc.bitky.bitkyshop.fragment.userfragment; public class UserFragment extends Fragment implements View.OnClickListener { private TextView textViewUserNameShow; private TextView textViewUserLogOut; private Button btnLogout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_user, container, false); textViewUserNameShow = (TextView) view.findViewById(R.id.userFragment_userName_show); btnLogout = (Button) view.findViewById(R.id.userfragment_button_logout); textViewUserLogOut = (TextView) view.findViewById(R.id.userFragment_userName_logout); LinearLayout cardViewAddress = (LinearLayout) view.findViewById(R.id.userFragment_addressCardView); LinearLayout cardViewOrder = (LinearLayout) view.findViewById(R.id.userFragment_orderCardView); textViewUserNameShow.setOnClickListener(this); textViewUserLogOut.setOnClickListener(this); btnLogout.setOnClickListener(this); cardViewAddress.setOnClickListener(this); cardViewOrder.setOnClickListener(this); initCurrentUser(); return view; } /** * 读取本地缓存的已登录用户 */ private void initCurrentUser() { KyUser kyUser = KyBmobHelper.getCurrentUser(); if (kyUser != null) { String username = kyUser.getUsername(); if (KyPattern.checkPhoneNumber(username)) { textViewUserNameShow.setText(username.substring(0, 3) + "****" + username.substring(7, 11)); } else { textViewUserNameShow.setText(username); } textViewUserLogOut.setVisibility(View.VISIBLE); btnLogout.setVisibility(View.VISIBLE); } else { textViewUserNameShow.setText("点击登录"); textViewUserLogOut.setVisibility(View.GONE); btnLogout.setVisibility(View.GONE); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (resultCode) { case KySet.USER_RESULT_LOG_IN: initCurrentUser(); break; } } @Override public void onClick(View v) { if (textViewUserNameShow.getText().toString().trim().equals("点击登录") || KyBmobHelper.getCurrentUser() == null) {
Intent intent = new Intent(getContext(), LoginActivity.class);
2
koendeschacht/count-db
count-db-run/src/main/java/be/bagofwords/db/interfaces/rocksdb/RocksDBDataInterfaceFactory.java
[ "public abstract class CoreDataInterface<T> extends BaseDataInterface<T> {\n\n protected final UpdateListenerCollection<T> updateListenerCollection = new UpdateListenerCollection<>();\n\n public CoreDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporary) {\n super(name, objectClass, combinator, objectSerializer, isTemporary);\n }\n\n @Override\n public DataInterface<T> getCoreDataInterface() {\n return this;\n }\n\n @Override\n public void registerUpdateListener(UpdateListener<T> updateListener) {\n updateListenerCollection.registerUpdateListener(updateListener);\n }\n\n @Override\n public void flush() {\n flushImpl();\n updateListenerCollection.dataFlushed();\n }\n\n protected abstract void flushImpl();\n\n}", "public interface DataInterface<T extends Object> extends DataIterable<KeyValue<T>> {\n\n T read(long key);\n\n default long readCount(long key) {\n Long result = (Long) read(key);\n if (result == null)\n return 0;\n else\n return result;\n }\n\n default T read(String key) {\n return read(HashUtils.hashCode(key));\n }\n\n default T read(BowString key) {\n return read(HashUtils.hashCode(key));\n }\n\n default long readCount(BowString key) {\n return readCount(HashUtils.hashCode(key));\n }\n\n default long readCount(String key) {\n return readCount(HashUtils.hashCode(key));\n }\n\n default boolean mightContain(String key) {\n return mightContain(HashUtils.hashCode(key));\n }\n\n default boolean mightContain(long key) {\n return read(key) != null;\n }\n\n default CloseableIterator<Long> keyIterator() {\n return IterableUtils.mapIterator(iterator(), KeyValue::getKey);\n }\n\n default CloseableIterator<T> valueIterator() {\n return IterableUtils.mapIterator(iterator(), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(KeyFilter keyFilter) {\n return IterableUtils.mapIterator(iterator(keyFilter), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(Predicate<T> valueFilter) {\n return IterableUtils.mapIterator(iterator(valueFilter), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(CloseableIterator<Long> keyIterator) {\n return IterableUtils.mapIterator(iterator(keyIterator), KeyValue::getValue);\n }\n\n default CloseableIterator<T> valueIterator(Stream<Long> keyStream) {\n return valueIterator(StreamUtils.iterator(keyStream));\n }\n\n default CloseableIterator<KeyValue<T>> iterator(KeyFilter keyFilter) {\n final CloseableIterator<KeyValue<T>> keyValueIterator = iterator();\n return IterableUtils.iterator(new SimpleIterator<KeyValue<T>>() {\n @Override\n public KeyValue<T> next() throws Exception {\n while (keyValueIterator.hasNext()) {\n KeyValue<T> next = keyValueIterator.next();\n if (keyFilter.acceptKey(next.getKey())) {\n return next;\n }\n }\n return null;\n }\n\n @Override\n public void close() throws Exception {\n keyValueIterator.close();\n }\n });\n }\n\n default CloseableIterator<KeyValue<T>> iterator(Predicate<T> valueFilter) {\n final CloseableIterator<KeyValue<T>> keyValueIterator = iterator();\n return IterableUtils.iterator(new SimpleIterator<KeyValue<T>>() {\n @Override\n public KeyValue<T> next() throws Exception {\n while (keyValueIterator.hasNext()) {\n KeyValue<T> next = keyValueIterator.next();\n if (valueFilter.test(next.getValue())) {\n return next;\n }\n }\n return null;\n }\n\n @Override\n public void close() throws Exception {\n keyValueIterator.close();\n }\n });\n }\n\n default CloseableIterator<KeyValue<T>> iterator(Stream<Long> keyStream) {\n return iterator(StreamUtils.iterator(keyStream));\n }\n\n default CloseableIterator<KeyValue<T>> iterator(CloseableIterator<Long> keyIterator) {\n return new CloseableIterator<KeyValue<T>>() {\n\n KeyValue<T> next;\n\n {\n //Constructor\n findNext();\n }\n\n private void findNext() {\n next = null;\n while (next == null && keyIterator.hasNext()) {\n Long nextKey = keyIterator.next();\n T nextValue = read(nextKey);\n if (nextValue != null) {\n next = new KeyValue<>(nextKey, nextValue);\n }\n }\n }\n\n @Override\n protected void closeInt() {\n keyIterator.close();\n }\n\n @Override\n public boolean hasNext() {\n return next != null;\n }\n\n @Override\n public KeyValue<T> next() {\n KeyValue<T> curr = next;\n findNext();\n return curr;\n }\n };\n }\n\n default CloseableIterator<KeyValue<T>> cachedValueIterator() {\n return new CloseableIterator<KeyValue<T>>() {\n @Override\n protected void closeInt() {\n //ok\n }\n\n @Override\n public boolean hasNext() {\n return false;\n }\n\n @Override\n public KeyValue<T> next() {\n return null;\n }\n };\n }\n\n CloseableIterator<KeyValue<T>> iterator();\n\n long apprSize();\n\n long apprDataChecksum();\n\n long exactSize();\n\n default Stream<KeyValue<T>> stream() {\n return StreamUtils.stream(this, true);\n }\n\n default Stream<KeyValue<T>> stream(KeyFilter keyFilter) {\n return StreamUtils.stream(iterator(keyFilter), apprSize(), true);\n }\n\n default Stream<KeyValue<T>> stream(Predicate<T> valueFilter) {\n return StreamUtils.stream(iterator(valueFilter), apprSize(), true);\n }\n\n default Stream<KeyValue<T>> stream(CloseableIterator<Long> keyIterator) {\n return StreamUtils.stream(iterator(keyIterator), apprSize(), true);\n }\n\n default Stream<T> streamValues() {\n return StreamUtils.stream(valueIterator(), apprSize(), false);\n }\n\n default Stream<T> streamValues(KeyFilter keyFilter) {\n return StreamUtils.stream(valueIterator(keyFilter), apprSize(), false);\n }\n\n default Stream<T> streamValues(Predicate<T> valueFilter) {\n return StreamUtils.stream(valueIterator(valueFilter), apprSize(), false);\n }\n\n default Stream<T> streamValues(CloseableIterator<Long> keyIterator) {\n return StreamUtils.stream(valueIterator(keyIterator), apprSize(), false);\n }\n\n default Stream<T> streamValues(Stream<Long> keysStream) {\n //This could be improved... Mapping twice from streams to closeable iterators does have a certain overhead\n return StreamUtils.stream(valueIterator(StreamUtils.iterator(keysStream)), apprSize(), false);\n }\n\n default Stream<Long> streamKeys() {\n return StreamUtils.stream(keyIterator(), apprSize(), true);\n }\n\n Class<T> getObjectClass();\n\n String getName();\n\n void optimizeForReading();\n\n void write(long key, T value);\n\n default void write(Iterator<KeyValue<T>> entries) {\n write(IterableUtils.iterator(entries));\n }\n\n default void write(CloseableIterator<KeyValue<T>> entries) {\n while (entries.hasNext()) {\n KeyValue<T> entry = entries.next();\n write(entry.getKey(), entry.getValue());\n }\n entries.close();\n }\n\n default void write(BowString key, T value) {\n write(HashUtils.hashCode(key.getS()), value);\n }\n\n default void write(String key, T value) {\n write(HashUtils.hashCode(key), value);\n }\n\n default void increaseCount(String key, Long value) {\n write(key, (T) value);\n }\n\n default void increaseCount(long key, Long value) {\n write(key, (T) value);\n }\n\n default void increaseCount(String key) {\n increaseCount(key, 1l);\n }\n\n default void increaseCount(long key) {\n increaseCount(key, 1l);\n }\n\n default void remove(String key) {\n remove(HashUtils.hashCode(key));\n }\n\n default void remove(long key) {\n write(key, null);\n }\n\n Combinator<T> getCombinator();\n\n void close();\n\n boolean wasClosed();\n\n boolean isTemporaryDataInterface();\n\n void flush();\n\n void dropAllData();\n\n void ifNotClosed(Runnable action);\n\n DataInterface<T> getCoreDataInterface();\n\n ObjectSerializer<T> getObjectSerializer();\n\n void registerUpdateListener(UpdateListener<T> updateListener);\n}", "public interface Combinator<T extends Object> extends Serializable {\n\n T combine(T first, T second);\n\n default void addRemoteClasses(RemoteObjectConfig objectConfig) {\n //Don't add any classes by default\n }\n\n default RemoteObjectConfig createExecConfig() {\n RemoteObjectConfig result = RemoteObjectConfig.create(this);\n result.add(getClass());\n addRemoteClasses(result);\n return result;\n }\n}", "public abstract class BaseDataInterfaceFactory implements LifeCycleBean, DataInterfaceFactory {\n\n private int tmpDataInterfaceCount = 0;\n\n private final CachesManager cachesManager;\n protected final MemoryManager memoryManager;\n protected final AsyncJobService asyncJobService;\n private final List<DataInterfaceReference> allInterfaces;\n private final ReferenceQueue<DataInterface> allInterfacesReferenceQueue;\n\n private BaseDataInterface<LongBloomFilterWithCheckSum> bloomFiltersInterface;\n\n public BaseDataInterfaceFactory(ApplicationContext context) {\n this.cachesManager = context.getBean(CachesManager.class);\n this.memoryManager = context.getBean(MemoryManager.class);\n this.asyncJobService = context.getBean(AsyncJobService.class);\n this.allInterfaces = new ArrayList<>();\n this.allInterfacesReferenceQueue = new ReferenceQueue<>();\n }\n\n public <T> DataInterfaceConfig<T> dataInterface(String name, Class<T> objectClass, Class... genericParams) {\n return new DataInterfaceConfig<>(name, objectClass, this, genericParams);\n }\n\n @Override\n public <T> MultiDataInterfaceIndex<T> multiIndex(DataInterface<T> dataInterface, String nameOfIndex, MultiDataIndexer<T> indexer) {\n return new MultiDataInterfaceIndex<>(nameOfIndex, this, dataInterface, indexer);\n }\n\n @Override\n public <T> UniqueDataInterfaceIndex<T> uniqueIndex(DataInterface<T> dataInterface, String nameOfIndex, UniqueDataIndexer<T> indexer) {\n return new UniqueDataInterfaceIndex<>(nameOfIndex, this, dataInterface, indexer);\n }\n\n public <T> BaseDataInterface<T> createFromConfig(DataInterfaceConfig<T> config) {\n BaseDataInterface<T> dataInterface;\n String name = config.name;\n if (config.isTemporary) {\n name = createNameForTemporaryInterface(name);\n }\n if (config.objectClass == null) {\n throw new RuntimeException(\"The object class is not set\");\n }\n if (config.combinator == null) {\n throw new RuntimeException(\"The object combinator is not set\");\n }\n if (config.inMemory) {\n dataInterface = new InMemoryDataInterface<>(name, config.objectClass, config.combinator);\n } else {\n if (config.objectSerializer == null) {\n throw new RuntimeException(\"The object serializer is not set\");\n }\n dataInterface = createBaseDataInterface(name, config.objectClass, config.combinator, config.objectSerializer, config.isTemporary);\n }\n if (config.cache) {\n dataInterface = new CachedDataInterface<>(memoryManager, cachesManager, dataInterface, asyncJobService);\n }\n if (config.bloomFilter) {\n checkInitialisationCachedBloomFilters();\n dataInterface = new BloomFilterDataInterface<>(dataInterface, bloomFiltersInterface, asyncJobService);\n }\n registerInterface(dataInterface);\n return dataInterface;\n }\n\n private <T> void registerInterface(BaseDataInterface<T> dataInterface) {\n synchronized (allInterfaces) {\n allInterfaces.add(new DataInterfaceReference(dataInterface, allInterfacesReferenceQueue));\n }\n }\n\n protected abstract <T extends Object> BaseDataInterface<T> createBaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface);\n\n protected abstract Class<? extends DataInterface> getBaseDataInterfaceClass();\n\n public DataInterface<Long> createCountDataInterface(String name) {\n return createDataInterface(name, Long.class, new LongCombinator(), new LongObjectSerializer(), false, false);\n }\n\n public DataInterface<Long> createTmpCountDataInterface(String name) {\n return createDataInterface(createNameForTemporaryInterface(name), Long.class, new LongCombinator(), new LongObjectSerializer(), true, false);\n }\n\n public DataInterface<Long> createInMemoryCountDataInterface(String name) {\n return createDataInterface(name, Long.class, new LongCombinator(), new LongObjectSerializer(), false, true);\n }\n\n public <T extends Object> BaseDataInterface<T> createDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer) {\n return createDataInterface(name, objectClass, combinator, objectSerializer, false, false);\n }\n\n private <T extends Object> BaseDataInterface<T> createDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean temporary, boolean inMemory) {\n DataInterfaceConfig<T> config = dataInterface(name, objectClass);\n config.combinator(combinator);\n config.serializer(objectSerializer);\n if (temporary) {\n config.temporary();\n }\n if (inMemory) {\n config.inMemory();\n }\n return config.create();\n }\n\n private void checkInitialisationCachedBloomFilters() {\n if (bloomFiltersInterface == null) {\n bloomFiltersInterface = createBaseDataInterface(\"system/bloomFilter\", LongBloomFilterWithCheckSum.class, new OverWriteCombinator<>(), new JsonObjectSerializer<>(LongBloomFilterWithCheckSum.class), false);\n synchronized (allInterfaces) {\n allInterfaces.add(new DataInterfaceReference(bloomFiltersInterface, allInterfacesReferenceQueue));\n }\n }\n }\n\n public List<DataInterfaceReference> getAllInterfaces() {\n return allInterfaces;\n }\n\n @Override\n public void startBean() {\n //Do nothing\n }\n\n @Override\n public synchronized void stopBean() {\n terminate();\n }\n\n public synchronized void terminate() {\n closeAllInterfaces();\n }\n\n public void closeAllInterfaces() {\n synchronized (allInterfaces) {\n for (WeakReference<DataInterface> referenceToDI : allInterfaces) {\n final DataInterface dataInterface = referenceToDI.get();\n if (dataInterface != null && !isSystemInterface(dataInterface)) {\n dataInterface.close();\n }\n }\n if (bloomFiltersInterface != null) {\n bloomFiltersInterface.close();\n bloomFiltersInterface = null;\n }\n allInterfaces.clear();\n }\n\n }\n\n private boolean isSystemInterface(DataInterface dataInterface) {\n return dataInterface == bloomFiltersInterface;\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n public void cleanupClosedInterfaces() {\n DataInterfaceReference reference = (DataInterfaceReference) allInterfacesReferenceQueue.poll();\n while (reference != null) {\n synchronized (allInterfaces) {\n allInterfaces.remove(reference);\n }\n reference = (DataInterfaceReference) allInterfacesReferenceQueue.poll();\n }\n }\n\n private String createNameForTemporaryInterface(String name) {\n return \"tmp/\" + name + \"_\" + System.currentTimeMillis() + \"_\" + tmpDataInterfaceCount++ + \"/\";\n }\n\n}", "public interface ObjectSerializer<T> extends Serializable {\n\n void writeValue(T obj, DataStream ds);\n\n T readValue(DataStream ds, int size);\n\n int getObjectSize();\n\n default RemoteObjectConfig createExecConfig() {\n return RemoteObjectConfig.create(this).add(getClass());\n }\n}" ]
import be.bagofwords.db.CoreDataInterface; import be.bagofwords.db.DataInterface; import be.bagofwords.db.combinator.Combinator; import be.bagofwords.db.impl.BaseDataInterfaceFactory; import be.bagofwords.db.methods.ObjectSerializer; import be.bagofwords.minidepi.ApplicationContext; import be.bagofwords.util.Utils; import org.rocksdb.RocksDB; import java.io.File;
package be.bagofwords.db.interfaces.rocksdb; /** * Created by Koen Deschacht ([email protected]) on 9/17/14. */ public class RocksDBDataInterfaceFactory extends BaseDataInterfaceFactory { private final String directory; private final boolean usePatch; public RocksDBDataInterfaceFactory(ApplicationContext applicationContext, boolean usePatch) { super(applicationContext); this.directory = applicationContext.getProperty("data_directory"); this.usePatch = usePatch; File libFile = findLibFile(); if (libFile == null) { throw new RuntimeException("Could not find librocksdbjni.so"); } Utils.addLibraryPath(libFile.getParentFile().getAbsolutePath()); RocksDB.loadLibrary(); } private File findLibFile() { File libFile = new File("./lib/rocksdb/linux-x86_64/librocksdbjni.so"); if (libFile.exists()) { return libFile; } libFile = new File("./count-db/lib/rocksdb/linux-x86_64/librocksdbjni.so"); if (libFile.exists()) { return libFile; } return null; } @Override
protected <T> CoreDataInterface<T> createBaseDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface) {
0
AstartesGuardian/WebDAV-Server
WebDAV-Server/src/webdav/server/commands/light/WDL_Propfind.java
[ "public class FileSystemPath\r\n{\r\n public FileSystemPath(String fileName, FileSystemPath parent)\r\n {\r\n this.fileName = fileName;\r\n this.parent = parent;\r\n this.fileSystemPathManager = parent.fileSystemPathManager;\r\n }\r\n public FileSystemPath(String fileName, FileSystemPathManager fileSystemPathManager)\r\n {\r\n this.fileName = fileName;\r\n this.parent = null;\r\n this.fileSystemPathManager = fileSystemPathManager;\r\n }\r\n \r\n private final String fileName;\r\n private final FileSystemPath parent;\r\n private final FileSystemPathManager fileSystemPathManager;\r\n \r\n public String getName()\r\n {\r\n return fileName;\r\n }\r\n \r\n public FileSystemPath getParent()\r\n {\r\n return parent;\r\n }\r\n \r\n public boolean isRoot()\r\n {\r\n return parent == null;\r\n }\r\n \r\n public FileSystemPath createChild(String childName)\r\n {\r\n return new FileSystemPath(childName, this);\r\n }\r\n \r\n \r\n public LinkedList<FileSystemPath> toPaths()\r\n {\r\n LinkedList<FileSystemPath> paths = toReversePaths();\r\n Collections.reverse(paths);\r\n return paths;\r\n }\r\n public LinkedList<FileSystemPath> toReversePaths()\r\n {\r\n LinkedList<FileSystemPath> paths = new LinkedList<>();\r\n \r\n FileSystemPath path = this;\r\n do\r\n {\r\n paths.add(path);\r\n } while((path = path.getParent()) != null && !path.isRoot());\r\n \r\n return paths;\r\n }\r\n \r\n public String[] toStrings()\r\n {\r\n return toString().split(fileSystemPathManager.standardFileSeparator);\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n if(isRoot())\r\n return getName();\r\n \r\n String result = getParent() + fileSystemPathManager.standardFileSeparator + getName();\r\n if(result.startsWith(fileSystemPathManager.standardFileSeparator + fileSystemPathManager.standardFileSeparator))\r\n result = result.substring(1);\r\n return result;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object o)\r\n {\r\n return o instanceof FileSystemPath && o.hashCode() == this.hashCode();\r\n }\r\n @Override\r\n public int hashCode()\r\n {\r\n return toString().hashCode();\r\n }\r\n}\r", "public class StringJoiner\r\n{\r\n private StringJoiner()\r\n { }\r\n \r\n public static BinaryOperator<String> join(String separator)\r\n {\r\n return (s1, s2) -> s1.isEmpty() ?\r\n s2 : s1 + separator + s2;\r\n }\r\n public static BinaryOperator<String> join()\r\n {\r\n return (s1, s2) -> s1.isEmpty() ?\r\n s2 : s1 + s2;\r\n }\r\n}\r", "public abstract class HTTPCommand\r\n{\r\n public HTTPCommand(String command)\r\n {\r\n this.name = command.trim().toUpperCase();\r\n openedResources = new HashMap<>();\r\n }\r\n \r\n private final String name;\r\n \r\n /**\r\n * Get the name of the command.\r\n * \r\n * @return String\r\n */\r\n public String getName()\r\n {\r\n return name;\r\n }\r\n \r\n /**\r\n * Execute the command with the HTTPMessage 'input' and in the 'environment'.\r\n * \r\n * @param input Received HTTP message\r\n * @param environment Server environment\r\n * @return HTTPMessage\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public abstract HTTPResponse.Builder Compute(HTTPEnvRequest environment) throws UserRequiredException, NotFoundException, UnexpectedException;\r\n \r\n public void Continue(HTTPEnvRequest environment) throws UserRequiredException, NotFoundException\r\n { }\r\n \r\n /**\r\n * Find a HTTPCommand in 'commands' with the command name 'command'.\r\n * If no HTTPCommand found, returns null.\r\n * \r\n * @param commands Set of HTTPCommand to search in.\r\n * @param command Command name to find.\r\n * @return HTTPCommand\r\n */\r\n public static HTTPCommand getFrom(Set<HTTPCommand> commands, String command)\r\n {\r\n return commands.stream()\r\n .filter(c -> c.name.equals(command.trim().toUpperCase()))\r\n .findFirst()\r\n .orElse(null);\r\n }\r\n \r\n /**\r\n * Generate the command list with : OPTIONS, PROPFIND, PROPPATCH, MKCOL,\r\n * HEAD, GET, PUT, DELETE, LOCK, UNLOCK and MOVE.\r\n * \r\n * @return HTTPCommand[]\r\n */\r\n public static HTTPCommand[] getStandardCommands()\r\n {\r\n return new HTTPCommand[]\r\n {\r\n new WD_Options(),\r\n new WD_Propfind(),\r\n new WD_Proppatch(),\r\n new WD_Mkcol(),\r\n new WD_Head(),\r\n new WD_Post(),\r\n new WD_Get(),\r\n new WD_Put(),\r\n new WD_Delete(),\r\n new WD_Lock(),\r\n new WD_Unlock(),\r\n new WD_Move()\r\n };\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj)\r\n {\r\n return obj instanceof HTTPCommand && this.getName().equals(((HTTPCommand)obj).getName())\r\n || obj instanceof String && this.getName().equals(obj.toString());\r\n }\r\n\r\n @Override\r\n public int hashCode()\r\n {\r\n return getName().hashCode();\r\n }\r\n\r\n @Override\r\n public String toString()\r\n {\r\n return name;\r\n }\r\n \r\n \r\n \r\n \r\n protected Document createDocument() throws ParserConfigurationException\r\n {\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(true);\r\n DocumentBuilder xmlBuilder = factory.newDocumentBuilder();\r\n return xmlBuilder.newDocument();\r\n }\r\n protected Document createDocument(HTTPMessage input) throws ParserConfigurationException, IOException, SAXException\r\n {\r\n return createDocument(input.getContent());\r\n }\r\n protected Document createDocument(byte[] content) throws ParserConfigurationException, IOException, SAXException\r\n {\r\n return new ExtendableByteBuffer()\r\n .write(content)\r\n .toXML();\r\n }\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n protected String getHostPath(String path, String host)\r\n {\r\n return \"http://\" + (host.replace(\"/\", \"\") + path.replace(\"\\\\\", \"/\")).trim().replace(\"//\", \"/\").replace(\" \", \"%20\");\r\n }\r\n \r\n \r\n private final Map<FileSystemPath, IResource> openedResources;\r\n /*\r\n protected String getPath(String path, HTTPEnvironment environment)\r\n {\r\n return path.replace(\"/\", \"\\\\\").trim();\r\n }\r\n private IResource getResource_(String path, HTTPEnvRequest environment)\r\n {\r\n return environment.getResourceFromPath(getPath(path, environment));\r\n }*/\r\n private IResource getNonBufferedResource(FileSystemPath path, HTTPEnvRequest environment)\r\n {\r\n return environment.getSettings()\r\n .getFileManager()\r\n .getResourceFromPath(path, environment);\r\n }\r\n protected IResource getResource(FileSystemPath path, HTTPEnvRequest environment)\r\n {\r\n if(environment.getSettings().getUseResourceBuffer())\r\n {\r\n if(openedResources.containsKey(path))\r\n return openedResources.get(path);\r\n else\r\n {\r\n IResource rs = getNonBufferedResource(path, environment);\r\n openedResources.put(path, rs);\r\n return rs;\r\n }\r\n }\r\n else\r\n return getNonBufferedResource(path, environment);\r\n }\r\n protected IResource getResource(String path, HTTPEnvRequest environment)\r\n {\r\n return getResource(environment.getSettings()\r\n .getFileSystemPathManager()\r\n .createFromString(path)\r\n , environment);\r\n }\r\n protected void closeResource(String path, HTTPEnvRequest environment)\r\n {\r\n closeResource(environment.getSettings()\r\n .getFileSystemPathManager()\r\n .createFromString(path)\r\n , environment);\r\n }\r\n protected void closeResource(FileSystemPath path, HTTPEnvRequest environment)\r\n {\r\n if(environment.getSettings().getUseResourceBuffer())\r\n openedResources.remove(path);\r\n }\r\n}\r", "public class HTTPResponse extends HTTPMessage\r\n{\r\n public HTTPResponse(\r\n int code,\r\n String message,\r\n String httpVersion,\r\n Map<String, String> headers,\r\n byte[] content)\r\n {\r\n super(httpVersion, headers, content);\r\n this.code = code;\r\n this.message = message;\r\n }\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Builder\">\r\n public static Builder create()\r\n {\r\n return new Builder();\r\n }\r\n\r\n public static class Builder\r\n {\r\n private int code = 207;\r\n private String httpVersion = \"HTTP/1.1\";\r\n private String message = \"Multi-Status\";\r\n private Map<String, String> headers = new HashMap<>();\r\n private byte[] content = null;\r\n \r\n public Builder setHTTPVersion(double version)\r\n {\r\n this.httpVersion = \"HTTP/\" + version;\r\n return this;\r\n }\r\n public Builder setHTTPVersion(String version)\r\n {\r\n version = version.trim();\r\n \r\n if(!version.toUpperCase().startsWith(\"HTTP/\"))\r\n version = \"HTTP/\" + version;\r\n \r\n this.httpVersion = version;\r\n return this;\r\n }\r\n \r\n public Builder setCode(String code)\r\n {\r\n this.code = Integer.parseInt(code);\r\n return this;\r\n }\r\n public Builder setCode(int code)\r\n {\r\n this.code = code;\r\n return this;\r\n }\r\n \r\n public Builder setContent(byte[] content)\r\n {\r\n this.content = content;\r\n return this;\r\n }\r\n public Builder setContent(String content)\r\n {\r\n return setContent(content, \"UTF-8\");\r\n }\r\n public Builder setContent(String content, String charset)\r\n {\r\n try\r\n {\r\n this.content = content.getBytes(charset);\r\n }\r\n catch(UnsupportedEncodingException ex)\r\n { }\r\n \r\n return this;\r\n }\r\n \r\n public Builder setHeaders(Map<String, String> headers)\r\n {\r\n this.headers.clear();\r\n addHeaders(headers);\r\n \r\n return this;\r\n }\r\n public Builder addHeaders(Map<String, String> headers)\r\n {\r\n headers.entrySet()\r\n .stream()\r\n .forEach(e -> this.headers.put(formatHeaderName(e.getKey()), e.getValue()));\r\n \r\n return this;\r\n }\r\n public Builder setHeader(String name, String value)\r\n {\r\n this.headers.put(formatHeaderName(name), value);\r\n return this;\r\n }\r\n \r\n public Builder setMessage(String message)\r\n {\r\n this.message = message.trim();\r\n return this;\r\n }\r\n \r\n \r\n public HTTPResponse build()\r\n {\r\n if(content == null)\r\n content = new byte[0];\r\n \r\n setHeader(\"Content-Length\", String.valueOf(content.length));\r\n \r\n return new HTTPResponse(\r\n code,\r\n message,\r\n httpVersion,\r\n headers,\r\n content);\r\n }\r\n }\r\n // </editor-fold>\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Parser\">\r\n public static HTTPResponse parseHTTPResponse(byte[] byteMessage)\r\n {\r\n final Builder builder = create();\r\n \r\n parseHTTPMessage(byteMessage,\r\n headLine -> \r\n {\r\n builder.setHTTPVersion(headLine[0]);\r\n builder.setCode(headLine[1]);\r\n builder.setMessage(headLine[2]);\r\n },\r\n builder::setHeader,\r\n builder::setContent);\r\n \r\n return builder.build();\r\n }\r\n // </editor-fold>\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Properties\">\r\n private final int code;\r\n private final String message;\r\n // </editor-fold>\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Accessors\">\r\n public int getCode()\r\n {\r\n return code;\r\n }\r\n public String getMessage()\r\n {\r\n return message;\r\n }\r\n // </editor-fold>\r\n \r\n @Override\r\n protected String getHeadLine()\r\n {\r\n return httpVersion + \" \" + code + \" \" + message;\r\n }\r\n \r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Code manager\">\r\n public <T extends Throwable> HTTPResponse throwCode(int code, Supplier<T> supplier) throws T\r\n {\r\n if(this.code == code)\r\n throw supplier.get();\r\n return this;\r\n }\r\n public <T extends Throwable> HTTPResponse throwCodes(int[] codes, Supplier<T> supplier) throws T\r\n {\r\n for(int code : codes)\r\n if(this.code == code)\r\n throw supplier.get();\r\n return this;\r\n }\r\n // </editor-fold>\r\n}\r", "public interface IResource\r\n{\r\n /**\r\n * Get if the resource is visible.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean isVisible(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the type of the resource.\r\n * \r\n * @param env\r\n * @return ResourceType\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public ResourceType getResourceType(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the web name of the resource.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public String getWebName(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the resource name.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n //public FileSystemPath getPath(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the mime type of the resource.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public String getMimeType(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the size of the resource (byte).\r\n * \r\n * @param env\r\n * @return long\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public long getSize(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the creation time.\r\n * \r\n * @param env\r\n * @return Instant\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Instant getCreationTime(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the last modified date.\r\n * \r\n * @param env\r\n * @return Instant\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Instant getLastModified(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the list of the resources contained in this resource.\r\n * \r\n * @param env\r\n * @return Collection of IResource\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Collection<IResource> listResources(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the content of the resource.\r\n * \r\n * @param env\r\n * @return byte[]\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public byte[] getContent(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Set the content of the resource.\r\n * \r\n * @param content Content to put in the resource\r\n * @param env\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public void setContent(byte[] content, HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Append a content to the resource.\r\n * \r\n * @param content Content to append in the resource\r\n * @param env\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public void appendContent(byte[] content, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Delete the resource.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean delete(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Rename or move a resource from the current path to 'resource' path.\r\n * \r\n * @param newPath\r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean moveTo(FileSystemPath oldPath, FileSystemPath newPath, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public boolean rename(String newName, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Define if the resource exists or not.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws UserRequiredException \r\n */\r\n public boolean exists(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public IResource creates(ResourceType resourceType, HTTPEnvRequest env) throws UserRequiredException;\r\n public IResource creates(IResource resource, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public boolean isOnTheSameFileSystemWith(IResource resource);\r\n \r\n public IResource getResource(LinkedList<FileSystemPath> reversedPath, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n \r\n public boolean equals(FileSystemPath path, HTTPEnvRequest env);\r\n \r\n \r\n public boolean addChild(IResource resource, HTTPEnvRequest env);\r\n public boolean removeChild(IResource resource, HTTPEnvRequest env);\r\n \r\n public boolean isInstanceOf(Class<?> c);\r\n \r\n \r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Properties\">\r\n public void setProperty(String namespace, String name, String value, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeProperty(String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeProperty(String namespace, String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public String getProperty(String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public String getProperty(String namespace, String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public Map<Pair<String, String>, String> getProperties(HTTPEnvRequest env) throws UserRequiredException;\r\n // </editor-fold>\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Locks\">\r\n public Collection<LockKind> getAvailableLocks() throws UserRequiredException;\r\n public List<Lock> getLocks(HTTPEnvRequest env) throws UserRequiredException;\r\n public List<Lock> getLocks(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean setLock(Lock lock, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean setLock(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeLock(Lock lock, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeLock(String uuid, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean canLock(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n // </editor-fold>\r\n}\r", "public class NotFoundException extends HTTPException\r\n{\r\n public NotFoundException()\r\n {\r\n super(\"Resource not found\");\r\n }\r\n \r\n public static HTTPResponse.Builder getHTTPResponse()\r\n {\r\n return HTTPResponse.create()\r\n .setCode(404)\r\n .setMessage(\"Not found\");\r\n }\r\n}\r", "public class UserRequiredException extends HTTPException\r\n{\r\n public UserRequiredException()\r\n {\r\n super(\"User required\");\r\n }\r\n}\r", "public class HTTPEnvRequest\r\n{\r\n public static Builder create()\r\n {\r\n return new Builder();\r\n }\r\n public static class Builder\r\n {\r\n public Builder()\r\n { }\r\n \r\n private HTTPRequest request;\r\n private HTTPCommand command;\r\n private HTTPServerSettings settings;\r\n private Collection<IResourceMutation> mutations = null;\r\n private byte[] bytesReceived = null;\r\n \r\n public Builder setRequest(HTTPRequest request)\r\n {\r\n this.request = request;\r\n return this;\r\n }\r\n \r\n public Builder setCommand(HTTPCommand command)\r\n {\r\n this.command = command;\r\n return this;\r\n }\r\n \r\n public Builder setBytesReceived(byte[] bytesReceived)\r\n {\r\n this.bytesReceived = bytesReceived;\r\n return this;\r\n }\r\n \r\n public Builder setSettings(HTTPServerSettings settings)\r\n {\r\n this.settings = settings;\r\n return this;\r\n }\r\n \r\n public Builder setMutations(Collection<IResourceMutation> mutations)\r\n {\r\n this.mutations = mutations;\r\n return this;\r\n }\r\n public Builder addMutations(IResourceMutation[] mutations)\r\n {\r\n this.mutations.addAll(Arrays.asList(mutations));\r\n return this;\r\n }\r\n public Builder addMutations(Collection<IResourceMutation> mutations)\r\n {\r\n this.mutations.addAll(mutations);\r\n return this;\r\n }\r\n public Builder addMutation(IResourceMutation mutation)\r\n {\r\n this.mutations.add(mutation);\r\n return this;\r\n }\r\n \r\n public HTTPEnvRequest build()\r\n {\r\n if(mutations == null)\r\n mutations = Collections.EMPTY_LIST;\r\n \r\n return new HTTPEnvRequest(\r\n bytesReceived,\r\n request,\r\n command,\r\n settings.getAuthenticationManager().checkAuth(request),\r\n settings,\r\n settings.getFileManager().getResourceMutations());\r\n }\r\n }\r\n \r\n public HTTPEnvRequest(\r\n byte[] bytesReceived,\r\n HTTPRequest request,\r\n HTTPCommand command,\r\n HTTPUser user,\r\n HTTPServerSettings settings,\r\n Collection<IResourceMutation> mutations)\r\n {\r\n this.bytesReceived = bytesReceived;\r\n this.request = request;\r\n this.command = command;\r\n this.user = user;\r\n this.settings = settings;\r\n this.mutations = mutations;\r\n }\r\n \r\n private byte[] bytesReceived;\r\n private FileSystemPath path = null;\r\n \r\n private final HTTPRequest request;\r\n private final HTTPCommand command;\r\n private final HTTPUser user;\r\n private final HTTPServerSettings settings;\r\n private final Collection<IResourceMutation> mutations;\r\n \r\n public FileSystemPath getPath()\r\n {\r\n if(path == null)\r\n path = settings.getFileSystemPathManager()\r\n .createFromString(request.getDecodedPath());\r\n \r\n return path;\r\n }\r\n \r\n public Collection<IResourceMutation> getMutations()\r\n {\r\n return mutations;\r\n }\r\n \r\n public byte[] getBytesReceived()\r\n {\r\n if(bytesReceived == null)\r\n bytesReceived = request.toBytes();\r\n return bytesReceived;\r\n }\r\n \r\n public HTTPRequest getRequest()\r\n {\r\n return request;\r\n }\r\n \r\n public HTTPCommand getCommand()\r\n {\r\n return command;\r\n }\r\n \r\n public HTTPUser getUser()\r\n {\r\n return user;\r\n }\r\n \r\n public HTTPServerSettings getSettings()\r\n {\r\n return settings;\r\n }\r\n}\r" ]
import http.FileSystemPath; import http.StringJoiner; import http.server.HTTPCommand; import http.server.message.HTTPResponse; import java.time.Instant; import webdav.server.resource.IResource; import http.server.exceptions.NotFoundException; import http.server.exceptions.UserRequiredException; import http.server.message.HTTPEnvRequest;
package webdav.server.commands.light; public class WDL_Propfind extends HTTPCommand { public WDL_Propfind() { super("lightpropfind"); } private static String addString(String name, String value) { return "<" + name + ">" + value + "</" + name + ">"; } private static String addString(String name, long value) { return addString(name, String.valueOf(value)); }
private String getInfo(IResource resource, FileSystemPath path, String host, HTTPEnvRequest environment) throws UserRequiredException
7
nchambers/probschemas
src/main/java/nate/probschemas/EventPairScores.java
[ "public class Pair<A,B> {\n A first;\n B second;\n\n public Pair(A one, B two) {\n first = one;\n second = two;\n }\n\n public A first() { return first; }\n public B second() { return second; }\n public void setFirst(A obj) { first = obj; }\n public void setSecond(B obj) { second = obj; }\n \n public String toString() {\n return (first + \":\" + second);\n }\n}", "public class WordEvent {\n public static final String DEP_SUBJECT = \"s\";\n public static final String DEP_OBJECT = \"o\";\n public static final String DEP_PREP = \"p\";\n\n public static final int VERB = 0;\n public static final int NOUN = 1;\n public static final int JJ = 2;\n\n String token;\n int posTag;\n int eventID;\n int sentenceID; // indexed from 1, not 0\n int position; // in the sentence\n HashMap<Integer, String> arguments = null;\n HashMap<Integer, EntityMention> argumentMentions = null;\n // Entity ID to the Index in the sentence that is the head in the dependency.\n HashMap<Integer, Integer> argumentIndices = null;\n\n\n public WordEvent(String word, int pos, int sid) {\n this(0,word,pos,sid); \n }\n public WordEvent(String word, int pos, int sid, String tag) {\n this(0,word,pos,sid);\n setPOSTag(tag);\n }\n public WordEvent(int eid, String word, int pos, int sid) {\n eventID = eid;\n token = word; \n position = pos;\n sentenceID = sid;\n }\n\n /*\n private void addSubject(int id) {\n if( subjects == null ) subjects = new Vector();\n subjects.add(id);\n }\n\n private void addObject(int id) {\n if( objects == null ) objects = new Vector();\n objects.add(id);\n }\n */\n\n public void setSentenceID(int id) {\n sentenceID = id;\n }\n\n public void setPosition(int pos) {\n position = pos;\n }\n\n public void setToken(String w) {\n token = w;\n }\n\n public void setPOSTag(int tag) {\n posTag = tag;\n }\n\n /**\n * Set the POS tag for this event using the string representation.\n * e.g. NN, NNS, VBG, JJ, etc.\n */\n public void setPOSTag(String tag) {\n int num = posTagType(tag);\n if( num == -1 ) {\n System.out.println(\"ERROR: unknown tag string \" + tag);\n System.exit(1);\n }\n else setPOSTag(num);\n }\n\n /**\n * @return The int representing the POS tag. \n * -1 if not a noun, verb or adjective.\n */\n public static int posTagType(String tag) {\n if( tag.startsWith(\"V\") || tag.startsWith(\"v\") )\n return VERB;\n else if( tag.startsWith(\"N\") || tag.startsWith(\"n\") )\n return NOUN;\n else if( tag.startsWith(\"N\") || tag.startsWith(\"n\") )\n return JJ;\n else\n return -1;\n }\n\n /**\n * Build a concatenated version of a word with its posTag type.\n */\n public static String stringify(String word, int posTag) {\n return word + \"*\" + posTag;\n }\n\n /**\n * Check a string for a POS tag: \"arrest*0\" and return just the\n * word without the tag: \"arrest\"\n */\n public static String stripWordFromPOSTag(String str) {\n int marker = str.length()-2;\n if( str.charAt(marker) == '*' )\n return str.substring(0, marker);\n else return str;\n }\n\n public static String stripPOSTagFromWord(String str) {\n int marker = str.length()-2;\n if( str.charAt(marker) == '*' )\n return str.substring(marker+1);\n else return str;\n }\n\n /**\n * Don't normalize the relation string.\n */\n public void addArgAsIs(String relation, int argid) {\n if( arguments == null ) arguments = new HashMap<Integer, String>(8);\n arguments.put(argid, relation);\n }\n\n public void addArg(String relation, int argid) {\n addArg(relation, argid, false);\n }\n\n /**\n * Adds the relation as an argument, and normalizes the relation type.\n * @param relation The relation (e.g. nsubj)\n * @param argid The ID of the argument filler.\n * @param fullprep True if you want full prep relations: e.g. 'p_during'\n * False if just 'p'\n */\n public void addArg(String relation, int argid, boolean fullprep) {\n if( arguments == null ) arguments = new HashMap<Integer, String>(8);\n if( fullprep )\n arguments.put(argid, normalizeRelationFullPrep(relation));\n else\n arguments.put(argid, normalizeRelation(relation));\n }\n\n /**\n * Adds the relation as an argument and saves the EntityMention. Don't call this one\n * if you don't need the mentions later ... saves space.\n */\n public void addArg(String relation, int index, EntityMention mention, boolean fullprep) {\n addArg(relation, mention.entityID(), fullprep);\n\n if( argumentMentions == null ) argumentMentions = new HashMap<Integer, EntityMention>(8);\n argumentMentions.put(mention.entityID(), mention);\n \n if( argumentIndices == null ) argumentIndices = new HashMap<Integer, Integer>(8);\n argumentIndices.put(mention.entityID(), index);\n }\n\n public static String normalizeRelation(String rel) {\n // assume one letter words are already reduced...\n if( rel.length() == 1 ) return rel;\n\n // nsubj, xsubj, SUBJ\n if( !rel.contains(\"pass\") && // !nsubjpass\n (rel.contains(\"subj\") || rel.startsWith(\"S\") || rel.startsWith(\"s\")) )\n return DEP_SUBJECT;\n // agent\n if( rel.equals(\"agent\") ) \n return DEP_SUBJECT;\n // prep_X, PPOBJ\n if( rel.startsWith(\"prep\") || rel.startsWith(\"pp\") || rel.equals(\"PPOBJ\") ) \n return DEP_PREP;\n // dobj, iobj\n if( rel.endsWith(\"obj\") || rel.equals(\"nsubjpass\") ) \n return DEP_OBJECT;\n // others\n else return rel;\n }\n\n public static String normalizeRelationFullPrep(String rel) {\n // assume one letter words are already reduced...\n if( rel.length() == 1 ) return rel;\n\n // nsubj, xsubj, SUBJ\n if( !rel.contains(\"pass\") && // !nsubjpass\n (rel.contains(\"subj\") || rel.startsWith(\"S\") || rel.startsWith(\"s\")) )\n return DEP_SUBJECT;\n // agent\n if( rel.equals(\"agent\") ) \n return DEP_SUBJECT;\n // prep_X, PPOBJ\n if( rel.startsWith(\"prep\") || rel.startsWith(\"pp\") || rel.equals(\"PPOBJ\") ) {\n int underscore = rel.indexOf('_');\n if( underscore == -1 )\n return DEP_PREP;\n else\n return DEP_PREP + \"_\" + rel.substring(underscore+1);\n }\n // dobj, iobj\n if( rel.endsWith(\"obj\") || rel.equals(\"nsubjpass\") ) \n return DEP_OBJECT;\n // others\n else return rel;\n }\n\n public boolean containsArg(int argid) {\n if( arguments != null && arguments.containsKey(argid) ) return true;\n return false;\n }\n\n public EntityMention getArgMention(int argid) {\n if( argumentMentions != null )\n return argumentMentions.get(argid);\n else\n return null;\n }\n\n public Integer getArgIndex(int argid) {\n if( argumentIndices != null )\n return argumentIndices.get(argid);\n else\n return null;\n }\n\n /**\n * @return True if one integer in the parameter appears in\n * this object's args list.\n */\n /*\n public boolean shares(Vector<Integer> others) {\n if( (subjects != null || objects != null ) && others != null ) {\n for( Integer id : others )\n\tif( containsArg(id) ) return true;\n }\n return false;\n }\n */\n\n public boolean shares(Vector<Integer> others) {\n if( arguments != null )\n for( Integer id : arguments.keySet() )\n if( others.contains(id) ) return true;\n return false;\n }\n\n /**\n * @return A string of the relation pair that is shared\n * i.e. SUBJECT:OBJECT or OBJECT:PP-OBJECT\n */\n public String sharedArgument(HashMap<Integer,String> others) {\n if( arguments != null && others != null ) {\n for( Integer id : arguments.keySet() ) {\n if( others.containsKey(id) ) \n return arguments.get(id) + \":\" + others.get(id);\n }\n }\n return null;\n }\n\n /**\n * @return A string ID of the entity that is shared\n */\n public Integer sharedArgumentID(HashMap<Integer,String> others) {\n if( arguments != null && others != null ) {\n for( Integer id : arguments.keySet() ) {\n if( others.containsKey(id) ) \n return id;\n }\n }\n return null;\n }\n\n // public Vector<Integer> subjects() { return subjects; }\n // public Vector<Integer> objects() { return objects; }\n public HashMap<Integer,String> arguments() { return arguments; }\n public String token() { return token; }\n public int posTag() { return posTag; }\n public int position() { return position; }\n public int eventID() { return eventID; }\n public int sentenceID() { return sentenceID; }\n\n /**\n * Create a WordEvent instance from a string representation\n * e.g. \"124 word 4 51 [ ]\"\n * \"124 ask a 4 51 [ ]\"\n */\n public static WordEvent fromString(String str) {\n // Messy space finding because the event string can have spaces in it! \n int space = str.indexOf(' ');\n int space4 = str.indexOf(\" [\");\n int i = 2;\n while( str.charAt(space4-i) != ' ' ) i++;\n int space3 = space4-i;\n i = 2;\n while( str.charAt(space3-i) != ' ' ) i++;\n int space2 = space3-i;\n\n // System.out.println(\"***\\n\" + str);\n // System.out.println(space + \" \" + space2 + \" \" + space3 + \" \" + space4);\n\n /*\n // be more cautious with the string...\n int space = str.indexOf(' ');\n int space2 = str.indexOf(' ',space+1);\n int space3 = str.indexOf(' ',space2+1);\n int space4 = str.indexOf(' ',space3+1);\n */\n\n try {\n int eid = Integer.parseInt(str.substring(0,space));\n String word = str.substring(space+1,space2);\n int sid = Integer.parseInt(str.substring(space2+1,space3));\n int pos;\n if( space4 > -1 ) pos = Integer.parseInt(str.substring(space3+1,space4));\n else pos = Integer.parseInt(str.substring(space3+1,str.length()));\n\n // System.out.println(new WordEvent(eid,word,pos,sid));\n return new WordEvent(eid,word,pos,sid);\n } catch( Exception ex ) { \n // Some numbers \"1 1/2\" get through as events... try recursing\n if( Character.isDigit(str.charAt(space+1)) )\n return fromString(str.substring(space2+1,str.length()));\n else {\n //\tex.printStackTrace(); \n System.out.println(\"WordEvent Exception: *\" + str + \"*\");\n }\n }\n return null;\n }\n\n public String toStringWithMentions() { \n // String str = eventID + \" \" + token + \" \" + sentenceID + \" \" + position + \" [\";\n String str = eventID + \" \" + token + \" \" + posTag + \" \" + sentenceID + \" \" + position + \" [\";\n if( argumentMentions != null )\n for( Integer id : argumentMentions.keySet() ) str += \" \" + arguments.get(id) + \",\" + argumentMentions.get(id);\n str += \" ]\";\n return str; \n }\n\n public String toStringFull() { \n // String str = eventID + \" \" + token + \" \" + sentenceID + \" \" + position + \" [\";\n String str = eventID + \" \" + token + \" \" + posTag + \" \" + sentenceID + \" \" + position + \" [\";\n if( arguments != null )\n for( Integer id : arguments.keySet() ) str += \" \" + arguments.get(id) + \",\" + id;\n str += \" ]\";\n return str; \n }\n\n public String toString() { \n // String str = eventID + \" \" + token + \" \" + sentenceID + \" \" + position + \" [\";\n String str = eventID + \" \" + token + \" \" + posTag + \" \" + sentenceID + \" \" + position + \" [\";\n if( arguments != null )\n for( Integer id : arguments.keySet() ) str += \" \" + id;\n str += \" ]\";\n return str; \n }\n}", "public class WordIndex {\n HashMap<String,Integer> index = new HashMap();\n HashMap<Integer,String> indexToString = new HashMap();\n int count = 0;\n\n public WordIndex() { }\n public WordIndex(String filename) {\n setIndex(indexFromFile(filename));\n invertIndex();\n }\n\n\n private boolean isNumeral(String token) {\n if( token.matches(\"[\\\\d\\\\,\\\\-\\\\.$%]+\") )\n return true;\n else return false;\n }\n\n\n /**\n * Index the given string word * lowercase before calling!\n */\n private void index(String word) {\n // Normalize all numerals\n if( isNumeral(word) ) word = \"<NUM>\";\n\n // Save the index\n if( !index.containsKey(word) ) index.put(word, ++count);\n }\n\n /**\n * Lookup the word for a given index.\n */\n public String indexToWord(Integer index) {\n return indexToString.get(index);\n }\n\n /**\n * Write a String->Integer mapping to a file\n * @param index HashMap of Strings to Strings\n * @param filename The file to write to\n */\n public void indexToFile(HashMap<String,Integer> index, String filename) {\n try {\n BufferedWriter out = new BufferedWriter(new FileWriter(filename));\n for( String str : index.keySet() ) {\n\tout.write(str + \" \" + index.get(str) + \"\\n\");\n }\n out.close();\n } catch( Exception ex ) { ex.printStackTrace(); }\n }\n\n\n /**\n * Read an index from a text file\n * @return Mapping from String to Integer\n */\n public HashMap<String,Integer> indexFromFile(String filename) {\n HashMap<String,Integer> index = new HashMap();\n String line;\n\n try {\n BufferedReader in = new BufferedReader(new FileReader(filename));\n while( (line = in.readLine()) != null ) {\n\tint pos = line.lastIndexOf(' ');\n\tInteger ind = Integer.parseInt(line.substring(pos+1));\n\tindex.put(line.substring(0,pos), ind);\n }\n in.close();\n } catch( Exception ex ) { ex.printStackTrace(); }\n\n return index;\n }\n\n\n /**\n * Create the opposite lookup table.\n */\n public void invertIndex() {\n for( Map.Entry<String,Integer> entry : index.entrySet() ) {\n indexToString.put(entry.getValue(), entry.getKey());\n }\n }\n\n\n /**\n * Set the hashmap and last word index\n */\n public void setIndex(HashMap newindex) {\n index = newindex;\n count = 0;\n for( Integer val : index.values() ) {\n if( val > count ) count = val;\n }\n System.out.println(\"Set words max: \" + count);\n }\n\n\n\n /**\n * Returns the integer for a word, or if it doesn't exist, creates a\n * new index and adds it to our list.\n */\n public Integer get(String word) {\n String atom;\n if( isNumeral(word) ) atom = \"<NUM>\";\n else atom = word.toLowerCase();\n\n if( !index.containsKey(atom) ) {\n // System.out.println(\"ERROR: new word \" + atom);\n index(atom);\n }\n return index.get(atom);\n }\n\n public HashMap<String,Integer> index() { return index; }\n\n}", "public class SortableScore implements Comparable<SortableScore> {\n double score = 0.0f;\n String key;\n\n public SortableScore(double s, String k) {\n score = s;\n key = k;\n }\n public SortableScore() { }\n\n public int compareTo(SortableScore b) {\n if( b == null ) return -1;\n if( score < ((SortableScore)b).score() ) return 1;\n else if( ((SortableScore)b).score() > score ) return -1;\n else return 0;\n }\n\n public void setScore(double s) { score = s; }\n public void setKey(String k) { key = k; }\n\n public double score() { return score; }\n public String key() { return key; }\n public String toString() {\n return key + \" \" + score;\n }\n}", "public class Util {\n public Util() { }\n\n /**\n * Given an event, increment its count by the given amount.\n */\n public static <E> void incrementCount(Map<E,Integer> counts, E key, int count) {\n Integer currentCount = counts.get(key);\n if( currentCount == null ) currentCount = 0;\n counts.put(key, currentCount+count);\n }\n\n /**\n * Given an event, increment its count by the given amount.\n */\n public static void incrementCount(Map<String, Float> counts,\n String eventString, float count) {\n Float currentCount = counts.get(eventString);\n if( currentCount == null ) currentCount = 0.0f;\n counts.put(eventString, currentCount+count);\n }\n\n /**\n * Given an event, increment its count by the given amount.\n */\n public static void incrementCount(Map<String, Double> counts,\n String eventString, double count) {\n Double currentCount = counts.get(eventString);\n if( currentCount == null ) currentCount = 0.0;\n counts.put(eventString, currentCount+count);\n }\n\n /**\n * Given an Integer ID, increment its count by the given amount.\n */\n public static void incrementCount(Map<Integer, Integer> counts,\n Integer id, int count) {\n Integer currentCount = counts.get(id);\n if( currentCount == null ) currentCount = 0;\n counts.put(id, currentCount+count);\n }\n\n /**\n * Given an Integer ID, increment its count by the given amount.\n */\n public static void incrementCount(Map<Integer, Float> counts,\n Integer id, float count) {\n Float currentCount = counts.get(id);\n if( currentCount == null ) currentCount = 0.0f;\n counts.put(id, currentCount+count);\n }\n\n /**\n * Given an Integer ID, increment its count by the given amount.\n */\n public static void incrementCount(Map<Integer, Double> counts, Integer id, double count) {\n Double currentCount = counts.get(id);\n if( currentCount == null ) currentCount = 0.0;\n counts.put(id, currentCount+count);\n }\n\n public static int sumValues(Map<String,Integer> counts) {\n int sum = 0;\n if( counts != null )\n for( Map.Entry<String, Integer> entry : counts.entrySet() )\n sum += entry.getValue();\n return sum;\n }\n\n public static <E> void countsToFile(String path, Map<E,Integer> counts) {\n try {\n PrintWriter writer;\n writer = new PrintWriter(new BufferedWriter(new FileWriter(path, false)));\n for( E key : sortKeysByIntValues(counts) ) {\n writer.write(key + \"\\t\" + counts.get(key) + \"\\n\");\n }\n writer.close();\n } catch( Exception ex ) { ex.printStackTrace(); } \n }\n \n public static Map<String,Integer> countsFromFile(String path) {\n Map<String,Integer> counts = new HashMap<String,Integer>();\n try {\n BufferedReader in = new BufferedReader(new FileReader(path));\n String line;\n while( (line = in.readLine()) != null ) {\n int tabindex = line.indexOf('\\t');\n String key = line.substring(0,tabindex);\n int count = Integer.valueOf(line.substring(tabindex+1));\n counts.put(key, count);\n }\n } catch( Exception ex ) { \n System.err.println(\"Error opening \" + path);\n ex.printStackTrace();\n }\n return counts; \n }\n \n public static List<String> readLinesFromFile(String path) {\n List<String> lines = new ArrayList<String>();\n try {\n BufferedReader in = new BufferedReader(new FileReader(path));\n String line;\n while( (line = in.readLine()) != null ) {\n lines.add(line);\n }\n } catch( Exception ex ) { \n System.err.println(\"Error reading from \" + path);\n ex.printStackTrace();\n }\n return lines; \n }\n \n /**\n * Read a file of strings and counts. Return all strings that have a count greater\n * than or equal to the given threshold n.\n * @param path The file path.\n * @param n The threshold, all counts higher or equal are returned.\n * @return All keys in the file that have higher/equal counts to n.\n */\n public static Set<String> keysFromFileMeetingThreshold(String path, int n) {\n Set<String> keys = new HashSet<String>();\n try {\n BufferedReader in = new BufferedReader(new FileReader(path));\n String line;\n while( (line = in.readLine()) != null ) {\n int tabindex = line.indexOf('\\t');\n String key = line.substring(0,tabindex);\n int count = Integer.valueOf(line.substring(tabindex+1));\n if( count >= n )\n keys.add(key);\n }\n } catch( Exception ex ) { \n System.err.println(\"Error opening \" + path);\n ex.printStackTrace();\n }\n return keys; \n }\n \n /**\n * Scale the values of the map to be between [0,1].\n */\n public static void scaleToUnit(Map<Object, Double> counts) {\n double max = 0.0;\n double min = Double.MAX_VALUE;\n for( Map.Entry<Object,Double> entry : counts.entrySet() ) {\n double value = entry.getValue();\n if( value > max ) max = value;\n if( value < min ) min = value;\n }\n\n double range = max - min;\n\n // Scale between [0,1]\n for( Map.Entry<Object,Double> entry : counts.entrySet() ) {\n double value = entry.getValue();\n double scaledValue = (value - min) / range;\n entry.setValue(scaledValue);\n }\n }\n\n /**\n * Scale the values of the map to be between [0,1].\n */\n public static void scaleToUnit(SortableScore scores[]) {\n double max = 0.0;\n double min = Double.MAX_VALUE;\n for( SortableScore score : scores ) {\n double value = score.score();\n if( value > max ) max = value;\n if( value < min ) min = value;\n }\n\n double range = max - min;\n\n // Scale between [0,1]\n for( SortableScore score : scores ) {\n double value = score.score();\n double scaledValue = (value - min) / range;\n score.setScore(scaledValue);\n }\n }\n\n public static <E> void scaleToUnit(SortableObject<E> scores[]) {\n double max = 0.0;\n double min = Double.MAX_VALUE;\n for( SortableObject<E> score : scores ) {\n double value = score.score();\n if( value > max ) max = value;\n if( value < min ) min = value;\n }\n\n double range = max - min;\n\n // Scale between [0,1]\n for( SortableObject<E> score : scores ) {\n double value = score.score();\n double scaledValue = (value - min) / range;\n score.setScore(scaledValue);\n }\n }\n\n\n /**\n * Read integers from a file, one integer per line.\n */\n public static List<Integer> slurpIntegers(String filename) {\n List<Integer> guesses = new ArrayList<Integer>();\n\n try {\n BufferedReader in = new BufferedReader(new FileReader(filename));\n String line;\n\n while( (line = in.readLine()) != null ) {\n if( line.matches(\"-?\\\\d+\") )\n guesses.add(Integer.parseInt(line));\n else\n System.out.println(\"WARNING: skipping line in \" + filename + \": \" + line);\n }\n\n in.close();\n } catch( Exception ex ) { ex.printStackTrace(); }\n\n return guesses;\n }\n\n /**\n * @return A String array of length two, the directory and the file.\n * Directory is null if there is none.\n */\n public static String[] splitDirectoryAndFile(String path) {\n int index = path.lastIndexOf(File.separatorChar);\n String[] pair = new String[2];\n\n // strip trailing separators\n while( index >= 0 && index == path.length()-1 ) {\n path = path.substring(0, path.length()-1);\n index = path.lastIndexOf(File.separatorChar);\n }\n\n // if no directory in the path\n if( index == -1 ) {\n pair[0] = null;\n pair[1] = path;\n }\n // split off the directory\n else {\n pair[0] = path.substring(0, index);\n pair[1] = path.substring(index+1);\n }\n return pair;\n }\n\n /**\n * @return A new list with only n elements.\n */\n public static <E> List<E> getFirstN(Collection<E> objects, int n) {\n if( objects == null ) return null;\n\n List<E> newlist = new ArrayList<E>();\n int i = 0;\n for( E item : objects ) {\n if( i < n )\n newlist.add(item);\n else break;\n i++;\n }\n return newlist;\n }\n\n /**\n * DESTRUCTIVE: Trim the list to just the first n objects.\n */\n public static <E> void firstN(List<E> objects, int n) {\n if( objects == null ) return;\n\n while( objects.size() > n ) {\n objects.remove(objects.size()-1);\n }\n }\n\n /**\n * Create a new array with just the first n objects.\n */\n public static SortableScore[] firstN(SortableScore[] scores, int n) {\n if( scores == null ) return null;\n\n int newsize = Math.min(n, scores.length);\n SortableScore[] arr = new SortableScore[newsize];\n for( int i = 0; i < newsize; i++ )\n arr[i] = scores[i];\n return arr;\n }\n\n public static <E> List<E> mergeLists(List<E> first, List<E> second) {\n List<E> merged = new ArrayList<E>(first);\n for( E obj : second ) {\n if( !merged.contains(obj) )\n merged.add(obj);\n }\n return merged;\n }\n \n public static <E> List<E> arrayToList(E[] arr) {\n List<E> thelist = new ArrayList<E>();\n for( E obj : arr )\n thelist.add(obj);\n return thelist;\n }\n\n /**\n * String match search for a string in a list.\n */\n public static boolean findInListOfStrings(List<String> items, String target) {\n \tif( items == null || target == null )\n \t\treturn false;\n \t\n \tfor( String item : items )\n \t\tif( target.equalsIgnoreCase(item) )\n \t\t\treturn true;\n \t\n \treturn false;\n }\n \n public static <E> List<E> collectionToList(Collection<E> theset) {\n List<E> thelist = new ArrayList<E>();\n for( E obj : theset ) thelist.add(obj);\n return thelist;\n }\n\n public static String[] sortStrings(Collection<String> unsorted) {\n String[] sorted = new String[unsorted.size()];\n sorted = unsorted.toArray(sorted);\n Arrays.sort(sorted);\n return sorted;\n }\n\n /**\n * Sort the keys of the map by their values, return the list in order.\n */\n public static <E> List<E> sortCounterKeys(Counter<E> map) {\n return sortCounterKeys(map, false);\n }\n public static <E> List<E> sortCounterKeys(Counter<E> map, boolean reverse) {\n SortableObject<E>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<E, Double> entry : map.entrySet() )\n sorted[i++] = new SortableObject<E>(entry.getValue(), entry.getKey());\n if( !reverse ) Arrays.sort(sorted);\n else Arrays.sort(sorted, Collections.reverseOrder());\n\n List<E> strs = new ArrayList<E>(sorted.length);\n for( SortableObject<E> obj : sorted )\n strs.add(obj.key());\n return strs;\n }\n \n /**\n * Sort the keys of the map by their strings. Just the keys, ignore values.\n */\n public static List<String> sortCounterKeysByKeys(Counter<String> map) {\n return sortCounterKeysByKeys(map, false);\n }\n public static List<String> sortCounterKeysByKeys(Counter<String> map, boolean reverse) {\n String[] sorted = new String[map.size()];\n int i = 0;\n for( String key : map.keySet() )\n sorted[i++] = key;\n if( !reverse ) Arrays.sort(sorted);\n else Arrays.sort(sorted, Collections.reverseOrder());\n\n List<String> strs = new ArrayList<String>(sorted.length);\n for( String key : sorted )\n strs.add(key);\n return strs;\n }\n \n /**\n * Sort the keys of the map by their values, return the list in order.\n */\n public static <E> List<E> sortKeysByValues(Map<E,Double> map) {\n return sortKeysByValues(map, false);\n }\n public static <E> List<E> sortKeysByValues(Map<E,Double> map, boolean reverse) {\n SortableObject<E>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<E, Double> entry : map.entrySet() )\n sorted[i++] = new SortableObject<E>(entry.getValue(), entry.getKey());\n if( !reverse ) Arrays.sort(sorted);\n else Arrays.sort(sorted, Collections.reverseOrder());\n\n List<E> strs = new ArrayList<E>(sorted.length);\n for( SortableObject<E> obj : sorted )\n strs.add(obj.key());\n return strs;\n }\n \n /**\n * Sort the keys of the map by their values, return the list in order.\n */\n public static <E> List<E> sortKeysByIntValues(Map<E,Integer> map) {\n return sortKeysByIntValues(map, false);\n }\n public static <E> List<E> sortKeysByIntValues(Map<E,Integer> map, boolean reverse) {\n if( map == null ) return null; \n SortableObject<E>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<E, Integer> entry : map.entrySet() )\n sorted[i++] = new SortableObject<E>(entry.getValue(), entry.getKey());\n if( !reverse ) Arrays.sort(sorted);\n else Arrays.sort(sorted, Collections.reverseOrder());\n \n List<E> strs = new ArrayList<E>(sorted.length);\n for( SortableObject<E> obj : sorted )\n strs.add((E)obj.key());\n return strs;\n }\n\n /**\n * Sort the keys of the map by their values, return the list in order.\n */\n public static <E> List<E> sortKeysByFloatValues(Map<E,Float> map) {\n return sortKeysByFloatValues(map, false);\n }\n public static <E> List<E> sortKeysByFloatValues(Map<E,Float> map, boolean reverse) {\n if( map == null ) return null; \n SortableObject<E>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<E, Float> entry : map.entrySet() )\n sorted[i++] = new SortableObject<E>(entry.getValue(), entry.getKey());\n if( !reverse ) Arrays.sort(sorted);\n else Arrays.sort(sorted, Collections.reverseOrder());\n \n List<E> strs = new ArrayList<E>(sorted.length);\n for( SortableObject<E> obj : sorted )\n strs.add((E)obj.key());\n return strs;\n }\n \n public static void printMapSortedByValue(Map<String,Integer> map) {\n printMapSortedByValue(map, (map == null ? 0 : map.size()));\n }\n\n public static void printMapSortedByValue(Map<String,Integer> map, int max) {\n if( map == null || map.size() == 0 )\n System.out.println(\"null\");\n else {\n SortableObject<String>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<String, Integer> entry : map.entrySet() )\n sorted[i++] = new SortableObject<String>(entry.getValue(), entry.getKey());\n Arrays.sort(sorted);\n\n int num = 0;\n for( SortableObject<String> obj : sorted ) {\n System.out.print(obj.key + \" \" + map.get(obj.key) + \" \");\n num++;\n if( num == max ) break;\n }\n System.out.println();\n }\n }\n \n public static void printDoubleMapSortedByValue(Map<String,Double> map, int max) {\n if( map == null || map.size() == 0 )\n System.out.println(\"null\");\n else {\n SortableObject<String>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<String, Double> entry : map.entrySet() )\n sorted[i++] = new SortableObject<String>(entry.getValue(), entry.getKey());\n Arrays.sort(sorted);\n\n int num = 0;\n for( SortableObject<String> obj : sorted ) {\n System.out.printf(\"%s %.3f \", obj.key, map.get(obj.key));\n num++;\n if( num == max ) break;\n }\n System.out.println();\n }\n }\n \n public static void printFloatMapSortedByValue(Map<String,Float> map, int max) {\n if( map == null || map.size() == 0 )\n System.out.println(\"null\");\n else {\n SortableObject<String>[] sorted = new SortableObject[map.size()];\n int i = 0;\n for( Map.Entry<String, Float> entry : map.entrySet() )\n sorted[i++] = new SortableObject<String>(entry.getValue(), entry.getKey());\n Arrays.sort(sorted);\n\n int num = 0;\n for( SortableObject<String> obj : sorted ) {\n System.out.printf(\"%s %.3f \", obj.key, map.get(obj.key));\n num++;\n if( num == max ) break;\n }\n System.out.println();\n }\n }\n \n /**\n * Removes all map entries whose integer count is the cutoff or less.\n */\n public static void trimIntegerCounts(Map<String,Integer> map, int cutoff) {\n List<String> removed = new ArrayList<String>();\n\n for( Map.Entry<String,Integer> entry : map.entrySet() ) {\n Integer count = entry.getValue();\n // Remove the pair if it is sparse\n if( count == null || count <= cutoff ) removed.add(entry.getKey());\n }\n\n for( String key : removed ) map.remove(key);\n // System.out.println(\"Trimmed \" + removed.size() + \" pairs\");\n }\n\n /**\n * Removes all map entries whose integer count is the cutoff or less.\n */\n public static void trimFloatCounts(Map<String,Float> map, float cutoff) {\n List<String> removed = new ArrayList<String>();\n\n for( Map.Entry<String,Float> entry : map.entrySet() ) {\n Float count = entry.getValue();\n // Remove the pair if it is sparse\n if( count == null || count <= cutoff ) removed.add(entry.getKey());\n }\n\n for( String key : removed ) map.remove(key);\n // System.out.println(\"Trimmed \" + removed.size() + \" pairs\");\n }\n \n /**\n * Create a string list of the items, up to n long.\n */\n public static String collectionToString(Collection<String> set, int n) {\n if( set == null ) return \"\";\n \n StringBuffer buf = new StringBuffer();\n int i = 0;\n for( String str : set ) {\n if( i > 0 ) buf.append(' ');\n buf.append(str);\n i++;\n if( i == n ) break;\n }\n return buf.toString();\n }\n \n public static double calculateEntropy(double[] probs) {\n double entropy = 0.0;\n for( int i = 0; i < probs.length; i++ ) {\n if( probs[i] > 0.0 )\n entropy -= probs[i] * Math.log(probs[i]);\n }\n return entropy;\n }\n \n /**\n * Standard factorial calculation.\n */\n public static int factorial(int n) {\n if( n == 0 ) return 1;\n int fact = 1;\n for( int i = 1; i <= n; i++ )\n fact *= i;\n return fact;\n }\n \n /**\n * Standard \"n choose k\" calculation.\n */\n public static int choose(int n, int k) {\n return factorial(n) / factorial(k)*factorial(n-k);\n }\n \n public static void reportMemory() {\n Runtime runtime = Runtime.getRuntime();\n long mb = 1024 * 1024;\n // long max = runtime.maxMemory();\n long used = runtime.totalMemory() - runtime.freeMemory();\n System.out.printf(\"......................... memory in use: %d MB .........................%n\", used / mb);\n }\n\n public static void reportElapsedTime(long startTime) {\n String str = timeString(System.currentTimeMillis()-startTime);\n System.out.println(\"............................ runtime \" + str + \" ..........................\");\n }\n\n public static String timeString(long milli) {\n long seconds = milli / 1000;\n long minutes = seconds/60;\n long hours = minutes/60;\n minutes = minutes%60;\n seconds = seconds%60;\n return (hours + \"h \" + minutes + \"m \" + seconds + \"s\");\n }\n\n public static void main(String[] args) {\n double[] probs = new double[4];\n probs[0] = 0.7;\n probs[1] = 0.3;\n probs[2] = 0.45;\n probs[3] = 0.1;\n \n System.out.println(\"sorted = \" + Arrays.toString(probs));\n \n String feature = \"running somewhere\";\n System.out.println(\"bytes = \" + feature.getBytes().length);\n\n// System.out.println(\"entropy = \" + calculateEntropy(probs));\n }\n}" ]
import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import nate.util.Pair; import nate.WordEvent; import nate.WordIndex; import nate.util.SortableScore; import nate.util.Util;
float bestscore = 0.0f; for( String str : _scores.keySet() ) { Map<String,Float> events = _scores.get(str); for( String str2 : events.keySet() ) { Float score = events.get(str2); if( score > bestscore ) { bestscore = score; best = str; } } } return best; } public Set<String> keySet() { return getSingleEvents(); } /** * @return All of the event strings involved in any pairs this class has. */ public Set<String> getSingleEvents() { Set<String> events = new HashSet<String>(); for( Map.Entry<String,Map<String,Float>> entry : _scores.entrySet() ) { events.add(entry.getKey()); for( String sib : entry.getValue().keySet() ) events.add(sib); } return events; } /** * Saves the score of an event pair key1 and key2. */ public void addScore(String key1, String key2, float score) { Map<String,Float> counts; if( _scores.containsKey(key1) ) counts = _scores.get(key1); else { counts = new HashMap<String, Float>(); _scores.put(key1,counts); } counts.put(key2,score); } public void setScore(String key1, String key2, float score) { addScoreSorted(key1, key2, score); } /** * Saves the score of an event pair key1 and key2 in sorted order. */ public void addScoreSorted(String key1, String key2, float score) { if( key1.compareTo(key2) > 0 ) addScore(key2, key1, score); else addScore(key1, key2, score); } /** * Removes any pairs that contain the given key. */ public void removeKey(String key) { // Remove all pairs starting with the key. _scores.remove(key); // Remove all pairs ending with the key. for( Map.Entry<String,Map<String,Float>> entry : _scores.entrySet() ) { Map<String,Float> scores = entry.getValue(); scores.remove(key); } } public void clear() { _scores.clear(); } public int size() { return _scores.size(); } /** * Print the pairs with their scores in sorted order. */ public void printSorted() { printSorted(Integer.MAX_VALUE); } public void printSorted(int maxpairs) { List<SortableScore> scores = new ArrayList<SortableScore>(); for( Map.Entry<String,Map<String,Float>> entry : _scores.entrySet() ) { for( Map.Entry<String,Float> entry2 : entry.getValue().entrySet() ) { String pair = entry.getKey() + "\t" + entry2.getKey(); scores.add(new SortableScore(entry2.getValue(), pair)); } } System.out.println("Num pairs: " + scores.size()); // Sort and Print. SortableScore[] arr = new SortableScore[scores.size()]; arr = scores.toArray(arr); Arrays.sort(arr); int num = 0; for( SortableScore scored : arr ) { if( scored.score() > 0.0f ) { System.out.printf("%s\t%.1f\n", scored.key(), scored.score()); num++; } if( num >= maxpairs ) break; } } /** * Main: Just for debugging. */ public static void main(String[] args) { EventPairScores scores = new EventPairScores(); scores.fromFile(args[0], null, 0.0f, 0, true); // testing...
Util.reportMemory();
4
MFlisar/StorageManager
lib/src/main/java/com/michaelflisar/storagemanager/utils/StorageDebugUtil.java
[ "public class StorageManager\n{\n public static final String TAG = StorageManager.class.getName();\n\n private static StorageManager INSTANCE = null;\n\n public static StorageManager get()\n {\n if (INSTANCE == null)\n INSTANCE = new StorageManager();\n return INSTANCE;\n }\n\n private StorageManager()\n {\n }\n\n // -------------------------\n // main functions\n // -------------------------\n\n private ICopyHandler mDefaultCopyHandler = null;\n private IMoveHandler mDefaultMoveHandler = null;\n private IMetaDataHandler mDefaultMetaDataHandler = null;\n private ICopyHandler mCopyHandler = null;\n private IMoveHandler mMoveHandler = null;\n private IMetaDataHandler mMetaDataHandler = null;\n private Context mContext;\n private FileFolder mRoot = null;\n private IFolder mSDCardRoot = null;\n private Uri mSDCardUri = null;\n private String mSDCardID = null;\n private int mTimeToWaitToRecheckMediaScanner;\n\n public void init(Context appContext, int timeToWaitToRecheckMediaScanner)\n {\n initDefaultHandlers();\n mContext = appContext;\n mTimeToWaitToRecheckMediaScanner = timeToWaitToRecheckMediaScanner;\n mRoot = StorageFolderUtil.getMainRootFolderWithoutFolderData();\n Log.d(TAG, \"Main root: \" + mRoot.getFolder().getPath());\n\n mSDCardRoot = StorageFolderUtil.getSDCardRootFolder(mRoot);\n if (mSDCardRoot == null)\n Log.d(TAG, \"SD Card root: \" + \"NULL\");\n else\n {\n if (mSDCardRoot instanceof FileFolder)\n Log.d(TAG, \"SD Card root: \" + ((FileFolder) mSDCardRoot).getFolder().getPath());\n else if (mSDCardRoot instanceof DocumentFolder)\n {\n mSDCardUri = ((DocumentFolder) mSDCardRoot).getFolder().getUri();\n Log.d(TAG, \"SD Card root: \" + ((DocumentFolder) mSDCardRoot).getFolder().getUri().toString() + \" | \" + ((DocumentFolder) mSDCardRoot).getFolder().getWrapped().canRead() + \" | \" + ((DocumentFolder) mSDCardRoot).getFolder().getWrapped().canWrite());\n\n // Example String: content://com.android.externalstorage.documents/tree/0FEC-3001%3A\n extractSDCardIDFromSDRoot();\n }\n }\n }\n\n private void initDefaultHandlers()\n {\n mDefaultCopyHandler = new ICopyHandler() {\n @Override\n public boolean copy(IFile source, IFile target) {\n try\n {\n if (source == null || target == null || !source.exists())\n return false;\n\n if (target instanceof StorageDocument && !target.exists())\n {\n String mimeType = ExtensionUtil.getExtension(target.getName());\n DocumentFile df = ((StorageDocument)target).getWrapped().getParentFile().createFile(mimeType, target.getName());\n if (df == null)\n return false;\n target.setWrapped(df);\n }\n return InternalStorageUtil.copyStream(source.getInputStream(), target.getOutputStream());\n }\n catch (IOException e)\n {\n return false;\n }\n }\n };\n mDefaultMoveHandler = new IMoveHandler() {\n @Override\n public boolean move(IFile source, IFile target) {\n try\n {\n return InternalStorageUtil.move(source, target);\n }\n catch (IOException e)\n {\n return false;\n }\n }\n };\n mDefaultMetaDataHandler = new IMetaDataHandler() {\n @Override\n public HashMap<String, String> getExifInformations(IFile file) {\n if (file.getType() == StorageDefinitions.FileType.File)\n return ExifFileUtil.getExifInformations(file.getPath());\n return null;\n }\n };\n }\n\n private void extractSDCardIDFromSDRoot()\n {\n String[] parts = ((DocumentFolder) mSDCardRoot).getFolder().getUri().toString().split(\"/\");\n if (parts.length >= 5)\n mSDCardID = parts[4].replace(StorageDefinitions.AUTHORITY_COLON, \"\");\n else\n mSDCardID = null;\n }\n\n public void setCopyHandler(ICopyHandler copyHandler)\n {\n mCopyHandler = copyHandler;\n }\n\n public void setMoveHandler(IMoveHandler moveHandler)\n {\n mMoveHandler = moveHandler;\n }\n\n public void setMetaDataHandler(IMetaDataHandler metaDataHandler)\n {\n mMetaDataHandler = metaDataHandler;\n }\n\n private void checkInitialised()\n {\n if (mRoot == null)\n throw new RuntimeException(getClass().getSimpleName() + \" has not been initialised!\");\n }\n\n public FileFolder getRoot()\n {\n checkInitialised();\n return mRoot;\n }\n\n public IFolder getSDCardRoot()\n {\n checkInitialised();\n return mSDCardRoot;\n }\n\n public String getSDCardID()\n {\n checkInitialised();\n return mSDCardID;\n }\n\n public Uri getSDCardUri()\n {\n checkInitialised();\n return mSDCardUri;\n }\n\n public Context getContext()\n {\n checkInitialised();\n return mContext;\n }\n\n\n public ICopyHandler getDefaultCopyHandler()\n {\n checkInitialised();\n return mDefaultCopyHandler;\n }\n\n public IMoveHandler getDefaultMoveHandler()\n {\n checkInitialised();\n return mDefaultMoveHandler;\n }\n\n public IMetaDataHandler getDefaultMetaDataHandler()\n {\n checkInitialised();\n return mDefaultMetaDataHandler;\n }\n\n public ICopyHandler getCopyHandler()\n {\n checkInitialised();\n if (mCopyHandler != null)\n return mCopyHandler;\n return mDefaultCopyHandler;\n }\n\n public IMoveHandler getMoveHandler()\n {\n checkInitialised();\n if (mMoveHandler != null)\n return mMoveHandler;\n return mDefaultMoveHandler;\n }\n\n public IMetaDataHandler getMetaDataHandler()\n {\n checkInitialised();\n if (mMetaDataHandler != null)\n return mMetaDataHandler;\n return mDefaultMetaDataHandler;\n }\n\n public int getTimeToWaitToRecheckMediaScanner()\n {\n checkInitialised();\n return mTimeToWaitToRecheckMediaScanner;\n }\n\n public interface ICopyHandler\n {\n boolean copy(IFile source, IFile target);\n }\n\n public interface IMoveHandler\n {\n boolean move(IFile source, IFile target);\n }\n\n public interface IMetaDataHandler\n {\n HashMap<String, String> getExifInformations(IFile file);\n }\n\n public void resetSDCard()\n {\n checkInitialised();\n mSDCardRoot = null;\n mSDCardUri = null;\n }\n\n public void updateSDCard(Uri treeUri, DocumentFile doc)\n {\n checkInitialised();\n if (mSDCardRoot == null)\n// mSDCardRoot = StorageFolderUtil.getSDCardRootFolder(mRoot);\n mSDCardRoot = new DocumentFolder(new StorageDocument(doc, null, null));\n else\n ((DocumentFolder)mSDCardRoot).updateDocument(doc);\n mSDCardUri = treeUri;\n }\n}", "public class StoragePermissionManager\n{\n private static final String TAG = StoragePermissionManager.class.getName();\n\n public static boolean hasSDCardPermissions()\n {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)\n return true;\n if (StorageManager.get().getSDCardRoot() == null)\n return false;\n return ((DocumentFolder)StorageManager.get().getSDCardRoot()).getFolder().getWrapped().canRead() && ((DocumentFolder)StorageManager.get().getSDCardRoot()).getFolder().getWrapped().canWrite();\n }\n\n public static boolean hasPermissionsToEdit(List<IFile> files)\n {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)\n return true;\n\n Boolean hasPermissions = hasSDCardPermissions();\n if (hasPermissions)\n return true;\n\n for (int i = 0; i < files.size(); i++)\n {\n if (files.get(i).getType() == StorageDefinitions.FileType.Document)\n return false;\n }\n return true;\n }\n\n public static boolean needsToGetPermissionsForSDCardIfNecessary(IFolder sdCardRoot)\n {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && sdCardRoot != null)\n return sdCardRoot.getFolder().getUri().equals(StorageManager.get().getSDCardUri()); // default is treeUri, afterwards it will be exchanged with the document uri based on the tree!\n return false;\n }\n\n public static void letUserSelectSDCard(Activity activity, int requestCode)\n {\n Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);\n intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);\n intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n activity.startActivityForResult(intent, requestCode);\n }\n\n @TargetApi(Build.VERSION_CODES.KITKAT)\n public static boolean handleOnActivityResult(Activity activity, int requestCode, int resultCode, Intent data, int resultCodeToCheck, IStorageSelectionManager manager)\n {\n if (requestCode == resultCodeToCheck)\n {\n if (resultCode == Activity.RESULT_OK)\n {\n // Get Uri from Storage Access Framework.\n Uri treeUri = data.getData();\n\n activity.grantUriPermission(activity.getPackageName(), treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n\n DocumentFile doc = DocumentFile.fromTreeUri(activity, treeUri);\n Log.d(TAG, \"SD Card Root AFTER asking user: \" + treeUri.toString() + \" | \" + doc.canRead() + \" | \" + doc.canWrite());\n\n if (manager.isSelectionOk(doc))\n {\n // Persist access permissions.\n if (manager.takePersistableUri())\n updatePersistUriPermissions(activity, treeUri);\n\n if (manager.updateSDCardDocument())\n {\n StorageManager.get().updateSDCard(treeUri, doc);\n// DocumentFolder sdCardRoot = (DocumentFolder) StorageManager.get().getSDCardRoot();\n// if (sdCardRoot != null)\n// sdCardRoot.updateDocument(doc);\n }\n\n manager.onAcceptableUriSelected(treeUri);\n }\n }\n return true;\n }\n return false;\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n public static boolean checkPersistUriPermissionsAndUpdate(Context context, DocumentFolder documentFolder)\n {\n Uri uri = documentFolder.getFolder().getUri();\n List<UriPermission> permissions = context.getContentResolver().getPersistedUriPermissions();\n for (UriPermission permission : permissions)\n {\n String permissionTreeId = DocumentsContract.getTreeDocumentId(permission.getUri());\n String uriTreeId = DocumentsContract.getTreeDocumentId(uri);\n if (uriTreeId.startsWith(permissionTreeId))\n {\n // update permissions - after a restart this is necessary...\n updatePersistUriPermissions(context, uri);\n documentFolder.updateDocument(DocumentFile.fromTreeUri(context, permission.getUri()));\n return true;\n }\n }\n return false;\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n public static boolean checkPersistUriPermissionsAndUpdate(Context context, StorageDocument storageDocument)\n {\n Uri uri = storageDocument.getUri();\n List<UriPermission> permissions = context.getContentResolver().getPersistedUriPermissions();\n for (UriPermission permission : permissions)\n {\n String permissionTreeId = DocumentsContract.getTreeDocumentId(permission.getUri());\n String uriTreeId = DocumentsContract.getTreeDocumentId(uri);\n if (uriTreeId.startsWith(permissionTreeId))\n {\n // update permissions - after a restart this is necessary...\n updatePersistUriPermissions(context, uri);\n storageDocument.setWrapped(DocumentFile.fromTreeUri(context, permission.getUri()));\n return true;\n }\n }\n return false;\n }\n\n\n @TargetApi(Build.VERSION_CODES.KITKAT)\n public static boolean releasePersistUriPermissions(Activity activity, Uri uri)\n {\n try\n {\n// int takeFlags = flags;\n// takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n activity.getContentResolver().releasePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n return true;\n }\n catch (SecurityException e)\n {\n return false;\n }\n }\n\n @TargetApi(Build.VERSION_CODES.KITKAT)\n private static void updatePersistUriPermissions(Context context, Uri uri)\n {\n// int takeFlags = flags;\n// takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n context.getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n context.grantUriPermission(context.getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\n }\n\n public interface IStorageSelectionManager\n {\n boolean takePersistableUri();\n boolean updateSDCardDocument();\n boolean isSelectionOk(DocumentFile selectedFile);\n void onAcceptableUriSelected(Uri uri);\n }\n}", "public class StorageUtil\n{\n public static final String TAG = StorageUtil.class.getName();\n\n // --------------------------------\n // File functions\n // --------------------------------\n\n public static boolean exists(String path)\n {\n IFile f = getFileByPath(path, null, false, null);\n if (f == null)\n return false;\n // actually returning true directly would be fine as well...\n return f.exists();\n }\n\n public static boolean canCreate(String path)\n {\n IFile f = getFileByPath(path, null, false, null);\n if (f != null)\n return false;\n\n // create file and delete it again => no media store update!\n f = getFileByPath(path, null, true, null);\n boolean success = f.exists();\n f.delete(StorageDefinitions.MediaStoreUpdateType.None);\n return success;\n }\n\n public static boolean isPathAFile(String path)\n {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ||\n path.startsWith(StorageManager.get().getRoot().getFolder().getPath()))\n return true;\n return false;\n }\n\n public static IFile getFileByPath(String path, Boolean isHidden)\n {\n return getFileByPath(path, isHidden, false, null);\n }\n\n public static IFile getFileByPath(String path, Boolean isHidden, boolean createEmptyFile, String mimeType)\n {\n // before android M we just return a normal File...\n // 1) check if file is on internal storage\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ||\n path.startsWith(StorageManager.get().getRoot().getFolder().getPath()))\n {\n return FileUtil.createFile(path, isHidden, createEmptyFile);\n }\n\n // 2) check if file is on sd card storage\n // first 3 parts are an empty string, the storage and the id of the storage\n if (StoragePermissionManager.hasSDCardPermissions())\n return DocumentUtil.createFileFromPath(path, mimeType, isHidden, createEmptyFile);\n return null;\n }\n\n public static IFile getFileByPath(String folder, String name, String mimeType, Boolean isHidden, boolean createEmptyFile)\n {\n // before android M we just return a normal File...\n // 1) check if file is on internal storage\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || folder.startsWith(StorageManager.get().getRoot().getFolder().getPath()))\n {\n File f = new File(folder, name);\n if (!f.exists() && createEmptyFile)\n {\n try\n {\n if (!f.createNewFile())\n f = null;\n }\n catch (IOException e)\n {\n f = null;\n }\n }\n else if (!f.exists())\n f = null;\n // TODO: decide via parameter if media store data should be loaded\n if (f != null)\n return new StorageFile(f, isHidden, false);\n return null;\n }\n\n // 2) check if file is on sd card storage\n // first 3 parts are an empty string, the storage and the id of the storage\n// List<String> parts = Arrays.asList(folder.split(\"/\"));\n// parts.add(name);\n if (StoragePermissionManager.hasSDCardPermissions())\n return DocumentUtil.createFileFromPath(folder + \"/\" + name, mimeType, isHidden, createEmptyFile);\n return null;\n }\n\n public static IFolder createFolderFromFile(IFile file)\n {\n if (file.getType() == StorageDefinitions.FileType.File)\n return new FileFolder(((StorageFile)file).getWrapped());\n else\n return new DocumentFolder(((StorageDocument)file));\n }\n\n public static IFolder getFolderFromUriStringAndUpdatePermissions(Context context, String uriOrPath, boolean loadFolderContent)\n {\n// IFile folderFile = getFileFromUriStringAndUpdatePermissions(context, uriOrPath);\n if (uriOrPath.startsWith(\"content\"))\n {\n if (uriOrPath.endsWith(\"/\"))\n uriOrPath = uriOrPath.substring(0, uriOrPath.length() - 1);\n// uriOrPath = uriOrPath.replace(StorageDefinitions.AUTHORITY_COLON, \":\");\n// uriOrPath = uriOrPath.replace(StorageDefinitions.AUTHORITY_SLASH, \"/\");\n Uri treeUri = Uri.parse(uriOrPath);\n\n// DocumentFile doc = DocumentFile.fromTreeUri(StorageManager.get().getContext(), Uri.parse(uriOrPath));\n// DocumentFolder f = new DocumentFolder(new StorageDocument(doc, null, false));\n\n// DocumentFolder f = new DocumentFolder((StorageDocument)StorageUtil.getFileByPath(uriOrPath, null));\n DocumentFolder f = new DocumentFolder(treeUri);\n if (StoragePermissionManager.checkPersistUriPermissionsAndUpdate(context, f))\n Log.d(TAG, \"Permissions available and updated\");\n else\n Log.d(TAG, \"Permissions lost!\");\n\n if (loadFolderContent)\n f.loadFiles(null, false, null, null, null, null, null, null);\n return f;\n }\n else\n {\n FileFolder f = new FileFolder(new File(uriOrPath));\n if (loadFolderContent)\n f.loadFiles(null, false, null, null, null, null, null, null);\n return f;\n }\n }\n\n public static IFile getFileFromUriStringAndUpdatePermissions(Context context, String uriOrPath)\n {\n if (uriOrPath.startsWith(\"content\"))\n {\n if (uriOrPath.endsWith(\"/\"))\n uriOrPath = uriOrPath.substring(0, uriOrPath.length() - 1);\n Uri treeUri = Uri.parse(uriOrPath);\n DocumentFile f = DocumentFile.fromTreeUri(context, treeUri);\n StorageDocument storageDocument = new StorageDocument(f, null, null);\n if (StoragePermissionManager.checkPersistUriPermissionsAndUpdate(context, storageDocument))\n Log.d(TAG, \"Permissions available and updated\");\n else\n Log.d(TAG, \"Permissions lost!\");\n\n return storageDocument;\n }\n else\n {\n return new StorageFile(new File(uriOrPath), null, null);\n }\n }\n\n public static String cleanPath(String path)\n {\n // we don't know if other apps use the API calls, so we consider following:\n // \"/storage/emulated/0\" == \"/storage/emulated/legacy\"\n // we replace any of those strings with our API reference!\n // useful if another app shares a PATH (instead of a URI) with your app and you want to clean this path\n\n if (path == null)\n return path;\n\n String apiRootPath = StorageManager.get().getRoot().getFolder().getPath();\n path = path.replace(\"/storage/emulated/0\", apiRootPath);\n path = path.replace(\"/storage/emulated/legacy\", apiRootPath);\n return path;\n }\n\n public static String getUnusedFileName(String path, String... namesThatAreNotAllowed)\n {\n IFile file = null;\n ArrayList<String> notAllowedNames = new ArrayList<>();\n if (namesThatAreNotAllowed != null && namesThatAreNotAllowed.length > 0)\n notAllowedNames.addAll(Arrays.asList(namesThatAreNotAllowed));\n\n File f = new File(path);\n String folder = f.getParentFile().getAbsolutePath() + \"/\";\n String filename = f.getPath().substring(folder.length());\n String name = filename;\n String ext = \"\";\n String mimeType = ExtensionUtil.getMimeType(path);\n //IFile file = StorageUtil.getFileByPath(path, false, mimeType);\n\n boolean search = false;\n // 1) check if path itself contains names that are not allowed\n if (notAllowedNames != null && notAllowedNames.contains(name))\n search = true;\n // 2) check if path exists\n else\n {\n file = StorageUtil.getFileByPath(path, null, false, mimeType);\n if (file != null && file.exists())\n {\n search = true;\n file = null;\n }\n }\n\n // if necessary, find next free path...\n String freePath = null;\n if (!search)\n freePath = path;\n else\n {\n long startNumber = 1;\n if (name.contains(\".\"))\n {\n String[] tokens = filename.split(\"\\\\.(?=[^\\\\.]+$)\");\n name = tokens[0];\n ext = \".\" + tokens[1];\n\n // TODO: limit length? Name could contain invalid number (too long number). Currently this case is handled by the exception handler...\n // TODO: Eventuell Länge limitieren? Sonst könnte eine ungültig lange Zahl dastehen!!! Wird aber eh von Overflow korrigiert und von Catch...\n// // check name for number\n Pattern p = Pattern.compile(\"(.*)-(\\\\d+)$\");\n Matcher m = p.matcher(name);\n if (m.find()) {\n name = m.group(1);\n try {\n startNumber = Long.valueOf(m.group(2));\n } catch (NumberFormatException e) {\n startNumber = 1;\n }\n }\n }\n\n while (true)\n {\n freePath = folder + name + \"-\" + startNumber + ext;\n if (canCreate(freePath))\n break;\n startNumber++;\n }\n }\n\n return freePath;\n }\n\n public static IFile createUnusedFile(String path, Boolean isHidden, String... namesThatAreNotAllowed)\n {\n String mimeType = ExtensionUtil.getMimeType(path);\n return getFileByPath(getUnusedFileName(path, namesThatAreNotAllowed), isHidden, true, mimeType);\n }\n\n public static IFile createNewFile(String path, Boolean isHidden)\n {\n if (exists(path))\n return null;\n String mimeType = ExtensionUtil.getMimeType(path);\n return getFileByPath(path, isHidden, true, mimeType);\n }\n\n public static IFile createNewFile(IFolder folder, String name, Boolean isHidden)\n {\n String path = folder.getFolder().getPath() + \"/\" + name;\n return createNewFile(path, isHidden);\n }\n\n public static IFile createFolder(IFile folder, String name)\n {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || folder.getType() == StorageDefinitions.FileType.File)\n {\n File f = new File(folder.getPath(), name);\n if (!f.exists())\n f.mkdir();\n if (f != null && f.exists() && f.isDirectory())\n return new StorageFile(f, null, false);\n return null;\n }\n\n // 2) check if file is on sd card storage\n // first 3 parts are an empty string, the storage and the id of the storage\n ArrayList<String> parts = new ArrayList(Arrays.asList(folder.getPath().split(\"/\")));\n parts.add(name);\n return DocumentUtil.createFolderFromPath(parts, null, true);\n }\n\n // -------------------\n // No Media File\n // -------------------\n\n public static boolean hasNoMediaFile(File fileFolder, boolean recursive)\n {\n IFile folder = getFileByPath(fileFolder.getAbsolutePath(), null, false, null);\n return hasNoMediaFile(folder, recursive);\n }\n\n// public static boolean hasNoMediaFile(String folderPath, boolean recursive)\n// {\n// IFile folder = getFileByPath(folderPath, null, false, null);\n// return hasNoMediaFile(folder, recursive);\n// }\n\n public static boolean hasNoMediaFile(String folderPath, boolean recursive)\n {\n if (folderPath == null)\n return false;\n\n // for checking if file exists, we can always use the File class with the path\n File noMediaFile = new File(folderPath + \"/.nomedia\");\n return noMediaFile.exists();\n }\n\n public static boolean hasNoMediaFile(IFile folder, boolean recursive)\n {\n if (folder == null)\n return false;\n\n // for checking if file exists, we can always use the File class with the path\n File noMediaFile = new File(folder.getPath() + \"/.nomedia\");\n return noMediaFile.exists();\n\n// boolean hasNoMediaFile = getFileByPath(folder.getPath() + \"/.nomedia\", null, false, null) != null;\n// if (!hasNoMediaFile && recursive)\n// {\n// IFile parent = folder.getParent();\n// while (parent != null && !hasNoMediaFile)\n// {\n// hasNoMediaFile = hasNoMediaFile(parent, false);\n// parent = parent.getParent();\n// }\n// }\n// return hasNoMediaFile;\n }\n\n// public static boolean hasNoMediaFile(String folderPath)\n// {\n// return hasNoMediaFile(new File(folderPath));\n// }\n\n// public static boolean hasNoMediaFile(File folder)\n// {\n// if (!folder.isDirectory())\n// return false;\n//\n// File[] files = folder.listFiles();\n// if (files == null || files.length == 0)\n// return false;\n//\n// // 1) prüfen ob der Ordner ein .nomedia folder enthält\n// File fNoMedia = new File(folder, \".nomedia\");\n// if (!Arrays.asList(files).contains(fNoMedia))\n// return false;\n//\n// return true;\n// }\n\n// public static boolean hasNoMediaFileRecursive(IFile folder)\n// {\n// return hasNoMediaFileRecursive(folder.getPath());\n// }\n//\n// public static boolean hasNoMediaFileRecursive(String folderPath)\n// {\n// return hasNoMediaFileRecursive(new File(folderPath));\n// }\n//\n// public static boolean hasNoMediaFileRecursive(File folder)\n// {\n// boolean hasNoMediaFile = hasNoMediaFile(folder);\n// if (hasNoMediaFile)\n// return true;\n//\n// if (folder.getParentFile() != null)\n// return hasNoMediaFileRecursive(folder.getParentFile());\n// else\n// return false;\n// }\n\n\n}", "public class MediaStoreFileData\n{\n private StorageDefinitions.MediaType mType;\n\n // MediaStore\n private Uri mUri;\n private long mId;\n private String mName;\n private String mData;\n private long mDateTaken;\n private long mDateModified;\n private String mMimeType;\n private int mWidth;\n private int mHeight;\n private Double mLatitude;\n private Double mLongitude;\n private int mRotation;\n\n public MediaStoreFileData(StorageDefinitions.MediaType type, Uri uri, long id, String name, String data, long dateTaken, long dateModified, String mimeType, int width, int height, Double latitude, Double longitude, int rotation)\n {\n mType = type;\n mUri = uri;\n mId = id;\n mName = name;\n mData = data;\n mDateTaken = dateTaken;\n mDateModified = dateModified;\n mMimeType = mimeType;\n mWidth = width;\n mHeight = height;\n mLatitude = latitude;\n mLongitude = longitude;\n mRotation = rotation;\n }\n\n public MediaStoreFileData(MediaStoreFileData source)\n {\n mType = source.mType;\n mUri = source.mUri;\n mId = source.mId;\n mName = source.mName;\n mData = source.mData;\n mDateTaken = source.mDateTaken;\n mDateModified = source.mDateModified;\n mMimeType = source.mMimeType;\n mWidth = source.mWidth;\n mHeight = source.mHeight;\n mLatitude = source.mLatitude;\n mLongitude = source.mLongitude;\n mRotation = source.mRotation;\n }\n\n public MediaStoreFileData copy()\n {\n return new MediaStoreFileData(this);\n }\n\n // --------------------------------\n // Getter\n // --------------------------------\n \n public StorageDefinitions.MediaType getType()\n {\n return mType;\n }\n\n public Uri getUri()\n {\n return mUri;\n }\n\n public long getId()\n {\n return mId;\n }\n\n public String getName()\n {\n return mName;\n }\n\n public String getData()\n {\n return mData;\n }\n\n public long getDateTaken()\n {\n return mDateTaken;\n }\n\n public long getDateModified()\n {\n return mDateModified;\n }\n\n public String getMimeType()\n {\n return mMimeType;\n }\n\n public int getWidth()\n {\n return mWidth;\n }\n\n public int getHeight()\n {\n return mHeight;\n }\n\n public Double getLatitude()\n {\n return mLatitude;\n }\n\n public Double getLongitude()\n {\n return mLongitude;\n }\n\n public int getOrientation()\n {\n return ExifFileUtil.convertNormalisedDegreesToExif(mRotation);\n }\n\n public int getRotation()\n {\n return mRotation;\n }\n\n public Location getLocation()\n {\n if (mLatitude == null || mLongitude == null)\n return null;\n\n Location location = new Location(\"\");\n location.setLatitude(mLatitude);\n location.setLongitude(mLongitude);\n return location;\n }\n\n // --------------------------------\n // Setter (Updater)\n // --------------------------------\n\n public void updateUri(Uri uri)\n {\n mUri = uri;\n mId = Long.valueOf(uri.getLastPathSegment());\n }\n\n public void updateRotation(int degrees)\n {\n mRotation = degrees;\n }\n\n public void updateOrientation(int orientation)\n {\n mRotation = ExifFileUtil.convertExifOrientationToDegrees(orientation);\n }\n\n public void updateName(String path, String name)\n {\n mData = path;\n mName = name;\n }\n\n public void updateSize(int w, int h)\n {\n mWidth = w;\n mHeight = h;\n }\n\n}", "public interface IFile<T> extends IMediaStoreFile<T>, IHideableFile<T>\n{\n boolean isFile();\n StorageDefinitions.FileType getType();\n StorageDefinitions.MediaType getMediaType();\n String getMimeType();\n String getExtension();\n\n T getWrapped();\n void setWrapped(T file);\n IFile<T> getParent();\n\n // Properties\n String getName();\n String getPath();\n Uri getUri();\n long created();\n long lastModified();\n boolean setLastModified(long time);\n long size();\n Location location();\n Integer rotation();\n\n // File operations\n boolean exists();\n boolean delete(StorageDefinitions.MediaStoreUpdateType mediaStoreUpdateType);\n boolean renameName(String newName, StorageDefinitions.MediaStoreUpdateType mediaStoreUpdateType);\n boolean move(IFile target, StorageDefinitions.MediaStoreUpdateType mediaStoreUpdateType, Boolean isTargetHidden);\n boolean copy(IFile target, StorageDefinitions.MediaStoreUpdateType mediaStoreUpdateType, Boolean isTargetHidden);\n\n // Streams\n byte[] getBytes() throws IOException;\n InputStream getInputStream() throws IOException;\n OutputStream getOutputStream() throws IOException;\n\n}", "public interface IFolder<T> extends IMediaStoreFolder<T>\n{\n StorageDefinitions.FolderType getType();\n String getName();\n Integer getCount();\n IFolderData getFolderData();\n\n List<StorageDefinitions.MediaType> getFileTypes();\n\n StorageDefinitions.FolderStatus getStatus();\n void reset();\n IFile<T> getFolder();\n void loadFiles(List<StorageDefinitions.MediaType> typeToContain, boolean loadFromMediaStore, StorageDefinitions.FileSortingType limitSortingType, StorageDefinitions.FileSortingOrder limitSortingOrder, Integer limit, Long minDate, Long maxDate, MediaStoreUtil.DateType dateType);\n List<IFile<T>> loadFilesInternally(boolean loadFromMediaStore, StorageDefinitions.FileSortingType limitSortingType, StorageDefinitions.FileSortingOrder limitSortingOrder, Integer limit, Long minDate, Long maxDate, MediaStoreUtil.DateType dateType);\n void initFiles(List<StorageDefinitions.MediaType> typeToContain, List<IFile<T>> files);\n List<IFile<T>> getFiles();\n\n boolean addFile(IFile file);\n boolean removeFile(IFile file);\n boolean removeFile(String path);\n}" ]
import com.michaelflisar.storagemanager.StorageManager; import com.michaelflisar.storagemanager.StoragePermissionManager; import com.michaelflisar.storagemanager.StorageUtil; import com.michaelflisar.storagemanager.data.MediaStoreFileData; import com.michaelflisar.storagemanager.interfaces.IFile; import com.michaelflisar.storagemanager.interfaces.IFolder; import java.io.File; import java.util.ArrayList;
package com.michaelflisar.storagemanager.utils; /** * Created by flisar on 10.03.2016. */ public class StorageDebugUtil { public static final ArrayList<String> debugAvailableInfos() { ArrayList<String> messages = new ArrayList<>(); // 1) add paths
IFolder sdCard = StorageManager.get().getSDCardRoot();
0
caligin/tinytypes
jackson/src/main/java/tech/anima/tinytypes/jackson/TinyTypesDeserializers.java
[ "public class BooleanTinyTypes implements MetaTinyType<BooleanTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n\n return BooleanTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public boolean isMetaOf(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return BooleanTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public String stringify(BooleanTinyType value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return Boolean.toString(value.value);\n }\n\n @Override\n public <U extends BooleanTinyType> U newInstance(Class<U> type, Object value) {\n if (type == null || !includes(type)) {\n throw new IllegalArgumentException(String.format(\"Not a %s: %s\", BooleanTinyType.class.getSimpleName(), type == null ? \"null\" : type.getCanonicalName()));\n }\n try {\n return type.getConstructor(boolean.class).newInstance(value);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new RuntimeException(ex);\n } catch (InstantiationException | NoSuchMethodException | ClassCastException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n\n @Override\n public <U extends BooleanTinyType> U fromString(Class<U> type, String value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return newInstance(type, Boolean.parseBoolean(value));\n }\n\n}", "public class ByteTinyTypes implements MetaTinyType<ByteTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return ByteTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public boolean isMetaOf(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return ByteTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public String stringify(ByteTinyType value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return Byte.toString(value.value);\n }\n\n @Override\n public <U extends ByteTinyType> U newInstance(Class<U> type, Object value) {\n if (type == null || !includes(type)) {\n throw new IllegalArgumentException(String.format(\"Not a %s: %s\", ByteTinyType.class.getSimpleName(), type == null ? \"null\" : type.getCanonicalName()));\n }\n try {\n return type.getConstructor(byte.class).newInstance(value);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new RuntimeException(ex);\n } catch (InstantiationException | NoSuchMethodException | ClassCastException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n\n @Override\n public <U extends ByteTinyType> U fromString(Class<U> type, String value) {\n return newInstance(type, Byte.parseByte(value));\n }\n\n}", "public class IntTinyTypes implements MetaTinyType<IntTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return IntTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public boolean isMetaOf(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return IntTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public String stringify(IntTinyType value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return Integer.toString(value.value);\n }\n\n @Override\n public <U extends IntTinyType> U newInstance(Class<U> type, Object value) {\n if (type == null || !includes(type)) {\n throw new IllegalArgumentException(String.format(\"Not a %s: %s\", IntTinyType.class.getSimpleName(), type == null ? \"null\" : type.getCanonicalName()));\n }\n try {\n return type.getConstructor(int.class).newInstance(value);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new RuntimeException(ex);\n } catch (InstantiationException | NoSuchMethodException | ClassCastException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n\n @Override\n public <U extends IntTinyType> U fromString(Class<U> type, String value) {\n return newInstance(type, Integer.parseInt(value));\n }\n\n}", "public class LongTinyTypes implements MetaTinyType<LongTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return LongTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public boolean isMetaOf(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return LongTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public String stringify(LongTinyType value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return Long.toString(value.value);\n }\n\n @Override\n public <U extends LongTinyType> U newInstance(Class<U> type, Object value) {\n if (type == null || !includes(type)) {\n throw new IllegalArgumentException(String.format(\"Not a %s: %s\", LongTinyType.class.getSimpleName(), type == null ? \"null\" : type.getCanonicalName()));\n }\n try {\n return type.getConstructor(long.class).newInstance(value);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new RuntimeException(ex);\n } catch (InstantiationException | NoSuchMethodException | ClassCastException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n\n @Override\n public <U extends LongTinyType> U fromString(Class<U> type, String value) {\n return newInstance(type, Long.parseLong(value));\n }\n\n}", "public abstract class MetaTinyTypes {\n\n public static final MetaTinyType[] metas = new MetaTinyType[]{\n new StringTinyTypes(),\n new BooleanTinyTypes(),\n new ByteTinyTypes(),\n new ShortTinyTypes(),\n new IntTinyTypes(),\n new LongTinyTypes()\n };\n\n /**\n * Provides a type-specific Meta class for the given TinyType.\n *\n * @param <T> the TinyType class type\n * @param candidate the TinyType class to obtain a Meta for\n * @return a Meta implementation suitable for the candidate\n * @throws IllegalArgumentException for null or a non-TinyType\n */\n public static <T> MetaTinyType<T> metaFor(Class<?> candidate) {\n for (MetaTinyType meta : metas) {\n if (meta.isMetaOf(candidate)) {\n return meta;\n }\n }\n throw new IllegalArgumentException(String.format(\"not a tinytype: %s\", candidate == null ? \"null\" : candidate.getCanonicalName()));\n }\n\n /**\n * Checks whether a class is a TinyType. A class is considered a TinyType if\n * is a direct ancestor of a tech.anima.tinytypes.*TinyType, is not abstract\n * and provides a ctor matching super.\n *\n * @param candidate the class to be checked\n * @return true if the candidate is a TinyType, false otherwise.\n */\n public static boolean isTinyType(Class<?> candidate) {\n for (MetaTinyType meta : metas) {\n if (meta.isMetaOf(candidate)) {\n return true;\n }\n }\n return false;\n }\n\n}", "public class ShortTinyTypes implements MetaTinyType<ShortTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return ShortTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public boolean isMetaOf(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return ShortTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public String stringify(ShortTinyType value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return Short.toString(value.value);\n }\n\n @Override\n public <U extends ShortTinyType> U newInstance(Class<U> type, Object value) {\n if (type == null || !includes(type)) {\n throw new IllegalArgumentException(String.format(\"Not a %s: %s\", ShortTinyType.class.getSimpleName(), type == null ? \"null\" : type.getCanonicalName()));\n }\n try {\n return type.getConstructor(short.class).newInstance((short) value);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new RuntimeException(ex);\n } catch (InstantiationException | NoSuchMethodException | ClassCastException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n\n @Override\n public <U extends ShortTinyType> U fromString(Class<U> type, String value) {\n return newInstance(type, Short.parseShort(value));\n }\n\n}", "public class StringTinyTypes implements MetaTinyType<StringTinyType> {\n\n public static boolean includes(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return StringTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public boolean isMetaOf(Class<?> candidate) {\n if (candidate == null) {\n return false;\n }\n return StringTinyType.class.equals(candidate.getSuperclass());\n }\n\n @Override\n public String stringify(StringTinyType value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n return value.value;\n }\n\n @Override\n public <U extends StringTinyType> U newInstance(Class<U> type, Object value) {\n if (value == null) {\n throw new IllegalArgumentException(\"value must be not null\");\n }\n if (type == null || !includes(type)) {\n throw new IllegalArgumentException(String.format(\"Not a %s: %s\", StringTinyType.class.getSimpleName(), type == null ? \"null\" : type.getCanonicalName()));\n }\n try {\n return type.getConstructor(String.class).newInstance(value);\n } catch (IllegalAccessException | InvocationTargetException ex) {\n throw new RuntimeException(ex);\n } catch (InstantiationException | NoSuchMethodException | ClassCastException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n\n @Override\n public <U extends StringTinyType> U fromString(Class<U> type, String value) {\n return newInstance(type, value);\n }\n\n}" ]
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.deser.Deserializers; import java.io.IOException; import tech.anima.tinytypes.meta.BooleanTinyTypes; import tech.anima.tinytypes.meta.ByteTinyTypes; import tech.anima.tinytypes.meta.IntTinyTypes; import tech.anima.tinytypes.meta.LongTinyTypes; import tech.anima.tinytypes.meta.MetaTinyTypes; import tech.anima.tinytypes.meta.ShortTinyTypes; import tech.anima.tinytypes.meta.StringTinyTypes;
package tech.anima.tinytypes.jackson; public class TinyTypesDeserializers extends Deserializers.Base { @Override public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException { Class<?> candidateTT = type.getRawClass(); if (MetaTinyTypes.isTinyType(candidateTT)) { return new TinyTypesDeserializer(candidateTT); } return null; } public static class TinyTypesDeserializer<T> extends JsonDeserializer<T> { private final Class<T> type; public TinyTypesDeserializer(Class<T> type) { if (type == null || !MetaTinyTypes.isTinyType(type)) { throw new IllegalArgumentException(String.format("not a tinytype: %s", type == null ? "null" : type.getCanonicalName())); } this.type = type; } @Override public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { return MetaTinyTypes.metaFor(type).newInstance(type, extractValue(p)); } private Object extractValue(JsonParser p) throws IOException { if (StringTinyTypes.includes(type)) { return p.getText(); } if (BooleanTinyTypes.includes(type)) { return p.getBooleanValue(); } if (ByteTinyTypes.includes(type)) { return p.getByteValue(); } if (ShortTinyTypes.includes(type)) { return p.getShortValue(); } if (IntTinyTypes.includes(type)) { return p.getIntValue(); }
if (LongTinyTypes.includes(type)) {
3
cettia/asity
example-spring-webflux5/src/main/java/io/cettia/asity/example/spring/webflux5/EchoServer.java
[ "@FunctionalInterface\npublic interface Action<T> {\n\n /**\n * Some action is taken.\n */\n void on(T object);\n\n}", "public class AsityHandlerFunction implements HandlerFunction<ServerResponse> {\n\n private Actions<ServerHttpExchange> httpActions = new ConcurrentActions<>();\n\n @Override\n public Mono<ServerResponse> handle(ServerRequest request) {\n SpringWebFluxServerHttpExchange http = new SpringWebFluxServerHttpExchange(request);\n return http.getServerResponse().doFinally($ -> httpActions.fire(http));\n }\n\n /**\n * Registers an action to be called when {@link ServerHttpExchange} is available.\n */\n public AsityHandlerFunction onhttp(Action<ServerHttpExchange> action) {\n httpActions.add(action);\n return this;\n }\n\n}", "public class AsityWebSocketHandler implements WebSocketHandler {\n\n private Actions<ServerWebSocket> wsActions = new ConcurrentActions<>();\n\n @Override\n public Mono<Void> handle(WebSocketSession session) {\n SpringWebFluxServerWebSocket ws = new SpringWebFluxServerWebSocket(session);\n return ws.getMono().doOnSubscribe($ -> wsActions.fire(ws));\n }\n\n /**\n * Registers an action to be called when {@link ServerWebSocket} is available.\n */\n public AsityWebSocketHandler onwebsocket(Action<ServerWebSocket> action) {\n wsActions.add(action);\n return this;\n }\n\n}", "public class HttpEchoServer implements Action<ServerHttpExchange> {\n @Override\n public void on(ServerHttpExchange http) {\n // Reads request URI, method and headers\n System.out.println(http.method() + \" \" + http.uri());\n http.headerNames().stream().forEach(name -> System.out.println(name + \": \" + String.join(\", \", http.headers(name))));\n\n // Writes response status code and headers\n http.setStatus(HttpStatus.OK).setHeader(\"content-type\", http.header(\"content-type\"));\n\n // Reads a chunk from request body and writes it to response body\n http.onchunk((String chunk) -> http.write(chunk)).readAsText();\n // If request body is binary,\n // http.onchunk((ByteBuffer binary) -> http.write(binary)).readAsBinary();\n\n // Ends response if request ends\n http.onend((Void v) -> http.end());\n\n // Exception handling\n http.onerror((Throwable t) -> t.printStackTrace()).onclose((Void v) -> System.out.println(\"disconnected\"));\n }\n}", "public interface ServerHttpExchange {\n\n /**\n * The request URI.\n */\n String uri();\n\n /**\n * The name of the request method.\n */\n HttpMethod method();\n\n /**\n * The names of the request headers. HTTP header is not case-sensitive but\n * {@link Set} is case-sensitive.\n */\n Set<String> headerNames();\n\n /**\n * Returns the first request header associated with the given name.\n */\n String header(String name);\n\n /**\n * Returns the request headers associated with the given name or empty list\n * if no header is found.\n */\n List<String> headers(String name);\n\n /**\n * Reads the request body. If the request header, {@code content-type},\n * starts with {@code text/}, the body is read as text, and if not, as\n * binary. In case of text body, the charset is also determined by the same\n * header. If it's not given, {@code ISO-8859-1} is used by default.\n * <p/>\n * The read data will be passed to event handlers as {@link String} if it's\n * text and {@link ByteBuffer} if it's binary attached through\n * {@link ServerHttpExchange#onchunk(Action)}.\n * <p/>\n * This method should be called after adding\n * {@link ServerHttpExchange#onchunk(Action)},\n * {@link ServerHttpExchange#onbody(Action)}, and\n * {@link ServerHttpExchange#onend(Action)} and has no side effect if called\n * more than once.\n */\n ServerHttpExchange read();\n\n /**\n * Reads the request body as text. The charset is determined by the request\n * header, {@code content-type}. If it's not given, {@code ISO-8859-1} is\n * used by default.\n * <p/>\n * The read data will be passed to event handlers as {@link String} attached\n * through {@link ServerHttpExchange#onchunk(Action)}.\n * <p/>\n * This method should be called after adding\n * {@link ServerHttpExchange#onchunk(Action)},\n * {@link ServerHttpExchange#onbody(Action)}, and\n * {@link ServerHttpExchange#onend(Action)} and has no side effect if called\n * more than once.\n */\n ServerHttpExchange readAsText();\n\n /**\n * Reads the request body as text using the given charset.\n * <p/>\n * The read data will be passed to event handlers as {@link String} attached\n * through {@link ServerHttpExchange#onchunk(Action)}.\n * <p/>\n * This method should be called after adding\n * {@link ServerHttpExchange#onchunk(Action)},\n * {@link ServerHttpExchange#onbody(Action)}, and\n * {@link ServerHttpExchange#onend(Action)} and has no side effect if called\n * more than once.\n */\n ServerHttpExchange readAsText(String charsetName);\n\n /**\n * Reads the request body as binary.\n * <p/>\n * The read data will be passed to event handlers as {@link ByteBuffer}\n * attached through {@link ServerHttpExchange#onchunk(Action)}.\n * <p/>\n * This method should be called after adding\n * {@link ServerHttpExchange#onchunk(Action)},\n * {@link ServerHttpExchange#onbody(Action)}, and\n * {@link ServerHttpExchange#onend(Action)} and has no side effect if called\n * more than once.\n */\n ServerHttpExchange readAsBinary();\n\n /**\n * Attaches an action to be called with a chunk from the request body.\n *\n * @param <T> The allowed data type. {@link String} for text body and {@link ByteBuffer} for\n * binary body.\n */\n <T> ServerHttpExchange onchunk(Action<T> action);\n\n /**\n * Attaches an action to be called when the request is fully read. It's the\n * end of the request.\n */\n ServerHttpExchange onend(Action<Void> action);\n\n /**\n * Attaches an action to be called with the whole request body. If the body is quite big, it\n * may drain memory quickly. If that's the case, use {@link ServerHttpExchange#onchunk(Action)}\n * and {@link ServerHttpExchange#onend(Action)}.\n *\n * @param <T> The allowed data type. {@link String} for text body and {@link ByteBuffer} for\n * binary body.\n */\n <T> ServerHttpExchange onbody(Action<T> action);\n\n /**\n * Sets the HTTP status for the response.\n */\n ServerHttpExchange setStatus(HttpStatus status);\n\n /**\n * Sets a response header.\n */\n ServerHttpExchange setHeader(String name, String value);\n\n /**\n * Sets response headers.\n */\n ServerHttpExchange setHeader(String name, Iterable<String> value);\n\n /**\n * Writes a text chunk to the response body using the charset from the\n * response header, {@code content-type}. If it's not given,\n * {@code ISO-8859-1} is used.\n */\n ServerHttpExchange write(String data);\n\n /**\n * Writes a text chunk to the response body using the given charset.\n */\n ServerHttpExchange write(String data, String charsetName);\n\n /**\n * Writes a binary chunk to the response body.\n */\n ServerHttpExchange write(ByteBuffer byteBuffer);\n\n /**\n * Completes the response. Each exchange's response must be finished with\n * this method when done. It's the end of the response. This method has no\n * side effect if called more than once.\n */\n ServerHttpExchange end();\n\n /**\n * Writes a text chunk to the response body using the charset from the\n * response header, {@code content-type} and completes the response through\n * {@link ServerHttpExchange#end()}.\n */\n ServerHttpExchange end(String data);\n\n /**\n * Writes a text chunk to the response body using the given charset and\n * completes the response through {@link ServerHttpExchange#end()}.\n */\n ServerHttpExchange end(String data, String charsetName);\n\n /**\n * Writes a binary chunk to the response body and completes the response\n * through {@link ServerHttpExchange#end()}.\n */\n ServerHttpExchange end(ByteBuffer byteBuffer);\n\n /**\n * Attaches an action to be called when the response is fully written. It's\n * the end of the response.\n */\n ServerHttpExchange onfinish(Action<Void> action);\n\n /**\n * Attaches an action to be called when this exchange gets an error. It may\n * or may not accompany the closure of connection. Its exact behavior is\n * platform-specific and error created by the platform is propagated.\n */\n ServerHttpExchange onerror(Action<Throwable> action);\n\n /**\n * Attaches an action when the underlying connection is aborted for some\n * reason like an error. After this event, all the other event will be\n * disabled.\n */\n ServerHttpExchange onclose(Action<Void> action);\n\n /**\n * Returns the provider-specific component.\n */\n <T> T unwrap(Class<T> clazz);\n\n}", "public interface ServerWebSocket {\n\n /**\n * The URI used to connect.\n */\n String uri();\n\n /**\n * The names of the handshake request headers. HTTP header is not case-sensitive\n * but {@link Set} is case-sensitive.\n */\n Set<String> headerNames();\n\n /**\n * Returns the first handshake request header associated with the given name.\n */\n String header(String name);\n\n /**\n * Returns the handshake request headers associated with the given name or empty list\n * if no header is found.\n */\n List<String> headers(String name);\n\n /**\n * Closes the connection. This method has no side effect if called more than\n * once.\n */\n void close();\n\n /**\n * Sends a text frame through the connection.\n */\n ServerWebSocket send(String data);\n\n /**\n * Sends a binary frame through the connection.\n */\n ServerWebSocket send(ByteBuffer byteBuffer);\n\n /**\n * Attaches an action for the text frame.\n */\n ServerWebSocket ontext(Action<String> action);\n\n /**\n * Attaches an action for the binary frame.\n */\n ServerWebSocket onbinary(Action<ByteBuffer> action);\n\n /**\n * Attaches an action for the close event. After this event, the instance\n * shouldn't be used and all the other events will be disabled.\n */\n ServerWebSocket onclose(Action<Void> action);\n\n /**\n * Attaches an action to handle error from various things. Its exact\n * behavior is platform-specific and error created by the platform is\n * propagated.\n */\n ServerWebSocket onerror(Action<Throwable> action);\n\n /**\n * Returns the provider-specific component.\n */\n <T> T unwrap(Class<T> clazz);\n\n}" ]
import io.cettia.asity.action.Action; import io.cettia.asity.bridge.spring.webflux5.AsityHandlerFunction; import io.cettia.asity.bridge.spring.webflux5.AsityWebSocketHandler; import io.cettia.asity.example.echo.HttpEchoServer; import io.cettia.asity.example.echo.WebSocketEchoServer; import io.cettia.asity.http.ServerHttpExchange; import io.cettia.asity.websocket.ServerWebSocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.config.EnableWebFlux; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; import java.util.LinkedHashMap; import java.util.Map; import static org.springframework.web.reactive.function.server.RequestPredicates.headers; import static org.springframework.web.reactive.function.server.RequestPredicates.path;
/* * Copyright 2018 the original author or authors. * * 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 io.cettia.asity.example.spring.webflux5; @SpringBootApplication @EnableWebFlux public class EchoServer { @Bean public Action<ServerHttpExchange> httpAction() { return new HttpEchoServer(); } @Bean public Action<ServerWebSocket> wsAction() { return new WebSocketEchoServer(); } @Bean public RouterFunction<ServerResponse> httpMapping() {
AsityHandlerFunction asityHandlerFunction = new AsityHandlerFunction().onhttp(httpAction());
1
Ohohcakester/Any-Angle-Pathfinding
src/main/TextOutputVisualisation.java
[ "public class GridAndGoals {\r\n\tpublic final GridGraph gridGraph;\r\n\tpublic final StartGoalPoints startGoalPoints;\r\n\t\r\n\tpublic GridAndGoals(GridGraph gridGraph, StartGoalPoints startGoalPoints) {\r\n\t\tthis.gridGraph = gridGraph;\r\n\t\tthis.startGoalPoints = startGoalPoints;\r\n\t}\r\n\t\r\n\tpublic GridAndGoals(GridGraph gridGraph, int sx, int sy, int ex, int ey) {\r\n\t\tthis.gridGraph = gridGraph;\r\n\t\tthis.startGoalPoints = new StartGoalPoints(sx, sy, ex, ey);\r\n\t}\r\n\r\n public final void validateStartAndEndPoints() {\r\n int sx = startGoalPoints.sx;\r\n int sy = startGoalPoints.sy;\r\n int ex = startGoalPoints.ex;\r\n int ey = startGoalPoints.ey;\r\n int sizeX = gridGraph.sizeX;\r\n int sizeY = gridGraph.sizeY;\r\n\r\n ArrayList<String> issues = new ArrayList<>();\r\n\r\n if (sx < 0) issues.add(\"sx < 0\");\r\n if (sy < 0) issues.add(\"sy < 0\");\r\n if (sx > sizeX) issues.add(\"sx > sizeX\");\r\n if (sy > sizeY) issues.add(\"sy > sizeY\");\r\n\r\n if (ex < 0) issues.add(\"ex < 0\");\r\n if (ey < 0) issues.add(\"ey < 0\");\r\n if (ex > sizeX) issues.add(\"ex > sizeX\");\r\n if (ey > sizeY) issues.add(\"ey > sizeY\");\r\n \r\n if (issues.size() > 0) {\r\n throw new UnsupportedOperationException(\"INVALID START/END POINTS: \" + issues);\r\n }\r\n }\r\n}\r", "public class GridGraph {\n\n private boolean[] tiles; // Flattened 2D Array\n public final int sizeX;\n public final int sizeY;\n public final int sizeXplusOne;\n\n private static final float SQRT_TWO = (float)Math.sqrt(2);\n private static final double SQRT_TWO_DOUBLE = Math.sqrt(2);\n private static final float SQRT_TWO_MINUS_ONE = (float)(Math.sqrt(2) - 1);\n \n public GridGraph(int sizeX, int sizeY) {\n this.sizeX = sizeX;\n this.sizeY = sizeY;\n this.sizeXplusOne = sizeX+1;\n \n tiles = new boolean[sizeY*sizeX];\n }\n \n public final void setBlocked(int x, int y, boolean value) {\n tiles[sizeX*y + x] = value;\n }\n \n public final void trySetBlocked(int x, int y, boolean value) {\n if (isValidBlock(x,y))\n tiles[sizeX*y + x] = value;\n }\n \n public final boolean isBlocked(int x, int y) {\n if (x >= sizeX || y >= sizeY) return true;\n if (x < 0 || y < 0) return true;\n return tiles[sizeX*y + x];\n }\n \n public final boolean isBlockedRaw(int x, int y) {\n return tiles[sizeX*y + x];\n }\n \n public final boolean isValidCoordinate(int x, int y) {\n return (x <= sizeX && y <= sizeY &&\n x >= 0 && y >= 0);\n }\n \n public final boolean isValidBlock(int x, int y) {\n return (x < sizeX && y < sizeY &&\n x >= 0 && y >= 0);\n }\n\n public final int toOneDimIndex(int x, int y) {\n return y*sizeXplusOne + x;\n }\n \n public final int toTwoDimX(int index) {\n return index%sizeXplusOne;\n }\n \n public final int toTwoDimY(int index) {\n return index/sizeXplusOne;\n }\n\n public final boolean isUnblockedCoordinate(int x, int y) {\n return !topRightOfBlockedTile(x,y) ||\n !topLeftOfBlockedTile(x,y) ||\n !bottomRightOfBlockedTile(x,y) ||\n !bottomLeftOfBlockedTile(x,y);\n }\n \n public final boolean topRightOfBlockedTile(int x, int y) {\n return isBlocked(x-1, y-1);\n }\n\n public final boolean topLeftOfBlockedTile(int x, int y) {\n return isBlocked(x, y-1);\n }\n\n public final boolean bottomRightOfBlockedTile(int x, int y) {\n return isBlocked(x-1, y);\n }\n\n public final boolean bottomLeftOfBlockedTile(int x, int y) {\n return isBlocked(x, y);\n }\n \n /**\n * x1,y1,x2,y2 refer to the top left corner of the tile.\n * @param x1 Condition: x1 between 0 and sizeX inclusive.\n * @param y1 Condition: y1 between 0 and sizeY inclusive.\n * @param x2 Condition: x2 between 0 and sizeX inclusive.\n * @param y2 Condition: y2 between 0 and sizeY inclusive.\n * @return distance.\n */\n public final float distance(int x1, int y1, int x2, int y2) {\n int xDiff = x2 - x1;\n int yDiff = y2 - y1;\n \n if (yDiff == 0) {\n return (float)Math.abs(xDiff);\n }\n if (xDiff == 0) {\n return (float)Math.abs(yDiff);\n }\n if (xDiff == yDiff || xDiff == -yDiff) {\n return SQRT_TWO*Math.abs(xDiff);\n }\n \n int squareDistance = xDiff*xDiff + yDiff*yDiff;\n \n return (float)Math.sqrt(squareDistance);\n }\n \n public final double distance_double(int x1, int y1, int x2, int y2) {\n int xDiff = x2 - x1;\n int yDiff = y2 - y1;\n \n if (xDiff == 0) {\n return Math.abs(yDiff);\n }\n if (yDiff == 0) {\n return Math.abs(xDiff);\n }\n if (xDiff == yDiff || xDiff == -yDiff) {\n return SQRT_TWO_DOUBLE*Math.abs(xDiff);\n }\n \n int squareDistance = xDiff*xDiff + yDiff*yDiff;\n \n return Math.sqrt(squareDistance);\n }\n \n /**\n * Octile distance:\n * min(dx,dy)*sqrt(2) + (max(dx,dy)-min(dx,dy))\n * = min(dx,dy)*(sqrt(2)-1) + max(dx,dy)\n */\n public final float octileDistance(int x1, int y1, int x2, int y2) {\n int dx = x1-x2;\n int dy = y1-y2;\n if (dx<0) dx = -dx;\n if (dy<0) dy = -dy;\n \n int min = dx;\n int max = dy;\n if (dy < dx) {\n min = dy;\n max = dx;\n }\n \n return min*SQRT_TWO_MINUS_ONE + max;\n }\n\n /**\n * Same as lineOfSight, but only works with a vertex and its 8 immediate neighbours.\n * Also (x1,y1) != (x2,y2)\n */\n public final boolean neighbourLineOfSight(int x1, int y1, int x2, int y2) {\n if (x1 == x2) {\n if (y1 > y2) {\n return !isBlocked(x1,y2) || !isBlocked(x1-1,y2);\n } else { // y1 < y2\n return !isBlocked(x1,y1) || !isBlocked(x1-1,y1);\n }\n } else if (x1 < x2) {\n if (y1 == y2) {\n return !isBlocked(x1,y1) || !isBlocked(x1,y1-1);\n } else if (y1 < y2) {\n return !isBlocked(x1,y1);\n } else { // y2 < y1\n return !isBlocked(x1,y2);\n }\n } else { // x2 < x1\n if (y1 == y2) {\n return !isBlocked(x2,y1) || !isBlocked(x2,y1-1);\n } else if (y1 < y2) {\n return !isBlocked(x2,y1);\n } else { // y2 < y1\n return !isBlocked(x2,y2);\n }\n }\n }\n\n\n /**\n * @return true iff there is line-of-sight from (x1,y1) to (x2,y2).\n */\n public final boolean lineOfSight(int x1, int y1, int x2, int y2) {\n int dy = y2 - y1;\n int dx = x2 - x1;\n\n int f = 0;\n\n int signY = 1;\n int signX = 1;\n int offsetX = 0;\n int offsetY = 0;\n \n if (dy < 0) {\n dy *= -1;\n signY = -1;\n offsetY = -1;\n }\n if (dx < 0) {\n dx *= -1;\n signX = -1;\n offsetX = -1;\n }\n \n if (dx >= dy) {\n while (x1 != x2) {\n f += dy;\n if (f >= dx) {\n if (isBlocked(x1 + offsetX, y1 + offsetY))\n return false;\n y1 += signY;\n f -= dx;\n }\n if (f != 0 && isBlocked(x1 + offsetX, y1 + offsetY))\n return false;\n if (dy == 0 && isBlocked(x1 + offsetX, y1) && isBlocked(x1 + offsetX, y1 - 1))\n return false;\n \n x1 += signX;\n }\n }\n else {\n while (y1 != y2) {\n f += dx;\n if (f >= dy) {\n if (isBlocked(x1 + offsetX, y1 + offsetY))\n return false;\n x1 += signX;\n f -= dy;\n }\n if (f != 0 && isBlocked(x1 + offsetX, y1 + offsetY))\n return false;\n if (dx == 0 && isBlocked(x1, y1 + offsetY) && isBlocked(x1 - 1, y1 + offsetY))\n return false;\n \n y1 += signY;\n }\n }\n return true;\n }\n\n public final Point findFirstBlockedTile(int x1, int y1, int dx, int dy) {\n \n int f = 0;\n\n int signY = 1;\n int signX = 1;\n int offsetX = 0;\n int offsetY = 0;\n \n if (dy < 0) {\n dy *= -1;\n signY = -1;\n offsetY = -1;\n }\n if (dx < 0) {\n dx *= -1;\n signX = -1;\n offsetX = -1;\n }\n \n if (dx >= dy) {\n while (true) {\n f += dy;\n if (f >= dx) {\n if (isBlocked(x1 + offsetX, y1 + offsetY))\n return new Point(x1+offsetX, y1+offsetY);\n y1 += signY;\n f -= dx;\n }\n if (f != 0 && isBlocked(x1 + offsetX, y1 + offsetY))\n return new Point(x1+offsetX, y1+offsetY);\n if (dy == 0 && isBlocked(x1 + offsetX, y1) && isBlocked(x1 + offsetX, y1 - 1))\n return new Point(x1+offsetX, -1);\n \n x1 += signX;\n }\n }\n else {\n while (true) {\n f += dx;\n if (f >= dy) {\n if (isBlocked(x1 + offsetX, y1 + offsetY))\n return new Point(x1+offsetX, y1+offsetY);\n x1 += signX;\n f -= dy;\n }\n if (f != 0 && isBlocked(x1 + offsetX, y1 + offsetY))\n return new Point(x1+offsetX, y1+offsetY);\n if (dx == 0 && isBlocked(x1, y1 + offsetY) && isBlocked(x1 - 1, y1 + offsetY))\n return new Point(-1, y1+offsetY);\n \n y1 += signY;\n }\n }\n //return null;\n }\n \n\n /**\n * Used by Accelerated A* and MazeAnalysis.\n * leftRange is the number of blocks you can move left before hitting a blocked tile.\n * downRange is the number of blocks you can move down before hitting a blocked tile.\n * For blocked tiles, leftRange, downRange are both -1.\n * \n * How to use the maxRange property:\n * \n * x,y is the starting point.\n * k is the number of tiles diagonally up-right of the starting point.\n * int i = x-y+sizeY;\n * int j = Math.min(x, y);\n * return maxRange[i][j + k] - k;\n */\n public final int[][] computeMaxDownLeftRanges() {\n int[][] downRange = new int[sizeY+1][sizeX+1];\n int[][] leftRange = new int[sizeY+1][sizeX+1];\n\n for (int y=0; y<sizeY; ++y) {\n if (isBlocked(0, y))\n leftRange[y][0] = -1;\n else \n leftRange[y][0] = 0;\n \n for (int x=1; x<sizeX; ++x) {\n if (isBlocked(x, y)) {\n leftRange[y][x] = -1;\n } else {\n leftRange[y][x] = leftRange[y][x-1] + 1;\n }\n }\n }\n\n for (int x=0; x<sizeX; ++x) {\n if (isBlocked(x, 0))\n downRange[0][x] = -1;\n else \n downRange[0][x] = 0;\n \n for (int y=1; y<sizeY; ++y) {\n if (isBlocked(x, y)) {\n downRange[y][x] = -1;\n } else {\n downRange[y][x] = downRange[y-1][x] + 1;\n }\n }\n }\n \n for (int x=0; x<sizeX+1; ++x) {\n downRange[sizeY][x] = -1;\n leftRange[sizeY][x] = -1;\n }\n \n for (int y=0; y<sizeY; ++y) {\n downRange[y][sizeX] = -1;\n leftRange[y][sizeX] = -1;\n }\n \n int[][] maxRanges = new int[sizeX+sizeY+1][];\n int maxSize = Math.min(sizeX, sizeY) + 1;\n for (int i=0; i<maxRanges.length; ++i) {\n int currSize = Math.min(i+1, maxRanges.length-i);\n if (maxSize < currSize)\n currSize = maxSize;\n maxRanges[i] = new int[currSize];\n \n int currX = i - sizeY;\n if (currX < 0) currX = 0;\n int currY = currX - i + sizeY;\n for (int j=0; j<maxRanges[i].length; ++j) {\n maxRanges[i][j] = Math.min(downRange[currY][currX], leftRange[currY][currX]);\n currY++;\n currX++;\n }\n \n }\n return maxRanges;\n }\n \n /**\n * @return the percentage of blocked tiles as compared to the total grid size.\n */\n public final float getPercentageBlocked() {\n return (float)getNumBlocked() / (sizeX*sizeY);\n }\n \n /**\n * @return the number of blocked tiles in the grid.\n */\n public final int getNumBlocked() {\n int nBlocked = 0;\n for (int y=0; y<sizeY; y++) {\n for (int x=0; x<sizeX; x++) {\n if (isBlocked(x, y)) {\n nBlocked++;\n }\n }\n }\n return nBlocked;\n }\n\n public final boolean isOuterCorner(int x, int y) {\n boolean a = isBlocked(x-1, y-1);\n boolean b = isBlocked(x, y-1);\n boolean c = isBlocked(x, y);\n boolean d = isBlocked(x-1, y);\n \n return ((!a && !c) || (!d && !b)) && (a || b || c || d);\n \n /* NOTE\n * ___ ___\n * | |||||\n * |...X'''| <-- this is considered a corner in the above definition\n * |||||___|\n * \n * The definition below excludes the above case.\n */\n \n /*int results = 0;\n if(a)results++;\n if(b)results++;\n if(c)results++;\n if(d)results++;\n return (results == 1);*/\n }\n\n /**\n * Checks whether the path (x1,y1),(x2,y2),(x3,y3) is taut.\n */\n public final boolean isTaut(int x1, int y1, int x2, int y2, int x3, int y3) {\n if (x1 < x2) {\n if (y1 < y2) {\n return isTautFromBottomLeft(x1, y1, x2, y2, x3, y3);\n } else if (y2 < y1) {\n return isTautFromTopLeft(x1, y1, x2, y2, x3, y3);\n } else { // y1 == y2\n return isTautFromLeft(x1, y1, x2, y2, x3, y3);\n }\n } else if (x2 < x1) {\n if (y1 < y2) {\n return isTautFromBottomRight(x1, y1, x2, y2, x3, y3);\n } else if (y2 < y1) {\n return isTautFromTopRight(x1, y1, x2, y2, x3, y3);\n } else { // y1 == y2\n return isTautFromRight(x1, y1, x2, y2, x3, y3);\n }\n } else { // x2 == x1\n if (y1 < y2) {\n return isTautFromBottom(x1, y1, x2, y2, x3, y3);\n } else if (y2 < y1) {\n return isTautFromTop(x1, y1, x2, y2, x3, y3);\n } else { // y1 == y2\n throw new UnsupportedOperationException(\"v == u?\");\n }\n }\n }\n\n \n private final boolean isTautFromBottomLeft(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (x3 < x2 || y3 < y2) return false;\n \n int compareGradients = (y2-y1)*(x3-x2) - (y3-y2)*(x2-x1); // m1 - m2\n if (compareGradients < 0) { // m1 < m2\n return bottomRightOfBlockedTile(x2, y2);\n } else if (compareGradients > 0) { // m1 > m2\n return topLeftOfBlockedTile(x2, y2);\n } else { // m1 == m2\n return true;\n }\n }\n\n \n private final boolean isTautFromTopLeft(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (x3 < x2 || y3 > y2) return false;\n \n int compareGradients = (y2-y1)*(x3-x2) - (y3-y2)*(x2-x1); // m1 - m2\n if (compareGradients < 0) { // m1 < m2\n return bottomLeftOfBlockedTile(x2, y2);\n } else if (compareGradients > 0) { // m1 > m2\n return topRightOfBlockedTile(x2, y2);\n } else { // m1 == m2\n return true;\n }\n }\n \n private final boolean isTautFromBottomRight(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (x3 > x2 || y3 < y2) return false;\n int compareGradients = (y2-y1)*(x3-x2) - (y3-y2)*(x2-x1); // m1 - m2\n if (compareGradients < 0) { // m1 < m2\n return topRightOfBlockedTile(x2, y2);\n } else if (compareGradients > 0) { // m1 > m2\n return bottomLeftOfBlockedTile(x2, y2);\n } else { // m1 == m2\n return true;\n }\n }\n\n \n private final boolean isTautFromTopRight(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (x3 > x2 || y3 > y2) return false;\n \n int compareGradients = (y2-y1)*(x3-x2) - (y3-y2)*(x2-x1); // m1 - m2\n if (compareGradients < 0) { // m1 < m2\n return topLeftOfBlockedTile(x2, y2);\n } else if (compareGradients > 0) { // m1 > m2\n return bottomRightOfBlockedTile(x2, y2);\n } else { // m1 == m2\n return true;\n }\n }\n\n \n private final boolean isTautFromLeft(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (x3 < x2) return false;\n \n int dy = y3 - y2;\n if (dy < 0) { // y3 < y2\n return topRightOfBlockedTile(x2, y2);\n } else if (dy > 0) { // y3 > y2\n return bottomRightOfBlockedTile(x2, y2);\n } else { // y3 == y2\n return true;\n }\n }\n\n private final boolean isTautFromRight(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (x3 > x2) return false;\n \n int dy = y3 - y2;\n if (dy < 0) { // y3 < y2\n return topLeftOfBlockedTile(x2, y2);\n } else if (dy > 0) { // y3 > y2\n return bottomLeftOfBlockedTile(x2, y2);\n } else { // y3 == y2\n return true;\n }\n }\n\n private final boolean isTautFromBottom(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (y3 < y2) return false;\n \n int dx = x3 - x2;\n if (dx < 0) { // x3 < x2\n return topRightOfBlockedTile(x2, y2);\n } else if (dx > 0) { // x3 > x2\n return topLeftOfBlockedTile(x2, y2);\n } else { // x3 == x2\n return true;\n }\n }\n\n private final boolean isTautFromTop(int x1, int y1, int x2, int y2, int x3,\n int y3) {\n if (y3 > y2) return false;\n \n int dx = x3 - x2;\n if (dx < 0) { // x3 < x2\n return bottomRightOfBlockedTile(x2, y2);\n } else if (dx > 0) { // x3 > x2\n return bottomLeftOfBlockedTile(x2, y2);\n } else { // x3 == x2\n return true;\n }\n }\n}", "public class StartGoalPoints {\r\n\tpublic final int sx, sy, ex, ey;\r\n\r\n\tpublic StartGoalPoints(int sx, int sy, int ex, int ey) {\r\n\t\tthis.sx = sx;\r\n\t\tthis.sy = sy;\r\n\t\tthis.ex = ex;\r\n\t\tthis.ey = ey;\r\n\t};\r\n}\r", "public class GraphImporter {\n private GridGraph gridGraph;\n \n private GraphImporter(String filepath) {\n boolean[][] result = null;\n\n File file = new File(filepath);\n try {\n FileReader fileReader = new FileReader(file);\n Scanner sc = new Scanner(fileReader);\n int x = sc.nextInt();\n int y = sc.nextInt();\n result = new boolean[y][];\n for (int i=0; i<y; i++) {\n result[i] = new boolean[x];\n for (int j=0; j<x; j++) {\n result[i][j] = (sc.nextInt() != 0);\n }\n }\n sc.close();\n } catch (FileNotFoundException e) {\n System.out.println(\"File \" + filepath + \" not found\");\n }\n /* Commented out because of Unreachable Catch Clause warning.\n catch (IOException e) {\n e.printStackTrace();\n }*/\n \n create(result); \n }\n\n private void create(boolean[][] result) {\n gridGraph = new GridGraph(result[0].length, result.length);\n for (int y=0;y<result.length;y++) {\n for (int x=0;x<result[0].length;x++) {\n gridGraph.setBlocked(x, y, result[y][x]);\n }\n }\n }\n\n private void createDoubleSize(boolean[][] result) {\n int size = 2;\n \n gridGraph = new GridGraph(result[0].length*size, result.length*size);\n for (int y=0;y<result.length*size;y++) {\n for (int x=0;x<result[0].length*size;x++) {\n gridGraph.setBlocked(x, y, result[y/size][x/size]);\n }\n }\n }\n \n private GridGraph retrieve() {\n return gridGraph;\n }\n \n public static ArrayList<String> getAllMazeNames() {\n ArrayList<String> mazeNames = new ArrayList<>();\n \n String path = AnyAnglePathfinding.PATH_MAZEDATA + \"/\";\n File dir = new File(path);\n File[] files = dir.listFiles();\n for (File file : files) {\n mazeNames.add(file.getName());\n }\n \n return mazeNames;\n }\n\n /**\n * Import a graph from a file in the predefinedgrids directory.\n * Look into the GraphImporter documentation for details on how to create a grid file.\n */\n public static GridGraph importGraphFromFile(String filename) {\n String filepath = AnyAnglePathfinding.PATH_GRAPHIMPORT + filename;\n return importGraphFromFilePath(filepath);\n }\n\n /**\n * Import a graph from a file in the predefinedgrids directory,\n * and also set the start and goal points.\n */\n public static GridAndGoals importGraphFromFile(String filename, int sx, int sy, int ex, int ey) {\n String filepath = AnyAnglePathfinding.PATH_GRAPHIMPORT + filename;\n return importGraphFromFilePath(filepath, sx, sy, ex, ey);\n }\n\n /**\n * Import a graph from a file in the AnyAnglePathfinding directory.\n */\n public static GridGraph importGraphFromFilePath(String filepath) {\n GridGraph gridGraph;\n GraphImporter graphImporter = new GraphImporter(filepath);\n gridGraph = graphImporter.retrieve();\n return gridGraph;\n }\n\n /**\n * Import a graph from a file in the AnyAnglePathfinding directory,\n * and also set the start and goal points.\n */\n public static GridAndGoals importGraphFromFilePath(String filepath, int sx, int sy, int ex, int ey) {\n GridGraph gridGraph = GraphImporter.importGraphFromFilePath(filepath);\n return new GridAndGoals(gridGraph, sx, sy, ex, ey);\n }\n\n public static GridAndGoals loadStoredMaze(String mazeName, String problemName) {\n String filepath = AnyAnglePathfinding.PATH_MAZEDATA + mazeName + \"/maze.txt\";\n TwoPoint tp = readProblem(problemName);\n return importGraphFromFilePath(filepath, tp.p1.x, tp.p1.y, tp.p2.x, tp.p2.y);\n }\n \n public static GridGraph loadStoredMaze(String mazeName) {\n String filepath = AnyAnglePathfinding.PATH_MAZEDATA + mazeName + \"/maze.txt\";\n return importGraphFromFilePath(filepath);\n }\n\n public static ArrayList<TwoPoint> loadStoredMazeProblems(String mazeName) {\n String path = AnyAnglePathfinding.PATH_MAZEDATA + mazeName + \"/\";\n File dir = new File(path);\n File[] files = dir.listFiles((file, name) -> name.endsWith(\".problem\"));\n \n ArrayList<TwoPoint> list = new ArrayList<>(files.length);\n for (File file : files) {\n TwoPoint tp = readProblem(file);\n list.add(tp);\n }\n return list;\n }\n\n public static ArrayList<StartEndPointData> loadStoredMazeProblemData(String mazeName) {\n String path = AnyAnglePathfinding.PATH_MAZEDATA + mazeName + \"/\";\n File dir = new File(path);\n File[] files = dir.listFiles((file, name) -> name.endsWith(\".problem\"));\n \n ArrayList<StartEndPointData> list = new ArrayList<>(files.length);\n for (File file : files) {\n TwoPoint tp = readProblem(file);\n String sp = readFile(file).get(\"shortestPathLength\");\n double shortestPath = Double.parseDouble(sp);\n list.add(new StartEndPointData(tp.p1, tp.p2, shortestPath));\n }\n return list;\n }\n \n private static TwoPoint readProblem(File file) {\n String s = file.getName();\n s = s.substring(0, s.lastIndexOf('.')); // remove extension\n return readProblem(s);\n }\n\n private static TwoPoint readProblem(String problemName) {\n String[] args = problemName.split(\"[-_]\");\n \n if (args.length != 4)\n throw new UnsupportedOperationException(\"Invalid problem name: \" + problemName);\n return new TwoPoint(\n Integer.parseInt(args[0]),\n Integer.parseInt(args[1]),\n Integer.parseInt(args[2]),\n Integer.parseInt(args[3])\n );\n }\n \n private static HashMap<String, String> readFile(File file) {\n HashMap<String,String> dict = new HashMap<>();\n try {\n FileReader fr = new FileReader(file);\n BufferedReader br = new BufferedReader(fr);\n String s = br.readLine();\n while (s != null) {\n put(dict, s);\n s = br.readLine();\n }\n \n } catch (IOException e) {\n e.printStackTrace();\n }\n \n return dict;\n }\n \n private static void put(HashMap<String,String> dict, String input) {\n String[] args = input.split(\":\", 2);\n dict.put(args[0].trim(), args[1].trim());\n }\n}", "public class SnapshotItem {\n private static HashMap<SnapshotItem,SnapshotItem> cached;\n public final Integer[] path;\n public final Color color;\n \n private SnapshotItem(Integer[] path, Color color) {\n this.path = path;\n this.color = color;\n }\n \n public static SnapshotItem generate(Integer[] path, Color color) {\n return getCached(new SnapshotItem(path, color));\n }\n \n public static SnapshotItem generate(Integer[] path) {\n return getCached(new SnapshotItem(path, null));\n }\n \n public static void clearCached() {\n if (cached == null) return;\n cached.clear();\n cached = null;\n }\n \n private static SnapshotItem getCached(SnapshotItem item) {\n if (cached == null) {\n cached = new HashMap<>();\n }\n SnapshotItem get = cached.get(item);\n if (get == null) {\n cached.put(item, item);\n return item;\n } else { \n return get;\n } \n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((color == null) ? 0 : color.hashCode());\n result = prime * result + path[0];\n result = prime * result + Arrays.hashCode(path);\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n SnapshotItem other = (SnapshotItem) obj;\n if (color == null) {\n if (other.color != null)\n return false;\n } else if (!color.equals(other.color))\n return false;\n if (!Arrays.equals(path, other.path))\n return false;\n return true;\n }\n}", "public class DrawCanvas extends JPanel {\n\n // DRAWING CONFIGURATION\n private static final int MAX_RES = 700;\n \n private static final Color UNBLOCKEDTILE_COLOR = Color.WHITE;\n private static final Color BLOCKEDTILE_COLOR = new Color(127,127,127);\n \n private static final Color STARTPOINT_COLOR = new Color(0,160,0);\n private static final Color ENDPOINT_COLOR = Color.YELLOW;\n // DRAWING CONFIGURATION - END\n \n public final int resY;\n public final int resX;\n \n private BufferedImage cachedGridGraphImage;\n private final Drawer gridGraphDrawer;\n private Drawer gridLineDrawer;\n private Drawer gridPointDrawer;\n private Drawer startEndPointDrawer;\n protected final GridGraph gridGraph;\n \n public DrawCanvas(GridGraph gridGraph, GridLineSet gridLineSet) {\n super();\n int sizeX = gridGraph.sizeX;\n int sizeY = gridGraph.sizeY;\n if (sizeX < sizeY) {\n resY = MAX_RES;\n resX = resY*sizeX/sizeY;\n } else {\n resX = MAX_RES;\n resY = resX*sizeY/sizeX;\n }\n \n setPreferredSize(new Dimension(resX,resY));\n \n this.gridGraph = gridGraph;\n gridGraphDrawer = new GridGraphDrawer(gridGraph, resX, resY);\n if (gridLineSet != null) {\n gridLineDrawer = new GridLineDrawer(gridGraph, gridLineSet, resX, resY);\n }\n }\n \n public DrawCanvas(GridGraph gridGraph) {\n this(gridGraph, null);\n }\n\n public void setStartAndEnd(int sx, int sy, int ex, int ey) {\n GridPointSet gridPointSet = new GridPointSet();\n gridPointSet.addPoint(sx, sy, STARTPOINT_COLOR);\n gridPointSet.addPoint(ex, ey, ENDPOINT_COLOR);\n startEndPointDrawer = new VariableSizePointDrawer(gridGraph,\n gridPointSet, resX, resY, 1.3f);\n }\n \n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n \n clearToColor(g);\n \n if (cachedGridGraphImage == null) {\n cachedGridGraphImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);\n Graphics g2 = cachedGridGraphImage.getGraphics();\n g2.setColor(BLOCKEDTILE_COLOR);\n gridGraphDrawer.draw(g2);\n }\n g.drawImage(cachedGridGraphImage, 0, 0, this);\n \n \n if (gridLineDrawer != null) {\n gridLineDrawer.draw(g);\n }\n if (gridPointDrawer != null) {\n gridPointDrawer.draw(g);\n }\n if (startEndPointDrawer != null) {\n startEndPointDrawer.draw(g);\n }\n }\n \n private void clearToColor(Graphics g) {\n g.setColor(UNBLOCKEDTILE_COLOR);\n g.fillRect(0,0,resX,resY);\n }\n \n \n public void changeSet(GridLineSet gridLineSet, GridPointSet gridPointSet) {\n gridLineDrawer = new GridLineDrawer(gridGraph, gridLineSet, resX, resY);\n gridPointDrawer = new GridPointDrawer(gridGraph, gridPointSet, resX, resY);\n repaint();\n }\n \n public void changeSet(GridPointSet gridPointSet) {\n gridPointDrawer = new GridPointDrawer(gridGraph, gridPointSet, resX, resY);\n repaint();\n }\n\n public void changeSet(GridLineSet gridLineSet) {\n gridLineDrawer = new GridLineDrawer(gridGraph, gridLineSet, resX, resY);\n repaint();\n }\n \n}", "public class GridLineSet {\n\n private ArrayList<Line> lineList;\n private ArrayList<FractionLine> fractionLineList;\n\n public class Line {\n public final Color color;\n public final int x1;\n public final int y1;\n public final int x2;\n public final int y2;\n\n public Line(int x1, int y1, int x2, int y2, Color color) {\n this.color = color;\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n }\n \n public class FractionLine {\n public final Color color;\n public final Fraction x1;\n public final Fraction y1;\n public final Fraction x2;\n public final Fraction y2;\n\n public FractionLine(Fraction x1, Fraction y1, Fraction x2,\n Fraction y2, Color color) {\n this.color = color;\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n }\n \n public GridLineSet() {\n lineList = new ArrayList<>();\n fractionLineList = new ArrayList<>();\n }\n\n public void addLine(int x1, int y1, int x2, int y2, Color color) {\n lineList.add(new Line(x1,y1,x2,y2,color));\n }\n\n public void addLine(Fraction x1, Fraction y1, Fraction x2, Fraction y2, Color color) {\n fractionLineList.add(new FractionLine(x1,y1,x2,y2,color));\n }\n \n public Collection<Line> getLineList() {\n return lineList;\n }\n \n public Collection<FractionLine> getFractionLineList() {\n return fractionLineList;\n }\n}", "public class GridObjects {\n private static final Color POINT_COLOR = new Color(0,64,255);\n private static final Color LINE_COLOR = Color.RED;\n \n \n public final GridLineSet gridLineSet;\n public final GridPointSet gridPointSet;\n\n public GridObjects(GridLineSet gridLineSet, GridPointSet gridPointSet) {\n this.gridLineSet = gridLineSet;\n this.gridPointSet = gridPointSet;\n }\n \n private GridObjects() {\n this.gridLineSet = null;\n this.gridPointSet = null;\n }\n\n public static GridObjects nullObject() {\n return new GridObjects();\n }\n \n public boolean isNull() {\n return gridLineSet == null && gridPointSet == null;\n }\n \n /**\n * Convert a snapshot of an algorithm into a GridObjects instance.\n */\n public static GridObjects create(List<SnapshotItem> snapshot) {\n GridLineSet gridLineSet = new GridLineSet();\n GridPointSet gridPointSet = new GridPointSet();\n \n for (SnapshotItem item : snapshot) {\n Integer[] path = item.path;\n Color color = item.color;\n if (path.length == 4) {\n gridLineSet.addLine(path[0], path[1], path[2], path[3], or(LINE_COLOR,color));\n } else if (path.length == 2) {\n gridPointSet.addPoint(path[0], path[1], or(POINT_COLOR,color));\n } else if (path.length == 7) {\n // y, xLn, xLd, xRn, xRd, px, py\n Fraction y = new Fraction (path[0]);\n Fraction xL = new Fraction(path[1], path[2]);\n Fraction xR = new Fraction(path[3], path[4]);\n Fraction xMid = xR.minus(xL).multiplyDivide(1, 2).plus(xL);\n Fraction px = new Fraction (path[5]);\n Fraction py = new Fraction (path[6]);\n gridLineSet.addLine(px, py, xL, y, or(Color.CYAN,color));\n //gridLineSet.addLine(px, py, xMid, y, or(Color.CYAN,color));\n gridLineSet.addLine(px, py, xR, y, or(Color.CYAN,color));\n gridLineSet.addLine(xL, y, xR, y, or(LINE_COLOR,color));\n gridPointSet.addPoint(path[5], path[6], or(Color.BLUE,color));\n } else if (path.length == 5) {\n Fraction y = new Fraction (path[0]);\n Fraction xL = new Fraction(path[1], path[2]);\n Fraction xR = new Fraction(path[3], path[4]);\n gridLineSet.addLine(xL, y, xR, y, or(Color.GREEN,color));\n }\n }\n return new GridObjects(gridLineSet,gridPointSet);\n }\n\n private static Color or(Color color, Color original) {\n return (original==null?color:original);\n }\n \n \n}" ]
import grid.GridAndGoals; import grid.GridGraph; import grid.StartGoalPoints; import java.awt.Color; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import uiandio.GraphImporter; import algorithms.datatypes.SnapshotItem; import draw.DrawCanvas; import draw.GridLineSet; import draw.GridObjects;
package main; public class TextOutputVisualisation { public static void run() { loadDefault(); //loadFromFile("anyacont2b.txt"); } private static void loadFromFile(String mazeFileName) { String textData = readStandardInput();
GridGraph gridGraph = GraphImporter.importGraphFromFile(mazeFileName);
3
ls1110924/ImmerseMode
immerse/src/main/java/com/yunxian/immerse/impl/TlSbNNbImmerseMode.java
[ "public final class ImmerseConfiguration {\n\n final ImmerseType mImmerseTypeInKK;\n final ImmerseType mImmerseTypeInL;\n\n public final boolean lightStatusBar;\n public final boolean coverCompatMask;\n public final int coverMaskColor;\n\n private ImmerseConfiguration(@NonNull ImmerseType immerseTypeInKK,\n @NonNull ImmerseType immerseTypeInL,\n Builder builder) {\n this.mImmerseTypeInKK = immerseTypeInKK;\n this.mImmerseTypeInL = immerseTypeInL;\n\n this.lightStatusBar = builder.lightStatusBar;\n this.coverCompatMask = builder.coverCompatMask;\n this.coverMaskColor = builder.coverMaskColor;\n }\n\n public static final int NORMAL = 1;\n public static final int TRANSLUCENT = 2;\n public static final int TRANSPARENT = 3;\n\n public static class Builder {\n\n @IntDef({NORMAL, TRANSLUCENT})\n @Retention(RetentionPolicy.SOURCE)\n private @interface ImmerseConfigType4KK {\n }\n\n @IntDef({NORMAL, TRANSLUCENT, TRANSPARENT})\n @Retention(RetentionPolicy.SOURCE)\n private @interface ImmerseConfigType4L {\n }\n\n private int mStatusBarModeInKK = NORMAL;\n private int mNavigationBarModeInKK = NORMAL;\n private boolean mFullScreenInKK = false;\n private boolean mAdjustResizeInKK = false;\n\n private int mStatusBarModeInL = NORMAL;\n private int mNavigationBarModeInL = NORMAL;\n private boolean mFullScreenInL = false;\n private boolean mAdjustResizeInL = false;\n\n private boolean lightStatusBar = false;\n private boolean coverCompatMask = false;\n private int coverMaskColor = Color.parseColor(\"#7F000000\");\n\n public Builder() {\n }\n\n public Builder setStatusBarModeInKK(@ImmerseConfigType4KK int statusBarModeInKK) {\n this.mStatusBarModeInKK = statusBarModeInKK;\n return this;\n }\n\n public Builder setNavigationBarModeInKK(@ImmerseConfigType4KK int navigationBarModeInKK) {\n this.mNavigationBarModeInKK = navigationBarModeInKK;\n return this;\n }\n\n public Builder setFullScreenInKK(boolean fullScreenInKK) {\n this.mFullScreenInKK = fullScreenInKK;\n return this;\n }\n\n public Builder setAdjustResizeInKK(boolean adjustResizeInKK) {\n this.mAdjustResizeInKK = adjustResizeInKK;\n return this;\n }\n\n public Builder setStatusBarModeInL(@ImmerseConfigType4L int statusBarModeInL) {\n this.mStatusBarModeInL = statusBarModeInL;\n return this;\n }\n\n public Builder setNavigationBarModeInL(@ImmerseConfigType4L int navigationBarModeInL) {\n this.mNavigationBarModeInL = navigationBarModeInL;\n return this;\n }\n\n public Builder setFullScreenInL(boolean fullScreenInL) {\n this.mFullScreenInL = fullScreenInL;\n return this;\n }\n\n public Builder setAdjustResizeInL(boolean adjustResizeInL) {\n this.mAdjustResizeInL = adjustResizeInL;\n return this;\n }\n\n public Builder setLightStatusBar(boolean lightStatusBar) {\n this.lightStatusBar = lightStatusBar;\n return this;\n }\n\n /**\n * 是否在状态栏上叠加一层蒙版,仅限大于等于5.0,小于6.0的系统<br>\n * 因为5.0可以设置白色状态栏,6.0才可以修改状态栏图标颜色。<br>\n * 在这两个版本之间,如果设置了浅色的状态栏,最好叠加一层半透明蒙版,负责图标可能看不清楚\n *\n * @param coverCompatMask true为叠加一层蒙版,false不叠加\n */\n public Builder setCoverCompatMask(boolean coverCompatMask) {\n this.coverCompatMask = coverCompatMask;\n return this;\n }\n\n public Builder setCoverMaskColor(@ColorInt int color) {\n this.coverMaskColor = color;\n return this;\n }\n\n public ImmerseConfiguration build() {\n ImmerseType immerseTypeInKK;\n ImmerseType immerseTypeInL;\n\n if (mStatusBarModeInKK == TRANSLUCENT && mFullScreenInKK && mAdjustResizeInKK) {\n immerseTypeInKK = ImmerseType.TLSB_NNB_FC_AR;\n } else if (mStatusBarModeInKK == TRANSLUCENT && mNavigationBarModeInKK == TRANSLUCENT) {\n immerseTypeInKK = mFullScreenInKK ? ImmerseType.TLSB_TLNB_FC : ImmerseType.TLSB_TLNB;\n } else if (mStatusBarModeInKK == TRANSLUCENT) {\n immerseTypeInKK = mFullScreenInKK ? ImmerseType.TLSB_NNB_FC : ImmerseType.TLSB_NNB;\n } else {\n immerseTypeInKK = ImmerseType.NSB_NNB;\n }\n\n if (mStatusBarModeInL == TRANSLUCENT && mFullScreenInL && mAdjustResizeInL) {\n immerseTypeInL = ImmerseType.TLSB_NNB_FC_AR;\n } else if (mStatusBarModeInL == TRANSPARENT && mFullScreenInL && mAdjustResizeInL) {\n immerseTypeInL = ImmerseType.TPSB_NNB_FC_AR;\n } else if (mStatusBarModeInL == TRANSPARENT && mNavigationBarModeInL == TRANSLUCENT) {\n immerseTypeInL = mFullScreenInL ? ImmerseType.TPSB_TLNB_FC : ImmerseType.TPSB_TLNB;\n } else if (mStatusBarModeInL == TRANSPARENT) {\n immerseTypeInL = mFullScreenInL ? ImmerseType.TPSB_NNB_FC : ImmerseType.TPSB_NNB;\n } else if (mStatusBarModeInL == TRANSLUCENT && mNavigationBarModeInL == TRANSLUCENT) {\n immerseTypeInL = mFullScreenInL ? ImmerseType.TLSB_TLNB_FC : ImmerseType.TLSB_TLNB;\n } else if (mStatusBarModeInL == TRANSLUCENT) {\n immerseTypeInL = mFullScreenInL ? ImmerseType.TLSB_NNB_FC : ImmerseType.TLSB_NNB;\n } else {\n immerseTypeInL = ImmerseType.NSB_NNB;\n }\n\n return new ImmerseConfiguration(immerseTypeInKK, immerseTypeInL, this);\n }\n\n }\n\n}", "public final class ImmerseGlobalConfig {\n\n private static ImmerseGlobalConfig INSTANCE = null;\n\n /**\n * 初始化方法,请在Application中调用该方法完成初始化\n *\n * @param context Context上下文对象\n */\n public static void init(@NonNull Context context) {\n if (INSTANCE == null) {\n synchronized (ImmerseGlobalConfig.class) {\n if (INSTANCE == null) {\n INSTANCE = new ImmerseGlobalConfig(context);\n }\n }\n }\n }\n\n /**\n * 获取单实例对象的方法\n *\n * @return Global单实例对象\n */\n @NonNull\n public static ImmerseGlobalConfig getInstance() throws IllegalStateException {\n if (INSTANCE == null) {\n throw new IllegalStateException(\"Plz init first on Application onCreate()!\");\n }\n return INSTANCE;\n }\n\n\n private static final String STATUS_BAR_HEIGHT_RES_NAME = \"status_bar_height\";\n\n private final int mStatusBarHeight;\n\n private ImmerseGlobalConfig(@NonNull Context context) {\n Resources res = context.getResources();\n mStatusBarHeight = ResourcesUtils.getDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME, \"android\", R.dimen.immerse_status_bar_height);\n }\n\n /**\n * 获取状态栏高度\n *\n * @return 状态栏高度\n */\n public int getStatusBarHeight() {\n return mStatusBarHeight;\n }\n}", "public final class DrawableUtils {\n\n private DrawableUtils() {\n throw new IllegalStateException(\"shouldn't init instance!\");\n }\n\n /**\n * 给View设置一个Background Drawable\n *\n * @param view View对象\n * @param drawable Drawable对象\n */\n @SuppressWarnings(\"Deprecated\")\n public static void setViewBackgroundDrawable(@Nullable View view, @Nullable Drawable drawable) {\n if (view == null) {\n return;\n }\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {\n view.setBackground(drawable);\n } else {\n view.setBackgroundDrawable(drawable);\n }\n }\n\n}", "public class ViewUtils {\n\n /**\n * 为DecorView对象设置或取消一些标志位集合\n *\n * @param decorView DecorView\n * @param on true为设置,false为取消\n * @param visibility {@link android.view.View#SYSTEM_UI_FLAG_FULLSCREEN}类标志位集合\n */\n private static void setSystemUiFlags(@NonNull View decorView, boolean on, int visibility) {\n int current = decorView.getSystemUiVisibility();\n if (on) {\n if ((current & visibility) != visibility) {\n decorView.setSystemUiVisibility(current | visibility);\n }\n } else {\n if ((current & visibility) != 0) {\n decorView.setSystemUiVisibility(current & ~visibility);\n }\n }\n }\n\n /**\n * 为DecorView对象增加标志位\n *\n * @param decorView DecorView\n * @param flags {@link android.view.View#SYSTEM_UI_FLAG_FULLSCREEN}类标志位集合\n */\n public static void addSystemUiFlags(@NonNull View decorView, int flags) {\n setSystemUiFlags(decorView, true, flags);\n }\n\n /**\n * 为DecorView对象取消标志位\n *\n * @param decorView DecorView\n * @param flags {@link android.view.View#SYSTEM_UI_FLAG_FULLSCREEN}类标志位集合\n */\n public static void clearSystemUiFlags(@NonNull View decorView, int flags) {\n setSystemUiFlags(decorView, false, flags);\n }\n\n}", "public final class WindowUtils {\n\n private WindowUtils() {\n throw new IllegalStateException(\"shouldn't init instance!\");\n }\n\n /**\n * 为Window对象设置或取消一些标志位集合\n *\n * @param window Window对象\n * @param on true为设置,false为取消\n * @param flags {@link android.view.WindowManager.LayoutParams}中的标志位集合\n */\n private static void setWindowFlags(@NonNull Window window, boolean on, int flags) {\n WindowManager.LayoutParams params = window.getAttributes();\n if (on) {\n if ((params.flags & flags) == 0) {\n params.flags |= flags;\n window.setAttributes(params);\n }\n } else {\n if ((params.flags & flags) != 0) {\n params.flags &= ~flags;\n window.setAttributes(params);\n }\n }\n }\n\n /**\n * 为Window对象增加标志位\n *\n * @param window Window对象\n * @param flags {@link android.view.WindowManager.LayoutParams}中的标志位集合\n */\n public static void addWindowFlags(@NonNull Window window, int flags) {\n setWindowFlags(window, true, flags);\n }\n\n /**\n * 为Window对象取消标志位\n *\n * @param window Window对象\n * @param flags {@link android.view.WindowManager.LayoutParams}中的标志位集合\n */\n public static void clearWindowFlags(@NonNull Window window, int flags) {\n setWindowFlags(window, false, flags);\n }\n\n}", "public class ConsumeInsetsFrameLayout extends FrameLayout {\n\n private boolean mConsumeInsets = false;\n\n private final Rect mTempInsets = new Rect();\n\n private final List<OnInsetsChangeListener> mOnInsetsChangeListeners = new ArrayList<>();\n\n public ConsumeInsetsFrameLayout(@NonNull Context context) {\n this(context, null);\n }\n\n public ConsumeInsetsFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public ConsumeInsetsFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n init(context, attrs, defStyleAttr, 0);\n }\n\n private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {\n TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.immerse_ConsumeInsetsLayout, defStyleAttr, defStyleRes);\n mConsumeInsets = a.getBoolean(R.styleable.immerse_ConsumeInsetsLayout_immerse_consumeInsets, false);\n a.recycle();\n }\n\n @Override\n protected boolean fitSystemWindows(Rect insets) {\n if (mConsumeInsets && SDK_INT >= KITKAT) {\n mTempInsets.left = insets.left;\n mTempInsets.right = insets.right;\n mTempInsets.top = insets.top;\n mTempInsets.bottom = insets.bottom;\n\n // Intentionally do not modify the bottom inset. For some reason,\n // if the bottom inset is modified, window resizing stops working.\n // maybe: insets.bottom has value(eg. Rect(0, 50 - 0, 597)) when keyboard is showing.\n insets.left = 0;\n insets.top = 0;\n insets.right = 0;\n\n for (OnInsetsChangeListener listener : mOnInsetsChangeListeners) {\n listener.onInsetsChanged(mTempInsets);\n }\n }\n return super.fitSystemWindows(insets);\n }\n\n /**\n * 设置是否消费Insets事件。\n * <p>沉浸Activity中包含EditText时,请设置为true,否则为false</p>\n * <p>一个Activity只包含一个fitSystemWindows为ture的控件,因此别的控件再行设置无效。\n * 需使用{@link OnInsetsChangeListener}进行监听</p>\n *\n * @param consumeInsets true为消费,否则不消费\n */\n public void setConsumeInsets(boolean consumeInsets) {\n if (mConsumeInsets != consumeInsets) {\n mConsumeInsets = consumeInsets;\n if (SDK_INT >= KITKAT) {\n setFitsSystemWindows(consumeInsets);\n }\n requestLayout();\n }\n }\n\n public void addOnInsetsChangeListener(@Nullable OnInsetsChangeListener listener) {\n if (listener != null && !mOnInsetsChangeListeners.contains(listener)) {\n mOnInsetsChangeListeners.add(listener);\n }\n }\n\n public void removeOnInsetsChangeListener(@Nullable OnInsetsChangeListener listener) {\n if (listener != null) {\n mOnInsetsChangeListeners.remove(listener);\n }\n }\n\n public interface OnInsetsChangeListener {\n\n void onInsetsChanged(Rect insets);\n\n }\n\n}" ]
import android.annotation.TargetApi; import android.app.Activity; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.view.Window; import androidx.annotation.ColorInt; import androidx.annotation.ColorRes; import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import com.yunxian.immerse.ImmerseConfiguration; import com.yunxian.immerse.R; import com.yunxian.immerse.manager.ImmerseGlobalConfig; import com.yunxian.immerse.utils.DrawableUtils; import com.yunxian.immerse.utils.ViewUtils; import com.yunxian.immerse.utils.WindowUtils; import com.yunxian.immerse.widget.ConsumeInsetsFrameLayout; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.KITKAT; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
package com.yunxian.immerse.impl; /** * 半透明状态栏普通导航栏 * <p>半透明状态栏支持到4.4及以上,普通导航栏着色支持到5.0及以上</p> * * @author AShuai * @email [email protected] * @date 17/1/31 下午2:42 */ @TargetApi(KITKAT) public class TlSbNNbImmerseMode extends AbsImmerseMode { private final View mCompatStatusBarView; public TlSbNNbImmerseMode(@NonNull Activity activity, @NonNull ImmerseConfiguration immerseConfiguration) { super(activity, immerseConfiguration); Window window = activity.getWindow(); WindowUtils.clearWindowFlags(window, FLAG_TRANSLUCENT_NAVIGATION); WindowUtils.addWindowFlags(window, FLAG_TRANSLUCENT_STATUS); if (immerseConfiguration.lightStatusBar && SDK_INT >= Build.VERSION_CODES.M) { ViewUtils.addSystemUiFlags(window.getDecorView(), View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); } mCompatStatusBarView = setupView(activity); } @Override public void setStatusColor(@ColorInt int color) { mCompatStatusBarView.setBackgroundColor(generateCompatStatusBarColor(color)); } @Override public void setStatusColorRes(@ColorRes int colorRes) { Activity activity = mActivityRef.get(); if (activity != null) { int color = ContextCompat.getColor(activity, colorRes); setStatusColor(color); } } @Override public boolean setStatusDrawable(@Nullable Drawable drawable) { DrawableUtils.setViewBackgroundDrawable(mCompatStatusBarView, drawable); return true; } @Override public boolean setStatusDrawableRes(@DrawableRes int drawableRes) { Activity activity = mActivityRef.get(); if (activity != null) { Drawable drawable = ContextCompat.getDrawable(activity, drawableRes); setStatusDrawable(drawable); } return true; } @Override public void setNavigationColor(@ColorInt int color) { Activity activity = mActivityRef.get(); if (activity != null && SDK_INT >= LOLLIPOP) { activity.getWindow().setNavigationBarColor(color); } } @Override public void setNavigationColorRes(@ColorRes int colorRes) { Activity activity = mActivityRef.get(); if (activity != null) { int color = ContextCompat.getColor(activity, colorRes); setNavigationColor(color); } } @Override public boolean setNavigationDrawable(@Nullable Drawable drawable) { return false; } @Override public boolean setNavigationDrawableRes(@DrawableRes int drawableRes) { return false; } @NonNull @Override public Rect getInsetsPadding() { return new Rect(0, 0, 0, 0); } @Override public void setOnInsetsChangeListener(boolean operation,
@Nullable ConsumeInsetsFrameLayout.OnInsetsChangeListener listener) {
5
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/OrgProviderUtils.java
[ "public static class Files implements FilesColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build();\n\n\tpublic static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME,\n\t\t\tCOMMENT, NODE_ID };\n\tpublic static final String DEFAULT_SORT = NAME + \" ASC\";\n\n\tpublic static String getId(Uri uri) {\n\t\treturn uri.getLastPathSegment();\n\t}\n\n\tpublic static String getFilename(Uri uri) {\n\t\treturn uri.getPathSegments().get(1);\n\t}\n\n\tpublic static Uri buildFilenameUri(String filename) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(filename)\n\t\t\t\t.appendPath(\"filename\").build();\n\t}\n\n\tpublic static Uri buildIdUri(Long fileId) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(fileId.toString()).build();\n\t}\n}", "public static class OrgData implements OrgDataColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build();\n\n\tpublic static final Uri CONTENT_URI_TODOS =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build();\n\tpublic static final String DEFAULT_SORT = ID + \" ASC\";\n\tpublic static final String NAME_SORT = NAME + \" ASC\";\n\tpublic static final String POSITION_SORT = POSITION + \" ASC\";\n\tpublic static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED,\n\t\t\tPARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY};\n\n\tpublic static String getId(Uri uri) {\n\t\treturn uri.getPathSegments().get(1);\n\t}\n\n\tpublic static Uri buildIdUri(String id) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(id).build();\n\t}\n\n\tpublic static Uri buildIdUri(Long id) {\n\t\treturn buildIdUri(id.toString());\n\t}\n\n\tpublic static Uri buildChildrenUri(String parentId) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(parentId).appendPath(\"children\").build();\n\t}\n\n\tpublic static Uri buildChildrenUri(long node_id) {\n\t\treturn buildChildrenUri(Long.toString(node_id));\n\t}\n}", "public static class Priorities implements PrioritiesColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build();\n}", "public static class Tags implements TagsColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build();\n}", "public static class Timestamps implements TimestampsColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build();\n\tpublic static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY};\n\n\tpublic static Uri buildIdUri(Long id) {\n\t\treturn CONTENT_URI.buildUpon().appendPath(id.toString()).build();\n\t}\n\n\tpublic static String getId(Uri uri) {\n\t\treturn uri.getLastPathSegment();\n\t}\n}", "public static class Todos implements TodosColumns {\n\tpublic static final Uri CONTENT_URI =\n\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build();\n\n\tpublic static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE};\n}" ]
import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.text.TextUtils; import com.matburt.mobileorg.orgdata.OrgContract.Files; import com.matburt.mobileorg.orgdata.OrgContract.OrgData; import com.matburt.mobileorg.orgdata.OrgContract.Priorities; import com.matburt.mobileorg.orgdata.OrgContract.Tags; import com.matburt.mobileorg.orgdata.OrgContract.Timestamps; import com.matburt.mobileorg.orgdata.OrgContract.Todos; import com.matburt.mobileorg.util.OrgFileNotFoundException; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List;
package com.matburt.mobileorg.orgdata; public class OrgProviderUtils { /** * * @param context * @return the list of nodes corresponding to a file */ public static List<OrgNode> getFileNodes(Context context){ return OrgProviderUtils.getOrgNodeChildren(-1, context.getContentResolver()); } public static ArrayList<String> getFilenames(ContentResolver resolver) { ArrayList<String> result = new ArrayList<String>(); Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS, null, null, Files.DEFAULT_SORT); cursor.moveToFirst(); while (!cursor.isAfterLast()) { OrgFile orgFile = new OrgFile(); try { orgFile.set(cursor); result.add(orgFile.filename); } catch (OrgFileNotFoundException e) {} cursor.moveToNext(); } cursor.close(); return result; } /** * Query the DB for the list of files * @param resolver * @return */ public static ArrayList<OrgFile> getFiles(ContentResolver resolver) { ArrayList<OrgFile> result = new ArrayList<>(); Cursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS, null, null, Files.DEFAULT_SORT); if(cursor == null) return result; cursor.moveToFirst(); while (!cursor.isAfterLast()) { OrgFile orgFile = new OrgFile(); try { orgFile.set(cursor); result.add(orgFile); } catch (OrgFileNotFoundException e) {} cursor.moveToNext(); } cursor.close(); return result; } public static String getNonNullString(Cursor cursor, int index){ String result = cursor.getString(index); return result!=null ? result : ""; } public static void addTodos(HashMap<String, Boolean> todos, ContentResolver resolver) { if(todos == null) return; for (String name : todos.keySet()) { ContentValues values = new ContentValues(); values.put(Todos.NAME, name); values.put(Todos.GROUP, 0); if (todos.get(name)) values.put(Todos.ISDONE, 1); try{ resolver.insert(Todos.CONTENT_URI, values); } catch (Exception e){ e.printStackTrace(); } } } public static ArrayList<String> getTodos(ContentResolver resolver) { Cursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID); if(cursor==null) return new ArrayList<>(); ArrayList<String> todos = cursorToArrayList(cursor); return todos; } public static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) {
resolver.delete(Priorities.CONTENT_URI, null, null);
2
dgomezferro/pasc-paxos
src/main/java/com/yahoo/pasc/paxos/handlers/acceptor/AcceptorAccept.java
[ "public class Accept extends PaxosMessage implements Serializable, CloneableDeep<Accept>, EqualsDeep<Accept> {\n\n private static final long serialVersionUID = -3781061394615967506L;\n\n public static class Descriptor implements PaxosDescriptor, EqualsDeep<Descriptor> {\n\n private long iid;\n\n public Descriptor(long iid) {\n this.iid = iid;\n }\n\n @Override\n public List<PaxosMessage> buildMessages(PaxosState state) {\n InstanceRecord instance = state.getInstancesElement(iid);\n ClientTimestamp cts[] = instance.getClientTimestamps();\n int threshold = state.getRequestThreshold();\n int size = instance.getArraySize();\n byte[][] requests = null;\n for (int i = 0; i < size; ++i) {\n IidRequest request = state.getReceivedRequest(cts[i]);\n if (request.getRequest().length <= threshold) {\n if (requests == null) {\n requests = new byte[size][];\n }\n requests[i] = request.getRequest();\n }\n }\n return Arrays.<PaxosMessage> asList(new Accept(state.getServerId(), instance, requests));\n }\n\n @Override\n public boolean equalsDeep(Descriptor other) {\n return this.iid == other.iid;\n }\n\n }\n\n int senderId;\n InstanceRecord instance;\n byte[][] requests;\n\n public Accept() {\n }\n\n public Accept(int senderId, InstanceRecord instance, byte[][] requests) {\n this.senderId = senderId;\n this.instance = instance;\n this.requests = requests;\n }\n\n public Accept(int senderId, long iid, int ballot, ClientTimestamp[] values, int arraySize) {\n super();\n this.senderId = senderId;\n this.instance = new InstanceRecord(iid, ballot, values, arraySize);\n }\n\n public int getSenderId() {\n return senderId;\n }\n\n public void setSenderId(int senderId) {\n this.senderId = senderId;\n }\n\n public InstanceRecord getInstance() {\n return instance;\n }\n\n public int getBallot() {\n return instance.getBallot();\n }\n\n public void setBallot(int ballot) {\n instance.setBallot(ballot);\n }\n\n public long getIid() {\n return instance.getIid();\n }\n\n public void setIid(long iid) {\n instance.setIid(iid);\n }\n\n public ClientTimestamp[] getValues() {\n return instance.getClientTimestamps();\n }\n\n public void setValues(ClientTimestamp[] values) {\n instance.setClientTimestamps(values);\n }\n\n public int getArraySize() {\n return instance.getArraySize();\n }\n\n public void setArraySize(int size) {\n instance.setArraySize(size);\n }\n\n public byte[][] getRequests() {\n return requests;\n }\n\n public void setRequests(byte[][] requests) {\n this.requests = requests;\n }\n\n @Override\n public String toString() {\n String acceptStr = Arrays.toString(instance.getClientTimestamps());\n if (acceptStr.length() > 20) {\n acceptStr = acceptStr.substring(0, 20) + \" ... ]\";\n }\n return String.format(\"{Accept %s sent from %d with ballot %d for iid %d with requests %s {%s}}\",\n acceptStr, senderId, instance.getBallot(), instance.getIid(), \n Arrays.deepToString(requests), super.toString());\n }\n\n public Accept cloneDeep() {\n byte[][] requests = null;\n if (this.requests != null) {\n int size = this.requests.length;\n requests = new byte[size][];\n for (int i = 0; i < size; i++) {\n byte[] request = this.requests[i];\n if (request != null) {\n requests[i] = new byte[request.length];\n System.arraycopy(request, 0, requests[i], 0, request.length);\n }\n }\n }\n return new Accept(this.senderId, instance.cloneDeep(), requests);\n }\n\n public boolean equalsDeep(Accept other) {\n return (this.senderId == other.senderId && this.instance.equalsDeep(other.instance));\n }\n}", "public interface PaxosDescriptor {\n public List<PaxosMessage> buildMessages(PaxosState state);\n}", "public class ClientTimestamp implements Comparable<ClientTimestamp>, EqualsDeep<ClientTimestamp>, CloneableDeep<ClientTimestamp> {\n int clientId;\n long timestamp;\n\n public ClientTimestamp() {\n // TODO Auto-generated constructor stub\n }\n\n public ClientTimestamp(int clientId, long timestamp) {\n super();\n this.clientId = clientId;\n this.timestamp = timestamp;\n }\n\n public int getClientId() {\n return clientId;\n }\n\n public void setClientId(int clientId) {\n this.clientId = clientId;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (!(obj instanceof ClientTimestamp)) return false;\n ClientTimestamp ct = (ClientTimestamp) obj;\n return this.clientId == ct.clientId && this.timestamp == ct.timestamp;\n }\n \n @Override\n public int hashCode() {\n return 37 * clientId + (int)(timestamp ^ (timestamp >>> 32));\n }\n\n @Override\n public int compareTo(ClientTimestamp o) {\n int diff = (int) (this.timestamp - o.timestamp);\n if (diff != 0) return diff;\n return this.clientId - o.clientId;\n }\n \n public ClientTimestamp cloneDeep(){\n \treturn new ClientTimestamp(this.clientId, this.timestamp);\n }\n \n public boolean equalsDeep (ClientTimestamp other){\n return this.clientId == other.clientId && this.timestamp == other.timestamp;\n }\n \n @Override\n public String toString() {\n return String.format(\"<%d,%d>\", clientId, timestamp);\n }\n}", "public final class IidAcceptorsCounts implements Serializable, EqualsDeep<IidAcceptorsCounts>, CloneableDeep<IidAcceptorsCounts> {\n\n private static final long serialVersionUID = 7587497611602103466L;\n\n long iid;\n int ballot;\n int acceptors;\n int receivedRequests;\t// actual number of different requests received so far\n int totalRequests;\t\t// number of requests with the same instance id (in the same batch from the leader)\n boolean accepted;\t\t// true if receivedRequests == totalRequests\n\n public IidAcceptorsCounts(long iid, int ballot) {\n this.acceptors = 0;\n this.iid = iid;\n this.ballot = ballot;\n }\n\n public long getIid() {\n return iid;\n }\n\n public void setIid(long iid) {\n this.iid = iid;\n }\n\n public int getAcceptors() {\n return acceptors;\n }\n\n public void setAcceptors(int acceptors) {\n this.acceptors = acceptors;\n }\n\n public void setAcceptor(int acceptor) {\n acceptors = acceptors | (1 << acceptor);\n }\n\n public int getCardinality(int servers) {\n int count = 0;\n for (int i = 0; i < servers; ++i) {\n if ((acceptors & (1 << i)) != 0)\n ++count;\n }\n return count;\n }\n\n public boolean isAccepted() {\n return accepted;\n }\n\n public void setAccepted(boolean accepted) {\n this.accepted = accepted;\n }\n\n public int getReceivedRequests() {\n return receivedRequests;\n }\n\n public void setReceivedRequests(int receivedRequests) {\n this.receivedRequests = receivedRequests;\n }\n\n public int getTotalRequests() {\n return totalRequests;\n }\n\n public void setTotalRequests(int totalRequests) {\n this.totalRequests = totalRequests;\n }\n\n public int getBallot() {\n return ballot;\n }\n\n public void setBallot(int ballot) {\n this.ballot = ballot;\n }\n\n public IidAcceptorsCounts cloneDeep() {\n IidAcceptorsCounts res = new IidAcceptorsCounts(this.iid, this.ballot);\n res.acceptors = this.acceptors;\n res.accepted = this.accepted;\n res.receivedRequests = this.receivedRequests;\n res.totalRequests = this.totalRequests;\n return res;\n }\n\n public boolean equalsDeep(IidAcceptorsCounts other) {\n return (this.iid == other.iid) && (this.ballot == other.ballot) && (this.acceptors == other.acceptors)\n && (this.accepted == other.accepted) && (this.receivedRequests == other.receivedRequests)\n && (this.totalRequests == other.totalRequests);\n }\n}", "public class IidRequest implements CloneableDeep<IidRequest>, EqualsDeep<IidRequest> {\n long iid;\n byte[] request;\n\n public IidRequest(long iid, byte[] request) {\n super();\n this.iid = iid;\n this.request = request;\n }\n\n public IidRequest(long iid) {\n super();\n this.iid = iid;\n }\n\n public IidRequest(byte[] request) {\n super();\n this.iid = -1;\n this.request = request;\n }\n\n public long getIid() {\n return iid;\n }\n\n public void setIid(long iid) {\n this.iid = iid;\n }\n\n public byte[] getRequest() {\n return request;\n }\n\n public void setRequest(byte[] request) {\n this.request = request;\n }\n\n @Override\n public boolean equalsDeep(IidRequest other) {\n return this.iid == other.iid && Arrays.equals(this.request, other.request);\n }\n\n @Override\n public IidRequest cloneDeep() {\n byte[] copyRequest = null;\n if (request != null) {\n copyRequest = Arrays.copyOf(request, request.length);\n }\n return new IidRequest(iid, copyRequest);\n }\n\n}", "public class PaxosState implements ProcessState {\n\n @SuppressWarnings(\"unused\")\n private static final Logger LOG = LoggerFactory.getLogger(PaxosState.class);\n\n private static final int MAX_CLIENTS = 4096;\n // this field is just for testing. will be replaced when the learner will\n // use the state machine\n public final int REPLY_SIZE = 1;\n\n public PaxosState(int maxInstances, int bufferSize, int serverId, int quorum, int digestQuorum,\n int servers, int congestionWindow, int maxDigests) {\n this.maxInstances = maxInstances;\n this.instances = new InstanceRecord[maxInstances];\n this.accepted = new IidAcceptorsCounts[maxInstances];\n this.requests = new IidRequest[MAX_CLIENTS][];\n this.bufferSize = bufferSize;\n this.serverId = serverId;\n this.quorum = quorum;\n this.digestQuorum = digestQuorum;\n this.servers = servers;\n this.congestionWindow = congestionWindow;\n this.maxDigests = maxDigests;\n this.digestStore = new DigestStore[maxDigests];\n this.maxExecuted = -1;\n this.leaderId = -1;\n this.replyCache = new TimestampReply[MAX_CLIENTS];\n inProgress = new long[MAX_CLIENTS];\n Arrays.fill(inProgress, -1);\n prepared = new PreparedMessages(servers);\n }\n \n // Digests\n int digestQuorum;\n DigestStore[] digestStore;\n long firstDigestId;\n int maxDigests;\n int checkpointPeriod = 256;\n\n // All\n int serverId;\n int leaderId;\n int quorum;\n int servers;\n int bufferSize;\n\n /*\n * Proposer\n */\n int congestionWindow;\n /** Execution pending instances */\n int pendingInstances;\n IidRequest[][] requests;\n boolean isLeader;\n int ballotProposer;\n /** Size under which request are forwarded through the leader */\n int requestThreshold;\n PreparedMessages prepared;\n\n /*\n * Proposer & Acceptor\n */\n\n InstanceRecord[] instances;\n long firstInstanceId;\n int maxInstances;\n long currIid;\n\n /*\n * Acceptor\n */\n int ballotAcceptor;\n\n /*\n * Learner\n */\n IidAcceptorsCounts[] accepted;\n long maxExecuted;\n\n // Generate messages\n TimestampReply[] replyCache;\n long[] inProgress;\n boolean leaderReplies;\n boolean completedPhaseOne;\n\n // ------------------------------\n\n public int getBallotProposer() {\n return ballotProposer;\n }\n\n public void setBallotProposer(int ballotProposer) {\n this.ballotProposer = ballotProposer;\n }\n\n public boolean getIsLeader() {\n return isLeader;\n }\n\n public void setIsLeader(boolean isLeader) {\n this.isLeader = isLeader;\n }\n\n public InstanceRecord[] getInstances() {\n return instances;\n }\n\n public void setInstances(InstanceRecord[] instances) {\n this.instances = instances;\n }\n\n public int getBallotAcceptor() {\n return ballotAcceptor;\n }\n\n public void setBallotAcceptor(int ballotAcceptor) {\n this.ballotAcceptor = ballotAcceptor;\n }\n\n public IidAcceptorsCounts[] getAccepted() {\n return accepted;\n }\n\n public void setAccepted(IidAcceptorsCounts[] accepted) {\n this.accepted = accepted;\n }\n\n public long getReplyCacheTimestampElement(int clientId){\n TimestampReply reply = replyCache[clientId];\n if (reply != null)\n return reply.getTimestamp();\n return -1;\n }\n \n public void setReplyCacheTimestampElement(int clientId, long newVal){\n }\n \n public TimestampReply getReplyCacheElement(int clientId){\n return replyCache[clientId];\n }\n \n public void setReplyCacheElement(int clientId, TimestampReply newVal){\n replyCache[clientId] = newVal;\n }\n \n public long getInProgressElement(int clientId){\n return inProgress[clientId];\n }\n \n public void setInProgressElement(int clientId, long timestamp){\n inProgress[clientId] = timestamp;\n }\n\n public void setClientTimestampBufferElem(IndexIid index, ClientTimestamp ct) {\n instances[(int) (index.getIid() % maxInstances)].setClientTimestamp(ct, index.getIndex());\n }\n\n public ClientTimestamp getClientTimestampBufferElem(IndexIid index) {\n return instances[(int) (index.getIid() % maxInstances)].getClientTimestamp(index.getIndex());\n }\n\n public int getInstanceBufferSize(long iid) {\n return instances[(int) (iid % maxInstances)].getArraySize();\n }\n\n public void setInstanceBufferSize(long iid, int newSize) {\n instances[(int) (iid % maxInstances)].setArraySize(newSize);\n }\n\n public InstanceRecord getInstancesElement(long iid) {\n return instances[(int) (iid % maxInstances)];\n }\n\n public long getInstancesIid (long iid) {\n return instances[(int) (iid % maxInstances)].getIid();\n }\n\n public void setInstancesElement(long iid, InstanceRecord instancesElement) {\n this.instances[(int) (iid % maxInstances)] = instancesElement;\n }\n\n public int getInstancesBallot(long iid){\n return instances[(int) (iid % maxInstances)].getBallot();\n }\n\n public IidAcceptorsCounts getAcceptedElement(long iid) {\n return accepted[(int) (iid % maxInstances)];\n }\n\n public boolean getIsAcceptedElement(long iid) {\n return accepted[(int) (iid % maxInstances)].isAccepted();\n }\n\n public void setAcceptedElement(long iid, IidAcceptorsCounts acceptedElement) {\n this.accepted[(int) (iid % maxInstances)] = acceptedElement;\n }\n\n public long getCurrIid() {\n return currIid;\n }\n\n public void setCurrIid(long firstInstancesElement) {\n this.currIid = firstInstancesElement;\n }\n\n public long getReceivedRequestIid(ClientTimestamp element) {\n IidRequest[] clientArray = requests[element.clientId];\n if (clientArray == null || clientArray.length == 0) {\n return -1;\n }\n IidRequest request = clientArray[(int) (element.timestamp % maxInstances)];\n if (request != null)\n return request.getIid();\n return -1;\n }\n\n public void setReceivedRequestIid(ClientTimestamp element, long value) {\n }\n\n public IidRequest getReceivedRequest(ClientTimestamp element) {\n IidRequest[] clientArray = requests[element.clientId];\n if (clientArray == null || clientArray.length == 0) {\n return null;\n }\n return clientArray[(int) (element.timestamp % maxInstances)];\n }\n\n public void setReceivedRequest(ClientTimestamp element, IidRequest value) {\n IidRequest[] clientArray = requests[element.clientId];\n if (clientArray == null || clientArray.length == 0) {\n clientArray = new IidRequest[maxInstances];\n requests[element.clientId] = clientArray;\n }\n clientArray[(int) (element.timestamp % maxInstances)] = value;\n }\n\n public int getMaxInstances() {\n return maxInstances;\n }\n\n public void setMaxInstances(int maxInstances) {\n this.maxInstances = maxInstances;\n }\n\n public int getServerId() {\n return serverId;\n }\n\n public void setServerId(int serverId) {\n this.serverId = serverId;\n }\n\n public int getLeaderId() {\n return leaderId;\n }\n\n public void setLeaderId(int leaderId) {\n this.leaderId = leaderId;\n }\n\n public int getQuorum() {\n return quorum;\n }\n\n public void setQuorum(int quorum) {\n this.quorum = quorum;\n }\n\n public int getBufferSize() {\n return bufferSize;\n }\n\n public void setBufferSize(int bufferSize) {\n this.bufferSize = bufferSize;\n }\n\n public int getServers() {\n return servers;\n }\n\n public void setServers(int servers) {\n this.servers = servers;\n }\n\n public int getCongestionWindow() {\n return congestionWindow;\n }\n\n public void setCongestionWindow(int congestionWindow) {\n this.congestionWindow = congestionWindow;\n }\n\n public int getPendingInstances() {\n return pendingInstances;\n }\n\n public void setPendingInstances(int pendingInstances) {\n this.pendingInstances = pendingInstances;\n }\n\n// public int getClientTimestampBufferSize() {\n// return clientTimestampBufferSize;\n// }\n//\n// public void setClientTimestampBufferSize(int clientTimestampBufferSize) {\n// this.clientTimestampBufferSize = clientTimestampBufferSize;\n// }\n\n// public ClientTimestamp getClientTimestampBufferElement(int index) {\n// return clientTimestampBuffer[index];\n// }\n//\n// public void setClientTimestampBufferElement(int index, ClientTimestamp clientTimestampBuffer) {\n// this.clientTimestampBuffer[index] = clientTimestampBuffer;\n// }\n//\n// public ClientTimestamp[] getClientTimestampBuffer() {\n// return clientTimestampBuffer;\n// }\n//\n// public void setClientTimestampBuffer(ClientTimestamp[] clientTimestampBuffer) {\n// this.clientTimestampBuffer = clientTimestampBuffer;\n// }\n\n public int getRequestThreshold() {\n return requestThreshold;\n }\n\n public void setRequestThreshold(int requestThreshold) {\n this.requestThreshold = requestThreshold;\n }\n\n public DigestStore[] getDigestStore() {\n return digestStore;\n }\n\n public void setDigestStore(DigestStore[] digestStore) {\n this.digestStore = digestStore;\n }\n\n public DigestStore getDigestStoreElement(long digestId) {\n return digestStore[(int) (digestId % maxDigests)];\n }\n\n public void setDigestStoreElement(long digestId, DigestStore digestStoreElement) {\n this.digestStore[(int) (digestId % maxDigests)] = digestStoreElement;\n }\n\n public int getCheckpointPeriod() {\n return checkpointPeriod;\n }\n\n public void setCheckpointPeriod(int checkpointPeriod) {\n this.checkpointPeriod = checkpointPeriod;\n }\n\n public long getMaxExecuted() {\n return maxExecuted;\n }\n\n public void setMaxExecuted(long maxExecuted) {\n this.maxExecuted = maxExecuted;\n }\n\n public long getFirstDigestId() {\n return firstDigestId;\n }\n\n public void setFirstDigestId(long firstDigestId) {\n this.firstDigestId = firstDigestId;\n }\n\n public int getMaxDigests() {\n return maxDigests;\n }\n\n public void setMaxDigests(int maxDigests) {\n this.maxDigests = maxDigests;\n }\n\n public long getFirstInstanceId() {\n return firstInstanceId;\n }\n\n public void setFirstInstanceId(long firstInstanceId) {\n this.firstInstanceId = firstInstanceId;\n }\n\n public int getDigestQuorum() {\n return digestQuorum;\n }\n\n public void setDigestQuorum(int digestQuorum) {\n this.digestQuorum = digestQuorum;\n }\n\n public boolean getLeaderReplies() {\n return leaderReplies;\n }\n\n public void setLeaderReplies(boolean leaderReplies) {\n this.leaderReplies = leaderReplies;\n }\n\n public PreparedMessages getPrepared() {\n return prepared;\n }\n\n public void setPrepared(PreparedMessages prepared) {\n this.prepared = prepared;\n }\n\n public void setCompletedPhaseOne(boolean completedPhaseOne) {\n this.completedPhaseOne = completedPhaseOne;\n }\n\n public boolean getCompletedPhaseOne() {\n return this.completedPhaseOne;\n }\n}" ]
import com.yahoo.pasc.paxos.state.IidRequest; import com.yahoo.pasc.paxos.state.PaxosState; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yahoo.pasc.Message; import com.yahoo.pasc.paxos.handlers.PaxosHandler; import com.yahoo.pasc.paxos.handlers.proposer.ProposerRequest; import com.yahoo.pasc.paxos.messages.Accept; import com.yahoo.pasc.paxos.messages.Accepted; import com.yahoo.pasc.paxos.messages.PaxosDescriptor; import com.yahoo.pasc.paxos.state.ClientTimestamp; import com.yahoo.pasc.paxos.state.IidAcceptorsCounts;
/** * Copyright (c) 2011 Yahoo! Inc. All rights reserved. * * 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. See accompanying LICENSE file. */ package com.yahoo.pasc.paxos.handlers.acceptor; public class AcceptorAccept extends PaxosHandler<Accept> { private static final Logger LOG = LoggerFactory.getLogger(ProposerRequest.class); @Override public List<PaxosDescriptor> processMessage(Accept message, PaxosState state) { if (state.getIsLeader()) return null; int ballot = message.getBallot(); int currentBallot = state.getBallotAcceptor(); if (ballot < currentBallot) { LOG.trace("Rejecting accept. msg ballot: {} current ballot: {}", ballot, currentBallot); // We promised not to accept ballots lower than our current ballot return null; } long iid = message.getIid(); long firstInstanceId = state.getFirstInstanceId(); if (firstInstanceId <= iid && iid < firstInstanceId + state.getMaxInstances()) { ClientTimestamp[] cts = message.getValues(); byte[][] requests = message.getRequests(); int arraySize = message.getArraySize(); int countReceivedRequests = 0; for (int i = 0; i < arraySize; ++i) { if (requests != null && requests[i] != null) { state.setReceivedRequest(cts[i], new IidRequest(iid, requests[i])); countReceivedRequests++; } else { IidRequest request = state.getReceivedRequest(cts[i]); if (request == null || (request.getIid() != -1 && request.getIid() < firstInstanceId)) { request = new IidRequest(iid); state.setReceivedRequest(cts[i], request); } else if (request.getRequest() != null && request.getIid() == -1) { request.setIid(iid); countReceivedRequests++; } else { LOG.warn("The acceptor created this request. Duplicated accept?"); } } }
IidAcceptorsCounts accepted = state.getAcceptedElement(iid);
3
mikkeliamk/osa
src/fi/mamk/osa/stripes/RoleAction.java
[ "public class AccessRight implements Serializable {\n\t\n private static final long serialVersionUID = -8302724810061640050L;\n\n public static final int ACCESSRIGHTLEVEL_DENY_META = -1;\n public static final int ACCESSRIGHTLEVEL_READ_META = 10;\n public static final int ACCESSRIGHTLEVEL_READ_DOC = 20;\n public static final int ACCESSRIGHTLEVEL_WRITE_META = 30;\n public static final int ACCESSRIGHTLEVEL_ADD_DOC = 40;\n public static final int ACCESSRIGHTLEVEL_RECORDSMANAGEMENT = 50;\n public static final int ACCESSRIGHTLEVEL_ADMIN = 100;\n public static final int ACCESSRIGHTLEVEL_INSTANCEADMIN = 200;\n\n public static final String PUBLICITYLEVEL_Confidential = \"confidential\";\n public static final String PUBLICITYLEVEL_Restricted = \"restricted\";\n public static final String PUBLICITYLEVEL_Public = \"public\";\n \n /**\n * publicityLevel\n * 0: access to public data\n * 1: access to restricted data\n * 2: access to confidential data\n */\n public String publicityLevel;\n private int accessRightLevel;\n private String accessRightPath;\n private boolean recursiveRule;\n \n // publicity level hierarchy\n public static final List<String> PUBLICITYLEVEL_LIST = \n Collections.unmodifiableList(new Vector<String>() {\n private static final long serialVersionUID = 1L;\n { \n add(\"public\");\n add(\"restricted\");\n add(\"confidential\");\n }});\n\t\n /**\n * Constructor\n */\n\tpublic AccessRight() {\n\t\tthis.publicityLevel = PUBLICITYLEVEL_Public;\n\t\tthis.accessRightLevel = ACCESSRIGHTLEVEL_READ_META;\n\t\tthis.accessRightPath = null;\n\t\tthis.recursiveRule = false;\n\t}\n\t\n\t/**\n * Constructor\n */\n public AccessRight(String publicityLevel, int accessRightLevel, String accessRightPath) {\n\t\tthis.publicityLevel = publicityLevel;\n\t\tthis.accessRightLevel = accessRightLevel;\n\t\tthis.accessRightPath = accessRightPath;\n\t\t\n\t\tif (this.accessRightPath.endsWith(\"+\")) {\n\t\t this.recursiveRule = true;\n\t\t} else {\n\t\t this.recursiveRule = false;\n\t\t}\n\t}\n \n /**\n * Get all publicity levels below determined level\n * (public, restricted, confidential)\n * @return\n */\n public String getPublicityLevels() {\n\n String levels = \"\";\n int index = PUBLICITYLEVEL_LIST.indexOf(this.publicityLevel);\n \n if (this.getAccessRightLevel() == AccessRight.ACCESSRIGHTLEVEL_DENY_META) {\n for (int i=0; i<PUBLICITYLEVEL_LIST.size(); i++) {\n if (i >= index) {\n if (levels != \"\") {\n levels += \" \";\n }\n levels += PUBLICITYLEVEL_LIST.get(i);\n }\n }\n \n } else {\n for (int i=0; i<PUBLICITYLEVEL_LIST.size(); i++) {\n if (i <= index) {\n if (levels != \"\") {\n levels += \" \";\n }\n levels += PUBLICITYLEVEL_LIST.get(i);\n }\n }\n }\n return levels;\n }\n \n public String getPublicityLevel() {\n\t\treturn publicityLevel;\n\t}\n\tpublic void setPublicityLevel(String publicityLevel) {\n\t\tthis.publicityLevel = publicityLevel;\n\t}\n\tpublic String getAccessRightPath() {\n\t\treturn accessRightPath;\n\t}\n\tpublic void setAccessRightPath(String accessRightPath) {\n\t\tthis.accessRightPath = accessRightPath;\n\t}\n\tpublic int getAccessRightLevel() {\n\t\treturn accessRightLevel;\n\t}\n\tpublic void setAccessRightLevel(int accessRightLevel) {\n\t\tthis.accessRightLevel = accessRightLevel;\n\t}\n public boolean isRecursiveRule() {\n return recursiveRule;\n }\n public void setRecursiveRule(boolean recursiveRule) {\n this.recursiveRule = recursiveRule;\n }\n\n}", "public class LdapManager extends AuthenticationManager {\n \n private static final Logger logger = Logger.getLogger(LdapManager.class);\n public static enum EntryType {\n \tUSER,\n \tROLE\n }\n \n // Ldap attributes for organization\n public static final String ORG_NAME = \"o\";\n public static final String ORG_VISIBLENAME = \"displayName\";\n public static final String ORG_DESC = \"description\";\n // Ldap attributes for group\n public static final String GROUP_NAME = \"ou\";\n // Ldap attributes for person\n public static final String PERSON_FIRSTNAME = \"givenName\";\n public static final String PERSON_LASTNAME = \"sn\";\n public static final String PERSON_COMMONNAME = \"cn\";\n public static final String PERSON_PASSWORD = \"userPassword\";\n public static final String PERSON_EMAIL = \"mail\";\n public static final String PERSON_LANGUAGE = \"preferredLanguage\";\n // Ldap attributes for role\n public static final String ROLE_NAME = \"cn\";\n public static final String ROLE_ACCESSRIGHTPATH = \"destinationIndicator\";\n public static final String ROLE_ACCESSRIGHTLEVEL = \"l\";\n public static final String ROLE_ACCESSRIGHTPUBLICITYLEVEL = \"ou\";\n public static final String ROLE_USER = \"roleOccupant\";\n \n /** LDAPManager status */\n public boolean status = false;\n \n /** Host:port where connected to */\n private String host;\n\n /** connection to LDAP */\n private DirContext context;\n private String admindn;\n private String adminpw;\n // domain components (dc=xx,dc=yy)\n private String domainComponents;\n // dn for instance admin\n private String instanceAdminDn;\n \n /**\n * Constructor\n */\n public LdapManager(String host, String AdminDn, String Adminpw, String baseDn, String adminDn) {\n this.host = host;\n this.admindn = AdminDn;\n this.adminpw = Adminpw;\n setDomainComponents(baseDn);\n setInstanceAdminDn(adminDn);\n context = getContext();\n // save host if connected\n if (context != null) {\n this.status = true;\n \n try {\n context.close();\n } catch (NamingException e) {\n logger.error(\"LdapManager initialization error.\");\n }\n }\n }\n \n public static String hash256(String data) {\n \tMessageDigest md = null;\n \t\n \ttry {\n \t\t\n \t\tmd = MessageDigest.getInstance(\"SHA-256\");\n \t\tmd.update(data.getBytes());\n \t\n \t} catch (NoSuchAlgorithmException e){\n \t\tlogger.error(\"LdapManager error: Hashing error\");\n \t}\n \t\n \treturn bytesToHex(md.digest());\n }\n \n public static String bytesToHex(byte[] bytes) {\n \tStringBuffer result = new StringBuffer();\n \tfor (byte byt : bytes) result.append(Integer.toString((byt & 0xff) + 0x100, 16).substring(1));\n \treturn result.toString();\n }\n \n public String getDefaultDn(String defaultOrg) {\n return \"o=\"+defaultOrg+\",\"+getDomainComponents();\n }\n \n /**\n * Check user\n * @param username email-address\n * @param password password\n * @return\n */\n public String isValidUser(String username, String password, String sessionid) {\n \n \tDirContext authContext = null;\n boolean status = false;\n String usrdn = \"\";\n String cnValue = \"\";\n String hashedPw = hash256(password);\n String retValue = \"\";\n \n try {\n \tauthContext = getContext();\n \tSearchControls ctls = new SearchControls();\n \t\n \t// Check e-mail and password\n \tString filter = \"(&(mail=\"+username+\")(userPassword=\"+hashedPw+\"))\";\n \t\n \tNamingEnumeration<SearchResult> answer3 = authContext.search(getDomainComponents(), filter, ctls);\n \tif (answer3.hasMore()) {\n \t status = true;\n\n \t SearchResult result = answer3.next();\n cnValue = result.getAttributes().get(\"cn\").get().toString();\n usrdn = \"cn=\"+cnValue+\",\"+getDomainComponents();\n \t}\n \t\n \tNamingEnumeration<NameClassPair> e = authContext.list(getDomainComponents());\n \twhile (e.hasMore()) {\n \t\tNameClassPair nc = e.next();\n \t\tString organization = nc.getName();\n \t\t\n \tNamingEnumeration<SearchResult> answer = authContext.search(organization+\",\"+getDomainComponents(), filter, ctls);\n\t \tif (answer.hasMore()) {\n\t \t status = true;\n\t \t \n SearchResult result = answer.next();\n cnValue = result.getAttributes().get(\"cn\").get().toString();\n usrdn = \"cn=\"+cnValue+\",\"+organization+\",\"+getDomainComponents();\n\t \t}\n\t \t\n \t\tNamingEnumeration<NameClassPair> ae = authContext.list(organization +\",\"+getDomainComponents());\n \t\twhile (ae.hasMore()) {\n NameClassPair ne = ae.next();\n String group = ne.getName();\n NamingEnumeration<SearchResult> answer2 = authContext.search(group+\",\"+organization+\",\"+getDomainComponents(), filter, ctls);\n if (answer2.hasMore()) {\n status = true;\n \n SearchResult result = answer2.next();\n cnValue = result.getAttributes().get(\"cn\").get().toString();\n usrdn = \"cn=\"+cnValue+\",\"+group+\",\"+organization+\",\"+getDomainComponents();\n }\n \t\t} \t\t\n \t}\n \t\n \tauthContext.close();\n \t\n } catch (Exception e) {\n \tlogger.error(\"LdapManager error: user check failed, \"+e);\n }\n \n if (usrdn != \"\") {\n // check if user already logged in \n status = Osa.dbManager.get(\"sql\").setCurrentuser(usrdn, sessionid);\n if (status == false) {\n retValue = \"alreadyloggedin;\"+usrdn;\n }\n \n } else {\n retValue = \"notfound\";\n }\n \n if (status) {\n \treturn usrdn; \t\n } else {\n \treturn retValue;\n }\n \n }\n \n /**\n * Get the directory service interface, containing methods for examining and \n * updating attributes associated with objects, \n * and for searching the directory. \n * @return\n */\n public DirContext getContext() {\n DirContext authContext = null;\n try {\n \t\n Properties props = new Properties();\n props.put(Context.INITIAL_CONTEXT_FACTORY, \"com.sun.jndi.ldap.LdapCtxFactory\");\n props.put(Context.PROVIDER_URL, this.host);\n props.put(Context.SECURITY_AUTHENTICATION, \"simple\");\n props.put(Context.SECURITY_PRINCIPAL, this.admindn);\n props.put(Context.SECURITY_CREDENTIALS, this.adminpw);\n \n authContext = new InitialDirContext(props);\n \n } catch (Exception e) {\n logger.error(\"LdapManager error: \"+e);\n }\n \n return authContext;\n \t\n }\n \n /**\n * Creates new user and adds user to specified roles\n */\n public boolean createNewUser(String fname, \n String lname, \n String mail, \n String lang, \n String pw, \n String userOrganization, \n String userGroup, \n Vector<String> fedoraRoles) {\n \t\n \tDirContext context = null;\n \tboolean status = false;\n \t\n \tString newdn = \"cn=\"+fname+\" \"+lname+\",ou=\"+userGroup+\",o=\"+userOrganization+\",\"+getDomainComponents();\n \t\n \tAttribute cn = new BasicAttribute(LdapManager.PERSON_COMMONNAME, fname+\" \"+lname);\n \tAttribute gn = new BasicAttribute(LdapManager.PERSON_FIRSTNAME, fname);\n \tAttribute sn = new BasicAttribute(LdapManager.PERSON_LASTNAME, lname);\n \tAttribute email = new BasicAttribute(LdapManager.PERSON_EMAIL, mail);\n \tAttribute preferredLanguage = new BasicAttribute(LdapManager.PERSON_LANGUAGE, lang);\n \tAttribute userPassword = new BasicAttribute(LdapManager.PERSON_PASSWORD, hash256(pw));\n \t\n \tAttribute oc = new BasicAttribute(\"objectClass\");\n \toc.add(\"person\");\n \toc.add(\"inetOrgPerson\");\n \t \t\n \ttry {\n \t\tcontext = getContext();\n \t\tAttributes entry = new BasicAttributes();\n \t\tentry.put(cn);\n \t\tentry.put(gn);\n \t\tentry.put(sn);\n \t\tentry.put(email);\n \t\tentry.put(preferredLanguage);\n \t\tentry.put(userPassword);\n \t\tentry.put(oc);\n \t\t\n \t\tcontext.createSubcontext(newdn, entry);\n \t\tlogger.debug(\"LdapManager: Created user: \" + newdn);\n \t\t\n \t\t// Add default role to user (access to public data)\n \t\taddUserToRole(newdn, userOrganization, Role.ROLE_PUBLIC);\n \t\t\n \t\t// Add fedora role(s) to user\n \t\tfor (String fedoraRole : fedoraRoles) {\n \t\t\tif (fedoraRole != null) { // Null-check in case vector has null indexes\n \t\t\t\taddUserToRole(newdn, userOrganization, fedoraRole);\n \t\t\t}\n \t\t}\n \t\tcontext.close();\n \t\t\n \t} catch (NamingException e) {\n \t\tlogger.error(\"LdapManager error: Error creating user, \"+e);\n \t\treturn status;\n \t}\n\n \tstatus = true;\n\t\treturn status;\n }\n \n /**\n * Updates user related data\n */\n public boolean updateUser(String usrDn, \n String organization, \n String userGroup, \n Vector<String> fedoraRoles) {\n \n DirContext context = null;\n String newDn = null;\n \n try {\n \n context = getContext();\n \n // get userGroup\n String currentUserGroup = \"\";\n String[] parts = usrDn.split(\",\");\n for (int i=0; i<parts.length; i++) {\n if (parts[i].startsWith(\"ou=\")) {\n currentUserGroup = parts[i].replaceFirst(\"ou=\", \"\");\n break;\n }\n }\n // check userGroup if changed\n if (!currentUserGroup.equals(userGroup)) {\n newDn = usrDn.replace(\"ou=\"+currentUserGroup, \"ou=\"+userGroup);\n // change dn \n context.rename(usrDn, newDn);\n }\n context.close();\n \n // Handle fedora roles, remove old roles\n this.removeUserFromRole(usrDn);\n \n // use newDn if changed\n if (newDn != null) {\n usrDn = newDn;\n }\n \n // Handle fedora roles, add modified\n for (String fedoraRole : fedoraRoles) {\n addUserToRole(usrDn, organization, fedoraRole);\n }\n \n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Error updating user, \"+e);\n return false;\n }\n return true;\n }\n \n /**\n * Function for instance_admin to reset user password \n */\n public boolean resetUserPassword(String usrDn, String pw) {\n DirContext context = null;\n \n try {\n context = getContext();\n Attribute userPassword = new BasicAttribute(LdapManager.PERSON_PASSWORD, hash256(pw));\n ModificationItem[] mods = new ModificationItem[1];\n mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);\n context.modifyAttributes(usrDn, mods);\n logger.info(\"LdapManager info: User '\"+usrDn+\"' password reseted by instance_admin.\");\n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Error reseting user password, \"+e);\n return false;\n }\n \n return true;\n }\n \n /**\n * Creates new group to the organization\n */\n public boolean createGroup(String groupName, String groupOrganization) {\n \t\n \tDirContext context = null;\n \tboolean status = false;\n \t\n \tString newdn = \"ou=\"+ groupName +\",o=\"+ groupOrganization + \",\" + getDomainComponents();\n \t\n \tAttribute ou = new BasicAttribute(LdapManager.GROUP_NAME, groupName);\n \tAttribute oc = new BasicAttribute(\"objectClass\");\n \toc.add(\"organizationalUnit\");\n \t\n \ttry {\n \t\t\n \t\tcontext = getContext();\n \t\tAttributes entry = new BasicAttributes();\n \t\tentry.put(ou);\n \t\tentry.put(oc);\n \t\t\n \t\tcontext.createSubcontext(newdn, entry);\n \t\tlogger.debug(\"LdapManager: Created group: \"+newdn);\n \t\tcontext.close();\n \t\t\n \t} catch (NamingException e) {\n \t\tlogger.error(\"LdapManager error: Error creating group, \"+e);\n \t\treturn status;\n \t}\n \t\n \tstatus = true;\n\t\treturn status;\n \t\n }\n \n /**\n * Creates new organization\n */\n public boolean createOrganization(String oName, String oDesc, String confFile, String afName, String alName, String aMail, String contact, String displayName) {\n \t\n \tDirContext context = null;\n \tboolean status = false;\n \tAttribute description = null;\n \tAttribute dN = null;\n \t\n \tString newdn = \"o=\" + oName + \",\"+ getDomainComponents();\n \t\n \tAttribute o = new BasicAttribute(LdapManager.ORG_NAME, oName);\n \tif (oDesc != null) {\n \t description = new BasicAttribute(LdapManager.ORG_DESC, oDesc);\n \t}\n \tif (displayName != null) {\n \t dN = new BasicAttribute(LdapManager.ORG_VISIBLENAME, displayName);\n \t}\n \tAttribute oc = new BasicAttribute(\"objectClass\");\n \toc.add(\"OpenLDAPorg\");\n \t\n \ttry {\n \t\t\n \t\tcontext = getContext();\n \t\tAttributes entry = new BasicAttributes();\n \t\tentry.put(o);\n \t\tif (dN != null) {\n \t\t entry.put(dN);\n \t\t}\n \t\tif (description != null) {\n \t\t entry.put(description);\n \t\t}\n \t\tentry.put(oc);\n \t\tcontext.createSubcontext(newdn, entry);\n \t\tlogger.debug(\"LdapManager: Created organization: \"+newdn);\n \t\tcontext.close();\n \t\t\n \t} catch (NamingException e) {\n \t\tlogger.error(\"LdapManager error: Error creating organization, \"+e);\n \t\treturn status;\n \t}\n \t\n \tstatus = true;\n\t\treturn status;\n \t\n }\n\n /**\n * Creates role to selected organization\n * @param roleName role name\n * @param roleOrganization role organization\n * @param roleAccessRightLevel public/restricted/confidential\n * @param roleDirectories path to directory or document, where role has in level roleAccessRightLevel\n */\n public boolean createRole(String roleName, String roleOrganization, Vector<AccessRight> accessrights) {\n \n DirContext context = null;\n boolean status = false;\n String newdn = \"cn=\"+roleName+\",o=\"+roleOrganization+\",\"+getDomainComponents();\n \n try {\n\n \tAttributes entry = new BasicAttributes();\n Attribute oc = new BasicAttribute(\"objectClass\", \"organizationalRole\");\n Attribute cn = new BasicAttribute(LdapManager.ROLE_NAME, roleName);\n Attribute ou = new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL);\n Attribute l = new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTLEVEL);\n Attribute di = new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTPATH);\n entry.put(oc);\n entry.put(cn);\n int i=0;\n \n for (AccessRight accessRight : accessrights) {\n \tif (accessRight != null) {\n\t String premark = Integer.toString(i)+\"-\";\n\t \tou.add(premark+accessRight.getPublicityLevel());\n\t \tl.add(premark+Integer.toString(accessRight.getAccessRightLevel()));\n\t \tdi.add(premark+accessRight.getAccessRightPath());\n\t \tentry.put(ou);\n\t \tentry.put(l);\n\t entry.put(di);\n\t i++;\n \t}\n }\n \n context = getContext();\n context.createSubcontext(newdn, entry);\n context.close();\n logger.debug(\"LdapManager: Created role: \"+newdn);\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Error creating role, \"+e);\n return status;\n }\n \n status = true;\n return status;\n }\n \n /**\n * Updates role related data\n */\n public boolean updateRole(String roleDn, String roleName, Vector<AccessRight> accessrights) {\n \n //role: cn=name,o=organization,dc=nn,dc=fi\n DirContext context = null;\n String newDn = null;\n \n try {\n \n context = getContext();\n \n // get name\n String currentRoleName = \"\";\n String[] parts = roleDn.split(\",\");\n for (int i=0; i<parts.length; i++) {\n if (parts[i].startsWith(\"cn=\")) {\n currentRoleName = parts[i].replaceFirst(\"cn=\", \"\");\n break;\n }\n }\n \n // modify role, remove accessrights\n ModificationItem[] mods = new ModificationItem[3];\n mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL));\n mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTLEVEL));\n mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTPATH));\n context.modifyAttributes(roleDn, mods);\n\n // check if roleName changed\n if (roleName != null && !currentRoleName.equals(roleName)) {\n newDn = roleDn.replace(\"cn=\"+currentRoleName, \"cn=\"+roleName);\n // change dn \n context.rename(roleDn, newDn);\n roleDn = newDn;\n }\n \n // modify role, add new accessrights\n int i=0;\n \n for (AccessRight accessRight : accessrights) {\n mods = new ModificationItem[3];\n if (accessRight != null) {\n String premark = Integer.toString(i)+\"-\";\n String publicityLevel = premark+accessRight.getPublicityLevel();\n String acLevel = premark+Integer.toString(accessRight.getAccessRightLevel());\n String di = premark+accessRight.getAccessRightPath();\n \n mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL, publicityLevel));\n mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTLEVEL, acLevel));\n mods[2] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(LdapManager.ROLE_ACCESSRIGHTPATH, di));\n \n context.modifyAttributes(roleDn, mods);\n i++;\n }\n }\n\n logger.debug(\"LdapManager:role '\"+roleDn+\"' updated.\");\n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Error updating role, \"+e);\n return false;\n }\n \n return true;\n }\n \n public Vector<String> getOrganizations() {\n \t\n \tDirContext context = null;\n \tVector<String> values = new Vector<String>();\n \t\n \ttry {\n \t\tcontext = getContext();\n SearchControls ctls = new SearchControls();\n String[] attrIDs = {\"o\"};\n ctls.setReturningAttributes(attrIDs);\n ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);\n\n NamingEnumeration<SearchResult> answer = context.search( getDomainComponents(), \"(objectclass=OpenLDAPorg)\",ctls );\n while (answer.hasMore()) {\n SearchResult rslt = answer.next();\n Attributes attrs = rslt.getAttributes();\n \n if (attrs.get(\"o\") != null) {\n \tString test = attrs.get(\"o\").toString();\n \ttest = test.replace(\"o: \",\"\");\n \tvalues.addElement(test);\n }\n }\n \n context.close();\n\n } catch (NamingException e) {\n \tlogger.error(\"LdapManager error: Error searching organizations, \"+e);\n }\n \t\n \treturn values;\n }\n \n public Vector<String> getGroups(String organization) {\n \t\n \tVector<String> values = new Vector<String>();\n \tif (organization == null) {\n \t\treturn values;\n \t}\n \tDirContext context = null;\n \tString usersContainer = \"o=\"+ organization +\",\"+getDomainComponents();\n \t\n \ttry {\n \t\tcontext = getContext();\n SearchControls ctls = new SearchControls();\n String[] attrIDs = {\"ou\"};\n ctls.setReturningAttributes(attrIDs);\n ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);\n\n NamingEnumeration<SearchResult> answer = context.search( usersContainer, \"(objectclass=organizationalUnit)\",ctls );\n while (answer.hasMore()) {\n SearchResult rslt = answer.next();\n Attributes attrs = rslt.getAttributes();\n \n if (attrs.get(\"ou\") != null) {\n \tString test = attrs.get(\"ou\").toString();\n \ttest = test.replace(\"ou: \",\"\");\n \tvalues.addElement(test);\n }\n }\n \n context.close();\n\n } catch (NamingException e) {\n \tlogger.error(\"LdapManager error: Error searching organizations, \"+e);\n }\n \t\n \treturn values;\n }\n \n /**\n * Returns all users for organization\n */\n public List<User> getUsers(String organization) {\n List<User> users = new ArrayList<User>();\n DirContext context = null;\n\n if (organization == null || organization == \"\") {\n return users;\n }\n\n String GROUP_CTX = \"o=\"+organization+\",\"+getDomainComponents();\n String ORGANIZATION_ROLES_QUERY = \"(&(objectClass=organizationalUnit))\";\n String ORGANIZATION_USERS_QUERY = \"(&(objectClass=inetOrgPerson))\";\n User user = null;\n String group = \"\";\n SearchControls ctls = new SearchControls();\n \n try {\n context = getContext();\n NamingEnumeration<SearchResult> groupResults = context.search(GROUP_CTX, ORGANIZATION_ROLES_QUERY, ctls);\n // groups\n while (groupResults.hasMore()) {\n SearchResult result = groupResults.next();\n group = result.getAttributes().get(\"ou\").get().toString();\n String USER_CTX = \"ou=\"+group+\",\"+GROUP_CTX;\n NamingEnumeration<SearchResult> userResults = context.search(USER_CTX, ORGANIZATION_USERS_QUERY, ctls);\n // users\n while (userResults.hasMore()) {\n SearchResult userResult = userResults.next();\n user = new User();\n user.setGroup(group);\n \n if (userResult.getAttributes().get(LdapManager.PERSON_COMMONNAME) != null) {\n user.setCn(userResult.getAttributes().get(LdapManager.PERSON_COMMONNAME).get().toString());\n user.setDn(\"cn=\"+user.getCn()+\",\"+USER_CTX);\n }\n if (userResult.getAttributes().get(LdapManager.PERSON_FIRSTNAME) != null) {\n user.setFirstName(userResult.getAttributes().get(LdapManager.PERSON_FIRSTNAME).get().toString());\n }\n if (userResult.getAttributes().get(LdapManager.PERSON_LASTNAME) != null) {\n user.setLastName(userResult.getAttributes().get(LdapManager.PERSON_LASTNAME).get().toString());\n }\n if (userResult.getAttributes().get(LdapManager.PERSON_EMAIL) != null) {\n user.setMail(userResult.getAttributes().get(LdapManager.PERSON_EMAIL).get().toString());\n }\n if (userResult.getAttributes().get(LdapManager.PERSON_LANGUAGE) != null) {\n user.setPreferredLanguage(userResult.getAttributes().get(LdapManager.PERSON_LANGUAGE).get().toString());\n }\n users.add(user);\n \n }\n userResults.close();\n }\n groupResults.close();\n \n // Find Fedora roles from ldap and set roles to users\n for (User currentUser : users) {\n currentUser.setFedoraRoles(Osa.authManager.getUserRoles(currentUser.getDn(), organization));\n }\n \n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: User query failed, \"+e);\n }\n \n return users;\n }\n \n /** Get user's info from LDAP\n * \n * @param dn\tUser dn\n * @return\t\tUser object\n */\n public User getUser(String userDn) {\n \tDirContext context \t= null;\n \tUser userInfo \t\t= new User();\n \tString dn \t\t\t= \"\";\n \tString org\t\t\t= \"\";\n \tString ou\t\t\t= \"\";\n \t\n \tif (!userDn.endsWith(getDomainComponents())) {\n \t\tdn = userDn +\",\"+ getDomainComponents();\n \t} else {\n \t\tdn = userDn;\n \t}\n \t\n \ttry {\n \t\tString[] parts = dn.split(\",\");\n \t\tfor (int i = 0; i < parts.length; i++) {\n \t\t\tif (parts[i].startsWith(\"ou=\")) {\n \t\t\t\tou = parts[i].split(\"=\")[1];\n \t\t\t}\n \t\t\tif (parts[i].startsWith(\"o=\")) {\n \t\t\t\torg = parts[i].split(\"=\")[1];\n \t\t\t}\n \t\t}\n \t\tuserInfo.setDn(dn);\n \t\tuserInfo.setGroup(ou);\n \t\t\n \t\tcontext = getContext();\n \t\t\n \t\tAttributes attrs = context.getAttributes(dn);\n \t\tNamingEnumeration<?> i = attrs.getAll();\n \t\twhile (i.hasMore()) {\n \t\t\tAttribute attr = (Attribute) i.next();\n \t\t\tString values = \"\";\n \t\t\t\n \t\t\tNamingEnumeration<?> e = attr.getAll();\n\n \t\t\twhile (e != null && e.hasMore()) {\n \t\t\t String value = e.next().toString();\n \t\t\t if (attr.getID().equals(LdapManager.ROLE_ACCESSRIGHTLEVEL) \n \t\t\t || attr.getID().equals(LdapManager.ROLE_ACCESSRIGHTPATH) \n \t\t\t || attr.getID().equals(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL)) {\n\n \t\t\t if (value.contains(\"-\")) {\n \t\t\t value = value.substring(value.indexOf(\"-\")+1);\n \t\t\t }\n \t\t\t } \n \t\t\t \n \t\t\t if (values == \"\") {\n \t\t\t values += value;\n \t\t\t } else {\n \t\t\t // separate values\n \t\t\t values = values+\";\"+value;\n \t\t\t }\n \t\t\t}\n \t\t\t\n \t\t\tif (LdapManager.PERSON_COMMONNAME.equals(attr.getID())) {\n \t\t\t\tif (!values.isEmpty()) {userInfo.setCn(values);}\n \t\t\t}\n \t\t\tif (LdapManager.PERSON_FIRSTNAME.equals(attr.getID())) {\n \t\t\t\tif (!values.isEmpty()) {userInfo.setFirstName(values);}\n \t\t\t}\n \t\t\tif (LdapManager.PERSON_LASTNAME.equals(attr.getID())) {\n \t\t\t\tif (!values.isEmpty()) {userInfo.setLastName(values);}\n \t\t\t}\n \t\t\tif (LdapManager.PERSON_EMAIL.equals(attr.getID())) {\n \t\t\t\tif (!values.isEmpty()) {userInfo.setMail(values);}\n \t\t\t}\n \t\t\tif (LdapManager.PERSON_LANGUAGE.equals(attr.getID())) {\n \t\t\t\tif (!values.isEmpty()) {userInfo.setPreferredLanguage(values);}\n \t\t\t}\n \t\t}\n \t\t\n \t\tuserInfo.setFedoraRoles(Osa.authManager.getUserRoles(userInfo.getDn(), org));\n \t\tcontext.close();\n \t\t\n \t} catch (Exception e) {\n logger.error(\"LdapManager error: user query failed, \"+e);\n \t}\n \t\n \treturn userInfo;\n }\n \n /**\n * Returns public role (f.ex. anonymous user)\n */\n public Role getPublicRole(String organization) {\n Role role = getRole(Role.ROLE_PUBLIC, organization);\n return role;\n }\n \n /**\n * Returns all roles for organization\n */\n public List<Role> getRoles(String organization) {\n List<Role> roles = new ArrayList<Role>();\n DirContext context = getContext();\n SearchControls ctls = new SearchControls();\n Role role = null;\n\n if (organization == null || organization == \"\") {\n return roles;\n }\n \n String CURRENT_CTX = \"o=\"+organization+\",\"+getDomainComponents();\n String ORGANIZATION_ROLE_QUERY = \"(&(objectClass=organizationalRole))\";\n \n try {\n NamingEnumeration<SearchResult> results = context.search(CURRENT_CTX, ORGANIZATION_ROLE_QUERY, ctls);\n while (results.hasMore()) {\n role = new Role();\n int groups = 0;\n int roleOccupants = 0;\n \n SearchResult result = results.next();\n \n if (result.getAttributes().get(LdapManager.ROLE_NAME) != null) {\n role.setName(result.getAttributes().get(LdapManager.ROLE_NAME).get().toString());\n }\n \n // Handle several attribute-groups (publicityLevel-accessRightLevel-destination)\n if (result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL) != null) {\n groups = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL).size();\n }\n \n for (int i=0; i<groups; i++) {\n String premark = Integer.toString(i)+\"-\";\n String publicityLevel = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL).get(i).toString();\n String accessRightLevel = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTLEVEL).get(i).toString();\n String destinationIndicator = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPATH).get(i).toString();\n \n publicityLevel = publicityLevel.replaceFirst(premark, \"\");\n accessRightLevel = accessRightLevel.replaceFirst(premark, \"\");\n destinationIndicator = destinationIndicator.replaceFirst(premark, \"\");\n \n AccessRight right = new AccessRight(publicityLevel, Integer.parseInt(accessRightLevel), destinationIndicator);\n role.setRoleAccessright(right);\n }\n \n if (result.getAttributes().get(LdapManager.ROLE_USER) != null) {\n roleOccupants = result.getAttributes().get(LdapManager.ROLE_USER).size();\n }\n\n for (int i=0; i<roleOccupants; i++) {\n // userdns, who has this role\n role.setRoleOccupant(result.getAttributes().get(LdapManager.ROLE_USER).get(i).toString());\n }\n \n roles.add(role);\n }\n results.close();\n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Role query failed, \"+e);\n }\n \n return roles;\n }\n \n public HashMap<String,String> getAttributes(String objectdn) {\n \tDirContext context = null;\n \tHashMap<String,String> datatable = new HashMap<String,String>();\n \t\n \tString dn = \"\";\n \t\n \tif (!objectdn.endsWith(getDomainComponents())) {\n \t\tdn = objectdn +\",\"+ getDomainComponents();\n \t} else {\n \t\tdn = objectdn;\n \t}\n \t\n \ttry {\n\n \t\tcontext = getContext(); \t\t\n \t\tAttributes attrs = context.getAttributes(dn);\n \t\t\n \t\tNamingEnumeration<?> i = attrs.getAll();\n \t\t\n \t\twhile (i.hasMore()) {\n \t\t\tAttribute attr = (Attribute) i.next();\n \t\t\tString values = \"\";\n \t\t\tNamingEnumeration<?> e = attr.getAll();\n\n \t\t\twhile (e != null && e.hasMore()) {\n \t\t\t String value = e.next().toString();\n \t\t\t \n \t\t\t if (attr.getID().equals(LdapManager.ROLE_ACCESSRIGHTLEVEL) \n \t\t\t || attr.getID().equals(LdapManager.ROLE_ACCESSRIGHTPATH) \n \t\t\t || attr.getID().equals(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL)) {\n\n \t\t\t if (value.contains(\"-\")) {\n \t\t\t value = value.substring(value.indexOf(\"-\")+1);\n \t\t\t }\n \t\t\t } \n \t\t\t \n \t\t\t if (values == \"\") {\n \t\t\t values += value;\n \t\t\t } else {\n \t\t\t // separate values\n \t\t\t values = values+\";\"+value;\n \t\t\t }\n \t\t\t}\n \t\t\tdatatable.put(attr.getID(), values);\n \t\t}\n \t\t\n \t\tcontext.close();\n \t\t\n \t} catch (Exception e) {\n logger.error(\"LdapManager error: attributes not found for \"+dn+\", \"+e);\n \t}\n \t\n \treturn datatable;\n \t\n }\n \n public Vector<String> getOrganizationRoles(String organization) {\n \n if (organization == null) {\n return null;\n }\n \n String CURRENT_CTX = \"o=\"+organization+\",\"+getDomainComponents();\n String ORGANIZATION_ROLE_QUERY = \"(&(objectClass=organizationalRole))\";\n DirContext context = getContext();\n SearchControls ctls = new SearchControls();\n Vector<String> roles = new Vector<String>();\n \n try {\n \n NamingEnumeration<SearchResult> results = context.search(CURRENT_CTX, ORGANIZATION_ROLE_QUERY, ctls);\n while (results.hasMore()) {\n SearchResult result = results.next();\n String roleName = result.getAttributes().get(LdapManager.ROLE_NAME).get().toString();\n roles.add(roleName);\n }\n results.close();\n context.close();\n \n } catch(NamingException e) {\n logger.error(\"LdapManager error: Role query failed, \"+e);\n }\n\n return roles;\n }\n \n /**\n * Get role details\n */\n public Role getRole(String roleName, String organization) {\n if (organization == null) {\n return null;\n }\n \n String CURRENT_CTX \t= \"o=\"+organization+\",\"+getDomainComponents();\n String ROLE_QUERY \t= \"(&(objectClass=organizationalRole)(cn=\"+roleName+\"))\";\n DirContext context \t= getContext();\n SearchControls ctls = new SearchControls();\n Role role \t\t\t= null;\n \n try {\n \n NamingEnumeration<SearchResult> results = context.search(CURRENT_CTX, ROLE_QUERY, ctls);\n while (results.hasMore()) {\n SearchResult result = results.next();\n String name = result.getAttributes().get(LdapManager.ROLE_NAME).get().toString();\n role = new Role(name);\n // Handle several attribute-groups (publicityLevel-accessRightLevel-destination)\n int groups = 0;\n int roleOccupants = 0;\n \n if (result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL) != null) {\n groups = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL).size();\n }\n \n for (int i=0; i<groups; i++) {\n String premark = Integer.toString(i)+\"-\";\n String publicityLevel = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL).get(i).toString();\n String accessRightLevel = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTLEVEL).get(i).toString();\n String destinationIndicator = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPATH).get(i).toString();\n \n publicityLevel = publicityLevel.replaceFirst(premark, \"\");\n accessRightLevel = accessRightLevel.replaceFirst(premark, \"\");\n destinationIndicator = destinationIndicator.replaceFirst(premark, \"\");\n \n AccessRight right = new AccessRight(publicityLevel, Integer.parseInt(accessRightLevel), destinationIndicator);\n role.setRoleAccessright(right);\n }\n \n if (result.getAttributes().get(LdapManager.ROLE_USER) != null) {\n roleOccupants = result.getAttributes().get(LdapManager.ROLE_USER).size();\n }\n\n for (int i=0; i<roleOccupants; i++) {\n // userdns, who has this role\n role.setRoleOccupant(result.getAttributes().get(LdapManager.ROLE_USER).get(i).toString());\n }\n }\n results.close();\n context.close();\n \n } catch(NamingException e) {\n logger.error(\"LdapManager error: Role query failed, \"+e);\n }\n \n return role;\n }\n \n /**\n * Get roles for user according to dn and organization name\n * @param user user dn (f.ex. \"cn=name,ou=group,o=organization,dc=nn,dc=fi\")\n * @param organization name of user organization\n */\n public Vector<Role> getUserRoles(String user, String organization) {\n if (organization == null) {\n return null;\n }\n \n String CURRENT_CTX \t\t= \"o=\"+organization+\",\"+getDomainComponents(); \n String USER_ROLE_QUERY \t= \"(&(objectClass=organizationalRole)(roleOccupant={0}))\";\n DirContext context \t\t= getContext();\n SearchControls ctls \t= new SearchControls();\n Vector<Role> roles \t\t= new Vector<Role>();\n \n try {\n \n NamingEnumeration<SearchResult> results = context.search(CURRENT_CTX, USER_ROLE_QUERY, new Object[] { user }, ctls);\n while (results.hasMore()) {\n SearchResult result = results.next();\n String name = result.getAttributes().get(LdapManager.ROLE_NAME).get().toString();\n Role role = new Role(name);\n // Handle several attribute-groups (publicityLevel-accessRightLevel-destination)\n int groups = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL).size();\n \n for (int i=0; i<groups; i++) {\n String premark = Integer.toString(i)+\"-\";\n String publicityLevel = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPUBLICITYLEVEL).get(i).toString();\n String accessRightLevel = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTLEVEL).get(i).toString();\n String destinationIndicator = result.getAttributes().get(LdapManager.ROLE_ACCESSRIGHTPATH).get(i).toString();\n publicityLevel = publicityLevel.replaceFirst(premark, \"\");\n accessRightLevel = accessRightLevel.replaceFirst(premark, \"\");\n destinationIndicator = destinationIndicator.replaceFirst(premark, \"\");\n \n AccessRight right = new AccessRight(publicityLevel, Integer.parseInt(accessRightLevel), destinationIndicator);\n role.setRoleAccessright(right);\n }\n \n roles.add(role);\n }\n results.close();\n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Role query for user failed, \"+e);\n }\n\n return roles;\n }\n \n /**\n * Add user to ldap role\n * @param userdn\n * @param organization\n * @param role\n */\n public void addUserToRole(String userdn, String organization, String role) {\n \n DirContext context = null;\n //role: cn=name,o=organization,dc=nn,dc=fi\n String ROLE_CTX = \"cn=\"+role+\",o=\"+organization+\",\"+getDomainComponents();\n \n if (role.equals(Role.ROLE_PUBLIC)) {\n Vector<String> orgRoles = getOrganizationRoles(organization);\n // check if public role exists\n if (orgRoles == null || orgRoles.isEmpty() || !orgRoles.contains(Role.ROLE_PUBLIC)) {\n // create public role\n this.createRole(Role.ROLE_PUBLIC, organization, Role.getPublicRoleAccessrights(organization));\n logger.info(\"LdapManager: \"+Role.ROLE_PUBLIC+\" role created\");\n }\n }\n \n try {\n \n context = getContext();\n \n ModificationItem[] mods = new ModificationItem[1];\n //user: cn=name,ou=group,o=organization,dc=nn,dc=fi\n Attribute mod0 = new BasicAttribute(LdapManager.ROLE_USER, userdn);\n mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, mod0);\n \n context.modifyAttributes(ROLE_CTX, mods);\n logger.debug(\"LdapManager: role '\"+role+\"' modified.\");\n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Error adding user to role, \"+e);\n }\n }\n \n public void removeUserFromRole(String userdn) {\n try {\n context = getContext();\n\n String organization = \"\";\n // get organization\n String[] parts = userdn.split(\",\");\n for (int i=0; i<parts.length; i++) {\n if (parts[i].startsWith(\"o=\")) {\n organization = parts[i].substring(2, parts[i].length());\n break;\n }\n }\n \n Vector<Role> roles = getUserRoles(userdn, organization);\n \n for (int i=0; i<roles.size(); i++) {\n String roleName = roles.get(i).name;\n String role_ctx = \"cn=\"+roleName+\",o=\"+organization+\",\"+getDomainComponents();\n \n ModificationItem[] mods = new ModificationItem[1];\n Attribute mod0 = new BasicAttribute(LdapManager.ROLE_USER, userdn);\n mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, mod0);\n\n context.modifyAttributes(role_ctx, mods);\n }\n context.close();\n \n } catch (NamingException e) {\n logger.error(\"LdapManager error: Error removing user from role, \"+e);\n }\n }\n \n public String modifyAttributes(String dn, String jsonMod) {\n \t\n \tString usrDn = \"\";\n \t\n \tif (!dn.endsWith(getDomainComponents())) {\n \t\tusrDn = dn +\",\"+ getDomainComponents();\n \t} else {\n \t\tusrDn = dn;\n \t}\n \tString newDn = usrDn;\n \t\n \tDirContext context = null;\n \tHashMap values = (HashMap) new JSONDeserializer().deserialize(jsonMod);\n \tHashMap modifiers = new HashMap();\n \t\n \tIterator iterEntries = values.entrySet().iterator();\n \tint i = 0;\n \t\n \ttry {\n \t\tcontext = getContext();\n \t\t\n\t \twhile (iterEntries.hasNext()) {\n\t \t Map.Entry entry = (Map.Entry) iterEntries.next();\n\t \t\tString attr = entry.getKey().toString();\n\t \t\tString value = \"\";\n\t \t\t\n\t \t\tif (attr.equalsIgnoreCase(LdapManager.PERSON_PASSWORD)) {\n\t \t\t value = hash256(entry.getValue().toString());\n\t \t\t} else {\n\t \t\t value = entry.getValue().toString();\n\t \t\t}\n\t \t\t \t\t\n\t \t\tif (attr.equals(\"cn\")) {\n\t \t\t\tString[] parts = newDn.split(\",\");\n\t \t\t\tint j = 0;\n\t \t\t\twhile (parts[j].indexOf(\"cn=\") != 0) {\n\t \t\t\t\tj++;\n\t \t\t\t}\n\t \t\t\tparts[j] = \"cn=\"+entry.getValue();\n\t \t\t\t\n\t \t\t\tnewDn = \"\";\n\t \t\t\tfor (int n = 0;n < parts.length;n++) {\n\t \t\t\t\tif (n == 0) {\n\t \t\t\t\t\tnewDn += parts[n];\n\t \t\t\t\t} else {\n\t \t\t\t\t\tnewDn += \",\"+parts[n];\n\t \t\t\t\t}\n\t \t\t\t}\t\n\t \t\t\t\n\t \t\t} else {\n\t \t\t\tmodifiers.put(attr, value);\n\t \t\t}\n\n\t \t}\n\t \t\n\t \tif (!newDn.equals(usrDn)) {\n\t \t\tcontext.rename(usrDn, newDn);\n\t \t}\n\t \t\n\t \tModificationItem[] mods = new ModificationItem[modifiers.size()];\n\t \tIterator iterModentries = modifiers.entrySet().iterator();\n\t \tint ae = 0;\n\t \twhile (iterModentries.hasNext()) {\n\t \t\tMap.Entry modentry = (Map.Entry) iterModentries.next();\n\t \t\t\n\t \t\tif ((modentry.getKey().toString().equals(LdapManager.ROLE_ACCESSRIGHTPATH) || modentry.getKey().toString().equals(LdapManager.ROLE_USER))\n\t \t\t && modentry.getValue().toString().contains(\"[\")) {\n\t \t\t \n\t \t\t // handle multivalues\n \t\t String multipleValues = modentry.getValue().toString();\n \t\t multipleValues = multipleValues.substring(1, multipleValues.length()-1);\n \t\t String[] arrayValues = multipleValues.split(\", \");\n \t\t \n \t\t BasicAttribute attribute = new BasicAttribute(modentry.getKey().toString());\n \t\t for (int index=0; index<arrayValues.length; index++) {\n \t\t attribute.add(arrayValues[index]);\n \t\t }\n \t\t \n \t\t mods[ae] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute);\n \t\t \n\t \t\t} else {\n\t \t\t\n\t \t\t mods[ae] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(modentry.getKey().toString(), modentry.getValue().toString()));\n\t \t\t}\n\t \t\tae++;\n\t \t} \t\t\n \t\tcontext.modifyAttributes(newDn, mods);\n \t\tcontext.close();\n \t\t\n \t} catch (Exception e) {\n \t logger.error(\"LdapManager error: modify attributes failed, \"+e);\n \t}\n \t\n \tString result = \"fail\";\n \treturn result;\n }\n \n public void deleteEntry(String dn, EntryType entryType) {\n \tDirContext context = null;\n \tString usrDn = dn+\",\"+getDomainComponents();\n \t\n \ttry {\n \t\tcontext = getContext();\n \t\tcontext.destroySubcontext(usrDn);\n \t\t\n \t\t// Delete user from role\n \t\tif (entryType.equals(EntryType.USER)) {\n \t\t\tremoveUserFromRole(usrDn);\n \t\t}\n \t\t\n \t\tcontext.close();\n \t\t\n \t} catch (Exception e) {\n \t logger.error(\"LdapManager error: deleteEntry failed, \"+e);\n \t}\t\n }\n \n private void setDomainComponents(String baseDomainComponents) {\n this.domainComponents = baseDomainComponents;\n }\n \n public String getDomainComponents() {\n return this.domainComponents;\n }\n \n private void setInstanceAdminDn(String instanceAdmin) {\n // Dn for instance admin\n if (!this.domainComponents.isEmpty() && instanceAdmin.endsWith(this.domainComponents)) {\n this.instanceAdminDn = instanceAdmin;\n }\n }\n \n public String getInstanceAdminDn() {\n return this.instanceAdminDn;\n }\n\n}", "public class Role implements Serializable {\n\n private static final long serialVersionUID = -6687757850396871383L;\n private static final Logger logger = Logger.getLogger(Role.class);\n public static final String ROLE_PUBLIC = \"public\";\n \n // role name\n public String name;\n // access rights\n private Vector<AccessRight> roleAccessrights = new Vector<AccessRight>();\n // user dns, who has this role\n private Vector<String> roleOccupants = new Vector<String>();\n \n /**\n * Constructor\n */\n public Role() {\n this.name = \"\";\n }\n \n /**\n * Constructor\n */\n public Role(String name) {\n this.name = name;\n }\n \n /**\n * Constructor\n */\n public Role(String name, Vector<AccessRight> roleAccessrights) {\n this.name = name;\n this.roleAccessrights = roleAccessrights;\n }\n \n /**\n * Constructor\n * @param isAnonymous user not logged in\n * @param organization organization name for public search \n */\n public Role(boolean isAnonymous, String organization) {\n this.name = \"\";\n \n if (isAnonymous) {\n this.name = \"anonymous\";\n String path = organization.toUpperCase()+\":root\";\n AccessRight bublicRight = new AccessRight();\n bublicRight.setAccessRightLevel(AccessRight.ACCESSRIGHTLEVEL_READ_META);\n bublicRight.setAccessRightPath(path);\n this.setRoleAccessright(bublicRight);\n }\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public String getName() {\n return this.name;\n }\n \n public void setRoleAccessright (AccessRight ac) {\n this.roleAccessrights.add(ac);\n }\n \n public Vector<AccessRight> getRoleAccessrights () {\n return this.roleAccessrights;\n }\n \n public void setRoleAccessrights (Vector<AccessRight> acrights) {\n this.roleAccessrights = acrights;\n }\n \n public void setRoleOccupant (String userdn) {\n this.roleOccupants.add(userdn);\n }\n \n public Vector<String> getRoleOccupants () {\n return this.roleOccupants;\n }\n \n public void setRoleOccupants (Vector<String> userdns) {\n this.roleOccupants = userdns;\n }\n \n /**\n * Access rights for public role\n * @param organization\n * @return\n */\n public static Vector<AccessRight> getPublicRoleAccessrights (String organization) {\n Vector<AccessRight> publicRoleAccessrights = new Vector<AccessRight>();\n AccessRight ac = new AccessRight();\n ac.setAccessRightPath(organization.toUpperCase()+\":root/+\");\n publicRoleAccessrights.add(ac);\n return publicRoleAccessrights;\n }\n \n /**\n * Return highest accessright for object based on its path and publicity level\n * @param roles user roles\n * @param path object path\n * @param publicityLevel object publicity level\n * @return\n */\n public static int getAccessRightForObject(Vector<Role> roles, String path, String publicityLevel) {\n Vector<Integer> accessRightValues = new Vector<Integer>();\n int retValue = AccessRight.ACCESSRIGHTLEVEL_DENY_META;\n \n if (path == null || path == \"\" || roles == null) {\n return retValue;\n }\n \n for (Role role : roles) {\n Vector<AccessRight> acRights = role.getRoleAccessrights();\n for (AccessRight ac : acRights) {\n String acPath = ac.getAccessRightPath();\n int acLevel = ac.getAccessRightLevel();\n if (acPath.endsWith(\"+\")) {\n // recursive path\n acPath = acPath.replace(\"+\", \"\");\n if (path.startsWith(acPath)) {\n if (ac.getPublicityLevels().contains(publicityLevel)) {\n accessRightValues.add(acLevel);\n }\n }\n \n } else {\n // exact path\n if (path.equals(acPath)) {\n if (ac.getPublicityLevels().contains(publicityLevel)) {\n accessRightValues.add(acLevel);\n }\n }\n }\n }\n }\n \n if (!accessRightValues.isEmpty()) {\n \n if (accessRightValues.contains(AccessRight.ACCESSRIGHTLEVEL_DENY_META)) {\n // if denied\n retValue = AccessRight.ACCESSRIGHTLEVEL_DENY_META;\n } else {\n // set the max accessright\n retValue = Collections.max(accessRightValues);\n }\n }\n \n return retValue;\n }\n \n /**\n * Method for comparing users accessrights to the object based on its path and publicity level.\n * @param roles\n * @param path\n * @param publicityLevel\n * @param requiredLevel\n * @return\n */\n public static boolean hasRights(Vector<Role> roles, String path, String publicityLevel, int requiredLevel) {\n Vector<Integer> accessRightValues = new Vector<Integer>();\n boolean retValue = false;\n \n if (path == null || path == \"\" || roles == null) {\n return retValue;\n }\n \n for (Role role : roles) {\n Vector<AccessRight> acRights = role.getRoleAccessrights();\n for (AccessRight ac : acRights) {\n String acPath = ac.getAccessRightPath();\n int acLevel = ac.getAccessRightLevel();\n if (acPath.endsWith(\"+\")) {\n // recursive path\n acPath = acPath.replace(\"+\", \"\");\n if (path.startsWith(acPath)) {\n if (ac.getPublicityLevels().contains(publicityLevel)) {\n accessRightValues.add(acLevel);\n }\n }\n \n } else {\n // exact path\n if (path.equals(acPath)) {\n if (ac.getPublicityLevels().contains(publicityLevel)) {\n accessRightValues.add(acLevel);\n }\n }\n }\n }\n }\n \n if (!accessRightValues.isEmpty()) {\n \n if (accessRightValues.contains(AccessRight.ACCESSRIGHTLEVEL_DENY_META)) {\n // if denied\n retValue = false;\n } else if (Collections.max(accessRightValues) >= requiredLevel) {\n retValue = true;\n }\n }\n \n return retValue;\n }\n \n @Override\n public String toString() {\n return \"role [name=\"+name+\", roleAccessrights: \"+roleAccessrights.size()+\" kpl]\";\n }\n}", "public static enum EntryType {\n\tUSER,\n\tROLE\n}", "public class User implements Serializable {\n \n private static final long serialVersionUID = -9105054849954016390L;\n private static final Logger logger = Logger.getLogger(User.class);\n \n\t/** Distinguished name */\n\tprivate String dn = null;\n\t/** Common name */\n\tprivate String cn = null;\n\t/** Password of the User. Could be cleartext, encoded or hash depending on implementation. */\n private String password = null;\n /** Unique identifier */\n private String uid = null;\n \n /** First name (given name) */ \n private String firstName = null;\n /** Last name (surname) */\n private String lastName = null;\n /** Description of the User */\n private String description = null;\n /** e-mail address of the User */\n private String mail = null;\n /** Preferred language of the User */\n private String preferredLanguage = null;\n /** Title of the User */\n private String title = null;\n /** Employee number of the User */\n private String employeeNumber = null;\n /** Jpeg photo of the User. Could be URI or file address depenging on implementation */\n\tprivate String jpegPhoto = null;\n\t/** Role for fedora commons repository */\n\tprivate Vector<Role> fedoraRoles = null;\n\t/** User's organization */\n private Organization organization = null;\n /** User's group in organization */\n private String group = null;\n\t/** Locale of the User */\n\tprivate Locale locale = null;\n\t/** User is anonymous */\n\tprivate boolean anonymous = false;\n\t/** User is instance admin */\n\tprivate boolean instance_admin = false;\n\t\n\tprivate int highestAccessRight = 0;\n\t\n\t/**\n * Constructor\n */\n\tpublic User() {\n\t \n\t}\n\t\n\t/**\n * Constructor\n */\n\tpublic User(String dn, Locale language) {\n\t \n this.setDn(dn);\n \n // get user attributes from ldap\n\t HashMap<String,String> usrAttrs = Osa.authManager.getAttributes(dn);\n\t \n\t if (dn.equals(Osa.authManager.getInstanceAdminDn())) {\n\t this.setInstanceAdmin(true);\n\t } \n\t \n\t if (usrAttrs.containsKey(\"cn\")) {\n this.setCn(usrAttrs.get(\"cn\"));\n this.setAnonymous(false);\n logger.info(\"logged in with dn: \"+dn);\n } else {\n this.setAnonymous(true);\n logger.info(\"logged in as anonymous user with dn: \"+dn);\n }\n\t \n if (usrAttrs.containsKey(\"preferredLanguage\")) {\n String[] localeParts = usrAttrs.get(\"preferredLanguage\").split(\"_\");\n this.locale = new Locale(localeParts[0],localeParts[1]);\n }\n \n // TODO: find better way to do this\n // parse organization name from dn\n\t String[] parts = dn.split(\",\");\n\t String orgname = \"\";\n\t for (int i=0; i<parts.length; i++) {\n\t \tif (parts[i].indexOf(\"o=\") == 0) {\n\t \t\torgname = parts[i].replace(\"o=\", \"\");\n\t \t\tbreak;\n\t \t}\n\t }\n\t \n\t Organization org = new Organization(dn.replaceAll(\"(cn=.*?,)\", \"\"), orgname, null);\n\t this.setOrganization(org);\n\n\t if (usrAttrs.containsKey(\"mail\")) {\n\t this.setMail(usrAttrs.get(\"mail\"));\n\t }\n\t \n\t if (anonymous) {\n\t Role anonymousRole = Osa.authManager.getPublicRole(orgname);\n\t Vector<Role> anonymousRoles = new Vector<Role>();\n\t anonymousRoles.add(anonymousRole);\n\t this.setFedoraRoles(anonymousRoles);\n\t logger.info(\"User role in Fedora: \"+anonymousRole.name);\n\t \n\t if (language != null) {\n\t this.locale = language;\n\t }\n\t \n\t } else if (!this.isInstanceAdmin()) {\n\t this.setFedoraRoles(Osa.authManager.getUserRoles(dn, org.getName()));\n\t for (Role role : this.getFedoraRoles()) {\n\t logger.info(\"User role in Fedora: \"+role.name);\n\t }\n\t }\n\t \n\t logger.info(\"User rolelevel: \"+this.getHighestAccessRight());\t \n\t logger.info(\"User locale: \"+this.locale);\n\t logger.info(\"User organization: \"+this.organization.getName());\n\t}\n\t\n\t/**\n * @return the application role\n */\n\tpublic String getRole() {\n\t int acRight = this.getHighestAccessRight();\n\t String role = \"\";\n\t \n\t if (this.isInstanceAdmin()) {\n\t role = \"instance_admin\";\n\t } else if (acRight == AccessRight.ACCESSRIGHTLEVEL_ADMIN) {\n\t role = \"admin\";\n\t } else if (acRight == AccessRight.ACCESSRIGHTLEVEL_RECORDSMANAGEMENT) {\n\t role = \"manager\";\n\t } else {\n\t role = \"reader\";\n\t }\n\t return role;\n\t}\n\n\t\n\t/**\n\t * @return the dn\n\t */\n\tpublic String getDn() {\n\t\treturn dn;\n\t}\n\t/**\n\t * @param dn the dn to set\n\t */\n\tpublic void setDn(String dn) {\n\t\tthis.dn = dn;\n\t}\n\t/**\n\t * @return the cn\n\t */\n\tpublic String getCn() {\n\t\treturn cn;\n\t}\n\t/**\n\t * @param cn the cn to set\n\t */\n\tpublic void setCn(String cn) {\n\t\tthis.cn = cn;\n\t}\n\t/**\n\t * @return the password\n\t */\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\t/**\n\t * @param password the password to set\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\t/**\n\t * @return the uid\n\t */\n\tpublic String getUid() {\n\t\treturn uid;\n\t}\n\t/**\n\t * @param uid the uid to set\n\t */\n\tpublic void setUid(String uid) {\n\t\tthis.uid = uid;\n\t}\n\t/**\n\t * @return the firstName\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\t/**\n\t * @param firstName the firstName to set\n\t */\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\t/**\n\t * @return the lastName\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\t/**\n\t * @param lastName the lastName to set\n\t */\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\t/**\n\t * @return the description\n\t */\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\t/**\n\t * @param description the description to set\n\t */\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\t/**\n\t * @return the mail\n\t */\n\tpublic String getMail() {\n\t\treturn mail;\n\t}\n\t/**\n\t * @param mail the mail to set\n\t */\n\tpublic void setMail(String mail) {\n\t\tthis.mail = mail;\n\t}\n\t/**\n\t * @return the preferredLanguage\n\t */\n\tpublic String getPreferredLanguage() {\n\t\treturn preferredLanguage;\n\t}\n\t/**\n\t * @param preferredLanguage the preferredLanguage to set\n\t */\n\tpublic void setPreferredLanguage(String preferredLanguage) {\n\t\tthis.preferredLanguage = preferredLanguage;\n\t}\n\t/**\n\t * @return the title\n\t */\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\t/**\n\t * @param title the title to set\n\t */\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\t/**\n\t * @return the employeeNumber\n\t */\n\tpublic String getEmployeeNumber() {\n\t\treturn employeeNumber;\n\t}\n\t/**\n\t * @param employeeNumber the employeeNumber to set\n\t */\n\tpublic void setEmployeeNumber(String employeeNumber) {\n\t\tthis.employeeNumber = employeeNumber;\n\t}\n\t/**\n\t * @return the jpegPhoto\n\t */\n\tpublic String getJpegPhoto() {\n\t\treturn jpegPhoto;\n\t}\n\t\n\t/**\n\t * Get all access right filters from user roles\n\t * @return\n\t */\n\tpublic Vector< HashMap<String, String> > getAccessRightFilters() {\n\t // Collect filters per role to vector\n\t Vector< HashMap<String, String> > filters = new Vector< HashMap<String, String> >();\n\t // vector to store paths, where access is denied\n Vector<String> nonAccessiblePaths = new Vector<String>();\n \n if (this.isInstanceAdmin()) {\n return filters;\n }\n \n // Check if access is denied\n for (Role role : this.getFedoraRoles()) {\n for (AccessRight acRight : role.getRoleAccessrights()) {\n int accessRightLevel = acRight.getAccessRightLevel();\n if (accessRightLevel == AccessRight.ACCESSRIGHTLEVEL_DENY_META) {\n // access denied to this path\n String accessRightPath = \"(\"+acRight.getAccessRightPath()+\"\";\n // replace '+' char with '*' for Solr. Query syntax: (\"publicityLevel AND accessRightPath/\"*)\n if (accessRightPath.contains(\"+\")) accessRightPath = accessRightPath.replace(\"+\", \"\") + \"*\";\n accessRightPath += \")\"; \n nonAccessiblePaths.add(accessRightPath);\n }\n }\n }\n \n // Go through all roles\n\t for (Role role : this.getFedoraRoles()) {\n // Go through all AccessRights of the Role\n for (AccessRight acRight : role.getRoleAccessrights()) {\n String publicityLevels = \"(\" + acRight.getPublicityLevels() + \")\";\n String accessRightPath = \"(\" + acRight.getAccessRightPath() + \"\";\n // replace '+' char with '*' for Solr. Query syntax: (\"publicityLevel AND accessRightPath/\"*)\n if (accessRightPath.contains(\"+\")) accessRightPath = accessRightPath.replace(\"+\", \"\") + \"*\";\n accessRightPath += \")\";\n int accessRightLevel = acRight.getAccessRightLevel();\n HashMap<String, String> filter = new HashMap<String, String>();\n\n if (accessRightLevel != AccessRight.ACCESSRIGHTLEVEL_DENY_META) {\n filter.put(\"c.accessRights\", publicityLevels);\n filter.put(\"m.objectPath\", accessRightPath);\n \n // add paths, where access is denied, to filter\n for (String path : nonAccessiblePaths) {\n filter.put(\"-m.objectPath\", path);\n }\n filters.add(filter);\n }\n }\n }\n return filters;\n }\n\t\n /**\n * @param User's highest accessright level to set\n */\n public void setHighestAccessRight(int value) {\n this.highestAccessRight = value;\n }\n \n\t/**\n\t * @return User's highest accessright\n\t */\n public int getHighestAccessRight() {\n int value = 0;\n if (this.highestAccessRight == 0) {\n if (this.isInstanceAdmin()) {\n value = AccessRight.ACCESSRIGHTLEVEL_INSTANCEADMIN;\n } else {\n for (Role role : this.getFedoraRoles()) {\n for (AccessRight acRight : role.getRoleAccessrights()) {\n if (acRight.getAccessRightLevel() > value) {\n value = acRight.getAccessRightLevel();\n }\n }\n }\n }\n setHighestAccessRight(value);\n }\n return this.highestAccessRight;\n }\n\t\n /**\n * @return the roles determined to fedora\n */\n public Vector<Role> getFedoraRoles() {\n \treturn this.fedoraRoles;\n }\n /**\n * @param roles to the roles set\n */\n public void setFedoraRoles(Vector<Role> roles) {\n \tthis.fedoraRoles = roles;\n }\n\t/**\n\t * @param jpegPhoto the jpegPhoto to set\n\t */\n\tpublic void setJpegPhoto(String jpegPhoto) {\n\t\tthis.jpegPhoto = jpegPhoto;\n\t}\n\t/**\n\t * @return the organization\n\t */\n\tpublic Organization getOrganization() {\n\t\treturn organization;\n\t}\n\t/**\n\t * @param organization the organization to set\n\t */\n\tpublic void setOrganization(Organization organization) {\n\t\tthis.organization = organization;\n\t}\n\t/**\n * @return group\n */\n\tpublic String getGroup() {\n return this.group;\n }\n\t/**\n * @param group the group to set\n */\n\tpublic void setGroup(String group) {\n\t this.group = group;\n\t}\n\t/**\n\t * @return the locale\n\t */\n\tpublic Locale getLocale() {\n\t\treturn locale;\n\t}\n\t/**\n\t * @param locale the locale to set\n\t */\n\tpublic void setLocale(Locale locale) {\n\t\tthis.locale = locale;\n\t}\n\n\tpublic String toString() { \n ReflectionToStringBuilder tsb = \n \tnew ReflectionToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);\n return tsb.toString();\n }\n\n\tpublic void setAnonymous(boolean anonymous) {\n\t\tthis.anonymous = anonymous;\n\t}\n\n\tpublic boolean isAnonymous() {\n\t\treturn anonymous;\n\t}\n\t\n\tpublic void setInstanceAdmin(boolean value) {\n\t this.instance_admin = value;\n\t}\n\t\n\tpublic boolean isInstanceAdmin() {\n return this.instance_admin;\n }\n\t\n\tpublic boolean isAdmin() {\n\t return this.getHighestAccessRight() >= AccessRight.ACCESSRIGHTLEVEL_ADMIN;\n }\n\n}", "public class Osa extends GenericServlet\n{\n private static final long serialVersionUID = 1L;\n private static final Logger logger = Logger.getLogger(Osa.class);\n\n public static AuthenticationManager authManager;\n\n public static HashMap<String, DatabaseManager> dbManager = new HashMap<String, DatabaseManager>();\n public static SearchManager searchManager;\n public static RepositoryManager fedoraManager;\n public static WorkflowManager workflowManager;\n public static TaskScheduler taskScheduler;\n \n public static String persistence;\n public static String systemDatabase;\n public static String documentDatabase;\n public static String authentication;\n public static String search;\n public static String logging;\n public static String defaultConfiguration;\n public static String defaultRoot;\n public static String configFolder;\n public static String onkiAccessKey;\n \n public static String tempDirectory;\n public static String dataDirectory;\n public static String logDirectory;\n public static String importDirectory; \n public static String ingestDirectory;\n public static String failedDirectory;\n public static String uploadDirectory;\n \n // TODO: move to database manager class\n public static DatabaseConfiguration dbConfiguration;\n \n // TODO: move to solr manager class\n public static String solrServerUrl;\n\t\n /** \n * \tInitializes Osa instance\n */\n public void init() throws ServletException {\n \n Properties properties = new Properties();\n try {\n \n properties.load(new FileInputStream(getServletContext().getRealPath(\"/\") + this.getInitParameter(\"config\")));\n \n // Directories\n // TODO check if directories exist and are accessible\n tempDirectory = properties.getProperty(\"osa.directory.temp\");\n dataDirectory = properties.getProperty(\"osa.directory.data\");\n logDirectory = properties.getProperty(\"osa.directory.log\");\n importDirectory = properties.getProperty(\"osa.directory.import\"); \n ingestDirectory = properties.getProperty(\"osa.directory.ingest\");\n failedDirectory = properties.getProperty(\"osa.directory.failed\");\n uploadDirectory = properties.getProperty(\"osa.directory.upload\"); \n \n // Persistence\n persistence = properties.getProperty(\"osa.persistence\");\n \n switch (persistence) {\n \tcase RepositoryManager.FEDORA3:\n \t String host = properties.getProperty(\"osa.fedora.server\");\n \t String port = properties.getProperty(\"osa.fedora.port\");\n \t String username = properties.getProperty(\"osa.fedora.username\");\n \t String password = properties.getProperty(\"osa.fedora.password\");\n \t String schemaPath = getServletContext().getRealPath(\"/\") + \"WEB-INF/\";\n \t \n \t\tOsa.fedoraManager = new Fedora3Manager(host, port, username, password, schemaPath);\n \t\t\n \t\t// TODO: Check Fedora server status\n \t\tbreak;\n \t\t\n \tcase RepositoryManager.FEDORA4:\n \t // TODO: version 4 support\n \t break;\n \n \tdefault:\n \t\tthrow new Exception(\"OSA instance requires a persistence module.\");\n } \n \n // Database\n systemDatabase = properties.getProperty(\"osa.database.system\");\n \n // TODO: Add support for multiple coexisting databases. \n switch (systemDatabase) {\n case \"mysql\":\n case \"mariadb\":\n\t Osa.dbConfiguration = new DatabaseConfiguration();\t\t\t\n\t Osa.dbConfiguration.setDbURI(properties.getProperty(\"osa.mysql.connectionString\"));\n\t Osa.dbConfiguration.setDbDriverName(properties.getProperty(\"osa.mysql.driver\"));\n\t Osa.dbConfiguration.setDbUser(properties.getProperty(\"osa.mysql.user\"));\n\t Osa.dbConfiguration.setDbPassword(properties.getProperty(\"osa.mysql.password\"));\n\t Osa.dbConfiguration.setDbPoolMinSize(Integer.parseInt(properties.getProperty(\"osa.mysql.poolMinSize\".trim())));\n\t Osa.dbConfiguration.setDbPoolMaxSize(Integer.parseInt(properties.getProperty(\"osa.mysql.poolMaxSize\").trim()));\n\t Osa.dbConfiguration.setDbTimeout( Integer.parseInt(properties.getProperty(\"osa.mysql.timeout\").trim()) );\n\t \n\t new ConnectionManager(dbConfiguration);\n\t Osa.dbManager.put(\"sql\", new MySQLManager());\n\t //logger.info(\"Database configuration loaded.\");\t \n\t\t\t\t\tbreak;\n\t\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OSA instance requires a system database module.\");\n\t\t\t}\n \n documentDatabase = properties.getProperty(\"osa.database.document\");\n \n switch (documentDatabase) {\n\t\t\t\tcase \"mongodb\":\n\t\t\t\t\tString mongohost = properties.getProperty(\"osa.mongo.host\");\n\t\t\t\t\tint mongoport = Integer.parseInt(properties.getProperty(\"osa.mongo.port\"));\n\t\t\t\t\tString mongoDefaultdb = properties.getProperty(\"osa.mongo.defaultdb\");\n\t\t\t\t\tString mongoDefautCollection = properties.getProperty(\"osa.mongo.defaultcollection\");\n\t\t\t\t\t\n\t Osa.dbManager.put(\"mongo\", new MongoManager(mongohost, mongoport, mongoDefaultdb, mongoDefautCollection));\n\t //logger.info(\"Mongo configuration loaded.\");\t \n\t\t\t\t\tbreak;\n\t\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OSA instance requires a document database module.\");\n\t\t\t}\n \n \n // Authentication\n authentication = properties.getProperty(\"osa.authentication\");\n switch (authentication) {\n \tcase \"ldap\":\n Osa.authManager = new LdapManager(\n properties.getProperty(\"osa.ldap.server\"),\n properties.getProperty(\"osa.ldap.admindn\"),\n properties.getProperty(\"osa.ldap.managepw\"),\n properties.getProperty(\"osa.ldap.basedn\"),\n properties.getProperty(\"osa.ldap.instanceadmin\")\n );\n \n // TODO: Check LDAP server status\n \t\tbreak;\n \n \tdefault:\n \t\tthrow new Exception(\"OSA instance requires an authentication module.\");\n }\n \n \n // Search\n search = properties.getProperty(\"osa.search\");\n switch (search) {\n\t\t\t\tcase \"solr\":\n\t\t\t\t\t\n\t\t\t\t\t// TODO Refactor inside the manager implementation\n\t \tOsa.solrServerUrl = properties.getProperty(\"osa.solr.server\");\n\n\t \tOsa.searchManager = new SolrManager();\n\t \t\n\t\t\t\t\t// TODO test sorl server status\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Exception(\"OSA instance requires a search module.\");\n\t\t\t}\n\n \n // Logger\n logging = properties.getProperty(\"osa.logger\");\n switch (logging) {\n \tcase \"log4j\":\n String configurationFile = this.getInitParameter(\"logger\");\n File file = new File(getServletContext().getRealPath(\"/\") + configurationFile);\n if(!file.canRead()) \n {\n throw new Exception(\"Couldn't read logger configuration file at \" + file.getAbsolutePath());\n }\n \n PropertyConfigurator.configure(file.getAbsolutePath()); \n \t\tbreak;\n \n \tdefault:\n \t\tthrow new Exception(\"OSA instance requires a logger module.\");\n } \n \n \n // Workflows\n String engineHost = properties.getProperty(\"osa.workflowengine.host\");\n String enginePort = properties.getProperty(\"osa.workflowengine.port\");\n try {\n Osa.workflowManager = new WorkflowManager(engineHost, enginePort);\n } catch (Exception e) {\n logger.info(\"WorkflowManager not available: \"+e);\n }\n \n // Load default conf.\n Osa.defaultConfiguration = properties.getProperty(\"osa.default.configuration\");\n Osa.configFolder = getServletContext().getRealPath(\"/\") + \"WEB-INF/config/\";\n Osa.defaultRoot = properties.getProperty(\"osa.default.root\");\n \n \n // ONKI access key according to external IP address\n final String prefix = \"osa.onki.key.\";\n String externalIP = getIP();\n char[] chArr = prefix.toCharArray(); \n chArr[chArr.length -1]++; \n String endPrefix = new String(chArr);\n Set<String> allNames = properties.stringPropertyNames(); \n SortedSet<String> names = new TreeSet<String>(allNames).subSet(prefix, endPrefix);\n Iterator<String> it = names.iterator(); \n while (it.hasNext()) {\n String key = it.next();\n if (key.endsWith(externalIP)) {\n Osa.onkiAccessKey = properties.getProperty(key);\n break;\n }\n }\n \n if (Osa.onkiAccessKey == null) {\n // Default value\n Osa.onkiAccessKey = properties.getProperty(\"osa.onki.key.default\");\n }\n \n // Scheduled tasks\n if (properties.getProperty(\"osa.scheduledtasks\").equals(\"1\")) {\n String configPath = getServletContext().getRealPath(\"/\") + \"WEB-INF/\";\n taskScheduler = new TaskScheduler(\"AutomaticDestruction\", \"triggername\", logDirectory, configPath);\n taskScheduler.start();\n }\n \n logger.info(\"OSA version [\" + getVersionString() + \"] + started. See log for more information.\");\n\n } catch (Exception e) {\n logger.error(\"Error initializing OSA instance. \" + e);\n System.exit(0);\n }\n }\n \n public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {\n \tthrow new UnsupportedOperationException(\"Not supported.\");\t\n }\n \n public static String getVersionString() {\n \treturn \"release 1.0 - december 2014\";\n }\n \n /**\n * Get external IP address\n */\n public String getIP() throws IOException {\n String ip = \"\";\n URL whatismyip = new URL(\"http://checkip.amazonaws.com\");\n BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));\n ip = in.readLine();\n return ip;\n }\n\n}", "public class RoleComparator extends BaseComparatorUtils implements Comparator<Role> {\n\tpublic static String NAME \t\t= \"name\";\n\t\n\tprivate String param \t= \"name\";\n\tprivate int order \t\t= 1;\n\t\n\t/** Sorts roles by name property with ascending order.\n\t * \n\t */\n\tpublic RoleComparator() {\n\t}\n\t\n\t/**\tSorts roles by given property with ascending order.\n\t * \n\t * @param parameter\t\tRole property to sort by\n\t */\n\tpublic RoleComparator(String parameter) {\n\t\tthis.param = parameter;\n\t}\n\t\n\t/**\n\t * \n\t * @param parameter\t\tRole property to sort by\n\t * @param reverse\t\tOrder of the sort. <b>True = descending, false = ascending</b>\n\t */\n\tpublic RoleComparator(String parameter, boolean reverse) {\n\t\tthis.param = parameter;\n\t\tthis.order = (reverse) ? -1 : 1;\n\t\t\n\t}\n\t\n\tpublic int compare(Role role1, Role role2) {\n\t\tInteger isNull = checkNull(role1, role2); \n\t\tif (isNull == null) {\n\t\t\tswitch (param) {\n\t\t\t\tcase \"name\":\n\t\t\t\t\tisNull = checkNull(role1.getName(), role2.getName());\n\t\t\t\t\tif (isNull == null) {\n\t\t\t\t\t\treturn role1.getName().toLowerCase().compareTo(role2.getName().toLowerCase()) * order;\n\t\t\t\t\t}\n\t\t\t\t\treturn isNull * order;\n\t\t\t\tdefault: \n\t\t\t\t\treturn role1.getName().toLowerCase().compareTo(role2.getName().toLowerCase()) * order;\n\t\t\t}\n\t\t} else {\n\t\t\treturn isNull.intValue() * order;\n\t\t}\n\t}\n}" ]
import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Vector; import fi.mamk.osa.auth.AccessRight; import fi.mamk.osa.auth.LdapManager; import fi.mamk.osa.auth.Role; import fi.mamk.osa.auth.LdapManager.EntryType; import fi.mamk.osa.auth.User; import fi.mamk.osa.core.Osa; import fi.mamk.osa.utils.RoleComparator; import net.sourceforge.stripes.action.HandlesEvent; import net.sourceforge.stripes.action.LocalizableMessage; import net.sourceforge.stripes.action.RedirectResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.StreamingResolution; import net.sourceforge.stripes.action.UrlBinding; import net.sourceforge.stripes.validation.LocalizableError; import net.sourceforge.stripes.validation.ValidationErrors; import net.sourceforge.stripes.validation.ValidationMethod; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger;
package fi.mamk.osa.stripes; /** * Role Action */ @UrlBinding("/Role.action") public class RoleAction extends OsaBaseActionBean { private static final Logger logger = Logger.getLogger(RoleAction.class); private String roleName; private String roleOrganization; private String messageAddSuccess; private String messageAddFail; private String sEcho; private String roleDn; private Vector<String> entryDns; Vector<AccessRight> accessrights = new Vector<AccessRight>(); @HandlesEvent("addRole") public Resolution addRole() { // get complete path for pids handleAccessrightPaths();
boolean added = Osa.authManager.createRole(roleName, roleOrganization, accessrights);
5
occi4java/occi4java
http/src/test/java/de/occi/test/TestRestCompute.java
[ "public class OcciConfig extends XMLConfiguration {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static final Logger LOGGER = LoggerFactory\n\t\t\t.getLogger(OcciConfig.class);\n\t/**\n\t * Instance of OcciConfig\n\t */\n\tprivate static OcciConfig instance = null;\n\tprivate static ConfigurationFactory factory;\n\t/**\n\t * Configuration for all occi properties\n\t */\n\tpublic Configuration config;\n\n\tprivate OcciConfig() {\n\t\tfactory = new ConfigurationFactory();\n\t\t// load configuration file\n\t\tURL configURL = getClass().getResource(\"/conf/config.xml\");\n\t\tfactory.setConfigurationURL(configURL);\n\t\ttry {\n\t\t\t// pick up configuration\n\t\t\tconfig = factory.getConfiguration();\n\t\t} catch (ConfigurationException e) {\n\t\t\tLOGGER.error(\"Failed to load config file.\");\n\t\t}\n\t}\n\n\tpublic static OcciConfig getInstance() {\n\t\tif (instance == null) {\n\t\t\t// create OcciConfig instance\n\t\t\tinstance = new OcciConfig();\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tnew OcciConfig();\n\t}\n}", "public class occiApi extends ServerResource {\n\t// initialize server component\n\tpublic static Component comp = new Component();\n\n\tpublic static void main(String[] args) throws Exception {\n\t\t// load all logger properties\n\t\tif (new File(\"conf/log4j.properties\").exists())\n\t\t\tPropertyConfigurator.configure(\"conf/log4j.properties\");\n\t\telse\n\t\t\tPropertyConfigurator\n\t\t\t\t\t.configure(\"../core/src/main/resources/conf/log4jTest.properties\");\n\t\t// Create the HTTP server and listen on port 8182\n\t\tcomp.getServers().add(Protocol.HTTP,\n\t\t\t\tOcciConfig.getInstance().config.getInt(\"occi.server.port\"));\n\n\t\tcomp.getDefaultHost().attach(\"/\", OcciRestRoot.class);\n\t\t// Router for the Query/Discovery Interface.\n\t\tcomp.getDefaultHost().attach(\"/-/\", OcciRestQuery.class);\n\n\t\t// Returns one single instance of a compute resource\n\t\tcomp.getDefaultHost().attach(\"/compute\", OcciRestCompute.class);\n\t\tcomp.getDefaultHost().attach(\"/compute/{uuid}\", OcciRestCompute.class);\n\n\t\t// Returns all compute instances\n\t\tcomp.getDefaultHost().attach(\"/compute/\", OcciRestComputes.class);\n\n\t\t// Router for storage instances\n\t\tcomp.getDefaultHost().attach(\"/storage\", OcciRestStorage.class);\n\n\t\t// Returns all storage instances\n\t\tcomp.getDefaultHost().attach(\"/storage/\", OcciRestStorages.class);\n\n\t\t// Router for storage instances\n\t\tcomp.getDefaultHost().attach(\"/network\", OcciRestNetwork.class);\n\t\tcomp.getDefaultHost().attach(\"/network/{uuid}\", OcciRestNetwork.class);\n\t\tcomp.getDefaultHost().attach(\"/networkinterface\",\n\t\t\t\tOcciRestNetworkInterface.class);\n\t\tcomp.getDefaultHost().attach(\"/networkinterface/{uuid}\",\n\t\t\t\tOcciRestNetworkInterface.class);\n\t\t// Returns all storage instances\n\t\tcomp.getDefaultHost().attach(\"/network/\", OcciRestNetworks.class);\n\t\t// Router for all available mixin instances. Returns mixin information.\n\t\tcomp.getDefaultHost().attach(\"/{mixin}\", OcciRestMixin.class);\n\t\t// start occi api\n\t\tcomp.start();\n\t}\n}", "public class Compute extends Resource {\n\t/**\n\t * Enumeration for CPU Architecture of the instance\n\t */\n\tpublic enum Architecture {\n\t\tx86, x64\n\t}\n\n\t/**\n\t * Number of CPU Cores assigned to the Instance\n\t */\n\tprivate int cores;\n\n\t/**\n\t * String DNS hostname for the Instance\n\t */\n\tprivate String hostname;\n\n\t/**\n\t * Float CPU Clock frequency in gigahertz\n\t */\n\tprivate float speed;\n\n\t/**\n\t * Float RAM in gigabytes allocated to the instance\n\t */\n\tprivate float memory;\n\n\t/**\n\t * State of the compute resource\n\t */\n\tprivate State state;\n\n\t/**\n\t * Architecture of the compute resource\n\t */\n\tprivate Architecture architecture;\n\n\t/**\n\t * Current State of the instance\n\t */\n\tpublic enum State {\n\t\tactive, inactive, suspended\n\t}\n\n\t/**\n\t * Static Hashmap of all Compute Resources. The Key is a UUID, the Value a\n\t * Compute Object.\n\t */\n\tprivate static Map<UUID, Compute> computeList = new HashMap<UUID, Compute>();\n\n\t/**\n\t * Static HashSet of all compute attributes.\n\t */\n\tprivate static HashSet<String> attributes = new HashSet<String>();\n\n\t/**\n\t * Random UUID of the compute resource.\n\t */\n\tprivate final UUID uuid;\n\n\t/*\n\t * All possible compute actions.\n\t */\n\tprivate static ListableBeanFactory beanFactory = new ClassPathXmlApplicationContext(\n\t\t\t\"occiConfig.xml\");\n\tprivate Action start = (Action) beanFactory.getBean(\"start\");\n\tprivate Action stop = (Action) beanFactory.getBean(\"stop\");\n\tprivate Action suspend = (Action) beanFactory.getBean(\"suspend\");\n\tprivate Action restart = (Action) beanFactory.getBean(\"restart\");\n\n\tprivate static final HashSet<Action> actionSet = new HashSet<Action>();\n\tprivate static final HashSet<String> actionNames = new HashSet<String>();\n\n\tpublic Compute(Architecture architecture, int cores, String hostname,\n\t\t\tfloat speed, float memory, State state, Set<String> attributes)\n\t\t\tthrows URISyntaxException, NumberFormatException,\n\t\t\tIllegalArgumentException, NamingException {\n\t\tsuper(\"Compute\", links, attributes);\n\t\tthis.architecture = architecture;\n\t\tthis.cores = cores;\n\t\tthis.hostname = hostname;\n\t\tthis.speed = speed;\n\t\tthis.memory = memory;\n\t\tthis.state = state;\n\n\t\tgenerateActionNames();\n\n\t\t// check if all attributes are correct\n\t\tif ((cores < 1)) {\n\t\t\tthrow new NumberFormatException(\"Number of cores is negative!\");\n\t\t} else if (speed < 0) {\n\t\t\tthrow new NumberFormatException(\"Number of speed is negative!\");\n\t\t} else if (memory < 0) {\n\t\t\tthrow new NumberFormatException(\"Number of memory is negative!\");\n\t\t}\n\t\t// check if there is a hostname\n\t\tif (hostname.length() == 0) {\n\t\t\tthrow new NamingException(\n\t\t\t\t\t\"Name of the Compute resource can not be null\");\n\t\t}\n\t\t/*\n\t\t * set Category\n\t\t */\n\t\tsetKind(new Kind(actionSet, null, null, null, \"compute\", \"Compute\",\n\t\t\t\tOcciConfig.getInstance().config.getString(\"occi.scheme\")\n\t\t\t\t\t\t+ \"/infrastructure#\", attributes));\n\t\tgetKind().setActionNames(actionNames);\n\t\t// set uuid for the resource\n\t\tuuid = UUID.randomUUID();\n\t\tsetId(new URI(uuid.toString()));\n\t\t// put resource into compute list\n\t\tcomputeList.put(uuid, this);\n\n\t\t// Generate attribute list\n\t\tgenerateAttributeList();\n\t}\n\n\t/**\n\t * Return the full computeList\n\t * \n\t * @return all compute resources\n\t */\n\tpublic static final Map<UUID, Compute> getComputeList() {\n\t\treturn computeList;\n\t}\n\n\t/**\n\t * Set compute list\n\t * \n\t * @param computeList\n\t */\n\tpublic static final void setComputeList(Map<UUID, Compute> computeList) {\n\t\tCompute.computeList = computeList;\n\t}\n\n\t/**\n\t * Returns the current UUID as a UUID Value\n\t * \n\t * @return current UUID assigned to the Instance\n\t */\n\tpublic final UUID getUuid() {\n\t\treturn uuid;\n\t}\n\n\t/**\n\t * Returns the current Cores as a int Value\n\t * \n\t * @return current Cores assigned to the Instance\n\t */\n\tpublic final int getCores() {\n\t\treturn cores;\n\t}\n\n\t/**\n\t * Sets the cores of the current Instance\n\t * \n\t * @param cores\n\t * of the current Instance as an int\n\t */\n\tpublic final void setCores(int cores) {\n\t\tthis.cores = cores;\n\t}\n\n\t/**\n\t * Returns the Hostname represented as a String of the current Instance\n\t * \n\t * @return Hostname as a String\n\t */\n\tpublic final String getHostname() {\n\t\treturn hostname;\n\t}\n\n\t/**\n\t * Sets the hostname of the current Instance\n\t * \n\t * @param hostname\n\t * of the current Instance as a String\n\t */\n\tpublic final void setHostname(String hostname) {\n\t\tthis.hostname = hostname;\n\t}\n\n\t/**\n\t * Returns the speed of the current Instance as a float\n\t * \n\t * @return speed of the current Instance\n\t */\n\tpublic final float getSpeed() {\n\t\treturn speed;\n\t}\n\n\t/**\n\t * Sets the speed of the current Instance\n\t * \n\t * @param speed\n\t * of the current Instance as a float\n\t */\n\tpublic final void setSpeed(float speed) {\n\t\tthis.speed = speed;\n\t}\n\n\t/**\n\t * Returns the memory of the current Instace as a float\n\t * \n\t * @return\n\t */\n\tpublic final float getMemory() {\n\t\treturn memory;\n\t}\n\n\t/**\n\t * Sets the memory of the current Instance\n\t * \n\t * @param memory\n\t * of the current Instance as a float\n\t */\n\tpublic final void setMemory(float memory) {\n\t\tthis.memory = memory;\n\t}\n\n\t/**\n\t * Returns the State of the current Instance\n\t * \n\t * @return State of the current Instance\n\t */\n\tpublic final State getState() {\n\t\treturn state;\n\t}\n\n\t/**\n\t * Sets the State of the current Instance\n\t * \n\t * @param State\n\t * state of the current Instance\n\t */\n\tpublic final void setState(State state) {\n\t\tthis.state = state;\n\t}\n\n\t/**\n\t * Returns the Architecture of the current Instance\n\t * \n\t * @return architecture of the current Instance of enum-type Architectures\n\t */\n\tpublic final Architecture getArchitecture() {\n\t\treturn architecture;\n\t}\n\n\t/**\n\t * Sets the Architecture of the current Instance\n\t * \n\t * @param architecture\n\t * of the current Instance\n\t */\n\tpublic final void setArchitecture(Architecture architecture) {\n\t\tthis.architecture = architecture;\n\t}\n\n\t/**\n\t * Return list of all action names.\n\t * \n\t * @return action names\n\t */\n\tpublic static final HashSet<String> getActionNames() {\n\t\treturn actionNames;\n\t}\n\n\t/**\n\t * Generate list with action names.\n\t */\n\tpublic static final HashSet<String> generateActionNames() {\n\t\tif (actionNames.isEmpty()) {\n\t\t\tfor (int i = 0; i < beanFactory.getBeanDefinitionNames().length; i++) {\n\t\t\t\tif (beanFactory\n\t\t\t\t\t\t.getBean(beanFactory.getBeanDefinitionNames()[i])\n\t\t\t\t\t\t.toString().contains(\"compute\")) {\n\t\t\t\t\tactionNames.add(OcciConfig.getInstance().config\n\t\t\t\t\t\t\t.getString(\"occi.scheme\")\n\t\t\t\t\t\t\t+ \"/infrastructure/compute/action#\"\n\t\t\t\t\t\t\t+ beanFactory.getBeanDefinitionNames()[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn actionNames;\n\t}\n\n\t/**\n\t * Generate list with actions.\n\t */\n\tpublic static final HashSet<Action> generateActionSet() {\n\t\tif (actionSet.isEmpty()) {\n\t\t\tfor (int i = 0; i < beanFactory.getBeanDefinitionNames().length; i++) {\n\t\t\t\tif (beanFactory\n\t\t\t\t\t\t.getBean(beanFactory.getBeanDefinitionNames()[i])\n\t\t\t\t\t\t.toString().contains(\"compute\")) {\n\t\t\t\t\tactionSet.add((Action) beanFactory.getBean(beanFactory\n\t\t\t\t\t\t\t.getBeanDefinitionNames()[i]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn actionSet;\n\t}\n\n\t/**\n\t * Generate attribute List.\n\t */\n\tpublic static final void generateAttributeList() {\n\t\tif (attributes.isEmpty()) {\n\t\t\t// add all attributes to attribute list\n\t\t\tattributes.add(\"occi.compute.architecture\");\n\t\t\tattributes.add(\"occi.compute.cores\");\n\t\t\tattributes.add(\"occi.compute.hostname\");\n\t\t\tattributes.add(\"occi.compute.memory\");\n\t\t\tattributes.add(\"occi.compute.speed\");\n\t\t\tattributes.add(\"occi.compute.state\");\n\t\t}\n\t}\n\n\t/**\n\t * Return the compute attributes.\n\t * \n\t * @return attributes\n\t */\n\tpublic static final HashSet<String> getAttributes() {\n\t\treturn attributes;\n\t}\n\n\t/**\n\t * @param start\n\t * the start to set\n\t */\n\tpublic final void setStart(Action start) {\n\t\tthis.start = start;\n\t}\n\n\t/**\n\t * @return the start\n\t */\n\tpublic final Action getStart() {\n\t\treturn start;\n\t}\n\n\t/**\n\t * @param stop\n\t * the stop to set\n\t */\n\tpublic final void setStop(Action stop) {\n\t\tthis.stop = stop;\n\t}\n\n\t/**\n\t * @return the stop\n\t */\n\tpublic final Action getStop() {\n\t\treturn stop;\n\t}\n\n\t/**\n\t * @param restart\n\t * the restart to set\n\t */\n\tpublic final void setRestart(Action restart) {\n\t\tthis.restart = restart;\n\t}\n\n\t/**\n\t * @return the restart\n\t */\n\tpublic final Action getRestart() {\n\t\treturn restart;\n\t}\n\n\t/**\n\t * @param suspend\n\t * the suspend to set\n\t */\n\tpublic final void setSuspend(Action suspend) {\n\t\tthis.suspend = suspend;\n\t}\n\n\t/**\n\t * @return the suspend\n\t */\n\tpublic final Action getSuspend() {\n\t\treturn suspend;\n\t}\n}", "public enum Architecture {\n\tx86, x64\n}", "public enum State {\n\tactive, inactive, suspended\n}" ]
import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; import java.net.URISyntaxException; import javax.naming.NamingException; import occi.config.OcciConfig; import occi.http.occiApi; import occi.infrastructure.Compute; import occi.infrastructure.Compute.Architecture; import occi.infrastructure.Compute.State; import org.restlet.Request;
/** * Copyright (C) 2010-2011 Sebastian Heckmann, Sebastian Laag * * Contact Email: <[email protected]>, <[email protected]> * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl-3.0.txt * * 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 de.occi.test; /** * Class to test the compute interface. The test class starts the occi api and * connects to it via client resource. * * Test cases are: HTTP POST HTTP GET HTTP DELETE HTTP PUT * * @author Sebastian Laag * @author Sebastian Heckmann */ public class TestRestCompute { private ClientResource clientResource = new ClientResource( OcciConfig.getInstance().config.getString("occi.server.location")); @BeforeTest public void setUp() { try { // start occi api
occiApi.main(null);
1
moovida/STAGE
eu.hydrologis.stage.treeslicesviewer/src/eu/hydrologis/stage/treeslicesviewer/TreeSlicesViewerEntryPoint.java
[ "public class StageLogger {\n\n public static final boolean LOG_INFO = true;\n public static final boolean LOG_DEBUG = false;\n public static final boolean LOG_ERROR = true;\n\n private static final String SEP = \":: \";\n\n private static SimpleDateFormat f = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n public static void logInfo( Object owner, String msg ) {\n if (LOG_INFO) {\n msg = toMessage(owner, msg);\n System.out.println(msg);\n }\n }\n\n public static void logDebug( Object owner, String msg ) {\n if (LOG_DEBUG) {\n msg = toMessage(owner, msg);\n System.out.println(msg);\n }\n }\n\n public static void logError( Object owner, String msg, Throwable e ) {\n if (LOG_ERROR) {\n msg = toMessage(owner, msg);\n System.err.println(msg);\n e.printStackTrace();\n }\n }\n\n public static void logError( Object owner, Throwable e ) {\n logError(owner, null, e);\n }\n\n private static String toMessage( Object owner, String msg ) {\n if (msg == null)\n msg = \"\";\n String newMsg = f.format(new Date()) + SEP;\n if (owner instanceof String) {\n newMsg = newMsg + owner + SEP;\n } else {\n newMsg = newMsg + owner.getClass().getSimpleName() + SEP;\n }\n newMsg = newMsg + msg;\n return newMsg;\n }\n\n}", "public class StageUtils {\n\n /**\n * Supported file formats in read and write mode.\n */\n public static String[] EXTENTIONS_READ_WRITE = {\"asc\", \"tiff\", \"tif\", \"shp\", \"las\", \"laz\"};\n\n /**\n * Supported vector formats in read and write mode.\n */\n public static String[] VECTOR_EXTENTIONS_READ_WRITE = {\"shp\", \"las\", \"laz\"};\n\n /**\n * Supported raster formats in read and write mode.\n */\n public static String[] RASTER_EXTENTIONS_READ_WRITE = {\"asc\", \"tiff\", \"tif\"};\n\n /**\n * General textcolor.\n */\n public static final String TEXTCOLOR = \"#505050\";\n\n public static String escapeHTML( String s ) {\n StringBuilder out = new StringBuilder(Math.max(16, s.length()));\n for( int i = 0; i < s.length(); i++ ) {\n char c = s.charAt(i);\n if (c > 127 || c == '\"' || c == '<' || c == '>' || c == '&') {\n out.append(\"&#\");\n out.append((int) c);\n out.append(';');\n } else {\n out.append(c);\n }\n }\n return out.toString();\n }\n\n public static String[] getUserPwdWithBasicAuthentication( String authHeader ) {\n if (authHeader != null) {\n StringTokenizer st = new StringTokenizer(authHeader);\n if (st.hasMoreTokens()) {\n String basic = st.nextToken();\n\n if (basic.equalsIgnoreCase(\"Basic\")) {\n String credentials;\n try {\n credentials = new String(Base64.decode(st.nextToken()), \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n return null;\n }\n int p = credentials.indexOf(\":\");\n if (p != -1) {\n String login = credentials.substring(0, p).trim();\n String password = credentials.substring(p + 1).trim();\n\n return new String[]{login, password};\n } else {\n return null;\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Open a url (or relative url).\n * \n * @param url the url.\n * @param openInNewTab if <code>true</code>, the url is opened in a new browser tab.\n */\n public static void openUrl( String url, boolean openInNewTab ) {\n if (openInNewTab) {\n UrlLauncher launcher = RWT.getClient().getService(UrlLauncher.class);\n launcher.openURL(url);\n } else {\n JavaScriptExecutor executor = RWT.getClient().getService(JavaScriptExecutor.class);\n executor.execute(\"window.location = \\\"\" + url + \"\\\";\");\n }\n }\n\n /**\n * Block until the browser object is safe to execute a script.\n * \n * <p>This is an ugly hack right now.\n * \n * @param browser the browser to check.\n * @throws NoSuchFieldException\n * @throws IllegalAccessException\n */\n public static void blockWhileOtherScriptIsBusy( final Browser browser ) throws NoSuchFieldException, IllegalAccessException {\n Field f = browser.getClass().getDeclaredField(\"executeScript\"); // NoSuchFieldException\n f.setAccessible(true);\n Object exeScript = null; // IllegalAccessException\n while( exeScript != null ) {\n exeScript = f.get(browser);\n }\n }\n}", "public class DownloadUtils {\n public boolean sendDownload( Shell parentShell, File file ) throws FileNotFoundException, IOException {\n byte[] data = IOUtils.toByteArray(new FileInputStream(file));\n DownloadService service = new DownloadService(data, file.getName());\n service.register();\n\n final Browser browser = new Browser(parentShell, SWT.NONE);\n browser.setSize(0, 0);\n browser.setUrl(service.getURL());\n\n return true;\n }\n\n public boolean sendDownload( Shell parentShell, String fileName, byte[] data ) throws FileNotFoundException, IOException {\n DownloadService service = new DownloadService(data, fileName);\n service.register();\n\n final Browser browser = new Browser(parentShell, SWT.NONE);\n browser.setSize(0, 0);\n browser.setUrl(service.getURL());\n\n return true;\n }\n\n public static final class DownloadService implements ServiceHandler {\n\n private final byte[] data;\n private final String filename;\n private String id;\n\n public DownloadService( byte[] data, String filename ) {\n this.data = data;\n this.filename = filename;\n this.id = calculateId();\n }\n\n public String getURL() {\n return RWT.getServiceManager().getServiceHandlerUrl(getId());\n }\n\n private String getId() {\n return id;\n }\n\n private String calculateId() {\n return String.valueOf(System.currentTimeMillis()) + data.length;\n }\n\n public boolean register() {\n try {\n RWT.getServiceManager().registerServiceHandler(getId(), this);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n private boolean unregister() {\n try {\n RWT.getServiceManager().unregisterServiceHandler(getId());\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n @Override\n public void service( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException {\n try {\n response.setContentType(\"application/octet-stream\");\n response.setContentLength(data.length);\n response.setHeader(\"Content-Disposition\", \"attachment; filename=\\\"\" + filename + \"\\\"\");\n response.getOutputStream().write(data);\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n unregister();\n }\n }\n\n }\n\n}", "public class LoginDialog extends Dialog {\n\n public static final String SESSION_USER_KEY = \"SESSION_USER\";\n\n private static final long serialVersionUID = 1L;\n\n private static final String LOGINMESSAGE = \"Please sign in with your username and password:\";\n private static final String LOGIN = \"Login\";\n private static final String CANCEL = \"Cancel\";\n private static final String PASSWORD = \"Password:\";\n private static final String USERNAME = \"Username:\";\n\n private static final int LOGIN_ID = IDialogConstants.CLIENT_ID + 1;\n private Text userText;\n private Text passText;\n private Label mesgLabel;\n private final String title;\n private final String message;\n private String username;\n private String password;\n\n public LoginDialog( Shell parent, String title, String message ) {\n super(parent);\n this.title = title;\n this.message = message;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setUsername( String username ) {\n this.username = username;\n }\n\n public String getUsername() {\n return username;\n }\n\n @Override\n protected void configureShell( Shell shell ) {\n super.configureShell(shell);\n if (title != null) {\n shell.setText(title);\n }\n }\n\n @Override\n protected Control createDialogArea( Composite parent ) {\n Composite composite = (Composite) super.createDialogArea(parent);\n composite.setLayout(new GridLayout(2, false));\n mesgLabel = new Label(composite, SWT.NONE);\n GridData messageData = new GridData(SWT.FILL, SWT.CENTER, true, false);\n messageData.horizontalSpan = 2;\n mesgLabel.setLayoutData(messageData);\n Label userLabel = new Label(composite, SWT.NONE);\n userLabel.setText(USERNAME);\n userText = new Text(composite, SWT.BORDER);\n userText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));\n Label passLabel = new Label(composite, SWT.NONE);\n passLabel.setText(PASSWORD);\n passText = new Text(composite, SWT.BORDER | SWT.PASSWORD);\n passText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));\n initilizeDialogArea();\n return composite;\n }\n\n @Override\n protected void createButtonsForButtonBar( Composite parent ) {\n createButton(parent, IDialogConstants.CANCEL_ID, CANCEL, false);\n createButton(parent, LOGIN_ID, LOGIN, true);\n }\n\n @Override\n protected void buttonPressed( int buttonId ) {\n if (buttonId == LOGIN_ID) {\n username = userText.getText();\n password = passText.getText();\n setReturnCode(OK);\n close();\n } else {\n password = null;\n }\n super.buttonPressed(buttonId);\n }\n\n private void initilizeDialogArea() {\n if (message != null) {\n mesgLabel.setText(message);\n }\n if (username != null) {\n userText.setText(username);\n }\n userText.setFocus();\n }\n\n /**\n * Show login screen and check pwd.\n * \n * <p>Dummy implementation.\n * \n * @param shell\n * @return the {@link User} or <code>null</code>.\n */\n public static boolean checkUserLogin( Shell shell ) {\n HttpSession httpSession = RWT.getUISession().getHttpSession();\n Object attribute = httpSession.getAttribute(SESSION_USER_KEY);\n if (attribute instanceof String) {\n return true;\n } else {\n String message = LOGINMESSAGE;\n final LoginDialog loginDialog = new LoginDialog(shell, LOGIN, message);\n loginDialog.setUsername(LoginChecker.TESTUSER);\n int returnCode = loginDialog.open();\n if (returnCode == Window.OK) {\n String username = loginDialog.getUsername();\n String password = loginDialog.getPassword();\n if (LoginChecker.isLoginOk(username, password)) {\n httpSession.setAttribute(SESSION_USER_KEY, username);\n\n try {\n StageWorkspace.getInstance().getDataFolder(username);\n StageWorkspace.getInstance().getScriptsFolder(username);\n StageWorkspace.getInstance().getGeopaparazziFolder(username);\n } catch (Exception e) {\n e.printStackTrace();\n MessageDialogUtil.openError(shell, \"Error\", \"An error occurred while trying to access the workspace.\",\n null);\n }\n return true;\n }\n }\n return false;\n }\n }\n\n}", "public class StageWorkspace {\n /**\n * Name of the default geopaparazzi project folder.\n */\n public static final String GEOPAPARAZZI_FOLDERNAME = \"geopaparazzi\";\n /**\n * Name of the default data folder.\n */\n public static final String DATA_FOLDERNAME = \"data\";\n /**\n * Name of the default scripts folder.\n */\n public static final String SCRIPTS_FOLDERNAME = \"scripts\";\n\n /**\n * Name of the string to use in scripts to refer to the remote data folder.\n * \n * <p>This will be substituted at runtime.\n */\n public static final String STAGE_DATA_FOLDER_SUBSTITUTION_NAME = \"@df\";\n\n private static final String COULD_NOT_CREATE_DATA_FOLDER = \"Could not create data folder in workspace.\";\n private static final String COULD_NOT_CREATE_GEOPAP_FOLDER = \"Could not create geopaparazzi folder in workspace.\";\n private static final String COULD_NOT_CREATE_SCRIPTS_FOLDER = \"Could not create scripts folder in workspace.\";\n private static final String COULD_NOT_CREATE_USER_FOLDER = \"Could not create user folder in workspace.\";\n private static final String NO_WORKSPACE_DEFINED = \"No workspace defined for the current installation.\";\n\n /**\n * The java -D commandline property that defines the workspace.\n */\n private static final String STAGE_WORKSPACE_JAVA_PROPERTIES_KEY = \"stage.workspace\";\n private static final String STAGE_DATAFOLDER_JAVA_PROPERTIES_KEY = \"stage.datafolder\";\n private static final String STAGE_SCRIPTSFOLDER_JAVA_PROPERTIES_KEY = \"stage.scriptsfolder\";\n private static final String STAGE_GEOPAPARAZZIFOLDER_JAVA_PROPERTIES_KEY = \"stage.geopaparazzifolder\";\n private static final String STAGE_ISLOCAL_KEY = \"stage.islocal\";\n\n private static StageWorkspace stageWorkspace;\n private File stageWorkspaceFolder;\n private File customDataFolder;\n private File customScriptsFolder;\n private File customGeopaparazziFolder;\n private boolean isLocal = false;\n\n public static StageWorkspace getInstance() {\n if (stageWorkspace == null) {\n stageWorkspace = new StageWorkspace();\n }\n return stageWorkspace;\n }\n\n private StageWorkspace() {\n String stageWorkspacepath = System.getProperty(STAGE_WORKSPACE_JAVA_PROPERTIES_KEY);\n if (stageWorkspacepath == null || !new File(stageWorkspacepath).exists()) {\n throw new RuntimeException(NO_WORKSPACE_DEFINED);\n }\n\n String dataFolderPath = System.getProperty(STAGE_DATAFOLDER_JAVA_PROPERTIES_KEY);\n if (dataFolderPath != null && new File(dataFolderPath).exists()) {\n customDataFolder = new File(dataFolderPath);\n StageLogger.logInfo(this, \"Custom data folder in use: \" + customDataFolder);\n }\n String scriptsFolderPath = System.getProperty(STAGE_SCRIPTSFOLDER_JAVA_PROPERTIES_KEY);\n if (scriptsFolderPath != null && new File(scriptsFolderPath).exists()) {\n customScriptsFolder = new File(scriptsFolderPath);\n StageLogger.logInfo(this, \"Custom scripts folder in use: \" + customScriptsFolder);\n }\n String geopaparazziFolderPath = System.getProperty(STAGE_GEOPAPARAZZIFOLDER_JAVA_PROPERTIES_KEY);\n if (geopaparazziFolderPath != null && new File(geopaparazziFolderPath).exists()) {\n customGeopaparazziFolder = new File(geopaparazziFolderPath);\n StageLogger.logInfo(this, \"Custom geopaparazzi folder in use: \" + customGeopaparazziFolder);\n }\n stageWorkspaceFolder = new File(stageWorkspacepath);\n\n String isLocalString = System.getProperty(STAGE_ISLOCAL_KEY);\n if (isLocalString != null) {\n try {\n isLocal = Boolean.parseBoolean(isLocalString);\n } catch (Exception e) {\n }\n }\n }\n\n private File getUserFolder( String user ) {\n File userFolder = new File(stageWorkspaceFolder, user);\n if (!userFolder.exists()) {\n if (!userFolder.mkdirs()) {\n throw new RuntimeException(COULD_NOT_CREATE_USER_FOLDER);\n }\n }\n return userFolder;\n }\n\n public File getScriptsFolder( String user ) {\n if (customScriptsFolder != null) {\n return customScriptsFolder;\n }\n File userFolder = getUserFolder(user);\n File scriptsFolder = new File(userFolder, SCRIPTS_FOLDERNAME);\n if (!scriptsFolder.exists() && !scriptsFolder.mkdirs()) {\n throw new RuntimeException(COULD_NOT_CREATE_SCRIPTS_FOLDER);\n }\n return scriptsFolder;\n }\n\n public File getDataFolder( String user ) {\n if (customDataFolder != null) {\n return customDataFolder;\n }\n File userFolder = getUserFolder(user);\n File dataFolder = new File(userFolder, DATA_FOLDERNAME);\n if (!dataFolder.exists() && !dataFolder.mkdirs()) {\n throw new RuntimeException(COULD_NOT_CREATE_DATA_FOLDER);\n }\n return dataFolder;\n }\n\n public void setCustomDataFolder( File customDataFolder ) {\n this.customDataFolder = customDataFolder;\n }\n\n public File getGeopaparazziFolder( String user ) {\n if (customGeopaparazziFolder != null) {\n return customGeopaparazziFolder;\n }\n File userFolder = getUserFolder(user);\n File geopaparazziFolder = new File(userFolder, GEOPAPARAZZI_FOLDERNAME);\n if (!geopaparazziFolder.exists() && !geopaparazziFolder.mkdirs()) {\n throw new RuntimeException(COULD_NOT_CREATE_GEOPAP_FOLDER);\n }\n return geopaparazziFolder;\n }\n\n /**\n * Getter for the isLocal var.\n * \n * @return <code>true</code>, if the app is being used locally, which enables some features.\n */\n public boolean isLocal() {\n return isLocal;\n }\n\n /**\n * Convert a file to its relative to datafolder version.\n * \n * @param currentFile the file to trim.\n * @return the relative path.\n */\n public static String makeRelativeToDataFolder( File currentFile ) {\n File dataFolder = getInstance().getDataFolder(User.getCurrentUserName());\n\n String dataFolderPath = dataFolder.getAbsolutePath();\n dataFolderPath = checkBackSlash(dataFolderPath);\n String filePath = currentFile.getAbsolutePath();\n filePath = checkBackSlash(filePath);\n\n String relativePath = filePath.replaceFirst(dataFolderPath, \"\");\n if (relativePath.startsWith(\"/\") && !new File(relativePath).exists()) {\n relativePath = relativePath.substring(1);\n }\n return relativePath;\n }\n\n /**\n * Substitute the datafolder in a string.\n * \n * @param stringToCheck\n * @return\n */\n public static String substituteDataFolder( String stringToCheck ) {\n File dataFolder = getInstance().getDataFolder(User.getCurrentUserName());\n\n String dataFolderPath = dataFolder.getAbsolutePath();\n dataFolderPath = checkBackSlash(dataFolderPath);\n\n String removed = stringToCheck.replaceAll(dataFolderPath, STAGE_DATA_FOLDER_SUBSTITUTION_NAME);\n return removed;\n }\n\n private static String checkBackSlash( String path ) {\n if (path != null) {\n path = path.replaceAll(\"\\\\\\\\\", \"/\");\n }\n return path;\n }\n\n public static String makeSafe( String path ) {\n path = path.replace('\\\\', '/');\n return path;\n }\n\n /**\n * Add to the relative file path the data folder. \n * \n * @param relativePath the relative path.\n * @param isOutFile <code>true</code>, if the path is supposed to be an outfile, in which\n * case the file doesn't exist, but the folder has to. \n * @return the complete absolute path.\n */\n public static File makeRelativeDataPathToFile( String relativePath, boolean isOutFile ) {\n int firstSlash = relativePath.indexOf('/');\n if (firstSlash > 2 || firstSlash == -1) {\n // it is assumed to be relative\n File dataFolder = getInstance().getDataFolder(User.getCurrentUserName());\n File file = new File(dataFolder, relativePath);\n return file;\n } else {\n File absolutePathFile = new File(relativePath);\n // if (!isOutFile) {\n // if (absolutePathFile.exists()) {\n // // it is an absolute path to an existing file, leave it as is\n // return absolutePathFile;\n // }\n // } else {\n // File parentFile = absolutePathFile.getParentFile();\n // if (parentFile != null && parentFile.exists()) {\n // // it is an absolute path to a file to be created,\n // // leave it if the folder exists\n // return absolutePathFile;\n // }\n // }\n return absolutePathFile;\n }\n }\n}", "public class User {\n\n private String name;\n\n public User( String name ) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n /**\n * @return the name of the current session user.\n */\n public static String getCurrentUserName() {\n HttpSession httpSession = RWT.getUISession().getHttpSession();\n Object attribute = httpSession.getAttribute(LoginDialog.SESSION_USER_KEY);\n if (attribute instanceof String) {\n return (String) attribute;\n }\n throw new IllegalArgumentException(\"No user defined for the session.\");\n }\n}" ]
import static java.lang.Math.max; import static java.lang.Math.min; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.text.DecimalFormat; import java.util.Arrays; import java.util.HashMap; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.rap.rwt.RWT; import org.eclipse.rap.rwt.application.AbstractEntryPoint; import org.eclipse.rap.rwt.widgets.BrowserCallback; import org.eclipse.rap.rwt.widgets.BrowserUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.BrowserFunction; import org.eclipse.swt.browser.ProgressEvent; import org.eclipse.swt.browser.ProgressListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.jgrasstools.gears.utils.files.FileUtilities; import org.json.JSONArray; import org.json.JSONObject; import eu.hydrologis.stage.libs.log.StageLogger; import eu.hydrologis.stage.libs.utils.StageUtils; import eu.hydrologis.stage.libs.utilsrap.DownloadUtils; import eu.hydrologis.stage.libs.utilsrap.LoginDialog; import eu.hydrologis.stage.libs.workspace.StageWorkspace; import eu.hydrologis.stage.libs.workspace.User;
public void completed( ProgressEvent event ) { addMapBrowserFunctions(); Rectangle clientArea = mapBrowser.getClientArea(); int w = clientArea.width; int h = clientArea.height; mapBrowser.evaluate("createMap(" + w + ", " + h + ")"); } public void changed( ProgressEvent event ) { System.out.println(); } }); } private void selectPlot( String selectedText ) { File plotFile = new File(selectedFile, selectedText + ".json"); id2TreeJsonMap.clear(); if (plotFile.exists()) { plotObjectTransfer = new JSONObject(); try { String fileJson = FileUtilities.readFile(plotFile); JSONObject plotObject = new JSONObject(fileJson); JSONObject plotData = plotObject.getJSONObject(JSON_PLOT_DATA); JSONArray plotsArray = plotData.getJSONArray(JSON_PLOTS); JSONObject selectedJsonPlot = plotsArray.getJSONObject(0); String id = selectedJsonPlot.getString(JSON_PLOT_ID); double lon = selectedJsonPlot.getDouble(JSON_PLOT_CENTERLON); double lat = selectedJsonPlot.getDouble(JSON_PLOT_CENTERLAT); double radius = selectedJsonPlot.getDouble(JSON_PLOT_RADIUS); double radiusLL = selectedJsonPlot.getDouble(JSON_PLOT_RADIUSDEG); plotObjectTransfer.put(JSON_PLOT_ID, id); plotObjectTransfer.put(JSON_PLOT_CENTERLAT, lat); plotObjectTransfer.put(JSON_PLOT_CENTERLON, lon); plotObjectTransfer.put(JSON_PLOT_RADIUSDEG, radiusLL); StringBuilder plotInfoSB = new StringBuilder(); plotInfoSB.append("<b>PLOT INFORMATION</b><br/>\n"); plotInfoSB.append("id = " + id + "<br/>"); plotInfoSB.append("lon = " + llFormatter.format(lon) + "<br/>"); plotInfoSB.append("lat = " + llFormatter.format(lat) + "<br/>"); plotInfoSB.append("radius = " + radiusFormatter.format(radius) + " m<br/>"); int fpCount = 0; int fnCount = 0; int matchedCount = 0; minHeight = Double.POSITIVE_INFINITY; minDiam = Double.POSITIVE_INFINITY; maxHeight = Double.NEGATIVE_INFINITY; maxDiam = Double.NEGATIVE_INFINITY; JSONArray treesArrayTransfer = new JSONArray(); int index = 0; plotObjectTransfer.put(JSON_PLOT_TREES, treesArrayTransfer); JSONArray treesArray = selectedJsonPlot.getJSONArray(JSON_PLOT_TREES); for( int i = 0; i < treesArray.length(); i++ ) { JSONObject treeObject = treesArray.getJSONObject(i); String treeId = treeObject.getString(JSON_TREE_ID); id2TreeJsonMap.put(treeId, treeObject); double treeHeight = treeObject.getDouble(JSON_TREE_HEIGHT); minHeight = min(minHeight, treeHeight); maxHeight = max(maxHeight, treeHeight); boolean hasDiam = false; boolean hasMatch = false; double diamLL = 0; double diam = 0; if (treeObject.has(JSON_TREE_DIAM)) { hasDiam = true; diam = treeObject.getDouble(JSON_TREE_DIAM); diamLL = treeObject.getDouble(JSON_TREE_DIAMDEG); minDiam = min(minDiam, diamLL); maxDiam = max(maxDiam, diamLL); } if (treeObject.has(JSON_TREE_ID_MATCHED)) { matchedCount++; hasMatch = true; } if (!hasDiam) { fpCount++; } else { if (!hasMatch) { fnCount++; } } JSONObject treeObjectTransfer = new JSONObject(); treesArrayTransfer.put(index++, treeObjectTransfer); treeObjectTransfer.put(JSON_TREE_ID, treeId); treeObjectTransfer.put(JSON_TREE_LAT, treeObject.getDouble(JSON_TREE_LAT)); treeObjectTransfer.put(JSON_TREE_LON, treeObject.getDouble(JSON_TREE_LON)); treeObjectTransfer.put(JSON_TREE_HEIGHT, treeObject.getDouble(JSON_TREE_HEIGHT)); if (hasDiam) { treeObjectTransfer.put(JSON_TREE_DIAMDEG, diamLL); treeObjectTransfer.put(JSON_TREE_DIAM, diam); } if (hasMatch) { treeObjectTransfer.put(JSON_TREE_ID_MATCHED, treeObject.getString(JSON_TREE_ID_MATCHED)); for( String dir : JSON_DIRECTIONS ) { double progressiveMatched = treeObject.getDouble(JSON_TREE_PROGRESSIVE_MATCHED + dir); treeObjectTransfer.put(JSON_TREE_PROGRESSIVE_MATCHED + dir, progressiveMatched); } treeObjectTransfer.put(JSON_TREE_HEIGHT_MATCHED, treeObject.getDouble(JSON_TREE_HEIGHT_MATCHED)); } } plotInfoSB.append("<br/><b>Matching:</b><br/>\n"); plotInfoSB.append("true positives = " + matchedCount + "<br/>"); plotInfoSB.append("false negatives = " + fnCount + "<br/>"); plotInfoSB.append("false positives = " + fpCount + "<br/>");
String text = "<font color=\"" + StageUtils.TEXTCOLOR + "\">" + plotInfoSB.toString() + "</font>";
1
bodar/yatspec
test/com/googlecode/yatspec/rendering/html/HtmlResultRendererTest.java
[ "public class ContentAtUrl implements Content {\n private final URL url;\n\n public ContentAtUrl(URL url) {\n this.url = url;\n }\n\n @Override\n public String toString() {\n InputStream inputStream = null;\n try {\n inputStream = url.openStream();\n return Strings.toString(inputStream);\n } catch (IOException e) {\n return e.toString();\n } finally {\n closeQuietly(inputStream);\n }\n }\n\n private static void closeQuietly(InputStream inputStream) {\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n}", "public interface Renderer<T> {\n String render(T t) throws Exception;\n}", "@SuppressWarnings(\"unused\")\npublic class Scenario {\n private TestState testState = new TestState();\n private final String name;\n private final JavaSource specification;\n private Throwable exception;\n private boolean wasRun = false;\n\n\n public Scenario(String name, JavaSource specification) {\n this.name = name;\n this.specification = specification;\n }\n\n public String getName() {\n return name;\n }\n\n public void setTestState(TestState testState) {\n this.testState = testState;\n }\n\n public Map<LogKey, Object> getLogs() {\n Map<LogKey, Object> result = new LinkedHashMap<LogKey, Object>();\n for (Map.Entry<String, Object> entry : getCapturedInputAndOutputs().entrySet()) {\n result.put(new LogKey(entry.getKey()), entry.getValue()); \n }\n return result;\n }\n\n public Map<String, Object> getCapturedInputAndOutputs() {\n return testState.capturedInputAndOutputs.getTypes();\n }\n\n public Map<String, Object> getInterestingGivens() {\n return testState.interestingGivens.getTypes();\n }\n\n public void setException(Throwable exception) {\n this.exception = exception;\n }\n\n public Throwable getException() {\n return exception;\n }\n\n public boolean hasFailed() {\n return exception != null;\n }\n\n public JavaSource getSpecification() {\n return specification;\n }\n\n public boolean wasRun() {\n return wasRun;\n }\n\n public void hasRun(boolean value) {\n wasRun = value;\n }\n\n public String getMessage() {\n String result = \"Test not run\";\n if (wasRun()) {\n result = \"Test passed\";\n }\n if (hasFailed()) {\n result = getException().toString();\n }\n return result;\n }\n\n public Status getStatus() {\n if (hasFailed()) {\n return Status.Failed;\n }\n if (wasRun()) {\n return Status.Passed;\n }\n return Status.NotRun;\n }\n\n public String getUid() {\n return Integer.toString(hashCode());\n }\n}", "@SuppressWarnings({\"unused\"})\npublic class TestResult implements Result {\n private final Class<?> klass;\n private List<TestMethod> testMethods;\n\n public TestResult(Class<?> klass) {\n this.klass = klass;\n }\n\n @Override\n public Class<?> getTestClass() {\n return klass;\n }\n\n @Override\n public List<TestMethod> getTestMethods() throws Exception {\n if (testMethods == null) {\n testMethods = TestParser.parseTestMethods(klass);\n }\n return testMethods;\n }\n\n @Override\n public Scenario getScenario(String name) throws Exception {\n final Scenario testScenario = findScenario(name);\n testScenario.hasRun(true);\n return testScenario;\n }\n\n @Override\n public String getName() {\n String className = getTestClass().getSimpleName();\n if (className.endsWith(\"Test\")) {\n className = removeTestFrom(className);\n }\n return wordify(className);\n }\n\n @Override\n public String getPackageName() {\n return getTestClass().getPackage().getName();\n }\n\n private static String removeTestFrom(String className) {\n final int index = className.lastIndexOf(\"Test\");\n return className.substring(0, index);\n }\n\n private Scenario findScenario(final String name) throws Exception {\n return sequence(getTestMethods()).filter(hasScenario(name)).head().getScenario(name);\n }\n\n private static Predicate<TestMethod> hasScenario(final String name) {\n return new Predicate<TestMethod>() {\n public boolean matches(TestMethod testMethod) {\n return testMethod.hasScenario(name);\n }\n };\n }\n\n public List<Annotation> getAnnotations() {\n return yatspecAnnotations(asList(getTestClass().getAnnotations()));\n }\n}", "@SuppressWarnings(\"unused\")\npublic class TestState implements TestLogger, WithTestState {\n public InterestingGivens interestingGivens = new InterestingGivens();\n public CapturedInputAndOutputs capturedInputAndOutputs = new CapturedInputAndOutputs();\n\n public TestState given(GivensBuilder builder) throws Exception {\n interestingGivens = builder.build(interestingGivens);\n return this;\n }\n\n public TestState and(GivensBuilder builder) throws Exception {\n return given(builder);\n }\n\n public TestState when(ActionUnderTest actionUndertest) throws Exception {\n capturedInputAndOutputs = actionUndertest.execute(interestingGivens, capturedInputAndOutputs);\n return this;\n }\n\n public <ItemOfInterest> TestState then(StateExtractor<ItemOfInterest> extractor, Matcher<? super ItemOfInterest> matcher) throws Exception {\n assertThat(extractor.execute(capturedInputAndOutputs), matcher);\n return this;\n }\n\n public synchronized void log(String name, Object value) {\n int count = 1;\n String keyName = name;\n while (capturedInputAndOutputs.contains(keyName)) {\n keyName = name + count;\n count++;\n }\n capturedInputAndOutputs.add(keyName, value);\n }\n\n public TestState testState() {\n return this;\n }\n}" ]
import com.googlecode.totallylazy.Strings; import com.googlecode.yatspec.rendering.ContentAtUrl; import com.googlecode.yatspec.rendering.Renderer; import com.googlecode.yatspec.state.Scenario; import com.googlecode.yatspec.state.TestResult; import com.googlecode.yatspec.state.givenwhenthen.TestState; import org.junit.Test; import java.nio.file.Paths; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.nullValue;
package com.googlecode.yatspec.rendering.html; public class HtmlResultRendererTest { public static final String CUSTOM_RENDERED_TEXT = "some crazy and likely random string that wouldn't appear in the html"; @Test public void providesLinksToResultOutputRelativeToOutputDirectory() throws Exception { assertThat( HtmlResultRenderer.htmlResultRelativePath(this.getClass()), is(Paths.get("com/googlecode/yatspec/rendering/html/HtmlResultRendererTest.html").toString())); } @Test public void loadsTemplateOffClassPath() throws Exception { TestResult result = new TestResult(this.getClass()); String html = new HtmlResultRenderer().render(result); assertThat(html, is(not(nullValue()))); } @Test public void supportsCustomRenderingOfScenarioLogs() throws Exception { TestResult result = aTestResultWithCustomRenderTypeAddedToScenarioLogs(); String html = new HtmlResultRenderer(). withCustomRenderer(RenderedType.class, new DefaultReturningRenderer(CUSTOM_RENDERED_TEXT)). render(result); assertThat(html, containsString(CUSTOM_RENDERED_TEXT)); } @Test public void supportsCustomHeaderContent() throws Exception { TestResult result = new TestResult(getClass()); String html = new HtmlResultRenderer().
withCustomHeaderContent(new ContentAtUrl(getClass().getResource("CustomHeaderContent.html"))).
0
yyxhdy/ManyEAs
src/jmetal/encodings/solutionType/IntRealSolutionType.java
[ "public abstract class Problem implements Serializable {\n\n\t/**\n\t * Defines the default precision of binary-coded variables\n\t */\n\tprivate final static int DEFAULT_PRECISSION = 16;\n\n\t/**\n\t * Stores the number of variables of the problem\n\t */\n\tprotected int numberOfVariables_;\n\n\t/**\n\t * Stores the number of objectives of the problem\n\t */\n\tprotected int numberOfObjectives_;\n\n\t/**\n\t * Stores the number of constraints of the problem\n\t */\n\tprotected int numberOfConstraints_;\n\n\t/**\n\t * Stores the problem name\n\t */\n\tprotected String problemName_;\n\n\t/**\n\t * Stores the type of the solutions of the problem\n\t */\n\tprotected SolutionType solutionType_;\n\n\t/**\n\t * Stores the lower bound values for each encodings.variable (only if\n\t * needed)\n\t */\n\tprotected double[] lowerLimit_;\n\n\t/**\n\t * Stores the upper bound values for each encodings.variable (only if\n\t * needed)\n\t */\n\tprotected double[] upperLimit_;\n\n\t/**\n\t * Stores the number of bits used by binary-coded variables (e.g.,\n\t * BinaryReal variables). By default, they are initialized to\n\t * DEFAULT_PRECISION)\n\t */\n\tprivate int[] precision_;\n\n\t/**\n\t * Stores the length of each encodings.variable when applicable (e.g.,\n\t * Binary and Permutation variables)\n\t */\n\tprotected int[] length_;\n\n\t/**\n\t * Stores the type of each encodings.variable\n\t */\n\t// public Class [] variableType_;\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Problem() {\n\t\tsolutionType_ = null;\n\t} // Problem\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Problem(SolutionType solutionType) {\n\t\tsolutionType_ = solutionType;\n\t} // Problem\n\n\t/**\n\t * Gets the number of decision variables of the problem.\n\t * \n\t * @return the number of decision variables.\n\t */\n\tpublic int getNumberOfVariables() {\n\t\treturn numberOfVariables_;\n\t} // getNumberOfVariables\n\n\t/**\n\t * Sets the number of decision variables of the problem.\n\t */\n\tpublic void setNumberOfVariables(int numberOfVariables) {\n\t\tnumberOfVariables_ = numberOfVariables;\n\t} // getNumberOfVariables\n\n\t/**\n\t * Gets the the number of objectives of the problem.\n\t * \n\t * @return the number of objectives.\n\t */\n\tpublic int getNumberOfObjectives() {\n\t\treturn numberOfObjectives_;\n\t} // getNumberOfObjectives\n\n\t/**\n\t * Gets the lower bound of the ith encodings.variable of the problem.\n\t * \n\t * @param i\n\t * The index of the encodings.variable.\n\t * @return The lower bound.\n\t */\n\tpublic double getLowerLimit(int i) {\n\t\treturn lowerLimit_[i];\n\t} // getLowerLimit\n\n\t/**\n\t * Gets the upper bound of the ith encodings.variable of the problem.\n\t * \n\t * @param i\n\t * The index of the encodings.variable.\n\t * @return The upper bound.\n\t */\n\tpublic double getUpperLimit(int i) {\n\t\treturn upperLimit_[i];\n\t} // getUpperLimit\n\n\t/**\n\t * Evaluates a <code>Solution</code> object.\n\t * \n\t * @param solution\n\t * The <code>Solution</code> to evaluate.\n\t */\n\tpublic abstract void evaluate(Solution solution) throws JMException;\n\n\t/**\n\t * Gets the number of side constraints in the problem.\n\t * \n\t * @return the number of constraints.\n\t */\n\tpublic int getNumberOfConstraints() {\n\t\treturn numberOfConstraints_;\n\t} // getNumberOfConstraints\n\n\t/**\n\t * Evaluates the overall constraint violation of a <code>Solution</code>\n\t * object.\n\t * \n\t * @param solution\n\t * The <code>Solution</code> to evaluate.\n\t */\n\tpublic void evaluateConstraints(Solution solution) throws JMException {\n\t\t// The default behavior is to do nothing. Only constrained problems have\n\t\t// to\n\t\t// re-define this method\n\t} // evaluateConstraints\n\n\t/**\n\t * Returns the number of bits that must be used to encode binary-real\n\t * variables\n\t * \n\t * @return the number of bits.\n\t */\n\tpublic int getPrecision(int var) {\n\t\treturn precision_[var];\n\t} // getPrecision\n\n\t/**\n\t * Returns array containing the number of bits that must be used to encode\n\t * binary-real variables.\n\t * \n\t * @return the number of bits.\n\t */\n\tpublic int[] getPrecision() {\n\t\treturn precision_;\n\t} // getPrecision\n\n\t/**\n\t * Sets the array containing the number of bits that must be used to encode\n\t * binary-real variables.\n\t * \n\t * @param precision\n\t * The array\n\t */\n\tpublic void setPrecision(int[] precision) {\n\t\tprecision_ = precision;\n\t} // getPrecision\n\n\t/**\n\t * Returns the length of the encodings.variable.\n\t * \n\t * @return the encodings.variable length.\n\t */\n\tpublic int getLength(int var) {\n\t\tif (length_ == null)\n\t\t\treturn DEFAULT_PRECISSION;\n\t\treturn length_[var];\n\t} // getLength\n\n\t/**\n\t * Sets the type of the variables of the problem.\n\t * \n\t * @param type\n\t * The type of the variables\n\t */\n\tpublic void setSolutionType(SolutionType type) {\n\t\tsolutionType_ = type;\n\t} // setSolutionType\n\n\t/**\n\t * Returns the type of the variables of the problem.\n\t * \n\t * @return type of the variables of the problem.\n\t */\n\tpublic SolutionType getSolutionType() {\n\t\treturn solutionType_;\n\t} // getSolutionType\n\n\t/**\n\t * Returns the problem name\n\t * \n\t * @return The problem name\n\t */\n\tpublic String getName() {\n\t\treturn problemName_;\n\t}\n\n\t/**\n\t * Returns the number of bits of the solutions of the problem\n\t * \n\t * @return The number of bits solutions of the problem\n\t */\n\tpublic int getNumberOfBits() {\n\t\tint result = 0;\n\t\tfor (int var = 0; var < numberOfVariables_; var++) {\n\t\t\tresult += getLength(var);\n\t\t}\n\t\treturn result;\n\t} // getNumberOfBits();\n} // Problem", "public abstract class SolutionType {\t\n\t\n\tpublic final Problem problem_ ; /** Problem to be solved */\n\t\n /**\n * Constructor\n * @param problem The problem to solve\n */\n public SolutionType(Problem problem) {\n \tproblem_ = problem ;\n } // Constructor\n \n /**\n * Abstract method to create the variables of the solution\n */\n\tpublic abstract Variable[] createVariables() throws ClassNotFoundException ;\n\t\n\t/**\n\t * Copies the decision variables\n\t * @param vars\n\t * @return An array of variables\n\t */\n\tpublic Variable[] copyVariables(Variable[] vars) {\n\t\tVariable[] variables ;\n\t\t\n\t\tvariables = new Variable[vars.length];\n\n\t\tfor (int var = 0; var < vars.length; var++) {\n\t\t\tvariables[var] = vars[var].deepCopy();\n\t\t} // for\n\t\t\n\t\treturn variables ;\n\t} // copyVariables\n\t \n} // SolutionType", "public abstract class Variable implements Serializable {\n\n /** \n * Creates an exact copy of a <code>Variable</code> object.\n * @return the copy of the object.\n */\n public abstract Variable deepCopy();\n\n /**\n * Gets the double value representating the encodings.variable.\n * It is used in subclasses of <code>Variable</code> (i.e. <code>Real</code> \n * and <code>Int</code>).\n * As not all objects belonging to a subclass of <code>Variable</code> have a \n * double value, a call to this method it is considered a fatal error by \n * default, and the program is terminated. Those classes requiring this method \n * must redefine it.\n */\n public double getValue() throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \" does not implement \" +\n \"method getValue\");\n throw new JMException(\"Exception in \" + name + \".getValue()\") ;\n } // getValue\n \n /**\n * Sets a double value to a encodings.variable in subclasses of <code>Variable</code>.\n * As not all objects belonging to a subclass of <code>Variable</code> have a \n * double value, a call to this method it is considered a fatal error by \n * default, and the program is terminated. Those classes requiring this method \n * must redefine it.\n */\n public void setValue(double value) throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \" does not implement \" +\n \"method setValue\");\n throw new JMException(\"Exception in \" + name + \".setValue()\") ;\n } // setValue\n\n /**\n * Gets the lower bound value of a encodings.variable. As not all\n * objects belonging to a subclass of <code>Variable</code> have a lower bound,\n * a call to this method is considered a fatal error by default,\n * and the program is terminated.\n * Those classes requiring this method must redefine it.\n */\n public double getLowerBound() throws JMException { \n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method getLowerBound()\");\n throw new JMException(\"Exception in \" + name + \".getLowerBound()\") ;\n } // getLowerBound\n \n /**\n * Gets the upper bound value of a encodings.variable. As not all\n * objects belonging to a subclass of <code>Variable</code> have an upper \n * bound, a call to this method is considered a fatal error by default, and the \n * program is terminated. Those classes requiring this method must redefine it.\n */\n public double getUpperBound() throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method getUpperBound()\");\n throw new JMException(\"Exception in \" + name + \".getUpperBound()\") ;\n } // getUpperBound\n \n /**\n * Sets the lower bound for a encodings.variable. As not all objects belonging to a\n * subclass of <code>Variable</code> have a lower bound, a call to this method \n * is considered a fatal error by default and the program is terminated.\n * Those classes requiring this method must to redefine it.\n */\n public void setLowerBound(double lowerBound) throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method setLowerBound()\");\n throw new JMException(\"Exception in \" + name + \".setLowerBound()\") ;\n } // setLowerBound\n \n /**\n * Sets the upper bound for a encodings.variable. As not all objects belonging to a\n * subclass of <code>Variable</code> have an upper bound, a call to this method\n * is considered a fatal error by default, and the program is terminated. \n * Those classes requiring this method must redefine it.\n */\n public void setUpperBound(double upperBound) throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method setUpperBound()\");\n throw new JMException(\"Exception in \" + name + \".setUpperBound()\") ;\n } // setUpperBound\n\n /**\n * Gets the type of the encodings.variable. The types are defined in class Problem.\n * @return The type of the encodings.variable\n */\n \n public Class getVariableType() {\n return this.getClass() ;\n } // getVariableType\n} // Variable", "public class Int extends Variable {\n\t\n\tprivate int value_; //Stores the value of the encodings.variable\n\tprivate int lowerBound_; //Stores the lower limit of the encodings.variable\n\tprivate int upperBound_; //Stores the upper limit of the encodings.variable\n\n\t/**\n\t * Constructor\n\t */\n\tpublic Int() {\n\t\tlowerBound_ = java.lang.Integer.MIN_VALUE ;\n\t\tupperBound_ = java.lang.Integer.MAX_VALUE ;\n\t\tvalue_ = 0 ;\n\t} // Int\n\n\t/**\n\t * Constructor\n\t * @param lowerBound Variable lower bound\n\t * @param upperBound Variable upper bound\n\t */\n\tpublic Int(int lowerBound, int upperBound){\n\t\tlowerBound_ = lowerBound;\n\t\tupperBound_ = upperBound;\n\t\tvalue_ = PseudoRandom.randInt(lowerBound, upperBound) ;\n\t} // Int\n\n\t/**\n\t * Constructor\n\t * @param value Value of the encodings.variable\n\t * @param lowerBound Variable lower bound\n\t * @param upperBound Variable upper bound\n\t */\n\tpublic Int(int value, int lowerBound, int upperBound) {\n\t\tsuper();\n\n\t\tvalue_ = value ;\n\t\tlowerBound_ = lowerBound ;\n\t\tupperBound_ = upperBound ;\n\t} // Int\n\n\t/**\n\t * Copy constructor.\n\t * @param variable Variable to be copied.\n\t * @throws JMException \n\t */\n\tpublic Int(Variable variable) throws JMException{\n\t\tlowerBound_ = (int)variable.getLowerBound();\n\t\tupperBound_ = (int)variable.getUpperBound();\n\t\tvalue_ = (int)variable.getValue(); \n\t} // Int\n\n\t/**\n\t * Returns the value of the encodings.variable.\n\t * @return the value.\n\t */\n\tpublic double getValue() {\n\t\treturn value_;\n\t} // getValue\n\n\t/**\n\t * Assigns a value to the encodings.variable.\n\t * @param value The value.\n\t */ \n\tpublic void setValue(double value) {\n\t\tvalue_ = (int)value;\n\t} // setValue\n\n\t/**\n\t * Creates an exact copy of the <code>Int</code> object.\n\t * @return the copy.\n\t */ \n\tpublic Variable deepCopy(){\n\t\ttry {\n\t\t\treturn new Int(this);\n\t\t} catch (JMException e) {\n\t\t\tConfiguration.logger_.severe(\"Int.deepCopy.execute: JMException\");\n\t\t\treturn null ;\n\t\t}\n\t} // deepCopy\n\n\t/**\n\t * Returns the lower bound of the encodings.variable.\n\t * @return the lower bound.\n\t */ \n\tpublic double getLowerBound() {\n\t\treturn lowerBound_;\n\t} // getLowerBound\n\n\t/**\n\t * Returns the upper bound of the encodings.variable.\n\t * @return the upper bound.\n\t */ \n\tpublic double getUpperBound() {\n\t\treturn upperBound_;\n\t} // getUpperBound\n\n\t/**\n\t * Sets the lower bound of the encodings.variable.\n\t * @param lowerBound The lower bound value.\n\t */\t \n\tpublic void setLowerBound(double lowerBound) {\n\t\tlowerBound_ = (int)lowerBound;\n\t} // setLowerBound\n\n\t/**\n\t * Sets the upper bound of the encodings.variable.\n\t * @param upperBound The new upper bound value.\n\t */ \n\tpublic void setUpperBound(double upperBound) {\n\t\tupperBound_ = (int)upperBound;\n\t} // setUpperBound\n\n\t/**\n\t * Returns a string representing the object\n\t * @return The string\n\t */ \n\tpublic String toString(){\n\t\treturn value_+\"\";\n\t} // toString\n} // Int", "public class Real extends Variable{\n\n /**\n * Stores the value of the real encodings.variable\n */\n private double value_;\n \n /**\n * Stores the lower bound of the real encodings.variable\n */\n private double lowerBound_;\n \n /**\n * Stores the upper bound of the real encodings.variable\n */\n private double upperBound_;\n \n /**\n * Constructor\n */\n public Real() {\n } // Real\n \n \n /**\n * Constructor\n * @param lowerBound Lower limit for the encodings.variable\n * @param upperBound Upper limit for the encodings.variable\n */\n public Real(double lowerBound, double upperBound){\n lowerBound_ = lowerBound;\n upperBound_ = upperBound;\n value_ = PseudoRandom.randDouble()*(upperBound-lowerBound)+lowerBound; \n } //Real\n\n /**\n * Constructor\n * @param lowerBound Lower limit for the encodings.variable\n * @param upperBound Upper limit for the encodings.variable\n * @param value Value of the variable\n */\n public Real(double lowerBound, double upperBound, double value){\n lowerBound_ = lowerBound;\n upperBound_ = upperBound;\n value_ = value ;\n } //Real\n \n /** \n * Copy constructor.\n * @param variable The encodings.variable to copy.\n * @throws JMException \n */\n public Real(Variable variable) throws JMException{\n lowerBound_ = variable.getLowerBound();\n upperBound_ = variable.getUpperBound();\n value_ = variable.getValue(); \n } //Real\n\n /**\n * Gets the value of the <code>Real</code> encodings.variable.\n * @return the value.\n */\n public double getValue() {\n return value_;\n } // getValue\n \n /**\n * Sets the value of the encodings.variable.\n * @param value The value.\n */\n public void setValue(double value) {\n value_ = value;\n } // setValue\n \n /** \n * Returns a exact copy of the <code>Real</code> encodings.variable\n * @return the copy\n */\n public Variable deepCopy(){\n try {\n return new Real(this);\n } catch (JMException e) {\n Configuration.logger_.severe(\"Real.deepCopy.execute: JMException\");\n return null ;\n }\n } // deepCopy\n\n \n /**\n * Gets the lower bound of the encodings.variable.\n * @return the lower bound.\n */\n public double getLowerBound() {\n return lowerBound_;\n } //getLowerBound\n\n /**\n * Gets the upper bound of the encodings.variable.\n * @return the upper bound.\n */\n public double getUpperBound() {\n return upperBound_;\n } // getUpperBound\n \n \n /**\n * Sets the lower bound of the encodings.variable.\n * @param lowerBound The lower bound.\n */\n public void setLowerBound(double lowerBound) {\n lowerBound_ = lowerBound;\n } // setLowerBound\n \n /**\n * Sets the upper bound of the encodings.variable.\n * @param upperBound The upper bound.\n */\n public void setUpperBound(double upperBound) {\n upperBound_ = upperBound;\n } // setUpperBound\n \n \n /**\n * Returns a string representing the object\n * @return the string\n */\n public String toString(){\n return value_+\"\";\n } //toString\n} // Real" ]
import jmetal.core.Problem; import jmetal.core.SolutionType; import jmetal.core.Variable; import jmetal.encodings.variable.Int; import jmetal.encodings.variable.Real;
// IntRealSolutionType.java // // Author: // Antonio J. Nebro <[email protected]> // Juan J. Durillo <[email protected]> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jmetal.encodings.solutionType; /** * Class representing a solution type including two variables: an integer * and a real. */ public class IntRealSolutionType extends SolutionType { private final int intVariables_ ; private final int realVariables_ ; /** * Constructor * @param problem Problem to solve * @param intVariables Number of integer variables * @param realVariables Number of real variables */
public IntRealSolutionType(Problem problem, int intVariables, int realVariables) {
0
DaiDongLiang/DSC
src/main/java/net/floodlightcontroller/core/internal/Controller.java
[ "public class ControllerId {\n private final short nodeId;\n\n private ControllerId(short nodeId) {\n if(nodeId == ClusterConfig.NODE_ID_UNCONFIGURED)\n throw new IllegalArgumentException(\"nodeId is unconfigured\");\n\n this.nodeId = nodeId;\n }\n\n public short getNodeId() {\n return nodeId;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + nodeId;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n ControllerId other = (ControllerId) obj;\n if (nodeId != other.nodeId)\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return Short.toString(nodeId);\n }\n\n public static ControllerId of(short nodeId) {\n return new ControllerId(nodeId);\n }\n\n}", "public class FloodlightContext {\n\t//一个线程安全的HashMap仓库\n protected ConcurrentHashMap<String, Object> storage =\n new ConcurrentHashMap<String, Object>();\n\n public ConcurrentHashMap<String, Object> getStorage() {\n return storage;\n }\n}", "@JsonSerialize(using=IOFSwitchSerializer.class)//Json序列化\npublic interface IOFSwitch extends IOFMessageWriter {\n // Attribute keys\n // These match our YANG schema, make sure they are in sync\n public static final String SWITCH_DESCRIPTION_FUTURE = \"description-future\";\n public static final String SWITCH_DESCRIPTION_DATA = \"description-data\";\n public static final String SWITCH_SUPPORTS_NX_ROLE = \"supports-nx-role\";\n public static final String PROP_FASTWILDCARDS = \"fast-wildcards\";\n public static final String PROP_REQUIRES_L3_MATCH = \"requires-l3-match\";\n public static final String PROP_SUPPORTS_OFPP_TABLE = \"supports-ofpp-table\";\n public static final String PROP_SUPPORTS_OFPP_FLOOD = \"supports-ofpp-flood\";\n public static final String PROP_SUPPORTS_NETMASK_TBL = \"supports-netmask-table\";\n public static final String PROP_SUPPORTS_BSN_SET_TUNNEL_DST_ACTION =\n \"supports-set-tunnel-dst-action\";\n public static final String PROP_SUPPORTS_NX_TTL_DECREMENT = \"supports-nx-ttl-decrement\";\n\n public enum SwitchStatus {\n /** this switch is in the process of being handshaked. Initial State. \n * 这个交换机在握手进程中初始状态\n */\n \tHANDSHAKE(false),\n /** the OF channel to this switch is currently in SLAVE role - the switch will not accept\n * state-mutating messages from this controller node.\n * OF链路连接的控制器当前是SLAVE角色,交换机将不承认此控制器修改的信息\n */\n SLAVE(true),\n /** the OF channel to this switch is currently in MASTER (or EQUALS) role - the switch is\n * controllable from this controller node.\n * OF链路连接的交换机当前是MASTER或者EQUALS角色。控制器能够控制交换机\n */\n MASTER(true),\n /** the switch has been sorted out and quarantined by the handshake. It does not show up\n * in normal switch listings\n * 这个交换机通过握手被挑选和隔离。它不能呈现在正常的交换机表\n */\n QUARANTINED(false),\n /** the switch has disconnected, and will soon be removed from the switch database \n * 这个交换机已断开连接,并且不就将会从交换机表中移除\n * */\n DISCONNECTED(false);\n\n private final boolean visible;\n\n SwitchStatus(boolean visible) {\n this.visible = visible;\n }\n\n /** wether this switch is currently visible for normal operation \n * 对于正常运行当前交换机是否可见\n * */\n public boolean isVisible() {\n return visible;\n }\n\n /** wether this switch is currently ready to be controlled by this controller\n * 当前交换机是否已经准备好被控制器控制\n * */\n public boolean isControllable() {\n return this == MASTER;\n }\n }\n /**\n * 得到交换机状态\n * @return\n */\n SwitchStatus getStatus();\n\n /**\n * Returns switch features from features Reply\n * 在特征回复中回复交换机特征\n * @return\n */\n long getBuffers();\n\n /**\n * Disconnect all the switch's channels and mark the switch as disconnected\n * 断开所有交换机连接,并标记交换机为disconnected\n */\n void disconnect();\n /**\n * 得到Actions集合\n * @return \n */\n Set<OFActionType> getActions();\n /**\n * 得到Capabilities集合\n * @return\n */\n Set<OFCapabilities> getCapabilities();\n /**\n * 得到流表\n * @return\n */\n short getTables();\n\n /**\n * 获取一个对这台交换机描述性统计的副本 \n * @return a copy of the description statistics for this switch\n */\n SwitchDescription getSwitchDescription();\n\n /**\n * Get the IP address of the remote (switch) end of the connection\n * 得到交换机IP\n * @return the inet address\n */\n SocketAddress getInetAddress();\n\n /**\n * Get list of all enabled ports. This will typically be different from\n * the list of ports in the OFFeaturesReply, since that one is a static\n * snapshot of the ports at the time the switch connected to the controller\n * whereas this port list also reflects the port status messages that have\n * been received.\n * 得到全部使能端口列表。\n * 这通常与OFFeaturesReply回复中的端口列表不同,因为这是此刻交换机连接控制器的端口快照。\n * 然而这个端口列表也能反映出端口状态信息已经收到\n * \n * @return Unmodifiable list of ports not backed by the underlying collection\n * 不可修改的列表\n */\n Collection<OFPortDesc> getEnabledPorts();\n\n /**\n * Get list of the port numbers of all enabled ports. This will typically\n * be different from the list of ports in the OFFeaturesReply, since that\n * one is a static snapshot of the ports at the time the switch connected\n * to the controller whereas this port list also reflects the port status\n * messages that have been received.\n * 获得所有活动端口的端口号。\n * @return Unmodifiable list of ports not backed by the underlying collection\n * 不可修改的列表\n */\n Collection<OFPort> getEnabledPortNumbers();\n\n /**\n * Retrieve the port object by the port number. The port object\n * is the one that reflects the port status updates that have been\n * received, not the one from the features reply.\n * 通过端口号获取端口对象.\n * 这个端口对象反映端口状态更新已被接收,不来自features回复\n * @param portNumber 端口号\n * @return port object 端口对象\n */\n OFPortDesc getPort(OFPort portNumber);\n\n /**\n * Retrieve the port object by the port name. The port object\n * is the one that reflects the port status updates that have been\n * received, not the one from the features reply.\n * Port names are case insentive\n * 通过端口名获取端口对象.\n * @param portName\n * @return port object\n */\n OFPortDesc getPort(String portName);\n\n /**\n * Get list of all ports. This will typically be different from\n * the list of ports in the OFFeaturesReply, since that one is a static\n * snapshot of the ports at the time the switch connected to the controller\n * whereas this port list also reflects the port status messages that have\n * been received.\n * 获得所有端口列表\n * @return Unmodifiable list of ports\n */\n Collection<OFPortDesc> getPorts();\n\n /**\n * This is mainly for the benefit of the DB code which currently has the\n * requirement that list elements be sorted by key. Hopefully soon the\n * DB will handle the sorting automatically or not require it at all, in\n * which case we could get rid of this method.\n * 这主要是为了当前数据库代码要求列表元素根据key排序。\n * 希望很快数据库能自动排序或不再需要排序,这种情况下我们可以拜托这个方法。\n * @return 已排序的端口列表\n */\n Collection<OFPortDesc> getSortedPorts();\n\n /**\n * 端口是否处在活动状态\n * 该端口是否被启用。(configured down、link down和生成树端口阻塞的情况不在此列) \n * @param portNumber\n * @return Whether a port is enabled per latest port status message\n * (not configured down nor link down nor in spanning tree blocking state)\n */\n boolean portEnabled(OFPort portNumber);\n\n /**\n * @param portNumber\n * @return Whether a port is enabled per latest port status message\n * (not configured down nor link down nor in spanning tree blocking state)\n */\n boolean portEnabled(String portName);\n\n /**\n * Check is switch is connected\n * 检查是否连接\n * @return Whether or not this switch is connected\n */\n boolean isConnected();\n\n /**\n * Retrieves the date the switch connected to this controller\n * 获取此交换机连接到控制器的时间\n * @return the date\n */\n Date getConnectedSince();\n\n /**\n * Get the datapathId of the switch\n * 获取此交换机的DPID\n * @return\n */\n DatapathId getId();\n\n /**\n * Retrieves attributes of this switch\n * 获取此交换机的属性\n * @return\n */\n Map<Object, Object> getAttributes();\n\n /**\n * 检查该交换机是否处于活动状态。\n * 交换机连接这个控制器并且处于master角色\n * Check if the switch is active. I.e., the switch is connected to this\n * controller and is in master role\n * @return\n */\n boolean isActive();\n\n /**\n * Get the current role of the controller for the switch\n * 获得当前控制器对于交换机的角色\n * @return the role of the controller\n */\n OFControllerRole getControllerRole();\n\n /**\n * Checks if a specific switch property exists for this switch\n * 检查一个特定的属性是否存在于这个交换机\n * @param name name of property\n * @return value for name\n */\n boolean hasAttribute(String name);\n\n /**\n * Set properties for switch specific behavior\n * 获取交换机特定行为的属性\n * @param name name of property\n * @return value for name\n */\n Object getAttribute(String name);\n\n /**\n * Check if the given attribute is present and if so whether it is equal\n * to \"other\"\n * 检查给定的属性是否存在,如果是,该属性是否为“other”\n * @param name the name of the attribute to check\n * @param other the object to compare the attribute against.\n * @return true if the specified attribute is set and equals() the given\n * other object.\n */\n boolean attributeEquals(String name, Object other);\n\n /**\n * Set properties for switch specific behavior\n * 设置交换机特定行为的属性\n * @param name name of property\n * @param value value for name\n */\n void setAttribute(String name, Object value);\n\n /**\n * Set properties for switch specific behavior\n * 移除交换机特定行为的属性\n * @param name name of property\n * @return current value for name or null (if not present)\n */\n Object removeAttribute(String name);\n\n /**\n * Returns a factory object that can be used to create OpenFlow messages.\n * 返回一个能够创造OpenFlow消息的工厂对象\n * @return\n */\n OFFactory getOFFactory();\n\n /**\n * Flush all flows queued for this switch on all connections that were written by the current thread.\n * 通过当前线程刷新所有连接在此交换机上流队列\n *\n */\n void flush();\n\n /**\n * Gets the OF connections for this switch instance\n * 获得此交换机实例的OF连接\n * @return Collection of IOFConnection\n */\n ImmutableList<IOFConnection> getConnections();\n\n /**\n * Writes a message to the connection specified by the logical OFMessage category\n * 写入一个正确的OFMessage到指定的连接\n * @param m an OF Message\n * @param category the category of the OF Message to be sent\n */\n void write(OFMessage m, LogicalOFMessageCategory category);\n\n /**\n * Writes a message list to the connection specified by the logical OFMessage category\n * 写入一个正确的OFMessage列表到指定的连接\n * @param msglist an OF Message list\n * @param category the category of the OF Message list to be sent\n */\n void write(Iterable<OFMessage> msglist, LogicalOFMessageCategory category);\n\n /**\n * Get a connection specified by the logical OFMessage category\n * 通过获得一个指定的连接\n * @param category the category for the connection the user desires\n * @return an OF Connection\n */\n OFConnection getConnectionByCategory(LogicalOFMessageCategory category);\n\n /** write a Stats (Multipart-) request, register for all corresponding reply messages.\n * 写入一个状态请求,登记所有相应的回复信息\n * Returns a Future object that can be used to retrieve the List of asynchronous\n * OFStatsReply messages when it is available.\n * 返回一个Future对象能被用来获得异步OFStatsReply回复报文列表当它可用\n *\n * @param request stats request\n * @param category the category for the connection that this request should be written to\n * @return Future object wrapping OFStatsReply\n * If the connection is not currently connected, will\n * return a Future that immediately fails with a @link{SwitchDisconnectedException}.\n */\n <REPLY extends OFStatsReply> ListenableFuture<List<REPLY>> writeStatsRequest(OFStatsRequest<REPLY> request, LogicalOFMessageCategory category);\n\n /** write an OpenFlow Request message, register for a single corresponding reply message\n * or error message.\n *\t写入一个OpenFlow请求信息,登记单个相应的回复报文\n * @param request\n * @param category the category for the connection that this request should be written to\n * @return a Future object that can be used to retrieve the asynchrounous\n * response when available.\n *\n * If the connection is not currently connected, will\n * return a Future that immediately fails with a @link{SwitchDisconnectedException}.\n */\n <R extends OFMessage> ListenableFuture<R> writeRequest(OFRequest<R> request, LogicalOFMessageCategory category);\n}", "public interface IShutdownService extends IFloodlightService {\n /**\n * Terminate floodlight process by calling System.exit() with the given\n * exitCode. If reason is non-null, reason will be logged. Before\n * terminating the shutdownListeners are called\n * 通过调用System.exit()并传入一个exitCode来终止floodlight线程。\n * 如果原因不为null,原因将会被记录。\n * 在终止前shutdownListeners将会被调用\n * If exitCode == 0 the termination cause is deemed \"normal\" and info\n * level log is used. In all other cases the exit is abnormal and an error\n * is logged.\n * 如果exitCode==0终止的原因是正常\n * 在所有其他反常的退出原因中错误将会被记录\n * @param reason 终止原因\n * @param exitCode 退出码\n */\n public void terminate(@Nullable String reason, int exitCode);\n\n /**\n * Terminate floodlight process by calling System.exit() with the given\n * exitCode. If reason is non-null, reason will be logged. In addition,\n * the throwable will be logged as well.\n * Before terminating the shutdownListeners are called\n *\n * This method is generally used to terminate floodlight due to an\n * unhandled Exception. As such all messages are logged as error and it is\n * recommended that an exitCode != 0 is used.\n * 这个方法通常用用来终止floodflight由于一个不能处理的异常。\n * 因此所有的信息被记录为错误并且推荐使用exitCode不为0\n * @param reason\n * @param e The throwable causing floodlight to terminate\n * @param exitCode\n */\n public void terminate(@Nullable String reason,\n @Nonnull Throwable e, int exitCode);\n\n /**\n * Register a shutdown listener. Registered listeners are called when\n * floodlight is about to terminate due to a call to terminate()\n * 注册一个监听器。\n * @param listener\n */\n public void registerShutdownListener(@Nonnull IShutdownListener listener);\n}", "public class ListenerDispatcher<U, T extends IListener<U>> {\n protected static final Logger logger = \n LoggerFactory.getLogger(ListenerDispatcher.class);\n volatile List<T> listeners = new ArrayList<T>();\n\n private void visit(List<T> newlisteners, U type, HashSet<T> visited,\n List<T> ordering, T listener) {\n if (!visited.contains(listener)) {\n visited.add(listener);\n\n for (T i : newlisteners) {\n if (ispre(type, i, listener)) {\n visit(newlisteners, type, visited, ordering, i);\n }\n }\n ordering.add(listener);\n }\n }\n\n private boolean ispre(U type, T l1, T l2) {\n return (l2.isCallbackOrderingPrereq(type, l1.getName()) ||\n l1.isCallbackOrderingPostreq(type, l2.getName()));\n }\n\n /**\n * Add a listener to the list of listeners\n * @param listener\n */\n @LogMessageDoc(level=\"ERROR\",\n message=\"No listener dependency solution: \" +\n \"No listeners without incoming dependencies\",\n explanation=\"The set of listeners installed \" +\n \"have dependencies with no solution\",\n recommendation=\"Install a different set of listeners \" +\n \"or install all dependencies. This is a defect in \" +\n \"the controller installation.\")\n public void addListener(U type, T listener) {\n List<T> newlisteners = new ArrayList<T>();\n if (listeners != null)\n newlisteners.addAll(listeners);\n\n newlisteners.add(listener);\n // Find nodes without outgoing edges\n List<T> terminals = new ArrayList<T>();\n for (T i : newlisteners) {\n boolean isterm = true;\n for (T j : newlisteners) {\n if (ispre(type, i, j)) {\n isterm = false;\n break;\n }\n }\n if (isterm) {\n terminals.add(i);\n }\n }\n\n if (terminals.size() == 0) {\n logger.error(\"No listener dependency solution: \" +\n \"No listeners without incoming dependencies\");\n listeners = newlisteners;\n return;\n }\n\n // visit depth-first traversing in the opposite order from\n // the dependencies. Note we will not generally detect cycles\n HashSet<T> visited = new HashSet<T>();\n List<T> ordering = new ArrayList<T>();\n for (T term : terminals) {\n visit(newlisteners, type, visited, ordering, term);\n }\n listeners = ordering;\n }\n\n /**\n * Remove the given listener\n * @param listener the listener to remove\n */\n public void removeListener(T listener) {\n if (listeners != null) {\n List<T> newlisteners = new ArrayList<T>();\n newlisteners.addAll(listeners);\n newlisteners.remove(listener);\n listeners = newlisteners;\n }\n }\n\n /**\n * Clear all listeners\n */\n public void clearListeners() {\n listeners = new ArrayList<T>();\n }\n\n /**\n * Get the ordered list of listeners ordered by dependencies\n * 获得一个根据依赖关系排列的有序监听器列表\n * @return\n */\n public List<T> getOrderedListeners() {\n return listeners;\n }\n}", "public class CoreWebRoutable implements RestletRoutable {\n\t// define the parts of each path the user can define in the REST message at runtime\n\t// access these same strings where the attributes are parsed\n\tpublic static final String STR_SWITCH_ID = \"switchId\";\n\tpublic static final String STR_STAT_TYPE = \"statType\";\n\tpublic static final String STR_CTR_TITLE = \"counterTitle\";\n\tpublic static final String STR_CTR_MODULE = \"counterModule\";\n\tpublic static final String STR_LAYER = \"layer\";\n\tpublic static final String STR_ALL = \"all\";\n\tpublic static final String STR_ROLE = \"role\";\n\tpublic static final String STR_CONTROLLER=\"controllerIp\";\n\t\n @Override\n public String basePath() {\n return \"/wm/core\";\n }\n @Override\n public Restlet getRestlet(Context context) {\n \t\n \t\n \t\n Router router = new Router(context);\n \n router.attach(\"/module/all/json\", ModuleLoaderResource.class);\n router.attach(\"/module/loaded/json\", LoadedModuleLoaderResource.class);\n // router.attach(\"/switch/{\" + STR_SWITCH_ID + \"}/role/json\", SwitchRoleResource.class);\n router.attach(\"/switch/all/{\" + STR_STAT_TYPE + \"}/json\", AllSwitchStatisticsResource.class);\n router.attach(\"/switch/{\" + STR_SWITCH_ID + \"}/{\" + STR_STAT_TYPE + \"}/json\", SwitchStatisticsResource.class);\n router.attach(\"/controller/switches/json\", ControllerSwitchesResource.class);\n router.attach(\"/counter/{\" + STR_CTR_MODULE + \"}/{\" + STR_CTR_TITLE + \"}/json\", CounterResource.class);\n router.attach(\"/memory/json\", ControllerMemoryResource.class);\n router.attach(\"/packettrace/json\", PacketTraceResource.class);\n router.attach(\"/storage/tables/json\", StorageSourceTablesResource.class);\n router.attach(\"/controller/summary/json\", ControllerSummaryResource.class);\n router.attach(\"/role/json\", ControllerRoleResource.class);\n router.attach(\"/health/json\", HealthCheckResource.class);\n router.attach(\"/system/uptime/json\", SystemUptimeResource.class);\n return router;\n }\n \n}", "public interface IDebugCounterService extends IFloodlightService {\n public enum MetaData {\n WARN,\n DROP,\n ERROR\n }\n\n /**\n * All modules that wish to have the DebugCounterService count for them, must\n * register themselves. If a module is registered multiple times subsequent\n * registrations will reset all counter in the module.\n *\t所有希望拥有DebugCounterService的模块必须注册。\n *\t如果模块在多个时间被注册,随后的注册将会重置模块中所有的计数器\n * @param moduleName\n * @return true if the module is registered for the first time, false if\n * the modue was previously registered\n * 当模块第一次注册时返回true,否则返回false\n */\n public boolean registerModule(String moduleName);\n\n /**\n * All modules that wish to have the DebugCounterService count for them, must\n * register their counters by making this call (typically from that module's\n * 'startUp' method). The counter can then be updated, displayed, reset etc.\n * using the registered moduleName and counterHierarchy.\n *\t所有希望拥有DebugCounterService的模块必须注册他们的计数器通过调用这个方法(通常从模块的startup方法)。\n *\t计数器之后能被更新,显示,重置等\n *\t使用moduleName和conterHierarchy\n * @param moduleName the name of the module which is registering the\n * counter eg. linkdiscovery or controller or switch\n * 哪一个模块注册的计数器\n * @param counterHierarchy the hierarchical counter name specifying all\n * the hierarchical levels that come above it.\n * For example: to register a drop counter for\n * packet-ins from a switch, the counterHierarchy\n * can be \"00:00:00:00:01:02:03:04/pktin/drops\"\n * It is necessary that counters in hierarchical levels\n * above have already been pre-registered - in this\n * example: \"00:00:00:00:01:02:03:04/pktin\" and\n * \"00:00:00:00:01:02:03:04\"\n * \n * @param counterDescription a descriptive string that gives more information\n * of what the counter is measuring. For example,\n * \"Measures the number of incoming packets seen by\n * this module\".\n * @param metaData variable arguments that qualify a counter\n * eg. warn, error etc.\n * @return IDebugCounter with update methods that can be\n * used to update a counter.\n */\n public IDebugCounter\n registerCounter(String moduleName, String counterHierarchy,\n String counterDescription, MetaData... metaData);\n\n\n /**\n * Resets the value of counters in the hierarchy to zero. Note that the reset\n * applies to the level of counter hierarchy specified AND ALL LEVELS BELOW it\n * in the hierarchy.\n * 重置控制器层次\n * 备注:重置适用于指定的计数器层次或所有的低于这个层次的计数器\n * For example: If a hierarchy exists like \"00:00:00:00:01:02:03:04/pktin/drops\"\n * specifying a reset hierarchy: \"00:00:00:00:01:02:03:04\"\n * will reset all counters for the switch dpid specified;\n * while specifying a reset hierarchy: \"\"00:00:00:00:01:02:03:04/pktin\"\n * will reset the pktin counter and all levels below it (like drops)\n * for the switch dpid specified.\n * @return false if the given moduleName, counterHierarchy\n * does not exist\n */\n public boolean resetCounterHierarchy(String moduleName, String counterHierarchy);\n\n /**\n * Resets the values of all counters in the system.\n * 重置所有计数器\n */\n public void resetAllCounters();\n\n /**\n * Resets the values of all counters belonging\n * to a module with the given 'moduleName'.\n * 重置属于指定模块的所有计数器\n * @return false if the given module name does not exists\n */\n public boolean resetAllModuleCounters(String moduleName);\n \n /**\n * Removes/deletes the counter hierarchy AND ALL LEVELS BELOW it in the hierarchy.\n * 移除/删除指定的计数器层次和低于此层次的计数器。\n * For example: If a hierarchy exists like \"00:00:00:00:01:02:03:04/pktin/drops\"\n * specifying a remove hierarchy: \"00:00:00:00:01:02:03:04\"\n * will remove all counters for the switch dpid specified;\n * while specifying a remove hierarchy: \"\"00:00:00:00:01:02:03:04/pktin\"\n * will remove the pktin counter and all levels below it (like drops)\n * for the switch dpid specified.\n * @return false if the given moduleName, counterHierarchy does not exist\n */\n public boolean removeCounterHierarchy(String moduleName, String counterHierarchy);\n\n\n /**\n * Get counter value and associated information for the specified counterHierarchy.\n * Note that information on the level of counter hierarchy specified\n * AND ALL LEVELS BELOW it in the hierarchy will be returned.\n * 得到计数器值和相应的信息从指定的层次中\n * 备注指定层级的信息和所有低于这个层级将会被返回\n * For example,\n * if a hierarchy exists like \"00:00:00:00:01:02:03:04/pktin/drops\", then\n * specifying a counterHierarchy of \"00:00:00:00:01:02:03:04/pktin\" in the\n * get call will return information on the 'pktin' as well as the 'drops'\n * counters for the switch dpid specified.\n *\n * If the module or hierarchy is not registered, returns an empty list\n *\n * @return A list of DebugCounterResource or an empty list if the counter\n * could not be found\n */\n public List<DebugCounterResource>\n getCounterHierarchy(String moduleName, String counterHierarchy);\n\n /**\n * Get counter values and associated information for all counters in the\n * system\n *\t得到所有的计数器值\n * @return the list of values/info or an empty list\n */\n public List<DebugCounterResource> getAllCounterValues();\n\n /**\n * Get counter values and associated information for all counters associated\n * with a module.\n * If the module is not registered, returns an empty list\n *\t得到所有的模块计数器值\n * @param moduleName\n * @return the list of values/info or an empty list\n */\n public List<DebugCounterResource> getModuleCounterValues(String moduleName);\n\n}" ]
import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import net.dsc.cluster.HAListenerTypeMarker; import net.dsc.cluster.HARole; import net.dsc.cluster.IClusterService; import net.dsc.cluster.RoleInfo; import net.dsc.cluster.model.ControllerModel; import net.dsc.hazelcast.IHazelcastService; import net.dsc.hazelcast.listener.IHAListener; import net.floodlightcontroller.core.ControllerId; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IInfoProvider; import net.floodlightcontroller.core.IListener.Command; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IOFSwitchListener; import net.floodlightcontroller.core.IShutdownService; import net.floodlightcontroller.core.LogicalOFMessageCategory; import net.floodlightcontroller.core.PortChangeType; import net.floodlightcontroller.core.annotations.LogMessageDoc; import net.floodlightcontroller.core.annotations.LogMessageDocs; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.FloodlightModuleLoader; import net.floodlightcontroller.core.util.ListenerDispatcher; import net.floodlightcontroller.core.web.CoreWebRoutable; import net.floodlightcontroller.debugcounter.IDebugCounterService; import net.floodlightcontroller.debugevent.IDebugEventService; import net.floodlightcontroller.notification.INotificationManager; import net.floodlightcontroller.notification.NotificationManagerFactory; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.perfmon.IPktInProcessingTimeService; import net.floodlightcontroller.restserver.IRestApiService; import net.floodlightcontroller.storage.IResultSet; import net.floodlightcontroller.storage.IStorageSourceListener; import net.floodlightcontroller.storage.IStorageSourceService; import net.floodlightcontroller.storage.StorageException; import net.floodlightcontroller.threadpool.IThreadPoolService; import net.floodlightcontroller.util.LoadMonitor; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timer; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPortDesc; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.types.DatapathId; import org.sdnplatform.sync.ISyncService; import org.sdnplatform.sync.ISyncService.Scope; import org.sdnplatform.sync.error.SyncException; import org.sdnplatform.sync.internal.config.ClusterConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Strings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
void setRestApiService(IRestApiService restApi) { this.restApiService = restApi; } void setThreadPoolService(IThreadPoolService tp) { this.threadPoolService = tp; } IThreadPoolService getThreadPoolService() { return this.threadPoolService; } public void setSwitchService(IOFSwitchService switchService) { this.switchService = switchService; } public IOFSwitchService getSwitchService() { return this.switchService; } @Override public int getWorkerThreads() { return this.workerThreads; } @Override public HARole getRole() { return notifiedRole; } @Override public RoleInfo getRoleInfo() { return roleManager.getRoleInfo(); } @Override public void setRole(HARole role, String changeDescription) { roleManager.setRole(role, changeDescription); } // **************** // Message handlers // **************** // Handler for SwitchPortsChanged was here (notifyPortChanged). Handled in OFSwitchManager //处理交换机端口变化 /** * flcontext_cache - Keep a thread local stack of contexts * FloodlightContext缓存,持有一个本地线程上下文栈 */ protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache = new ThreadLocal <Stack<FloodlightContext>> () { @Override protected Stack<FloodlightContext> initialValue() { return new Stack<FloodlightContext>(); } }; /** * flcontext_alloc - pop a context off the stack, if required create a new one * 从栈顶弹出一个上下文,如果有必要会创建一个新的 * @return FloodlightContext */ protected static FloodlightContext flcontext_alloc() { FloodlightContext flcontext = null; if (flcontext_cache.get().empty()) { flcontext = new FloodlightContext(); } else { flcontext = flcontext_cache.get().pop(); } return flcontext; } /** * flcontext_free - Free the context to the current thread * 在当前线程释放上下文 * @param flcontext */ protected void flcontext_free(FloodlightContext flcontext) { flcontext.getStorage().clear(); flcontext_cache.get().push(flcontext); } /** * * Handle and dispatch a message to IOFMessageListeners. * 处理,调度一个消息给IOFMessageListeners * We only dispatch messages to listeners if the controller's role is MASTER. * 我们只给是MASTER角色的控制器角度消息 * @param sw The switch sending the message 发送消息的交换机 * @param m The message the switch sent 消息 * @param flContext The floodlight context to use for this message. If * null, a new context will be allocated. * 使用这个消息的上下文,如果不存在将会被创建。 * @throws IOException * * FIXME: this method and the ChannelHandler disagree on which messages * should be dispatched and which shouldn't * 这个方法和ChannelHandler在哪个消息应该被调度上有分歧 */ @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Ignoring PacketIn (Xid = {xid}) because the data" + " field is empty.", explanation="The switch sent an improperly-formatted PacketIn" + " message", recommendation=LogMessageDoc.CHECK_SWITCH), @LogMessageDoc(level="WARN", message="Unhandled OF Message: {} from {}", explanation="The switch sent a message not handled by " + "the controller") }) @SuppressFBWarnings(value="SF_SWITCH_NO_DEFAULT", justification="False positive -- has default") @Override
public void handleMessage(IOFSwitch sw, OFMessage m,
2
tomdw/java-modules-context-boot
integration-tests/src/main/java/module-info.java
[ "@Configuration\n@Import(value = {IntegrationTestUsingConstructorInjectionService.class, IntegrationTestService.class})\npublic class IntegrationTestConfiguration {\n\n}", "public interface FailingSpeakerService {\n\n\tString getSpeakerNameButThrowsRuntimeException();\n\n\tString getSpeakerNameButThrowsCheckedException() throws NoSpeakerCheckedException;\n}", "public interface MultipleSpeakerService {\n\tString getName();\n\tvoid speak(String message);\n}", "public interface MultipleSpeakerWithGenericsService<T> {\n\n\tT getMultipleSpeakerName();\n}", "public interface NamedSpeakerService {\n\n\tString getSpeakerName();\n\n}", "public interface SpeakerService {\n\tString getName();\n\tvoid speak(String message);\n}" ]
import io.github.tomdw.java.modules.context.boot.api.ModuleContext; import io.github.tomdw.java.modules.spring.integration.tests.IntegrationTestConfiguration; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.FailingSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.MultipleSpeakerWithGenericsService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.NamedSpeakerService; import io.github.tomdw.java.modules.spring.samples.basicapplication.speaker.api.SpeakerService;
@ModuleContext(mainConfigurationClass = IntegrationTestConfiguration.class) module io.github.tomdw.java.modules.spring.integration.tests { requires io.github.tomdw.java.modules.context.boot; requires io.github.tomdw.java.modules.spring.samples.basicapplication.application; requires io.github.tomdw.java.modules.spring.samples.basicapplication.speaker; uses SpeakerService;
uses MultipleSpeakerService;
2
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/handler/MessageEventInterceptor.java
[ "@SuppressWarnings(\"serial\")\npublic class AccessDeniedException extends Exception {\n\n\tpublic AccessDeniedException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}", "@SuppressWarnings(\"serial\")\npublic class InvalidRelationException extends Exception {\n\n\tpublic InvalidRelationException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}", "public class PEPActivityHandler extends PEPNodeHandler {\n\n\tpublic static String NODE = \"urn:xmpp:microblog:0\";\n\t\n\tprivate XMPPServer server;\n\t\n\tprivate Map<String, PEPCommandHandler> handlers = new ConcurrentHashMap<String, PEPCommandHandler>();\n\n\tpublic PEPActivityHandler() {\n\t\tsuper(\"Handler for PEP microbloging PEP node\");\n\t}\n\t\t\n\t@Override\n\tpublic String getNode() {\n\t\treturn NODE;\n\t}\n\n\t@Override\n\tpublic void initialize(XMPPServer server) {\n\t\tsuper.initialize(server);\n\t\tthis.server = server;\n\t\taddHandler(new ActivityPublishHandler());\n\t\taddHandler(new ActivityQueryHandler());\n\t\taddHandler(new ActivityDeleteHandler());\n\t\taddHandler(new ActivitySubscribeHandler());\n\t\taddHandler(new ActivityUnsubscribeHandler());\n\t\taddHandler(new ActivitySubscribersHandler());\n\t\taddHandler(new ActivitySubscriptionsHandler());\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic IQ handleIQ(IQ packet) throws UnauthorizedException {\n\t\t// We search for a handler based on the element name\n\t\t// and process the packet with the handler if found.\n final Element childElement = packet.getChildElement();\n final List<Element> pubsubElements = childElement.elements();\t\n\n if (pubsubElements != null && pubsubElements.size() > 0) {\n \tElement actionElement = pubsubElements.get(0);\n \tPEPCommandHandler handler = getHandler(actionElement.getName());\n\t\t\tif (handler != null) {\n\t\t\t\treturn handler.handleIQ(packet);\n\t\t\t}\n\t\t}\n\n\t\t// No valid hanlder found. Return a feature not implemented\n\t\t// error.\n\t\tIQ result = IQ.createResultIQ(packet);\n\t\tresult.setChildElement(packet.getChildElement().createCopy());\n\t\tresult.setError(PacketError.Condition.feature_not_implemented);\n\t\treturn result;\n\t}\n\n\tprivate void addHandler(PEPCommandHandler handler) {\n\t\thandler.initialize(server);\n\t\thandlers.put(handler.getCommand(), handler);\n\t}\n\n\tprivate PEPCommandHandler getHandler(String name) {\n\t\treturn handlers.get(name);\n\t}\n\n}", "public class ActivityManager {\n\n\t/**\n\t * Singleton: keep a static reference to teh only instance\n\t */\n\tprivate static ActivityManager instance;\n\n\tpublic static ActivityManager getInstance() {\n\t\tif (instance == null) {\n\t\t\t// Carefull, we are in a threaded environment !\n\t\t\tsynchronized (ActivityManager.class) {\n\t\t\t\tinstance = new ActivityManager();\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Class dependencies \n\t * TODO Make this a true dependency injection\n\t */\n\tprivate final ActivityFactory activityFactory;\n\n\tprivate final AclFactory aclFactory;\n\n\t/**\n\t * Publish a new activity to the activity stream of the given user.\n\t * activity-actor element is overwrittern using the user profile data to\n\t * avoid spoofing. Notifications messages are sent to the users subscribed\n\t * to this user activities.\n\t * \n\t * @param user\n\t * The user who the activity belongs to\n\t * @param entry\n\t * The activity entry to publish\n\t * @throws UserNotFoundException\n\t */\n\tpublic void publishActivity(String userJID, ActivityEntry entry) throws UserNotFoundException {\n\t\t// Overide the actor to avoid spoofing\n\t\tUser user = UserManager.getInstance().getUser(new JID(userJID).getNode());\n\t\tActivityActor actor = activityFactory.actor();\n\t\tactor.setUri(userJID);\n\t\tactor.setName(user.getName());\n\t\tactor.setEmail(user.getEmail());\n\n\t\t// Persist the activities\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\tentry.setId(DefaultAtomHelper.generateId());\n\t\tfor (ActivityObject object : entry.getObjects()) {\n\t\t\tobject.setId(DefaultAtomHelper.generateId());\n\t\t}\n\t\tentry.setActor(actor);\n\t\tentry.setPublished(Calendar.getInstance().getTime());\n\t\tem.persist(entry);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// Broadcast the notifications\n\t\tnotify(userJID, entry);\n\t}\n\t\n\t/**\n\t * Updates an activity in the activity stream of the given user.\n\t * activity-actor element is overwrittern using the user profile data to\n\t * avoid spoofing. Notifications messages are sent to the users subscribed\n\t * to this user activities.\n\t * \n\t * @param user\n\t * The user who the activity belongs to\n\t * @param entry\n\t * The activity entry to update\n\t * @throws UserNotFoundException\n\t */\n\tpublic void updateActivity(String userJID, ActivityEntry entry) throws UserNotFoundException, UnauthorizedException {\n\t\t// Overide the actor to avoid spoofing\n\t\tUser user = UserManager.getInstance().getUser(new JID(userJID).getNode());\n\t\tActivityActor actor = activityFactory.actor();\n\t\tactor.setUri(userJID);\n\t\tactor.setName(user.getName());\n\t\tactor.setEmail(user.getEmail());\n\t\t\n\t\t// Persist the activities\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\tPersistentActivityEntry oldEntry=em.find(PersistentActivityEntry.class, entry.getId());\n\t\t\n\t\tif ((oldEntry==null) || (!oldEntry.getActor().getUri().equalsIgnoreCase(userJID)))\n\t\t\tthrow new UnauthorizedException();\n\t\t\n\t\t\n\t\tDate published=oldEntry.getPublished();\n\t\tentry.setPublished(published);\n\t\tentry.setUpdated(Calendar.getInstance().getTime());\n\t\t\n\t\tem.remove(oldEntry);\n\t\t\n\t\tentry.setActor(actor);\n\t\tem.persist(entry);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// Broadcast the notifications\n\t\tnotify(userJID, entry);\n\t}\n\t\n\tpublic void deleteActivity(String fromJID, String activityId) throws UnauthorizedException {\n\t\t\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\t\n\t\tPersistentActivityEntry activity= em.find(PersistentActivityEntry.class, activityId);\n\t\t\n\t\tif ((activity==null) || (!activity.getActor().getUri().equalsIgnoreCase(fromJID)))\n\t\t\tthrow new UnauthorizedException();\n\t\t\n\t\tem.remove(activity);\n\t\t\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t\t\n\t\tnotifyDelete(fromJID, activityId);\n\t}\n\t\n\tpublic void deleteMessage(String activityId) {\n\t\t\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\t\n\t\tQuery query = em.createQuery(\"SELECT x FROM Messages x WHERE x.activity.id = ?1\");\n\t\tquery.setParameter(1, activityId);\t\t\n\t\tList<ActivityMessage> messages = query.getResultList();\n\t\tfor (ActivityMessage message:messages){\n\t\t\tem.remove(message);\n\t\t}\n\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t}\n\n\t/**\n\t * Retrieve the last activities of the target user, taking into account the\n\t * access rights of the requesting user.\n\t * \n\t * @param requestorJID\n\t * the user requesting the activities\n\t * @param targetJID\n\t * the user whose activities are requested\n\t * @return an immutable list of the last activities of the target entity that can be seen by the\n\t * requesting entity\n\t * @throws UserNotFoundException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<ActivityEntry> getActivities(String requestorJID, String targetJID) throws UserNotFoundException {\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT DISTINCT entry FROM ActivityEntry entry\" + \" JOIN entry.rules rule \"\n\t\t\t\t+ \" JOIN rule.actions action \" + \" JOIN rule.subjects subject \"\n\t\t\t\t+ \" WHERE entry.actor.uri = :target \" + \" AND action.name = :view \"\n\t\t\t\t+ \" AND action.permission = :grant \" + \" AND (subject.type = :everyone \"\n\t\t\t\t+ \" OR (subject.type = :group_type \" + \" AND subject.name IN (:groups)) \"\n\t\t\t\t+ \" OR (subject.type = :person \" + \" AND subject.name = :jid)) ORDER BY entry.published DESC\");\n\n\t\t// Parametrize the query\n\t\tquery.setParameter(\"target\", targetJID);\n\t\tquery.setParameter(\"view\", AclAction.ACTION_VIEW);\n\t\tquery.setParameter(\"grant\", AclAction.PERMISSION_GRANT);\n\t\tquery.setParameter(\"everyone\", AclSubject.EVERYONE);\n\t\tquery.setParameter(\"group_type\", AclSubject.GROUP);\n\t\tquery.setParameter(\"groups\", getGroups(targetJID, requestorJID));\n\t\tquery.setParameter(\"person\", AclSubject.PERSON);\n\t\tquery.setParameter(\"jid\", requestorJID);\n\t\tquery.setMaxResults(20);\n\t\tList<ActivityEntry> result = query.getResultList();\n\t\tem.close();\n\n\t\treturn Collections.unmodifiableList(result);\n\t}\n\n\t/**\n\t * Handle an activity pubsub event. Such a message is usually\n\t * received by a user in these conditions: - the local user has subscribed\n\t * to the remote user activities - the local user is \"mentionned\" in this\n\t * activity - this activity relates to another activity of the local user\n\t * \n\t * @param remoteJID\n\t * the entity sending the message\n\t * @param localJID\n\t * the entity having received the message\n\t * @param activity\n\t * the activity contained in the message\n\t * @throws InvalidActivityException\n\t * @throws AccessDeniedException\n\t */\n\tpublic synchronized void handleMessage(String remoteJID, String localJID, ActivityEntry activity) throws InvalidActivityException, AccessDeniedException {\n\n\t\t// Validate the activity\n\t\tif (activity == null || !activity.hasId()) {\n\t\t\tthrow new InvalidActivityException();\n\t\t}\n\t\t\n\t\t// Create a message for the recipient\n\t\tActivityMessage message = new PersistentActivityMessage();\n\t\tmessage.setSender(remoteJID);\n\t\tmessage.setRecipient(localJID);\n\t\t//in case of an activity update we keep the received date as the date of\n\t\t//original publish, otherwise the updated posts will start showing on top of\n\t\t// the inbox..which we agreed we don't want...\n\t\tmessage.setReceived(activity.getPublished());\n\n\t\t// Search if the activity exists in the database\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tPersistentActivityEntry previousActivity = em.find(PersistentActivityEntry.class, activity.getId());\n\n\t\t// Assign the activity to the existing one if it exists\n\t\tif (previousActivity != null) {\n\t\t\tmessage.setActivity(previousActivity);\n\t\t} else {\n\t\t\tmessage.setActivity(activity);\n\t\t}\n\t\t\n\t\t//in case of an update the message will already exist in the DB\n\t\tQuery query = em.createQuery(\"SELECT x FROM Messages x WHERE x.activity.id = ?1\");\n\t\tquery.setParameter(1, activity.getId());\t\t\n\t\tList<ActivityMessage> messages = query.getResultList();\n\t\t\n\t\tem.getTransaction().begin();\n\t\tfor (ActivityMessage oldMessage:messages){\n\t\t\tif (oldMessage.getRecipient().equalsIgnoreCase(localJID))\n\t\t\t\tem.remove(oldMessage);\n\t\t}\n\t\tem.getTransaction().commit();\n\n\t\t// We go ahead and post the message to the recipient mailbox\n\t\tem.getTransaction().begin();\n\t\tem.persist(message);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t\t\t\t\n\t}\n\t\n\t\n\t\n\t/**\n\t * Subscribe an entity to another entity activities.\n\t * \n\t * @param from the subscriber\n\t * @param to entity being subscribed to\n\t * @throws AlreadySubscribed\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic synchronized void subscribe(String from, String to) {\n\t\t\n\t\t// Check if it already exist\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.subscriber = ?1 AND x.target = ?2\");\n\t\tquery.setParameter(1, from);\n\t\tquery.setParameter(2, to);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\t\n\t\t// If already exist, we don't have anything left to do\n\t\tif (subscriptions != null && subscriptions.size() > 0) {\n\t\t\tem.close();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Add the subscription\n\t\tSubscription subscription = new PersistentSubscription();\n\t\tsubscription.setSubscriber(from);\n\t\tsubscription.setTarget(to);\n\t\tsubscription.setCreated(Calendar.getInstance().getTime());\n\t\t\n\t\t// Store\n\t\tem.getTransaction().begin();\n\t\tem.persist(subscription);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\t\n\n\t/**\n\t * Delete a subscription.\n\t * \n\t * @param from the entity requesting to unsubscribe\n\t * @param to the subscription target\n\t * @throws SubscriptionNotFound\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic synchronized void unsubscribe(String from, String to) {\n\t\tEntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\t\n\t\t// Check if it already exist\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.subscriber = ?1 AND x.target = ?2\");\n\t\tquery.setParameter(1, from);\n\t\tquery.setParameter(2, to);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\t\n\t\t// If it does not exist, we don't have anything left to do \n\t\tif (subscriptions == null || subscriptions.size()== 0) {\n\t\t\tem.close();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Remove the subscriptions\n\t\t// There should never be more than one.. but better safe than sorry\n\t\tem.getTransaction().begin();\n\t\tfor (Subscription activitySubscription : subscriptions) {\n\t\t\tem.remove(activitySubscription);\n\t\t}\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Subscription> getSubscribers(String targetJID) {\n\t\t// Get a list of people who are interested by this stuff\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.target = ?1\");\n\t\tquery.setParameter(1, targetJID);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\tem.close();\n\t\treturn subscriptions;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Subscription> getSubscriptions(String subscriberJID) {\n\t\t// Get a list of people who are interested by this stuff\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.subscriber = ?1\");\n\t\tquery.setParameter(1, subscriberJID);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\tem.close();\n\t\treturn subscriptions;\n\t}\n\n\tprivate void notify(String fromJID, ActivityEntry entry) throws UserNotFoundException {\n\n\t\t// TODO We may want to do some cleaning of activities before\n\t\t// forwarding them (e.g. remove the acl, it is no one business)\n\t\tfinal ActivityDomWriter writer = new DefaultActivityDomWriter();\n\t\tfinal XMPPServer server = XMPPServer.getInstance();\n\t\tfinal List<Subscription> subscriptions = getSubscribers(fromJID);\n\t//\tfinal Roster roster = XMPPServer.getInstance().getRosterManager().getRoster(new JID(fromJID).getNode());\n\t\tfinal DOMDocument domDocument = new DOMDocument();\n\n\t\t// Prepare the message\n\t\tfinal Element entryElement = (Element) domDocument.appendChild(domDocument.createElementNS(Atom.NAMESPACE, Atom.ENTRY_ELEMENT));\n\t\twriter.write(entry, entryElement);\n\t\tdomDocument.removeChild(entryElement);\n\n\t\tfinal Message message = new Message();\n\t\tmessage.setFrom(fromJID);\n\t\tmessage.setBody(\"New activity: \" + entry.getTitle());\n\t\tmessage.setType(Message.Type.headline);\n\t\torg.dom4j.Element eventElement = message.addChildElement(\"event\", \"http://jabber.org/protocol/pubsub#event\");\n\t\torg.dom4j.Element itemsElement = eventElement.addElement(\"items\");\n\t\titemsElement.addAttribute(\"node\", PEPActivityHandler.NODE);\n\t\torg.dom4j.Element itemElement = itemsElement.addElement(\"item\");\n\t\titemElement.addAttribute(\"id\", entry.getId());\n\t\titemElement.add((org.dom4j.Element) entryElement);\n\n\t\t// Keep a list of people we sent it to avoid duplicates\n\t\tList<String> alreadySent = new ArrayList<String>();\n\t\t\n\t\t// Send to this user\n\t\talreadySent.add(fromJID);\n\t\tmessage.setTo(fromJID);\n\t\tserver.getMessageRouter().route(message);\t\n\t\t\t\t\t\t\n\t\t// Send to all subscribers\n\t\tfor (Subscription activitySubscription : subscriptions) {\n\t\t\tString recipientJID = activitySubscription.getSubscriber();\n\t\t\tif (!canSee(fromJID, entry, recipientJID)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\talreadySent.add(recipientJID);\t\t\t\t\t\t\n\t\t\tmessage.setTo(recipientJID);\n\t\t\tserver.getMessageRouter().route(message);\t\n\t\t}\n\n\t\t// Send to recipients, if they can see it and have not already received it\n\t\tif (entry.hasRecipients()) {\n\t\t\tfor (AtomReplyTo recipient : entry.getRecipients()) {\n\t\t\t\t//TODO This is dirty, the recipient should be an IRI etc...\n\t\t\t\tString recipientJID = recipient.getHref(); \n\t\t\t\tif (!alreadySent.contains(recipientJID) && canSee(fromJID, entry, recipientJID)) {\n\t\t\t\t\talreadySent.add(fromJID);\n\t\t\t\t\t\n\t\t\t\t\tmessage.setTo(recipientJID);\n\t\t\t\t\tserver.getMessageRouter().route(message);\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\t\n\t}\n\t\n\n\tprivate void notifyDelete(String fromJID, String activityId) {\n\n\t\t\n\t\tfinal XMPPServer server = XMPPServer.getInstance();\n\t\tfinal List<Subscription> subscriptions = getSubscribers(fromJID);\n\t\n\t\t// Prepare the message\n\t\t\n\t\tfinal Message message = new Message();\n\t\tmessage.setFrom(fromJID);\n\t\tmessage.setBody(\"Delete activity: \" + activityId);\n\t\tmessage.setType(Message.Type.headline);\n\t\t\n\t\torg.dom4j.Element eventElement = message.addChildElement(\"event\", \"http://jabber.org/protocol/pubsub#event\");\n\t\torg.dom4j.Element itemsElement = eventElement.addElement(\"items\");\n\t\titemsElement.addAttribute(\"node\", PEPActivityHandler.NODE);\n\t\torg.dom4j.Element retractElement = itemsElement.addElement(\"retract\");\n\t\tretractElement.addAttribute(\"id\", activityId);\n\t\t\n\n\t\t// Keep a list of people we sent it to avoid duplicates\n\t\tList<String> alreadySent = new ArrayList<String>();\n\t\t\n\t\t// Send to this user\n\t\talreadySent.add(fromJID);\n\t\tmessage.setTo(fromJID);\n\t\tserver.getMessageRouter().route(message);\t\n\t\t\t\t\t\t\n\t\t// Send to all subscribers\n\t\tfor (Subscription activitySubscription : subscriptions) {\n\t\t\tString recipientJID = activitySubscription.getSubscriber();\t\t\t\n\t\t\talreadySent.add(recipientJID);\t\t\t\t\t\t\n\t\t\tmessage.setTo(recipientJID);\n\t\t\tserver.getMessageRouter().route(message);\t\n\t\t}\t\t\t\n\t\t\n\t}\n\t\n\tprivate List<String> getGroups(String ownerJID, String userJID) {\n\t\tRosterManager rosterManager = XMPPServer.getInstance().getRosterManager();\n\t\tRoster roster;\n\t\ttry {\n\t\t\troster = rosterManager.getRoster(new JID(ownerJID).getNode());\n\t\t\tRosterItem rosterItem = roster.getRosterItem(new JID(userJID));\n\t\t\tif (rosterItem != null) {\n\t\t\t\treturn rosterItem.getGroups();\n\t\t\t}\n\t\t} catch (UserNotFoundException e) {\n\t\t}\n\n\t\treturn new ArrayList<String>();\n\t}\n\n\tprivate boolean canSee(String fromJID, ActivityEntry entry, String viewer) throws UserNotFoundException {\n\t\t// Get a view action\n\t\tfinal AclAction viewAction = aclFactory.aclAction(AclAction.ACTION_VIEW, AclAction.PERMISSION_GRANT);\n\t\tAclRule rule = null;\n\t\tfor (AclRule aclRule : entry.getAclRules()) {\n\t\t\tif (aclRule.hasAction(viewAction)) {\n\t\t\t\trule = aclRule;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no view action was found, we consider it is denied\n\t\tif (rule == null)\n\t\t\treturn false;\n\t\t\n\t\treturn AclManager.canSee(fromJID, rule, viewer);\n\t\t\n\t}\n\n\t/**\n\t * Private constructor to enforce the singleton\n\t */\n\tprivate ActivityManager() {\n\t\tactivityFactory = new PersistentActivityFactory();\n\t\taclFactory = new PersistentAclFactory();\n\t}\n}", "public class RelationManager {\n\n\tpublic static final String NODE = \"http://onesocialweb.org/spec/1.0/relations\";\n\t\n\t/**\n\t * Singleton: keep a static reference to teh only instance\n\t */\n\tprivate static RelationManager instance;\n\n\tpublic static RelationManager getInstance() {\n\t\tif (instance == null) {\n\t\t\t// Carefull, we are in a threaded environment !\n\t\t\tsynchronized (RelationManager.class) {\n\t\t\t\tinstance = new RelationManager();\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Retrieves the relation of the target user as can be seen by the requesting user.\n\t * \n\t * TODO ACL is not yet implemented. All relations are returned at this stage.\n\t * \n\t * @param requestorJID the entity requesting the relations.\n\t * @param targetJID the entity whose relations are requested.\n\t * @return the list of relations of the target user, as can be seen by the requestor \n\t * @throws UserNotFoundException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Relation> getRelations(String requestorJID, String targetJID) throws UserNotFoundException {\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT DISTINCT relation FROM Relation relation WHERE relation.owner = :target\");\n\n\t\t// Parametrize the query\n\t\tquery.setParameter(\"target\", targetJID);\n\t\tList<Relation> result = query.getResultList();\n\t\tem.close();\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Setup a new relation.\n\t * \n\t * @param userJID the user seting up the new relation\n\t * @param relation the relation to setup\n\t * @throws InvalidRelationException\n\t */\n\tpublic void setupRelation(String userJID, PersistentRelation relation) throws InvalidRelationException {\n\t\t// Validate the relation request\n\t\t// TODO More should be validated here\n\t\tif (!relation.hasFrom() || !relation.hasTo() || !relation.hasNature()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing required elements\");\n\t\t}\n\n\t\t// Verify that the from or to is the user making the request\n\t\tif (!(relation.getFrom().equals(userJID) || relation.getTo().equals(userJID))) {\n\t\t\tthrow new InvalidRelationException(\"Must be part of the relation to create it\");\n\t\t}\n\n\t\t// Assign a unique ID to this new relation\n\t\trelation.setId(DefaultAtomHelper.generateId());\n\n\t\t// Set the request status\n\t\trelation.setStatus(Relation.Status.REQUEST);\n\n\t\t// We store the relation for requestor\n\t\trelation.setOwner(userJID);\n\n\t\t// Persist the relation\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\tem.persist(relation);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// We cleanup and notifiy the relation for the recipient\n\t\trelation.setAclRules(null);\n\t\trelation.setComment(null);\n\t\tnotify(userJID, relation);\n\t}\n\n\t/**\n\t * Update an existing relation.\n\t * \n\t * @param userJID the user seting up the new relation\n\t * @param relation the relation to setup\n\t * @throws InvalidRelationException\n\t */\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void updateRelation(String userJID, PersistentRelation relation) throws InvalidRelationException {\n\t\t// Validate the relation request\n\t\t// TODO More should be validated here\n\t\tif (!relation.hasId() || !relation.hasStatus()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing required elements\");\n\t\t}\n\n\t\t// Search for an existing relation with the given ID\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2\");\n\t\tquery.setParameter(1, userJID);\n\t\tquery.setParameter(2, relation.getId());\n\t\tList<PersistentRelation> relations = query.getResultList();\n\n\t\t// If no match, or more than one, we have an issue\n\t\tif (relations.size() != 1) {\n\t\t\tthrow new InvalidRelationException(\"Could not find relationship with id \" + relation.getId());\n\t\t}\n\n\t\t// We update the persisted relation\n\t\tem.getTransaction().begin();\n\t\tPersistentRelation storedRelation = relations.get(0);\n\t\tstoredRelation.setStatus(relation.getStatus());\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// We cleanup and notifiy the relation for the recipient\n\t\tstoredRelation.setAclRules(null);\n\t\tstoredRelation.setComment(null);\n\t\tnotify(userJID, storedRelation);\n\t}\n\n\t/**\n\t * Handles a relation notification message.\n\t * \n\t * @param remoteJID the entity sending the message\n\t * @param localJID the entity having received the message\n\t * @param relation the relation being notified\n\t * @throws InvalidRelationException\n\t */\n\tpublic void handleMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {\n\t\t// We need at least a status field\n\t\tif (!relation.hasStatus()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing a status field\");\n\t\t}\n\n\t\t// Is this a new request ?\n\t\tif (relation.getStatus().equals(Relation.Status.REQUEST)) {\n\t\t\thandleRequestMessage(remoteJID, localJID, relation);\n\t\t} else {\n\t\t\thandleUpdateMessage(remoteJID, localJID, relation);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void handleRequestMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {\n\t\t// Are required fields for a new relation setup present ?\n\t\tif (!relation.hasNature() || !relation.hasStatus() || !relation.hasFrom() || !relation.hasTo() || !relation.hasId()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing required elements\");\n\t\t}\n\n\t\t// The relation should be between the sender and the receiver\n\t\tif (getDirection(relation, remoteJID, localJID) == 0) {\n\t\t\tthrow new InvalidRelationException(\"Relation from/to do not match message from/to\");\n\t\t}\n\n\t\t// Cannot add a relation to yourself\n\t\tif (relation.getFrom().equals(relation.getTo())) {\n\t\t\tthrow new InvalidRelationException(\"Cannot add relation to yourself\");\n\t\t}\n\n\t\t// Verify that this relation is not already here\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2\");\n\t\tquery.setParameter(1, localJID);\n\t\tquery.setParameter(2, relation.getId());\n\t\tList<PersistentRelation> relations = query.getResultList();\n\n\t\t// If there is a match, we give up\n\t\t// TODO Not that fast. The other end may jut have not received any\n\t\t// answer and wants to try again\n\t\t// we should deal with all these recovery features.\n\t\tif (relations.size() > 0) {\n\t\t\tthrow new InvalidRelationException(\"This relation has already been requested\");\n\t\t}\n\n\t\t// Save the relation\n\t\tPersistentRelation persistentRelation = (PersistentRelation) relation;\n\t\tpersistentRelation.setOwner(localJID);\n\n\t\tem.getTransaction().begin();\n\t\tem.persist(persistentRelation);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void handleUpdateMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {\n\t\t// Search for the stored relation\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2\");\n\t\tquery.setParameter(1, localJID);\n\t\tquery.setParameter(2, relation.getId());\n\t\tList<PersistentRelation> relations = query.getResultList();\n\n\t\t// If no match, or more than one, we have an issue\n\t\tif (relations.size() != 1) {\n\t\t\tthrow new InvalidRelationException(\"Could not find matching relationship\");\n\t\t}\n\n\t\t// We update the persisted relation\n\t\tem.getTransaction().begin();\n\t\tPersistentRelation previous = relations.get(0);\n\t\tprevious.setStatus(relation.getStatus());\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\n\tprivate void notify(String localJID, Relation relation) {\n\t\tfinal DOMDocument domDocument = new DOMDocument();\n\t\tfinal Element entryElement = (Element) domDocument.appendChild(domDocument.createElementNS(Onesocialweb.NAMESPACE, Onesocialweb.RELATION_ELEMENT));\n\t\tfinal RelationDomWriter writer = new DefaultRelationDomWriter();\n\t\twriter.write(relation, entryElement);\n\t\tdomDocument.removeChild(entryElement);\n\n\t\tfinal Message message = new Message();\n\t\tmessage.setFrom(localJID);\n\t\tmessage.setType(Message.Type.headline);\n\t\torg.dom4j.Element eventElement = message.addChildElement(\"event\", \"http://jabber.org/protocol/pubsub#event\");\n\t\torg.dom4j.Element itemsElement = eventElement.addElement(\"items\");\n\t\titemsElement.addAttribute(\"node\", NODE);\n\t\torg.dom4j.Element itemElement = itemsElement.addElement(\"item\");\n\t\titemElement.addAttribute(\"id\", relation.getId());\n\t\titemElement.add((org.dom4j.Element) entryElement);\n\n\t\t// Send to this user\n\t\tmessage.setTo(getOtherEnd(relation, localJID));\n\t\tserver.getMessageRouter().route(message);\n\t}\n\n\tprivate String getOtherEnd(Relation relation, String userJID) {\n\t\tif (!relation.hasFrom() || !relation.hasTo()) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (relation.getFrom().equals(userJID)) {\n\t\t\treturn relation.getTo();\n\t\t}\n\n\t\tif (relation.getTo().equals(userJID)) {\n\t\t\treturn relation.getFrom();\n\t\t}\n\n\t\t// The given JID is no part of this relation\n\t\treturn null;\n\t}\n\n\tprivate int getDirection(Relation relation, String fromJID, String toJID) {\n\t\tif (!relation.hasFrom() || !relation.hasTo()) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (relation.getFrom().equals(fromJID) && relation.getTo().equals(toJID)) {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (relation.getFrom().equals(toJID) && relation.getTo().equals(fromJID)) {\n\t\t\treturn -1;\n\t\t}\n\n\t\t// If we are here, the relation does not concern from & to\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Class dependencies (should be true dependency injection someday)\n\t */\n\n\tprivate final XMPPServer server;\n\n\t/**\n\t * Private constructor to enforce the singleton\n\t */\n\tprivate RelationManager() {\n\t\tserver = XMPPServer.getInstance();\n\t}\n\n}", "public class PersistentActivityDomReader extends ActivityDomReader {\n\n\t@Override\n\tprotected AclDomReader getAclDomReader() {\n\t\treturn new PersistentAclDomReader();\n\t}\n\n\t@Override\n\tprotected ActivityFactory getActivityFactory() {\n\t\treturn new PersistentActivityFactory();\n\t}\n\n\t@Override\n\tprotected AtomDomReader getAtomDomReader() {\n\t\treturn new PersistentAtomDomReader();\n\t}\n\n\t@Override\n\tprotected Date parseDate(String atomDate) {\n\t\treturn DefaultAtomHelper.parseDate(atomDate);\n\t}\n\n}", "public class PersistentRelationDomReader extends RelationDomReader {\n\n\t@Override\n\tprotected AclDomReader getAclDomReader() {\n\t\treturn new PersistentAclDomReader();\n\t}\n\n\t@Override\n\tprotected RelationFactory getRelationFactory() {\n\t\treturn new PersistentRelationFactory();\n\t}\n\n}" ]
import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.activity.InvalidActivityException; import org.dom4j.Element; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.interceptor.PacketInterceptor; import org.jivesoftware.openfire.interceptor.PacketRejectedException; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.util.Log; import org.onesocialweb.model.activity.ActivityEntry; import org.onesocialweb.model.relation.Relation; import org.onesocialweb.openfire.exception.AccessDeniedException; import org.onesocialweb.openfire.exception.InvalidRelationException; import org.onesocialweb.openfire.handler.activity.PEPActivityHandler; import org.onesocialweb.openfire.manager.ActivityManager; import org.onesocialweb.openfire.manager.RelationManager; import org.onesocialweb.openfire.model.activity.PersistentActivityDomReader; import org.onesocialweb.openfire.model.relation.PersistentRelationDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.RelationDomReader; import org.onesocialweb.xml.dom4j.ElementAdapter; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet;
/* * Copyright 2010 Vodafone Group Services Ltd. * * 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.onesocialweb.openfire.handler; public class MessageEventInterceptor implements PacketInterceptor { private final XMPPServer server; public MessageEventInterceptor() { server = XMPPServer.getInstance(); } @SuppressWarnings( { "deprecation", "unchecked" }) public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { // We only care for incoming Messages has not yet been processed if (incoming && !processed && packet instanceof Message) { final Message message = (Message) packet; final JID fromJID = message.getFrom(); final JID toJID = message.getTo(); // We are only interested by message to bareJID (we don't touch the one sent to fullJID) if (!toJID.toBareJID().equalsIgnoreCase(toJID.toString())) { return; } // We only care for messaes to local users if (!server.isLocal(toJID) || !server.getUserManager().isRegisteredUser(toJID)) { return; } // We only bother about pubsub events Element eventElement = message.getChildElement("event", "http://jabber.org/protocol/pubsub#event"); if (eventElement == null) { return; } // That contains items Element itemsElement = eventElement.element("items"); if (itemsElement == null || itemsElement.attribute("node") == null) return; // Relating to the microblogging node if (itemsElement.attribute("node").getValue().equals( PEPActivityHandler.NODE)) { Log.debug("Processing an activity event from " + fromJID + " to " + toJID); final ActivityDomReader reader = new PersistentActivityDomReader(); List<Element> items=(List<Element>) itemsElement.elements("item"); if ((items!=null) && (items.size()!=0)){ for (Element itemElement :items) { ActivityEntry activity = reader .readEntry(new ElementAdapter(itemElement .element("entry"))); try { ActivityManager.getInstance().handleMessage( fromJID.toBareJID(), toJID.toBareJID(), activity); } catch (InvalidActivityException e) { throw new PacketRejectedException(); } catch (AccessDeniedException e) { throw new PacketRejectedException(); } } } else if (itemsElement.element("retract")!=null) { Element retractElement = itemsElement.element("retract"); String activityId=reader.readActivityId(new ElementAdapter(retractElement)); ActivityManager.getInstance().deleteMessage(activityId); } Set<JID> recipientFullJIDs = getFullJIDs(toJID .toBareJID()); Iterator<JID> it = recipientFullJIDs.iterator(); Message extendedMessage = message.createCopy(); while (it.hasNext()) { String fullJid = it.next().toString(); extendedMessage.setTo(fullJid); server.getMessageRouter().route(extendedMessage); } throw new PacketRejectedException(); } // or a relation event else if (itemsElement.attribute("node").getValue().equals( RelationManager.NODE)) {
final RelationDomReader reader = new PersistentRelationDomReader();
6
sorinMD/MCTS
src/main/java/mcts/seeder/pdf/CatanTypePDFSeedTrigger.java
[ "public class GameFactory {\n\tpublic static final int TICTACTOE = 0;\n\tpublic static final int CATAN = 1;\n\t\n\tprivate GameConfig gameConfig;\n\tprivate Belief belief;\n\t\n\tpublic GameFactory(GameConfig gameConfig, Belief belief) {\n\t\tthis.gameConfig = gameConfig;\n\t\tthis.belief = belief;\n\t}\n\t\n\tpublic Game getNewGame(){\n\t\tif(gameConfig.id == CATAN){\n\t\t\tif(belief != null) {\n\t\t\t\tif(!CatanWithBelief.board.init)\n\t\t\t\t\t CatanWithBelief.initBoard();//we can safely create a new board here as this means that we don't need to use a specific board.\n\t\t\t\treturn new CatanWithBelief(((CatanConfig) gameConfig), (CatanFactoredBelief) belief);\n\t\t\t}else {\n\t\t\t\tif(!Catan.board.init)\n\t\t\t\t\t Catan.initBoard();\n\t\t\t\treturn new Catan(((CatanConfig) gameConfig));\n\t\t\t}\n\t\t}else\n\t\t\treturn new TicTacToe();\n\t} \n\t\n\tpublic Game getGame(int[] state){\n\t\tif(gameConfig.id == CATAN){\n\t\t\tif(belief != null)\n\t\t\t\treturn new CatanWithBelief(state, ((CatanConfig) gameConfig), (CatanFactoredBelief) belief);\n\t\t\telse\n\t\t\t\treturn new Catan(state, ((CatanConfig) gameConfig));\n\t\t}else\n\t\t\treturn new TicTacToe(state);\n\t} \n\n\tpublic GameConfig getConfig(){\n\t\treturn gameConfig;\n\t}\n\t\n\tpublic Belief getBelief() {\n\t\treturn belief;\n\t}\n\t\n\tpublic DeterminizationSampler getDeterminizationSampler() {\n\t\tif(gameConfig.id == CATAN && belief != null)\n\t\t\treturn new CatanDeterminizationSampler();\n\t\treturn new NullDeterminizationSampler();\n\t}\n\t\n\t/**\n\t * @return\n\t */\n\tpublic static int nMaxPlayers(){\n\t\treturn 4;\n\t}\n\t\n\tpublic GameFactory copy() {\n\t\tBelief clone = null;\n\t\tif(belief != null)\n\t\t\t clone = belief.copy();\n\t\tGameFactory factory = new GameFactory(gameConfig.copy(), clone);\n\t\treturn factory;\n\t}\n\t\n}", "public class Catan implements Game, GameStateConstants {\n\n\tprotected CatanConfig config;\t\n protected int[] state;\n\t\n\tpublic static long breadth = 0;\n\tpublic static long depth = 0;\n\t\n\t/**\n\t * The development cards\n\t */\n\tprivate int[] cardSequence = {\n\t\t\t// 14\n\t\t\tCARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT,\n\t\t\tCARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT, CARD_KNIGHT,\n\t\t\t// 5\n\t\t\tCARD_ONEPOINT, CARD_ONEPOINT, CARD_ONEPOINT, CARD_ONEPOINT, CARD_ONEPOINT,\n\t\t\t// 2, 2, 2\n\t\t\tCARD_MONOPOLY, CARD_MONOPOLY, CARD_FREERESOURCE, CARD_FREERESOURCE, CARD_FREEROAD, CARD_FREEROAD };\n\t\n\t/**\n\t * Contains all the info that doesn't change during a game, hence it is shared between all instances\n\t * TODO: this is fine for a single local game, but it will be problematic to have it static on the server side if multiple games are run in parallel.\n\t */\n\tpublic static Board board = new Board();\n\n\t/**\n\t * Stub constructor to allow for a simple extension by {@link CatanWithBelief}\n\t * Note: the child class should do all the initialisation\n\t */\n\tprotected Catan() {}\n\t/**\n\t * A new game object with the provided state, but assumes an existing board.\n\t * To initialise the board call {@link #initBoard()}\n\t * \n\t * @param state\n\t * the game state\n\t */\n\tpublic Catan(int[] state, CatanConfig config) {\n\t\tthis.config = config;\n\t\tthis.state = state;\n\t\t/*\n\t\t * NOTE: the following code is dealing with the imperfect knowledge of\n\t\t * the order of the deck of remaining development cards. Could\n\t\t * potentially shuffle the remaining cards only if the next action is\n\t\t * dealing a card or if a new roll-out is started, but no significant\n\t\t * performance gain was observed to make up for the extra complexity\n\t\t */\n\t\tif(state[OFS_NCARDSGONE] > 0 && state[OFS_NCARDSGONE] < NCARDS){\n\t int numvp, numkn, numdisc, nummono, numrb;//the drawn dev cards\n\t numvp = numdisc = numkn = nummono = numrb = 0;\n\t for (int pl=0; pl<NPLAYERS; pl++){\n\t \tnumkn += state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + CARD_KNIGHT] + state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_KNIGHT] + \n\t \t\t\tstate[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_KNIGHT];\n\t \tnumvp += state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + CARD_ONEPOINT] + state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_ONEPOINT] + \n\t \t\t\tstate[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_ONEPOINT];\n\t \tnumdisc += state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + CARD_FREERESOURCE] + state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREERESOURCE] + \n\t \t\t\tstate[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_FREERESOURCE];\n\t \tnummono += state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + CARD_MONOPOLY] + state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_MONOPOLY] + \n\t \t\t\tstate[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_MONOPOLY];\n\t \tnumrb += state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + CARD_FREEROAD] + state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREEROAD] + \n\t \t\t\tstate[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_FREEROAD];\n\t }\n\t \n\t int nDrawnCards = numvp + numkn + numdisc + nummono + numrb;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_KNIGHT] = 14 - numkn;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_ONEPOINT] = 5 - numvp;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_FREEROAD] = 2 - numrb;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_FREERESOURCE] = 2 - numdisc;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_MONOPOLY] = 2 - nummono;\n\t int[] remainingCards = new int[NCARDS - nDrawnCards];\n\t int i;\n\t int idx = 0;\n\t for(i = 0; i < (14 - numkn); i++){\n\t \tremainingCards[idx] = CARD_KNIGHT;\n\t \tidx++;\n\t }\n\t for(i = 0; i < (5 - numvp); i++){\n\t \tremainingCards[idx] = CARD_ONEPOINT;\n\t \tidx++;\n\t }\n\t for(i = 0; i < (2 - numdisc); i++){\n\t \tremainingCards[idx] = CARD_FREERESOURCE;\n\t \tidx++;\n\t }\n\t for(i = 0; i < (2 - nummono); i++){\n\t \tremainingCards[idx] = CARD_MONOPOLY;\n\t \tidx++;\n\t }\n\t for(i = 0; i < (2 - numrb); i++){\n\t \tremainingCards[idx] = CARD_FREEROAD;\n\t \tidx++;\n\t }\n\t \n\t //shuffle the remaining cards and add them to the sequence in the order that they will be dealt in\n\t shuffleArray(remainingCards);\n\t idx = state[OFS_NCARDSGONE];\n\t for(i = 0; i < remainingCards.length; i++){\n\t \tcardSequence[idx] = remainingCards[i];\n\t \tidx++;\n\t }\n\t\t}else if(state[OFS_NCARDSGONE] == 0){\n\t\t\tshuffleArray(cardSequence);\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_KNIGHT] = 14;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_ONEPOINT] = 5;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_FREEROAD] = 2;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_FREERESOURCE] = 2;\n\t\t\tstate[OFS_DEVCARDS_LEFT + CARD_MONOPOLY] = 2;\n\t\t}\n\t\trecalcScores();\n\t}\n\n\t/**\n\t * A new game, but assumes an existing board. To initialise the board call {@link #initBoard()}\n\t */\n\tpublic Catan(CatanConfig config) {\n\t\tthis.config = config;\n\t\tstate = new int[STATESIZE];\n\t\tshuffleArray(cardSequence);\n\t\tstate[OFS_DEVCARDS_LEFT + CARD_KNIGHT] = 14;\n\t\tstate[OFS_DEVCARDS_LEFT + CARD_ONEPOINT] = 5;\n\t\tstate[OFS_DEVCARDS_LEFT + CARD_FREEROAD] = 2;\n\t\tstate[OFS_DEVCARDS_LEFT + CARD_FREERESOURCE] = 2;\n\t\tstate[OFS_DEVCARDS_LEFT + CARD_MONOPOLY] = 2;\n state[OFS_LARGESTARMY_AT] = -1;\n state[OFS_LONGESTROAD_AT] = -1;\n state[OFS_DISCARD_FIRST_PL] = -1;\n\t\tif(board.init){\n\t\t\tstateTransition(null);\n\t\t}else\n\t\t\tthrow new RuntimeException(\"Cannot create game; the board was not initialised\");\n\t}\n\t\n\t/**\n\t * Generates a new board with all the info that is constant throughout a game.\n\t */\n\tpublic static void initBoard(){\n\t\tboard.InitBoard();\n\t}\n\t\n\t@Override\n\tpublic int[] getState() {\n\t\treturn state.clone();\n\t}\n\n\t@Override\n\tpublic int getWinner() {\n\t\t//only current player can win\n\t\tint pl = getCurrentPlayer();\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_SCORE] >= 10)\n\t\t\t\treturn pl;\n\t\treturn -1;\n\t}\n\n\t@Override\n\tpublic boolean isTerminal() {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\treturn state[OFS_FSMSTATE + fsmlevel] == S_FINISHED;\n\t}\n\n\t@Override\n\tpublic int getCurrentPlayer() {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\treturn state[OFS_FSMPLAYER + fsmlevel];\n\t}\n\n\t@Override\n\tpublic void performAction(int[] a, boolean sample) {\n int fsmlevel = state[OFS_FSMLEVEL];\n int fsmstate = state[OFS_FSMSTATE+fsmlevel];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n int i, j, ind, val, ind2, k;\n \n switch (a[0]){\n case A_BUILDSETTLEMENT: \n\t\t\tstate[OFS_VERTICES + a[1]] = VERTEX_HASSETTLEMENT + pl;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_NSETTLEMENTS]++;\n\t\t\t//keep track of the free initial settlements in order to be able to plan the free initial roads\n\t\t\tif(fsmstate == S_SETTLEMENT1 || fsmstate == S_SETTLEMENT2)\n\t\t\t\tstate[OFS_LASTVERTEX] = a[1];\n\t\t\tboolean[] hasOpponentRoad = new boolean[NPLAYERS];\n\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\tind = board.neighborVertexVertex[a[1]][j];\n\t\t\t\tif (ind != -1) {\n\t\t\t\t\tstate[OFS_VERTICES + ind] = VERTEX_TOOCLOSE;\n\t\t\t\t}\n\t\t\t\tind = board.neighborVertexEdge[a[1]][j];\n\t\t\t\tif ((ind != -1) && (state[OFS_EDGES + ind] != EDGE_EMPTY)) {\n\t\t\t\t\thasOpponentRoad[state[OFS_EDGES + ind] - EDGE_OCCUPIED] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\thasOpponentRoad[pl] = false;\n\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\tind = board.neighborVertexHex[a[1]][j];\n\t\t\t\tif ((ind != -1) && (board.hextiles[ind].type == TYPE_PORT)) {\n\t\t\t\t\tval = board.hextiles[ind].subtype - PORT_SHEEP;\n\t\t\t\t\tk = j - 2;\n\t\t\t\t\tif (k < 0)\n\t\t\t\t\t\tk += 6;\n\t\t\t\t\tif (k == board.hextiles[ind].orientation)\n\t\t\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_ACCESSTOPORT + val] = 1;\n\t\t\t\t\tk = j - 3;\n\t\t\t\t\tif (k < 0)\n\t\t\t\t\t\tk += 6;\n\t\t\t\t\tif (k == board.hextiles[ind].orientation)\n\t\t\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_ACCESSTOPORT + val] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int pl2 = 0; pl2 < NPLAYERS; pl2++) {\n\t\t\t\tif (hasOpponentRoad[pl2])\n\t\t\t\t\trecalcLongestRoad(state, pl2);\n\t\t\t}\n\t\t\tif (fsmstate == S_SETTLEMENT2) {\n\t\t\t\tint resource;\n\t\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\t\tind = board.neighborVertexHex[a[1]][j];\n\t\t\t\t\tif (ind != -1) {\n\t\t\t\t\t\tresource = board.hextiles[ind].yields();\n\t\t\t\t\t\tif (resource != -1) {\n\t\t\t\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + resource]++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (fsmstate == S_NORMAL) {\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WOOD]--;\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_CLAY]--;\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WHEAT]--;\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_SHEEP]--;\n\t\t\t}\n\n\t\t\tbreak;\n\t\tcase A_BUILDCITY:\n\t\t\tstate[OFS_VERTICES + a[1]] = VERTEX_HASCITY + pl;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_NSETTLEMENTS]--;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_NCITIES]++;\n\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_STONE] -= 3;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WHEAT] -= 2;\n\t\t\tbreak;\n\t\tcase A_BUILDROAD:\n\t\t\tstate[OFS_LASTVERTEX] = 0;//clear the last free settlement location;\n\t\t\tstate[OFS_EDGES + a[1]] = EDGE_OCCUPIED + pl;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_NROADS]++;\n\t\t\tif (fsmstate == S_NORMAL) {\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WOOD]--;\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_CLAY]--;\n\t\t\t}\n\t\t\trecalcLongestRoad(state, pl);\n\t\t\tbreak;\n case A_THROWDICE:\n \tstate[OFS_NATURE_MOVE] = 1;//next move is non-deterministic\n \tbreak;\n case A_CHOOSE_DICE:\n\t\t\tval = a[1];\n\t\t\tfor (ind = 0; ind < N_HEXES; ind++) {\n\t\t\t\tif ((val == board.hextiles[ind].productionNumber) && (state[OFS_ROBBERPLACE] != ind)) {\n\t\t\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\t\t\tind2 = board.neighborHexVertex[ind][j];\n\t\t\t\t\t\tif (ind2 != -1) {\n\t\t\t\t\t\t\tk = state[OFS_VERTICES + ind2];\n\t\t\t\t\t\t\t// production for settlement\n\t\t\t\t\t\t\tif ((k >= VERTEX_HASSETTLEMENT) && (k < VERTEX_HASSETTLEMENT + NPLAYERS)) {\n\t\t\t\t\t\t\t\tpl = k - VERTEX_HASSETTLEMENT;\n\t\t\t\t\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + board.hextiles[ind].yields()]++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// production for city\n\t\t\t\t\t\t\tif ((k >= VERTEX_HASCITY) && (k < VERTEX_HASCITY + NPLAYERS)) {\n\t\t\t\t\t\t\t\tpl = k - VERTEX_HASCITY;\n\t\t\t\t\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + board.hextiles[ind].yields()] += 2;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstate[OFS_DICE] = val;\n\t\t\tstate[OFS_NATURE_MOVE] = 0;\n\t\t\tbreak;\n\t\tcase A_ENDTURN:\n\t\t\t// new cards become old cards\n\t\t\tfor (ind = 0; ind < NCARDTYPES; ind++) {\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + ind] += state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + ind];\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + ind] = 0;\n\t\t\t}\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] = 0;\n\t\t\tstate[OFS_DICE] = 0;\n\t\t\tstate[OFS_NUMBER_OF_OFFERS] = 0;\n\t\t\tbreak;\n case A_PORTTRADE:\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[2]] -= a[1];\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[4]] += a[3];\n break;\n case A_BUYCARD:\n \tstate[OFS_NATURE_MOVE] = 1;//dealing a card is a non-deterministic action that always follows this one\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WHEAT]--;\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_SHEEP]--; \n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_STONE]--;\n \tbreak;\n case A_DEAL_DEVCARD:\n val = a[1];\n if (val==CARD_ONEPOINT)\n state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + val]++;\n else\n state[OFS_PLAYERDATA[pl] + OFS_NEWCARDS + val]++;\n state[OFS_DEVCARDS_LEFT + val]--;\n state[OFS_NCARDSGONE] ++;\n state[OFS_NATURE_MOVE] = 0;\n break;\n \n\t\tcase A_PLAYCARD_KNIGHT:\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] = 1;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_KNIGHT]--;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_KNIGHT]++;\n\t\t\trecalcLargestArmy();\n\t\t\t// flow to next case!!!\n\t\tcase A_PLACEROBBER:\n\t\t\tstate[OFS_ROBBERPLACE] = a[1];\n\t\t\tif((a[2] != -1)){\n\t\t\t\t//the stealing action is non-deterministic\n\t\t\t\tstate[OFS_NATURE_MOVE] = 1;\n\t\t\t\tstate[OFS_VICTIM] = a[2];\n\t\t\t}\n\t\t\tbreak;\n\t\tcase A_CHOOSE_RESOURCE:\n\t\t\tstate[OFS_PLAYERDATA[state[OFS_VICTIM]] + OFS_RESOURCES + a[1]]--;\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[1]]++;\n\t\t\tstate[OFS_NATURE_MOVE] = 0;\n\t\t\tstate[OFS_VICTIM] = 0;\n\t\t\tbreak;\n case A_PLAYCARD_MONOPOLY:\n state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] = 1;\n state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_MONOPOLY]--;\n state[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_MONOPOLY]++;\n\t\t\tstate[OFS_MONO_RSS_CHOICE] = a[1];\n\t\t\tstate[OFS_NATURE_MOVE] = 1; //a fake chance node required to synchronise with the belief version of the game\n break;\n \n case A_CHOOSE_MONO_TOTALS:\n \tint choice = state[OFS_MONO_RSS_CHOICE];\n for (ind = 0; ind<NPLAYERS; ind++)\n {\n if (ind==pl)\n continue;\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + choice] += state[OFS_PLAYERDATA[ind] + OFS_RESOURCES + choice]; \n state[OFS_PLAYERDATA[ind] + OFS_RESOURCES + choice] = 0;\n }\n\t\t\t//resetting the choice. Even if default is equal to sheep, we use nature move offset and state transition to guide the state flow\n\t\t\tstate[OFS_MONO_RSS_CHOICE] = 0;\n\t\t\tstate[OFS_NATURE_MOVE] = 0;\n \tbreak;\n case A_PLAYCARD_FREEROAD:\n state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] = 1;\n state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREEROAD]--;\n state[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_FREEROAD]++;\n break;\n case A_PLAYCARD_FREERESOURCE:\n state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] = 1;\n state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREERESOURCE]--;\n state[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_FREERESOURCE]++;\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[1]] ++;\n state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[2]] ++;\n break;\n\t\tcase A_PAYTAX:\n\t\t\t//the discard resources are specified (both types and amounts)\n\t\t\tfor (i = 0; i < NRESOURCES; i++) {\n\t\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i] -= a[i + 1];\n\t\t\t}\n\t\t\tbreak;\n case A_TRADE:\n \tstate[OFS_NUMBER_OF_OFFERS]++;//action trade is composed of offer and accept actions\n \t//execute the trade by swapping the resources;\n \tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[4]] -= a[3];\n \tif(a[5] > -1)\n \t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[6]] -= a[5];\n \tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[8]] += a[7];\n \tif(a[9] > -1)\n \t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[10]] += a[9];\n \t\n \t//for opponent \n \tstate[OFS_PLAYERDATA[a[2]] + OFS_RESOURCES + a[4]] += a[3];\n \tif(a[5] > -1)\n \t\tstate[OFS_PLAYERDATA[a[2]] + OFS_RESOURCES + a[6]] += a[5];\n \tstate[OFS_PLAYERDATA[a[2]] + OFS_RESOURCES + a[8]] -= a[7];\n \tif(a[9] > -1)\n \t\tstate[OFS_PLAYERDATA[a[2]] + OFS_RESOURCES + a[10]] -= a[9];\n \t\n \t//check if any player has negative resources and report the problem;\n \tif(state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[4]] < 0 || state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + a[6]] < 0 ||\n \t\t\tstate[OFS_PLAYERDATA[a[2]] + OFS_RESOURCES + a[8]] < 0 || state[OFS_PLAYERDATA[a[2]] + OFS_RESOURCES + a[10]] < 0)\n \t\tSystem.err.println(\"negative rss\");\n \tbreak;\n case A_ACCEPT:\n \t//same as above, only that we need to look into the currentOffer and the initiator field in bl when executing trade;\n \tstate[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 4]] -= state[OFS_CURRENT_OFFER + 3];\n \tif(state[OFS_CURRENT_OFFER + 5] > -1)\n \t\tstate[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES +state[OFS_CURRENT_OFFER + 6]] -= state[OFS_CURRENT_OFFER + 5];\n \tstate[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 8]] += state[OFS_CURRENT_OFFER + 7];\n \tif(state[OFS_CURRENT_OFFER + 9] > -1)\n \t\tstate[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 10]] += state[OFS_CURRENT_OFFER + 9];\n \t\n \t//for the accepting player\n \tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 4]] += state[OFS_CURRENT_OFFER + 3];\n \tif(state[OFS_CURRENT_OFFER + 5] > -1)\n \t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 6]] += state[OFS_CURRENT_OFFER + 5];\n \tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 8]] -= state[OFS_CURRENT_OFFER + 7];\n \tif(state[OFS_CURRENT_OFFER + 9] > -1)\n \t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 10]] -= state[OFS_CURRENT_OFFER + 9];\n \t\n \t//check if any player has negative resources and report the problem;\n \tif(state[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 4]] < 0 || state[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 6]] < 0 ||\n \t\t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 8]] < 0 || state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 10]] < 0)\n \t\tSystem.err.println(\"negative rss\");\n \t\n \tfor(i = 0; i < ACTIONSIZE; i++)\n \t\tstate[OFS_CURRENT_OFFER + i] = 0;\n \tbreak;\n case A_REJECT:\n \tfor(i = 0; i < ACTIONSIZE; i++)\n \t\tstate[OFS_CURRENT_OFFER + i] = 0;\n \tbreak;\n case A_OFFER:\n \tstate[OFS_NUMBER_OF_OFFERS]++;\n \tfor(i = 0; i < ACTIONSIZE; i++)\n \t\tstate[OFS_CURRENT_OFFER + i] = a[i];\n \tbreak;\n\t\t}\n stateTransition(a);\n\t}\n\n\t@Override\n\tpublic Options listPossiblities(boolean sample) {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint fsmstate = state[OFS_FSMSTATE + fsmlevel];\n\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\t\tArrayList<int[]> options = new ArrayList<>();\n\t\t\n\t\tswitch (fsmstate) {\n\t\tcase S_SETTLEMENT1:\n\t\tcase S_SETTLEMENT2:\n\t\t\tlistInitSettlementPossibilities(options);\n\t\t\tbreak;\n\t\tcase S_ROAD1:\n\t\tcase S_ROAD2:\n\t\t\tlistInitRoadPossibilities(options);\n\t\t\tbreak;\n\t\tcase S_BEFOREDICE:\n\t\t\tlistBeforeRollPossibilities(options, pl);\n\t\t\tbreak;\n\t\tcase S_DICE_RESULT:\n\t\t\tlistDiceResultPossibilities(options);\n\t\t\tbreak;\n\t\tcase S_FREEROAD1:\n\t\tcase S_FREEROAD2:\n\t\t\tlistRoadPossibilities(options);\n\t\t\tbreak;\n\t\tcase S_PAYTAX:\n\t\t\tlistDiscardPossiblities(options,sample);\n\t\t\tbreak;\n\t\tcase S_ROBBERAT7:\n\t\t\tlistRobberPossibilities(options, A_PLACEROBBER);\n\t\t\tbreak;\n\t\tcase S_STEALING:\n\t\t\tlistStealingPossiblities(options, state[OFS_VICTIM]);\n\t\t\tbreak;\n\t\tcase S_NORMAL:\n\t\t\tlistNormalPossibilities(options,sample);\n\t\t\tbreak;\n\t\tcase S_BUYCARD:\n\t\t\tlistDealDevCardPossibilities(options);\n\t\t\tbreak;\n\t\tcase S_NEGOTIATIONS:\n\t\t\tlistTradeResponsePossiblities(options);\n\t\t\tbreak;\n\t\tcase S_MONOPOLY_EFFECT:\n\t\t\tlistMonopolyTotals(options);\n\t\t\tbreak;\n\t\t}\n\t\tOptions opts = new Options(options, null);\n\t\treturn opts;\n\t}\n\t\n\t@Override\n\tpublic TreeNode generateNode() {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint fsmstate = state[OFS_FSMSTATE + fsmlevel];\n\t\tif(fsmstate == S_PAYTAX){\n\t\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\t\t\tint val = 0;\n\t\t\tfor (int i = 0; i < NRESOURCES; i++)\n\t\t\t\tval += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\tval = val / 2;\n\t\t\tif(val <= config.N_MAX_DISCARD)\n\t\t\t\treturn new StandardNode(getState(), null, isTerminal(), getCurrentPlayer());\n\t\t\telse\n\t\t\t\treturn new ChanceNode(getState(), null, isTerminal(), getCurrentPlayer());\n\t\t}\n\t\tif(state[OFS_NATURE_MOVE] == 0)\n\t\t\treturn new StandardNode(getState(), null, isTerminal(), getCurrentPlayer());\n\t\telse\n\t\t\treturn new ChanceNode(getState(), null, isTerminal(), getCurrentPlayer());\n\t}\n\n\t@Override\n\tpublic Game copy() {\n\t\treturn new Catan(getState(),config);\n\t}\n\n\t@Override\n\tpublic int[] sampleNextAction() {\n\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n int fsmlevel = state[OFS_FSMLEVEL];\n int fsmstate = state[OFS_FSMSTATE+fsmlevel];\n int val = -1;\n Options opts = listPossiblities(true);\n ArrayList<int[]> options = opts.getOptions();\n \n if(/*state[OFS_NATURE_MOVE] != 1 &&*/ options.size() >1){\n \tdepth ++;\n \tbreadth += options.size();\n }\n \n\t\tif(state[OFS_NATURE_MOVE] == 1){\n\t\t\tif(fsmstate == S_DICE_RESULT){\n\t\t\t\tval = rnd.nextInt(6) + rnd.nextInt(6) + 2;\n\t\t\t\treturn Actions.newAction(A_CHOOSE_DICE, val);\n\t\t\t}else if(fsmstate == S_STEALING){\n\t\t\t\tval = selectRandomResourceInHand(state[OFS_VICTIM]);\n\t\t\t\treturn Actions.newAction(A_CHOOSE_RESOURCE, val);\n\t\t\t}else if(fsmstate == S_BUYCARD){\n\t\t\t\tval = cardSequence[state[OFS_NCARDSGONE]];\n\t\t\t\treturn Actions.newAction(A_DEAL_DEVCARD, val);\n\t\t\t}else if(fsmstate == S_MONOPOLY_EFFECT) {\n\t\t\t\treturn opts.getOptions().get(0);//fake chance node, there should be a single option\n\t\t\t}\n\t\t}else{\n\t\t\treturn options.get(rnd.nextInt(options.size()));\n\t\t}\n\t\t//iterate and choose the corresponding one\n\t\tif(val != -1){\n\t\t\tfor(int i=0; i < options.size(); i++){\n\t\t\t\tif(options.get(i)[1] == val)\n\t\t\t\t\treturn options.get(i);\n\t\t\t}\n\t\t}\n\t\tSystem.err.println(\"Couldn't find option in the list when sampling next action \");\n\t\treturn options.get(rnd.nextInt(options.size()));\n\t}\n\t\n\t@Override\n\tpublic int sampleNextActionIndex() {\n\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n int fsmlevel = state[OFS_FSMLEVEL];\n int fsmstate = state[OFS_FSMSTATE+fsmlevel];\n int val = -1;\n Options opts = listPossiblities(true);\n ArrayList<int[]> options = opts.getOptions();\n\t\tif(state[OFS_NATURE_MOVE] == 1){\n\t\t\tif(fsmstate == S_DICE_RESULT){\n\t\t\t\tval = rnd.nextInt(6) + rnd.nextInt(6) + 2;\n\t\t\t}else if(fsmstate == S_STEALING){\n\t\t\t\tval = selectRandomResourceInHand(state[OFS_VICTIM]);\n\t\t\t}else if(fsmstate == S_BUYCARD){\n\t\t\t\tval = cardSequence[state[OFS_NCARDSGONE]];\n\t\t\t}else if(fsmstate == S_MONOPOLY_EFFECT) {\n\t\t\t\treturn 0;//fake chance node, there should be a single option\n\t\t\t}\n\t\t}else{\n\t\t\treturn rnd.nextInt(options.size());\n\t\t}\n\t\t//iterate and choose the corresponding one\n\t\tif(val != -1){\n\t\t\tfor(int i=0; i < options.size(); i++){\n\t\t\t\tif(options.get(i)[1] == val)\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\tSystem.err.println(\"Couldn't find option in the list when sampling next index\");\n\t\treturn rnd.nextInt(options.size());\n\t}\n\n\tpublic void recalcScores() {\n\t\tint[] auxScoreArray = new int[4];\n\t\tint pl;\n\t\tfor (pl = 0; pl < NPLAYERS; pl++) {\n\t\t\tauxScoreArray[pl] = 0;\n\t\t\tauxScoreArray[pl] += state[OFS_PLAYERDATA[pl] + OFS_NSETTLEMENTS];\n\t\t\tauxScoreArray[pl] += state[OFS_PLAYERDATA[pl] + OFS_NCITIES] * 2;\n\t\t\tauxScoreArray[pl] += state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_ONEPOINT];\n\t\t}\n\t\tfor (pl = 0; pl < NPLAYERS; pl++) {\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_SCORE] = auxScoreArray[pl];\n\t\t}\n\n\t\tpl = state[OFS_LARGESTARMY_AT];\n\t\tif (pl != -1)\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_SCORE] += 2;\n\n\t\tpl = state[OFS_LONGESTROAD_AT];\n\t\tif (pl != -1)\n\t\t\tstate[OFS_PLAYERDATA[pl] + OFS_SCORE] += 2;\n\t}\n\n\t/**\n\t * Performs the state transition and updates the current state id and player\n\t * based on the executed action and the current state\n\t * \n\t * @param a\n\t * the executed action\n\t */\n\tprivate void stateTransition(int[] a) {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint fsmstate = state[OFS_FSMSTATE + fsmlevel];\n\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\t\tint startingPl = state[OFS_STARTING_PLAYER];\n\n\t\tswitch (fsmstate) {\n\t\tcase S_GAME:\n\t\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_SETTLEMENT1;\n\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = rnd.nextInt(4);//randomly choose the starting player\n\t\t\tstate[OFS_STARTING_PLAYER] = state[OFS_FSMPLAYER + fsmlevel];\n\t //make sure the robber location is recorded\n\t\t\tfor (int i=0; i<N_HEXES; i++)\n\t {\n\t if (board.hextiles[i].subtype == LAND_DESERT)\n\t {\n\t \tstate[OFS_ROBBERPLACE] = i;\n\t break;\n\t }\n\t }\n\t\t\tbreak;\n\t\tcase S_SETTLEMENT1:\n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_ROAD1;\n\t\t\tbreak;\n\t\tcase S_ROAD1:\n\t\t\tpl++;\n\t\t\tif (pl > NPLAYERS - 1) {\n\t\t\t\tpl = 0;\n\t\t\t}\n\t\t\tif (pl == startingPl) {\n\t\t\t\t//the last player starts the next phase so don't modify the current player field in the state\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_SETTLEMENT2;\n\t\t\t} else {\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl;\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_SETTLEMENT1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_SETTLEMENT2:\n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_ROAD2;\n\t\t\tbreak;\n\t\tcase S_ROAD2:\n\t\t\tif (pl == startingPl) {\n\t\t\t\t// the starting player starts the next phase\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_BEFOREDICE;\n\t\t\t} else {\n\t\t\t\tpl--; //go back anti-clockwise for the second free settlement\n\t\t\t\tif (pl < 0)\n\t\t\t\t\tpl = NPLAYERS - 1;\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl;\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_SETTLEMENT2;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_BEFOREDICE:\n\t\t\tif (a[0] == A_THROWDICE) {\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_DICE_RESULT;\n\t\t\t}else if((a[0] == A_PLAYCARD_KNIGHT) && a[2] != -1){\n\t\t\t\tfsmlevel++;\n\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_STEALING;\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl;\n\t\t\t}//if no victim is specified, the player still needs to roll\n\t\t\tbreak;\n\t\tcase S_DICE_RESULT:\n\t\t\tif ((a[0] == A_CHOOSE_DICE) && (state[OFS_DICE] != 7)) {\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\t} else if ((a[0] == A_CHOOSE_DICE) && (state[OFS_DICE] == 7)) {\n\t\t\t\t//always start from the current player and finish at the current player; \n\t\t\t\tstate[OFS_DISCARD_FIRST_PL] = pl;\n\t\t\t\tint val = 0;\n\t\t\t\tfor (int i = 0; i < NRESOURCES; i++)\n\t\t\t\t\tval += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\t\tif(val > 7){\n\t\t\t\t\tfsmlevel++;\n\t\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_PAYTAX;\n\t\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl; \n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tint j = pl+1;\n\t\t\t\tif(j>=NPLAYERS)\n\t\t\t\t\tj=0;\n\t\t\t\twhile(j!=pl){\n\t\t\t\t\tval = 0;\n\t\t\t\t\tfor (int i = 0; i < NRESOURCES; i++)\n\t\t\t\t\t\tval += state[OFS_PLAYERDATA[j] + OFS_RESOURCES + i];\n\t\t\t\t\tif(val > 7){\n\t\t\t\t\t\tfsmlevel++;\n\t\t\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_PAYTAX;\n\t\t\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = j; \n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tj++;\n\t\t\t\t\tif(j>=NPLAYERS)\n\t\t\t\t\t\tj=0;\n\t\t\t\t}\n\t\t\t\t//if no player has to discard, then update to move robber\n\t\t\t\tif(state[OFS_FSMSTATE + fsmlevel] != S_PAYTAX){\n\t\t\t\t\tfsmlevel++;\n\t\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_ROBBERAT7;\n\t\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_PAYTAX:\n\t\t\t//go round the board until all players discarded or we are back to the original player\t\t\t\n\t\t\tboolean discardFinished = true;\n\t\t\tpl++;\n\t\t\tif(pl>=NPLAYERS)\n\t\t\t\tpl=0;\n\t\t\twhile(pl!=state[OFS_DISCARD_FIRST_PL]){\n\t\t\t\tint val = 0;\n\t\t\t\tfor (int i = 0; i < NRESOURCES; i++)\n\t\t\t\t\tval += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\t\tif(val > 7){\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_PAYTAX;\n\t\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl; \n\t\t\t\t\tdiscardFinished = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tpl++;\n\t\t\t\tif(pl>=NPLAYERS)\n\t\t\t\t\tpl=0;\n\t\t\t}\n\t\t\tif(discardFinished){\n\t\t\t\tstate[OFS_DISCARD_FIRST_PL] = -1;\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = state[OFS_FSMPLAYER + fsmlevel - 1]; //the player that rolled moves the robber\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_ROBBERAT7;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_ROBBERAT7:\n\t\t\tif(a[2] != -1)\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_STEALING;\n\t\t\telse{\n\t\t\t\tfsmlevel--;\n\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_STEALING:\n\t\t\tfsmlevel--;\n\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\tif(state[OFS_DICE] != 0)\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\telse\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_BEFOREDICE;\n\t\t\tbreak;\n\t\tcase S_NORMAL:\n\t\t\tswitch (a[0]) {\n\t\t\tcase A_PLAYCARD_MONOPOLY:\n\t\t\t\tif(state[OFS_NATURE_MOVE] == 1) {\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_MONOPOLY_EFFECT;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase A_PLAYCARD_KNIGHT:\n\t\t\t\tif(a[2] != -1){\n\t\t\t\t\tfsmlevel++;\n\t\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl;\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_STEALING;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase A_BUYCARD:\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_BUYCARD;\n\t\t\t\tbreak;\n\t\t\tcase A_OFFER:\n\t\t\t\tfsmlevel++;\n\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = a[2];\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NEGOTIATIONS;\n\t\t\t\tbreak;\n\t\t\tcase A_ENDTURN:\n\t\t\t\tstate[OFS_TURN]++;\n\t\t\t\tpl++;\n\t\t\t\tif (pl >= NPLAYERS)\n\t\t\t\t\tpl = 0;\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = pl;\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_BEFOREDICE;\n\t\t\t\tbreak;\n\t\t\tcase A_PLAYCARD_FREEROAD:\n\t\t\t\t// free road card can be played even if you only have one road left to build\n\t\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_NROADS] < 14)\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_FREEROAD1;\n\t\t\t\telse\n\t\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_FREEROAD2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_BUYCARD:\n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\tbreak;\n\t\tcase S_FREEROAD1:\n\t\t\t//the player may have roads left but there is no free space\n\t\t\tArrayList<int[]> roadOpt = new ArrayList<int[]>();\n\t\t\tlistRoadPossibilities(roadOpt);\n\t\t\tif (roadOpt.size() > 0)\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_FREEROAD2;\n\t\t\telse\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\tbreak;\n\t\tcase S_FREEROAD2:\n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\tbreak;\n\t\tcase S_NEGOTIATIONS:\n\t\t\tswitch (a[0]) {\n\t\t\tcase A_OFFER:\n\t\t\t\tstate[OFS_FSMPLAYER + fsmlevel] = a[2]; //counter-offer, change the current player only\n\t\t\t\tbreak;\n\t\t\tcase A_REJECT:\n\t\t\tcase A_ACCEPT:\n\t\t\t\tfsmlevel--;\n\t\t\t\tstate[OFS_FSMLEVEL] = fsmlevel;\n\t\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase S_MONOPOLY_EFFECT:\n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_NORMAL;\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\trecalcScores();\n\t\t//do not allow winning in the stealing chance event so the state transition will be synced with the belief version of the game\n\t\tif (getWinner() != -1 && state[OFS_FSMSTATE + fsmlevel] != S_STEALING) { \n\t\t\tstate[OFS_FSMSTATE + fsmlevel] = S_FINISHED;\n\t\t}\n\t}\n\n\t//private listing actions methods//\n \n\tprivate void listInitSettlementPossibilities(ArrayList<int[]> options) {\n\t\tint i;\n\t\tfor (i = 0; i < N_VERTICES; i++) {\n\t\t\tif (state[OFS_VERTICES + i] == 0) {\n\t\t\t\toptions.add(Actions.newAction(A_BUILDSETTLEMENT, i));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void listInitRoadPossibilities(ArrayList<int[]> options) {\n\t\tint i, ind;\n\t\tint lastvertex = state[OFS_LASTVERTEX];\n\t\tfor (i = 0; i < 6; i++) {\n\t\t\tind = board.neighborVertexEdge[lastvertex][i];\n\t\t\tif ((ind != -1) && (state[OFS_EDGES + ind] == 0)) {\n\t\t\t\toptions.add(Actions.newAction(A_BUILDROAD, ind));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void listBeforeRollPossibilities(ArrayList<int[]> options, int pl) {\n\t\toptions.add(Actions.newAction(A_THROWDICE));\n\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_KNIGHT] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] == 0)) {\n\t\t\tlistRobberPossibilities(options, A_PLAYCARD_KNIGHT);\n\t\t}\n\t}\n\t\n\tprivate void listDiceResultPossibilities(ArrayList<int[]> options){\n\t\tfor(int i = 2; i <= 12; i++){\n\t\t\toptions.add(Actions.newAction(A_CHOOSE_DICE, i));\n\t\t}\n\t}\n\t\n\tprivate void listNormalPossibilities(ArrayList<int[]> options, boolean sample){\n\t\t\n\t\tif(sample && config.SAMPLE_FROM_DISTRIBUTION_OVER_TYPES_IN_ROLLOUTS){\n\t\t\tlistNormalPossAndSampleType(options);\n\t\t\treturn;\n\t\t}\n listPaidRoadPossibilities(options);\n listPaidSettlementPossibilities(options);\n listCityPossibilities(options);\n listBuyDevCardPossibility(options);\n listBankTradePossibilities(options);\n listDevCardPossibilities(options);\n if(config.TRADES && state[OFS_NUMBER_OF_OFFERS] < config.OFFERS_LIMIT){\n \tif(config.ALLOW_SAMPLING_IN_NORMAL_STATE){\n \t\tlistTradePossibilities(options,sample);\n \t}else{\n \t\tlistTradePossibilities(options,false);\n \t}\n }\n options.add(Actions.newAction(A_ENDTURN));\n\t}\n\t\n\t/**\n\t * Chooses uniformly at random the action type to execute next and only\n\t * lists the normal possibilities of the chosen type.\n\t * \n\t * TODO: add option for weights on action types such that some would be executed more\n\t * often in the roll-outs (i.e. basic player types)\n\t */\n\tprivate void listNormalPossAndSampleType(ArrayList<int[]> options){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n\t\tint i,j;\n ArrayList<Integer> actionTypes = new ArrayList<>();\n\t\tArrayList<int[]> roadOptions = new ArrayList<>();\n\t\tArrayList<int[]> settlementOptions = new ArrayList<>();\n\t\tArrayList<int[]> cityOptions = new ArrayList<>();\n\t\tArrayList<int[]> buyCardOptions = new ArrayList<>();\n\t\tArrayList<int[]> portTradeOptions = new ArrayList<>();\n \n //can always end turn in the normal state\n\t\tactionTypes.add(A_ENDTURN);\n\t\t\n\t\tint[] playersWithResources = new int[NPLAYERS];\n\t\tfor (i = 0; i < NPLAYERS; i++) {\n\t\t\tfor (j = 0; j < NRESOURCES; j++)\n\t\t\t\tplayersWithResources[i] += state[OFS_PLAYERDATA[i] + OFS_RESOURCES + j];\n\t\t\t\t\n\t\t}\n\t\t//are there any other players with rss\n\t\tArrayList<Integer> oppWithRss = new ArrayList<>();\n\t\tfor (i = 0; i < NPLAYERS; i++) {\n\t\t\tif(i==pl)\n\t\t\t\tcontinue;\n\t\t\tif(playersWithResources[i] > 0)\n\t\t\t\toppWithRss.add(i);\n\t\t}\n\t\t\n\t\tif(playersWithResources[pl] > 0){\n\t\t\t//can only do trades if any of the opponents have resources\n\t\t\tif(oppWithRss.size() != 0)\n\t\t\t\tactionTypes.add(A_TRADE);\n\t\t\tlistPaidRoadPossibilities(roadOptions);\n\t\t\tlistPaidSettlementPossibilities(settlementOptions);\n\t\t\tlistCityPossibilities(cityOptions);\n\t\t\tlistBuyDevCardPossibility(buyCardOptions);\n\t\t\tlistBankTradePossibilities(portTradeOptions);\n\t\t\t\n\t\t\tif(roadOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUILDROAD);\n\t\t\t}\n\t\t\tif(settlementOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUILDSETTLEMENT);\n\t\t\t}\n\t\t\tif(cityOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUILDCITY);\n\t\t\t}\n\t\t\tif(buyCardOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUYCARD);\n\t\t\t}\n\t\t\tif(portTradeOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_PORTTRADE);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] == 0){\n\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_KNIGHT] >= 1)\n\t\t\t\tactionTypes.add(A_PLAYCARD_KNIGHT);\n\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_MONOPOLY] >= 1)\n\t\t\t\tactionTypes.add(A_PLAYCARD_MONOPOLY);\n\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREERESOURCE] >= 1)\n\t\t\t\tactionTypes.add(A_PLAYCARD_FREERESOURCE);\n\t\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREEROAD] >= 1)\n\t\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_NROADS] < 15)) {\n\t\t\t\t// need to check if the player can place roads first\n\t\t\t\tArrayList<int[]> roadOpt = new ArrayList<int[]>();\n\t\t\t\tlistRoadPossibilities(roadOpt);\n\t\t\t\tif (roadOpt.size() > 0)\n\t\t\t\t\tactionTypes.add(A_PLAYCARD_FREEROAD);\n\t\t\t}\n\t\t}\n\t\t\n\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n\t\tint chosenType = A_ENDTURN;\n\t\tif(config.rolloutTypeDist instanceof HumanActionTypePdf) {\n\t\t\tMap<Integer,Double> dist = config.rolloutTypeDist.getDist(actionTypes);\n\t\t\tdouble totalWeight = 0.0;\n\t\t\tfor (Entry<Integer,Double> e : dist.entrySet()){\n\t\t\t totalWeight += e.getValue();\n\t\t\t}\n\t\t\tdouble random = rnd.nextDouble() * totalWeight;\n\t\t\tfor (Entry<Integer,Double> e : dist.entrySet()){\n\t\t\t\trandom -= e.getValue();\n\t\t\t if (random <= 0.0) {\n\t\t\t chosenType = e.getKey();\n\t\t\t break;\n\t\t\t }\n\t\t\t}\n\t\t}else {\n\t\t\t//the alternative is uniform, so no need to do weighted random sampling\n\t\t\tchosenType = actionTypes.get(rnd.nextInt(actionTypes.size()));\n\t\t}\n\t\t\n\t\tswitch (chosenType) {\n\t\tcase A_ENDTURN:\n\t\t\toptions.add(Actions.newAction(A_ENDTURN));\n\t\t\tbreak;\n\t\tcase A_TRADE:\n\t\t\tlistTradePossibilities(options, true);\n\t\t\tbreak;\n\t\tcase A_BUILDROAD:\n\t\t\toptions.addAll(roadOptions);\n\t\t\tbreak;\n\t\tcase A_BUILDSETTLEMENT:\n\t\t\toptions.addAll(settlementOptions);\n\t\t\tbreak;\n\t\tcase A_BUILDCITY:\n\t\t\toptions.addAll(cityOptions);\n\t\t\tbreak;\n\t\tcase A_BUYCARD:\n\t\t\toptions.addAll(buyCardOptions);\n\t\t\tbreak;\n\t\tcase A_PORTTRADE:\n\t\t\toptions.addAll(portTradeOptions);\n\t\t\tbreak;\n\t\tcase A_PLAYCARD_KNIGHT:\n\t\t\tlistRobberPossibilities(options, A_PLAYCARD_KNIGHT);\n\t\t\tbreak;\n\t\tcase A_PLAYCARD_FREEROAD:\n\t\t\toptions.add(Actions.newAction(A_PLAYCARD_FREEROAD));\n\t\t\tbreak;\n\t\tcase A_PLAYCARD_MONOPOLY:\n\t\t\tlistMonopolyPossibilities(options);\n\t\t\tbreak;\n\t\tcase A_PLAYCARD_FREERESOURCE:\n\t\t\tlistFreeResourcePossibilities(options);\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tpublic ArrayList<Integer> listNormalActionTypes(){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n\t\tint i,j;\n ArrayList<Integer> actionTypes = new ArrayList<>();\n\t\tArrayList<int[]> roadOptions = new ArrayList<>();\n\t\tArrayList<int[]> settlementOptions = new ArrayList<>();\n\t\tArrayList<int[]> cityOptions = new ArrayList<>();\n\t\tArrayList<int[]> buyCardOptions = new ArrayList<>();\n\t\tArrayList<int[]> portTradeOptions = new ArrayList<>();\n \n //can always end turn in the normal state\n\t\tactionTypes.add(A_ENDTURN);\n\t\t\n\t\tint[] playersWithResources = new int[NPLAYERS];\n\t\tfor (i = 0; i < NPLAYERS; i++) {\n\t\t\tfor (j = 0; j < NRESOURCES; j++)\n\t\t\t\tplayersWithResources[i] += state[OFS_PLAYERDATA[i] + OFS_RESOURCES + j];\n\t\t\t\t\n\t\t}\n\t\t//are there any other players with rss\n\t\tArrayList<Integer> oppWithRss = new ArrayList<>();\n\t\tfor (i = 0; i < NPLAYERS; i++) {\n\t\t\tif(i==pl)\n\t\t\t\tcontinue;\n\t\t\tif(playersWithResources[i] > 0)\n\t\t\t\toppWithRss.add(i);\n\t\t}\n\t\t\n\t\tif(playersWithResources[pl] > 0){\n\t\t\t//can only do trades if any of the opponents have resources\n\t\t\tif(oppWithRss.size() != 0)\n\t\t\t\tactionTypes.add(A_TRADE);\n\t\t\tlistPaidRoadPossibilities(roadOptions);\n\t\t\tlistPaidSettlementPossibilities(settlementOptions);\n\t\t\tlistCityPossibilities(cityOptions);\n\t\t\tlistBuyDevCardPossibility(buyCardOptions);\n\t\t\tlistBankTradePossibilities(portTradeOptions);\n\t\t\t\n\t\t\tif(roadOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUILDROAD);\n\t\t\t}\n\t\t\tif(settlementOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUILDSETTLEMENT);\n\t\t\t}\n\t\t\tif(cityOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUILDCITY);\n\t\t\t}\n\t\t\tif(buyCardOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_BUYCARD);\n\t\t\t}\n\t\t\tif(portTradeOptions.size() > 0){\n\t\t\t\tactionTypes.add(A_PORTTRADE);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] == 0){\n\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_KNIGHT] >= 1)\n\t\t\t\tactionTypes.add(A_PLAYCARD_KNIGHT);\n\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_MONOPOLY] >= 1)\n\t\t\t\tactionTypes.add(A_PLAYCARD_MONOPOLY);\n\t\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREERESOURCE] >= 1)\n\t\t\t\tactionTypes.add(A_PLAYCARD_FREERESOURCE);\n\t\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREEROAD] >= 1)\n\t\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_NROADS] < 15)) {\n\t\t\t\t// need to check if the player can place roads first\n\t\t\t\tArrayList<int[]> roadOpt = new ArrayList<int[]>();\n\t\t\t\tlistRoadPossibilities(roadOpt);\n\t\t\t\tif (roadOpt.size() > 0)\n\t\t\t\t\tactionTypes.add(A_PLAYCARD_FREEROAD);\n\t\t\t}\n\t\t}\n\t\treturn actionTypes;\n\t}\n\t\n\t\n\tprivate void listPaidRoadPossibilities(ArrayList<int[]> options){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n \n\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WOOD] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_CLAY] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_NROADS] < 15)) {\n\t\t\tlistRoadPossibilities(options);\n\t\t}\n\t}\n\t\n\tprivate void listPaidSettlementPossibilities(ArrayList<int[]> options){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n int ind;\n boolean hasneighbor;\n \n\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WOOD] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_CLAY] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WHEAT] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_SHEEP] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_NSETTLEMENTS] < 5)) {\n\t\t\tfor (int i = 0; i < N_VERTICES; i++) {\n\t\t\t\tif (state[OFS_VERTICES + i] == VERTEX_EMPTY) {\n\t\t\t\t\thasneighbor = false;\n\t\t\t\t\tfor (int j = 0; j < 6; j++) {\n\t\t\t\t\t\tind = board.neighborVertexEdge[i][j];\n\t\t\t\t\t\tif ((ind != -1) && (state[OFS_EDGES + ind] == EDGE_OCCUPIED + pl))\n\t\t\t\t\t\t\thasneighbor = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (hasneighbor)\n\t\t\t\t\t\toptions.add(Actions.newAction(A_BUILDSETTLEMENT, i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void listCityPossibilities(ArrayList<int[]> options){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n \n\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_STONE] >= 3)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WHEAT] >= 2)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_NCITIES] < 4)) {\n\t\t\tfor (int i = 0; i < N_VERTICES; i++) {\n\t\t\t\tif (state[OFS_VERTICES + i] == VERTEX_HASSETTLEMENT + pl) {\n\t\t\t\t\toptions.add(Actions.newAction(A_BUILDCITY, i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void listBuyDevCardPossibility(ArrayList<int[]> options){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n \n if ((state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_STONE] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_WHEAT] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + RES_SHEEP] >= 1) \n\t\t\t\t&& state[OFS_NCARDSGONE] < NCARDS) {\n\t\t\toptions.add(Actions.newAction(A_BUYCARD));\n\t\t}\n\t}\n\t\n\tprivate void listBankTradePossibilities(ArrayList<int[]> options){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n \n for (int i=0; i<NRESOURCES; i++)\n {\n for (int j = 0; j<NRESOURCES; j++)\n {\n if (i==j) continue;\n // specific port\n if ( (state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+i] >= 2) &&\n (state[OFS_PLAYERDATA[pl]+OFS_ACCESSTOPORT+i] == 1) )\n \toptions.add(Actions.newAction(A_PORTTRADE, 2, i, 1, j));\n // misc port\n else if ( (state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+i] >= 3) &&\n (state[OFS_PLAYERDATA[pl]+OFS_ACCESSTOPORT+NRESOURCES] == 1) )\n \toptions.add(Actions.newAction(A_PORTTRADE, 3, i, 1, j));\n // bank\n else if ( (state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+i] >= 4) )\n \toptions.add(Actions.newAction(A_PORTTRADE, 4, i, 1, j));\n }\n }\n \n\t}\n\t\n\tprivate void listRoadPossibilities(ArrayList<int[]> options) {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\t\tint i, j, ind;\n\t\tboolean hasneighbor;\n\n\t\tfor (i = 0; i < N_VERTICES; i++) {\n\n\t\t\tif ((state[OFS_VERTICES + i] == VERTEX_EMPTY) || (state[OFS_VERTICES + i] == VERTEX_TOOCLOSE)\n\t\t\t\t\t|| (state[OFS_VERTICES + i] == VERTEX_HASSETTLEMENT + pl)\n\t\t\t\t\t|| (state[OFS_VERTICES + i] == VERTEX_HASCITY + pl)) {\n\t\t\t\thasneighbor = false;\n\t\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\t\tind = board.neighborVertexEdge[i][j];\n\t\t\t\t\tif ((ind != -1) && (state[OFS_EDGES + ind] == EDGE_OCCUPIED + pl)) {\n\t\t\t\t\t\thasneighbor = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hasneighbor) {\n\t\t\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\t\t\tind = board.neighborVertexEdge[i][j];\n\t\t\t\t\t\tif ((ind != -1) && (state[OFS_EDGES + ind] == EDGE_EMPTY))\n\t\t\t\t\t\t\toptions.add(Actions.newAction(A_BUILDROAD, ind));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Lists the options of where to move the robber and who is the victim, without the action of stealing\n\t * @param options\n\t * @param action is this robber at 7 or following a played knight?\n\t */\n\tprivate void listRobberPossibilities(ArrayList<int[]> options, int action) {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\t\tint i, j, ind, pl2, val;\n\n\t\tboolean[] adjacentPlayers = new boolean[NPLAYERS];\n\t\tboolean[] playersWithResources = new boolean[NPLAYERS];\n\t\tArrays.fill(playersWithResources, false);// make sure it is false\n\t\tfor (i = 0; i < NPLAYERS; i++) {\n\t\t\tint nrss = 0;\n\t\t\tfor (j = 0; j < NRESOURCES; j++)\n\t\t\t\tnrss += state[OFS_PLAYERDATA[i] + OFS_RESOURCES + j];\n\t\t\tif (nrss > 0) {\n\t\t\t\tplayersWithResources[i] = true;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0; i < N_HEXES; i++) {\n\t\t\tif (board.hextiles[i].type != TYPE_LAND)\n\t\t\t\tcontinue;\n\t\t\tif (i == state[OFS_ROBBERPLACE])\n\t\t\t\tcontinue;\n\t\t\tArrays.fill(adjacentPlayers, false);// clear adjacent array\n\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\tind = board.neighborHexVertex[i][j];\n\t\t\t\tif (ind == -1)\n\t\t\t\t\tcontinue;\n\t\t\t\tval = state[OFS_VERTICES + ind];\n\t\t\t\tif ((val >= VERTEX_HASSETTLEMENT) && (val < VERTEX_HASSETTLEMENT + NPLAYERS))\n\t\t\t\t\tpl2 = val - VERTEX_HASSETTLEMENT;\n\t\t\t\telse if ((val >= VERTEX_HASCITY) && (val < VERTEX_HASCITY + NPLAYERS))\n\t\t\t\t\tpl2 = val - VERTEX_HASCITY;\n\t\t\t\telse\n\t\t\t\t\tpl2 = -1;\n\n\t\t\t\tif ((pl2 != -1) && (pl2 != pl)) {\n\t\t\t\t\t// in order to only add one action per adjacent player and not per adjacent piece\n\t\t\t\t\tadjacentPlayers[pl2] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//add the victims based on who is adjacent and who has resources\n\t\t\tint counter = 0;\n\t\t\tfor(j = 0; j < NPLAYERS; j++){\n\t\t\t\tif(adjacentPlayers[j] && playersWithResources[j]){\n\t\t\t\t\toptions.add(Actions.newAction(action, i, j));\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(counter == 0)\n\t\t\t\toptions.add(Actions.newAction(action, i, -1));//can still move the robber on the hex, even if there will be no victim\n\t\t}\n\t}\n\t\n\tprivate void listDiscardPossiblities(ArrayList<int[]> options, boolean sample){\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\t\tint val = 0;\n\t\tint ind = 0;\n\t\tint i =0;\n\t\tfor (i = 0; i < NRESOURCES; i++)\n\t\t\tval += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\tval = val / 2;\n\t\tboolean random = false;\n\t\tif(sample) {\n\t\t\trandom = true;\n\t\t}else if(val <= config.N_MAX_DISCARD){\n\t\t\t//get the resources\n\t\t\tint[] resources = new int[NRESOURCES];\n\t\t\tResourceSet set = new ResourceSet();\n\t\t\tfor (i = 0; i < NRESOURCES; i++)\n\t\t\t\tset.add(state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i], i);\n\t\t\tList<ResourceSet> discardList = set.getSubsets(val,false);\n\t\t\tfor(ResourceSet opt: discardList){\n\t\t\t\tresources = opt.getResourceArrayClone();\n\t\t\t\toptions.add(Actions.newAction(A_PAYTAX, resources[0], resources[1],resources[2], resources[3], resources[4]));\n\t\t\t}\n\t\t}else {\n\t\t\trandom = true;\n\t\t}\n\t\t\n\t\tif(random) {\n\t\t\tint[] rssSet = new int[NRESOURCES];\n\t\t\tfor (i = 0; i < NRESOURCES; i++)\n\t\t\t\trssSet[i] = state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\tint[] action = Actions.newAction(A_PAYTAX);\n\t\t\tfor (i = 0; i < val; i++) {\n\t\t\t\tind = selectRandomResourceFromSet(rssSet);\n\t\t\t\trssSet[ind] --;\n\t\t\t\taction[ind + 1] +=1;\n\t\t\t}\n\t\t\toptions.add(action);\n\t\t}\n\t}\n\t\n\tprivate void listStealingPossiblities(ArrayList<int[]> options, int victim){\n\t\t//we know the victim, just list the possible rss as action (part 0 steal rss, 1 = type)\n\t\tfor (int i = 0; i < NRESOURCES; i++) {\n\t\t\tif(state[OFS_PLAYERDATA[victim] + OFS_RESOURCES + i] > 0)\n\t\t\t\toptions.add(Actions.newAction(A_CHOOSE_RESOURCE, i));\n\t\t}\n\t}\n\t\n\tprivate void listDealDevCardPossibilities(ArrayList<int[]> options){\n\t\tfor (int i = 0; i < NCARDTYPES; i++) {\n\t\t\tif(state[OFS_DEVCARDS_LEFT + i] > 0)\n\t\t\t\toptions.add(Actions.newAction(A_DEAL_DEVCARD, i));\n\t\t}\n\t}\n\t\n\tprivate void listDevCardPossibilities(ArrayList<int[]> options) {\n\t\tint fsmlevel = state[OFS_FSMLEVEL];\n\t\tint pl = state[OFS_FSMPLAYER + fsmlevel];\n\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_HASPLAYEDCARD] != 0)\n\t\t\treturn;\n\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREERESOURCE] >= 1) {\n\t\t\tlistFreeResourcePossibilities(options);\n\t\t}\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_MONOPOLY] >= 1) {\n\t\t\tlistMonopolyPossibilities(options);\n\t\t}\n\t\tif ((state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_FREEROAD] >= 1)\n\t\t\t\t&& (state[OFS_PLAYERDATA[pl] + OFS_NROADS] < 15)) {\n\t\t\t// need to check if the player can place roads first\n\t\t\tArrayList<int[]> roadOpt = new ArrayList<int[]>();\n\t\t\tlistRoadPossibilities(roadOpt);\n\t\t\tif (roadOpt.size() > 0)\n\t\t\t\toptions.add(Actions.newAction(A_PLAYCARD_FREEROAD));\n\t\t}\n\t\tif (state[OFS_PLAYERDATA[pl] + OFS_OLDCARDS + CARD_KNIGHT] >= 1) {\n\t\t\tlistRobberPossibilities(options, A_PLAYCARD_KNIGHT);\n\t\t}\n\t}\n\t\n\tprivate void listMonopolyPossibilities(ArrayList<int[]> options){\n\t\tfor (int i = 0; i < NRESOURCES; i++)\n\t\t\toptions.add(Actions.newAction(A_PLAYCARD_MONOPOLY, i, -1,-1,-1,-1));\n\t}\n\t\n\tprivate void listMonopolyTotals(ArrayList<int[]> options){\n int fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n int choice\t\t= state[OFS_MONO_RSS_CHOICE];\n \n\t\tint[] action = Actions.newAction(A_CHOOSE_MONO_TOTALS);\n\t\t//include the effects such as what was lost or gained depending on the player number\n\t\tint total = 0;\n\t\tfor (int ind = 0; ind<NPLAYERS; ind++){\n\t\t\tif(ind == pl)\n\t\t\t\tcontinue;\n\t\t\ttotal += state[OFS_PLAYERDATA[ind] + OFS_RESOURCES + choice];\n action[1 + ind] = state[OFS_PLAYERDATA[ind] + OFS_RESOURCES + choice]; \n }\n\t\taction[1 + pl] = total;\n\t\toptions.add(action);\n\t}\n\t\n\tprivate void listFreeResourcePossibilities(ArrayList<int[]> options){\n\t\tfor (int i = 0; i < NRESOURCES; i++)\n\t\t\tfor (int j = i; j < NRESOURCES; j++)\n\t\t\t\toptions.add(Actions.newAction(A_PLAYCARD_FREERESOURCE, i, j));\n\t}\n\t\n private void listTradePossibilities(ArrayList<int[]> options, boolean sample){\n int fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n int pl2, action, j, i;\n \n if(sample){//if sampling, pick a random legal exchange that can be 1:1, 2:1, 1:2 (the same or conjunctive for the latter two)\n \tint[] playersWithResources = new int[NPLAYERS];\n \t\tfor (i = 0; i < NPLAYERS; i++) {\n \t\t\tfor (j = 0; j < NRESOURCES; j++)\n \t\t\t\tplayersWithResources[i] += state[OFS_PLAYERDATA[i] + OFS_RESOURCES + j];\n \t\t\t\t\n \t\t}\n \t\t//does the current player have any rss?\n \t\tif(playersWithResources[pl] == 0)\n \t\t\treturn;\n \t\t//are there any other players with rss\n \t\tArrayList<Integer> oppWithRss = new ArrayList<>();\n \t\tfor (i = 0; i < NPLAYERS; i++) {\n \t\t\tif(i==pl)\n \t\t\t\tcontinue;\n \t\t\tif(playersWithResources[i] > 0)\n \t\t\t\toppWithRss.add(i);\n \t\t}\n \t\tif(oppWithRss.size() == 0)\n \t\t\treturn;\n \t\t//choose an opponent at random that is not us and has resources in their hand\n \t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n \t\tpl2 = oppWithRss.get(rnd.nextInt(oppWithRss.size()));\n \t\n \t\t//options are 0 is 1:1; 1 is 1:2; 2 is 2:1\n \t\tArrayList<Integer> quantityOptions = new ArrayList<>();\n \t\tquantityOptions.add(0);//1:1 is always true\n \t\tif(playersWithResources[pl2] >= 2)\n \t\t\tquantityOptions.add(1);\n \t\tif(playersWithResources[pl] >= 2)\n \t\t\tquantityOptions.add(2);\n \t\t\n \t\tint typeOfTrade = quantityOptions.get(rnd.nextInt(quantityOptions.size()));\n \t\tint giveable;\n \t\tint receiveable;\n \t\tint[] rss;\n \t\tswitch (typeOfTrade) {\n\t\t\tcase 0:\n\t \tgiveable = selectRandomResourceInHand(pl);\n\t \treceiveable = selectRandomResourceInHand(pl2);\n\t \toptions.add(Actions.newAction(A_TRADE, pl, pl2, 1, giveable, -1, -1, 1, receiveable, -1, -1));\n\t\t\t\tbreak;\n\t\t\tcase 1://pl2 gives 2 rss\n\t \tgiveable = selectRandomResourceInHand(pl);\n\t \trss = select2RandomResourcesInHand(pl2);\n\t \tif(rss[0] == rss[1]){\n\t \t\toptions.add(Actions.newAction(A_TRADE, pl, pl2, 1, giveable, -1, -1, 2, rss[0], -1, -1));\n\t \t}else{\n\t \t\toptions.add(Actions.newAction(A_TRADE, pl, pl2, 1, giveable, -1, -1, 1, rss[0], 1, rss[1]));\n\t \t}\n\t\t\t\tbreak;\n\t\t\tcase 2://current pl gives 2 rss\n\t\t\t\trss = select2RandomResourcesInHand(pl);\n\t \treceiveable = selectRandomResourceInHand(pl2);\n\t \tif(rss[0] == rss[1]){\n\t \t\toptions.add(Actions.newAction(A_TRADE, pl, pl2, 2, rss[0], -1, -1, 1, receiveable, -1, -1));\n\t \t}else{\n\t \t\toptions.add(Actions.newAction(A_TRADE, pl, pl2, 1, rss[0], 1, rss[1], 1, receiveable, -1, -1));\n\t \t}\n\t\t\t\tbreak;\n\t\t\t}\n }else{\n\t if(config.NEGOTIATIONS){\n\t \taction = A_OFFER;\n\t }else{\n\t \taction = A_TRADE;\n\t }\n\t \n\t for(int[] trade : Trades.legalTrades){\n\t \t//do we have the resources\n\t \tif(trade[0] <= state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+trade[1]] && trade[2] <= state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+trade[3]]){\n\t \t\t//for each opponent\n\t \t\tfor(pl2 = 0; pl2 < NPLAYERS; pl2++){\n\t \t\t\tif(pl2==pl) continue;\n\t \t\t\tif(trade[4] <= state[OFS_PLAYERDATA[pl2]+OFS_RESOURCES+trade[5]] && trade[6] <= state[OFS_PLAYERDATA[pl2]+OFS_RESOURCES+trade[7]]){\n\t \t\t\t\toptions.add(Actions.newAction(action, pl, pl2, trade[0], trade[1], trade[2], trade[3], trade[4], trade[5], trade[6], trade[7]));\n\t \t\t\t\t// order: initiator, recipient, (number of res given, type of rss given) x2, (number of rss received, type of rss received) x2\n\t \t\t\t}\n\t \t\t}\n\t \t}\n\t }\n }\n }\n\t\n private void listTradeResponsePossiblities(ArrayList<int[]> options){\n int fsmlevel = state[OFS_FSMLEVEL];\n int pl = state[OFS_FSMPLAYER+fsmlevel];\n \n \t//due to sampling from belief, accept may not be possible now because either the player that made the offer or the current player doesn't have the rss\n if(state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 8]] >= state[OFS_CURRENT_OFFER + 7] && \n \t\tstate[OFS_PLAYERDATA[pl] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 10]] >= state[OFS_CURRENT_OFFER + 9] &&\n \t\tstate[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES + state[OFS_CURRENT_OFFER + 4]] >= state[OFS_CURRENT_OFFER + 3] &&\n \t\tstate[OFS_PLAYERDATA[state[OFS_CURRENT_OFFER + 1]] + OFS_RESOURCES +state[OFS_CURRENT_OFFER + 6]] >= state[OFS_CURRENT_OFFER + 5]) {\n \toptions.add(Actions.newAction(A_ACCEPT));\n }\n options.add(Actions.newAction(A_REJECT));\n if(config.ALLOW_COUNTEROFFERS){\n int pl2 = state[OFS_CURRENT_OFFER + 1];\n for(int[] trade : Trades.legalTrades){\n \t//do we have the resources\n \tif(trade[0] <= state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+trade[1]] && trade[2] <= state[OFS_PLAYERDATA[pl]+OFS_RESOURCES+trade[3]]){\n \t\t//only to the initiator of the current offer\n \t\t\tif(trade[4] <= state[OFS_PLAYERDATA[pl2]+OFS_RESOURCES+trade[5]] && trade[6] <= state[OFS_PLAYERDATA[pl2]+OFS_RESOURCES+trade[7]]){\n \t\t\t\toptions.add(Actions.newAction(A_OFFER, pl, pl2, trade[0], trade[1], trade[2], trade[3], trade[4], trade[5], trade[6], trade[7]));\n \t\t\t\t// order: initiator, recipient, (number of res given, type of rss given) x2, (number of rss received, type of rss received) x2\n \t\t\t}\n \t}\n }\n }\n }\n \n\t// other utility methods //\n \n\tprivate int selectRandomResourceFromSet(int[] rss) {\n\t\tint i;\n\t\tdouble ind;\n\t\tdouble ncards = 0;\n\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n\t\tfor (i = 0; i < NRESOURCES; i++)\n\t\t\tncards += rss[i];\n\t\tif (ncards <= 0) {\n\t\t\tSystem.err.println(\"Player has \" + ncards + \" cards\");\n\t\t\treturn -1;\n\t\t}\n\t\tind = rnd.nextDouble(ncards);\n\t\tfor (i = 0; i < NRESOURCES; i++) {\n\t\t\tind -= rss[i];\n\t\t\tif (ind <= 0.0d)\n\t\t\t\treturn i;\n\t\t}\n\t\treturn Math.min(i, NRESOURCES - 1);\n\t}\n \n\tprivate int selectRandomResourceInHand(int pl) {\n\t\tint i, ind, j;\n\t\tint ncards = 0;\n\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n\t\tfor (i = 0; i < NRESOURCES; i++)\n\t\t\tncards += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\tif (ncards <= 0) {\n\t\t\tSystem.err.println(\"Player \" + pl + \" has \" + ncards + \" cards\");\n\t\t\treturn -1;\n\t\t}\n\t\tind = rnd.nextInt(ncards) + 1;\n\t\tj = 0;\n\t\tfor (i = 0; i < NRESOURCES; i++) {\n\t\t\tj += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\tif (j >= ind)\n\t\t\t\tbreak;\n\t\t}\n\t\treturn Math.min(i, NRESOURCES - 1);\n\t}\n\t\n\t/**\n\t * It may select the same type of rss if the player has multiple.\n\t * NOTE: it doesn't check if this is possible. This should have been done before!\n\t * @param pl\n\t * @return an array with 2 rss or null if smth went wrong so an exception will be thrown later\n\t */\n\tprivate int[] select2RandomResourcesInHand(int pl) {\n\t\tint[] rss = new int[2];\n\t\tint i, ind, j;\n\t\tint ncards = 0;\n\t\tThreadLocalRandom rnd = ThreadLocalRandom.current();\n\t\tfor (i = 0; i < NRESOURCES; i++)\n\t\t\tncards += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\tif (ncards <= 0) {\n\t\t\tSystem.err.println(\"Player \" + pl + \" has \" + ncards + \" cards\");\n\t\t\treturn null;\n\t\t}\n\t\tind = rnd.nextInt(ncards) + 1;\n\t\tj = 0;\n\t\tfor (i = 0; i < NRESOURCES; i++) {\n\t\t\tj += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\tif (j >= ind)\n\t\t\t\tbreak;\n\t\t}\n\t\trss[0] = i;//first rss;\n\t\tif (ncards < 2)\n\t\t\treturn null;\n\t\t//make sure not to select the same rss\n\t\tint prevInd = ind;\n\t\tboolean ok = false;\n\t\twhile(!ok){\n\t\t\tind = rnd.nextInt(ncards) + 1;\n\t\t\tif(ind != prevInd)\n\t\t\t\tok = true;\n\t\t}\n\t\t//find the type\n\t\tj = 0;\n\t\tfor (i = 0; i < NRESOURCES; i++) {\n\t\t\tj += state[OFS_PLAYERDATA[pl] + OFS_RESOURCES + i];\n\t\t\tif (j >= ind)\n\t\t\t\tbreak;\n\t\t}\n\t\trss[1] = i;//second rss;\n\t\t\n\t\treturn rss;\n\t}\n\t\n\t\n\tprivate static final int LR_EMPTY = 0;\n\tprivate static final int LR_UNCHECKED = 1;\n\tprivate static final int LR_CHECKED1 = 2;\n\tprivate static final int LR_CHECKED2 = 3;\n\tprivate static final int LR_CHECKED3 = 4;\n\tprivate static final int LR_MAXROUTE = 5;\n\n\tprivate boolean isOpponentPresentAtVertex(int[] s, int pl, int ind) {\n\t\tboolean returnval;\n\t\tint val = s[OFS_VERTICES + ind];\n\t\tif ((val == VERTEX_EMPTY) || (val == VERTEX_TOOCLOSE) || (val == VERTEX_HASSETTLEMENT + pl)\n\t\t\t\t|| (val == VERTEX_HASCITY + pl))\n\t\t\treturnval = false;\n\t\telse\n\t\t\treturnval = true;\n\t\tfor (int j = 0; j < 6; j++) {\n\t\t\tval = board.neighborVertexEdge[ind][j];\n\t\t\tif ((val != -1) && (s[OFS_EDGES + val] != EDGE_EMPTY)) // opponent\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// has road\n\t\t\t\treturnval = true;\n\t\t}\n\t\treturn returnval;\n\t}\n\n\tprivate void lrDepthFirstSearch(int[] s, int pl, int ind, int[] lrVertices, boolean[] lrOpponentPresent,\n\t\t\tboolean[] lrPlayerPresent, int UNCHECKEDVALUE, int CHECKEDVALUE, int[] returnvalues) {\n\t\tint cind, cpos, i, j;\n\t\tint[] lrStack = new int[N_VERTICES];\n\t\tint[] lrStackPos = new int[N_VERTICES];\n\t\tint lrStacklen;\n\t\tboolean foundnext, isstartind;\n\t\tint maxlen = 0, maxStartInd = 0;\n\t\tint nextind, nextedge;\n\n\t\tnextind = 0; // unnecessary, but otherwise \"uninitialized\" error\n\n\t\tlrStacklen = 0;\n\t\tcind = ind;\n\t\tcpos = 0;\n\t\tisstartind = true;\n\t\t// lrStack[0] = ind;\n\t\tdo {\n\t\t\t// System.out.printf(\"(%d,%d,%d) \",cind,cpos,lrStacklen);\n\t\t\tfoundnext = false;\n\t\t\t// System.out.printf(\"*\");\n\t\t\tisstartind = false;\n\t\t\tlrVertices[cind] = CHECKEDVALUE;\n\t\t\tboard.vertices[cind].debugLRstatus = CHECKEDVALUE;\n\t\t\t// TODO: if search starts in a \"broken\" vertex, the algorithm\n\t\t\t// believes that it is connected\n\t\t\tif ((cind == ind) || (lrPlayerPresent[cind]) || (!lrOpponentPresent[cind])) {\n\t\t\t\tfor (j = cpos; j < 6; j++) {\n\t\t\t\t\t// System.out.printf(\".\");\n\t\t\t\t\tnextind = board.neighborVertexVertex[cind][j];\n\t\t\t\t\tnextedge = board.neighborVertexEdge[cind][j];\n\t\t\t\t\tif (nextind == -1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (s[OFS_EDGES + nextedge] != EDGE_OCCUPIED + pl)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (lrVertices[nextind] != UNCHECKEDVALUE)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfoundnext = true;\n\t\t\t\t\tlrStack[lrStacklen] = cind;\n\t\t\t\t\tlrStackPos[lrStacklen] = j + 1;\n\t\t\t\t\tlrStacklen++;\n\t\t\t\t\tif (lrStacklen > maxlen) {\n\t\t\t\t\t\tmaxlen = lrStacklen;\n\t\t\t\t\t\tmaxStartInd = nextind;\n\t\t\t\t\t}\n\t\t\t\t\tif ((CHECKEDVALUE == LR_CHECKED3) && (maxlen == returnvalues[0])) {\n\t\t\t\t\t\tfor (i = 0; i < lrStacklen; i++) {\n\t\t\t\t\t\t\tboard.vertices[lrStack[i]].debugLRstatus = CHECKEDVALUE;\n\t\t\t\t\t\t\t// TODO: implement this correctly\n\t\t\t\t\t\t\t// edges[neighborVertexEdge[lrStack[i]][lrStackPos[i]-1]].isPartOfLongestRoad\n\t\t\t\t\t\t\t// = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tboard.vertices[nextind].debugLRstatus = CHECKEDVALUE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (foundnext) {\n\t\t\t\tcind = nextind;\n\t\t\t\tcpos = 0;\n\t\t\t} else {\n\t\t\t\tif (lrStacklen == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tlrStacklen--;\n\t\t\t\tcind = lrStack[lrStacklen];\n\t\t\t\tcpos = lrStackPos[lrStacklen];\n\t\t\t}\n\t\t\t// System.out.printf(\"x\");\n\t\t} while (lrStacklen >= 0);\n\t\treturnvalues[0] = maxlen;\n\t\treturnvalues[1] = maxStartInd;\n\n\t\tlrStack = null;\n\t\tlrStackPos = null;\n\t}\n\n\tprivate void recalcLongestRoad(int[] s, int pl) {\n\t\tint ind, cind, cpos, j, k;\n\t\tint[] lrVertices = new int[N_VERTICES];\n\t\tboolean[] lrOpponentPresent = new boolean[N_VERTICES];\n\t\tboolean[] lrPlayerPresent = new boolean[N_VERTICES];\n\t\tint[] returnvalues = new int[2];\n\t\tint maxlen, maxStartInd = 0;\n\t\tint val;\n\t\t// int pl;\n\n\t\tfor (ind = 0; ind < N_VERTICES; ind++)\n\t\t\tboard.vertices[ind].debugLRstatus = 0;\n\t\tfor (ind = 0; ind < N_EDGES; ind++)\n\t\t\tboard.edges[ind].isPartOfLongestRoad = false;\n\t\t// for (pl = 0; pl < NPLAYERS; pl++)\n\t\t{\n\t\t\tfor (ind = 0; ind < N_VERTICES; ind++) {\n\t\t\t\t// System.out.printf(\"/%d/\",ind);\n\n\t\t\t\tlrVertices[ind] = LR_EMPTY;\n\t\t\t\tlrOpponentPresent[ind] = false;\n\t\t\t\tval = s[OFS_VERTICES + ind];\n\t\t\t\tif ((val == VERTEX_EMPTY) || (val == VERTEX_TOOCLOSE))\n\t\t\t\t\t;\n\t\t\t\telse if ((val == VERTEX_HASSETTLEMENT + pl) || (val == VERTEX_HASCITY + pl))\n\t\t\t\t\tlrPlayerPresent[ind] = true;\n\t\t\t\telse\n\t\t\t\t\tlrOpponentPresent[ind] = true;\n\t\t\t\tfor (j = 0; j < 6; j++) {\n\t\t\t\t\tval = board.neighborVertexEdge[ind][j];\n\t\t\t\t\tif ((val != -1) && (s[OFS_EDGES + val] == EDGE_OCCUPIED + pl)) // player has road\n\t\t\t\t\t\tlrVertices[ind] = LR_UNCHECKED;\n\t\t\t\t\t// else if ((val!=-1) && (s[OFS_EDGES+val] != EDGE_EMPTY))\n\t\t\t\t\t// //opponent has road\n\t\t\t\t\t// lrOpponentPresent[ind] = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// TODO!!! 6-length cycles counts only as a 5 !!!\n\t\t\tmaxlen = 0;\n\t\t\tfor (ind = 0; ind < N_VERTICES; ind++) {\n\t\t\t\tif (lrVertices[ind] != LR_UNCHECKED)\n\t\t\t\t\tcontinue;\n\t\t\t\tlrDepthFirstSearch(s, pl, ind, lrVertices, lrOpponentPresent, lrPlayerPresent, LR_UNCHECKED,\n\t\t\t\t\t\tLR_CHECKED1, returnvalues);\n\t\t\t\tlrDepthFirstSearch(s, pl, returnvalues[1], lrVertices, lrOpponentPresent, lrPlayerPresent, LR_CHECKED1,\n\t\t\t\t\t\tLR_CHECKED2, returnvalues);\n\t\t\t\tif (maxlen < returnvalues[0]) {\n\t\t\t\t\tmaxlen = returnvalues[0];\n\t\t\t\t\tmaxStartInd = returnvalues[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\t// if (maxlen>0)\n\t\t\t// vertices[maxStartInd].isPartOfLongestRoad = LR_MAXROUTE;\n\t\t\t// maxlen = returnvalues[0];\n\n\t\t\t// the purpose of this call to DFS is to mark the longest road.\n\t\t\tlrDepthFirstSearch(s, pl, maxStartInd, lrVertices, lrOpponentPresent, lrPlayerPresent, LR_CHECKED2,\n\t\t\t\t\tLR_CHECKED3, returnvalues);\n\t\t\ts[OFS_PLAYERDATA[pl] + OFS_PLAYERSLONGESTROAD] = maxlen;\n\t\t}\n\n\t\tint maxpl = s[OFS_LONGESTROAD_AT]; // current player with longest road;\n\t\tif (maxpl != -1)\n\t\t\tmaxlen = s[OFS_PLAYERDATA[maxpl] + OFS_PLAYERSLONGESTROAD];\n\t\telse\n\t\t\tmaxlen = 0;\n\t\tfor (pl = 0; pl < NPLAYERS; pl++) {\n\t\t\tif (s[OFS_PLAYERDATA[pl] + OFS_PLAYERSLONGESTROAD] > maxlen) {\n\t\t\t\tmaxlen = s[OFS_PLAYERDATA[pl] + OFS_PLAYERSLONGESTROAD];\n\t\t\t\tmaxpl = pl;\n\t\t\t}\n\t\t}\n\t\tif (maxlen >= 5) {\n\t\t\ts[OFS_LONGESTROAD_AT] = maxpl;\n\t\t}\n\t\tlrVertices = null;\n\t\tlrOpponentPresent = null;\n\t\tlrPlayerPresent = null;\n\t\treturnvalues = null;\n\t}\n\n\tprivate void recalcLargestArmy() {\n\t\tint pl;\n\t\tint largestpl = state[OFS_LARGESTARMY_AT];\n\t\tint current;\n\n\t\tfor (pl = 0; pl < NPLAYERS; pl++) {\n\t\t\tcurrent = state[OFS_PLAYERDATA[pl] + OFS_USEDCARDS + CARD_KNIGHT];\n\t\t\tif ((largestpl == -1) && (current >= 3))\n\t\t\t\tstate[OFS_LARGESTARMY_AT] = pl;\n\t\t\tif ((largestpl != -1) && (current > state[OFS_PLAYERDATA[largestpl] + OFS_USEDCARDS + CARD_KNIGHT]))\n\t\t\t\tstate[OFS_LARGESTARMY_AT] = pl;\n\t\t}\n\t}\n\t\n\t/**\n\t * @param array\n\t */\n\tprivate void shuffleArray(int[] array) {\n\t\tint index, temp;\n\t\tRandom random = new Random();\n\t\tfor (int i = array.length - 1; i > 0; i--) {\n\t\t\tindex = random.nextInt(i + 1);\n\t\t\ttemp = array[index];\n\t\t\tarray[index] = array[i];\n\t\t\tarray[i] = temp;\n\t\t}\n\t}\n\t\n\t//display utilities\n\tpublic static void setBoardSize(int screenWidth, int screenHeight, double scale) {\n\t\tboard.screenWidth = screenWidth;\n\t\tboard.screenHeight = screenHeight;\n\t\t// scale = Math.min(screenHeight / 8.0, screenWidth / 8.0);\n\t\tboard.scale = scale;\n\t}\n\t\n\tpublic void gameTick(){\n\t\tint[] action = sampleNextAction();\n\t\tperformAction(action, true);\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tTimer t = new Timer();\n\t\tlong d = 0;\n\t\tdouble b = 0;\n\t\tint nGames = 10000;\n\t\tfor(int i =0; i < nGames; i++) {\n\t\t\tboard.InitBoard();// a new board every game to test more scenarios, but in this case the timing may be misleading\n\t\t\tCatanConfig config = new CatanConfig();\n\t\t\tCatan game = new Catan(config);\n\t\t\twhile(!game.isTerminal()) {\n\t\t\t\tgame.gameTick();\n\t\t\t}\n\t\t\td += depth;\n\t\t\tb += (double)breadth/depth;\n\t\t\tbreadth = 0;\n\t\t\tdepth = 0;\n\t\t\tif(game.getWinner() == -1)\n\t\t\t\tSystem.err.println(\"winner not recorded correctly\");\n\t\t\tif(i % 10000 == 0)\n\t\t\t\tSystem.out.println();\n\t\t\tif(i % 100 == 0)\n\t\t\t\tSystem.out.print(\".\");\n\t\t}\n\t\tSystem.out.println(t.elapsed());\n\t\tSystem.out.println(\"Done\");\n\t\tSystem.out.println(\"Done\");\n\t\tSystem.out.println(\"Depth: \" + (double)d/nGames);\n\t\tSystem.out.println(\"branch: \" + (double)b/nGames);\n\t}\n\n}", "public class CatanConfig extends GameConfig{\n\t//default values//\n\t/** Handle resource exchanges between players */\n\tpublic boolean TRADES = true;\n /** Allow full negotiations in the tree, i.e. offer, reject, accept */\n public boolean NEGOTIATIONS = true;\n /** Allow counter-offers in the tree */\n public boolean ALLOW_COUNTEROFFERS = false;\n /** The maximum number of resources to list the discard options for. Anything above this we will never run enough rollouts to even evaluate. */\n public int N_MAX_DISCARD = 8;\n /** Maximum number of resources in the victim's hand for which we consider all possible outcomes. Anything above this the system becomes slow, and also we will never run enough rollouts to consider all possible outcome states. */\n public int N_MAX_RSS_STEAL = 15;\n /** Should make the discard action observable in the rollouts? */\n public boolean OBS_DISCARDS_IN_ROLLOUTS = false;\n\t/** Sample uniformly over the action types before sampling specifics in rollouts */\n public boolean SAMPLE_FROM_DISTRIBUTION_OVER_TYPES_IN_ROLLOUTS = true;\n /** Maximum number of offers per turn, i.e. the total number of offers made*/\n public int OFFERS_LIMIT = Integer.MAX_VALUE;\n /** If an even dist over types is not used, is sampling of a single trade option allowed? This is the option in between the two extremes. TODO: this should be removed as there is no benefit to it */\n public boolean ALLOW_SAMPLING_IN_NORMAL_STATE = false;\n /** Use the abstract belief representation to enumerate the possible actions TODO: fix it!!! this breaks the current version of MCTS as we may end up executing illegal actions! */\n public boolean ABSTRACT_BELIEF = false;\n /** Make all new belief chance events sample from a uniform distribution to speed up the belief game model.*/\n public boolean UNIFORM_BELIEF_CHANCE_EVENTS = false;\n /** Special option to list the partially-observable actions of the opponents when the game is not fully-observable. It is needed if either the algorithm is POMCP or we want to make the POMs' effects observable.*/\n public boolean LIST_POMS = false;\n /** Special option that makes the POM effects observable. It allows planning in the game starting from a belief and in time this game may become fully-observable. */\n public boolean OBSERVABLE_POM_EFFECTS = false;\n\t/** Makes all actions equally likely to be legal and it also ignores the type distribution if there is any during belief rollouts. */\n public boolean ENFORCE_UNIFORM_TYPE_DIST_IN_BELIEF_ROLLOUTS = false;\n /** What distribution over action types should be used in rollouts.*/\n public ActionTypePdf rolloutTypeDist = new UniformActionTypePdf();\n /** Drawing a vp card becomes an observable move*/\n public boolean OBSERVABLE_VPS = false;\n \n public CatanConfig() {\n \tid = GameFactory.CATAN;\n\t}\n \n @Override\n protected CatanConfig copy() {\n \tCatanConfig newConfig = new CatanConfig();\n \tnewConfig.TRADES = this.TRADES;\n \tnewConfig.NEGOTIATIONS = this.NEGOTIATIONS;\n \tnewConfig.ALLOW_COUNTEROFFERS = this.ALLOW_COUNTEROFFERS;\n \tnewConfig.N_MAX_DISCARD = this.N_MAX_DISCARD;\n \tnewConfig.N_MAX_RSS_STEAL = this.N_MAX_RSS_STEAL;\n \tnewConfig.OBS_DISCARDS_IN_ROLLOUTS = this.OBS_DISCARDS_IN_ROLLOUTS;\n \tnewConfig.SAMPLE_FROM_DISTRIBUTION_OVER_TYPES_IN_ROLLOUTS = this.SAMPLE_FROM_DISTRIBUTION_OVER_TYPES_IN_ROLLOUTS;\n \tnewConfig.OFFERS_LIMIT = this.OFFERS_LIMIT;\n \tnewConfig.ALLOW_SAMPLING_IN_NORMAL_STATE = this.ALLOW_SAMPLING_IN_NORMAL_STATE;\n \tnewConfig.ABSTRACT_BELIEF = this.ABSTRACT_BELIEF;\n \tnewConfig.UNIFORM_BELIEF_CHANCE_EVENTS = this.UNIFORM_BELIEF_CHANCE_EVENTS;\n \tnewConfig.LIST_POMS = this.LIST_POMS;\n \tnewConfig.OBSERVABLE_POM_EFFECTS = this.OBSERVABLE_POM_EFFECTS;\n \tnewConfig.ENFORCE_UNIFORM_TYPE_DIST_IN_BELIEF_ROLLOUTS = this.ENFORCE_UNIFORM_TYPE_DIST_IN_BELIEF_ROLLOUTS;\n \tnewConfig.rolloutTypeDist = this.rolloutTypeDist;\n \tnewConfig.OBSERVABLE_VPS = this.OBSERVABLE_VPS;\n \treturn newConfig;\n }\n\t\n public void selfCheck(MCTSConfig config){\n \tif(ABSTRACT_BELIEF) {\n \t\tSystem.err.println(\"WARNING: listing and performing actions using the abstract representation is not stable in the current MCTS implementation\");\n \t}\n \tif(OBSERVABLE_POM_EFFECTS && !LIST_POMS) {\n \t\tSystem.err.println(\"WARNING: OBSERVABLE_POM_EFFECTS doesn't have any effect without LIST_POMS. Adding LIST_POMS\");\n \t\tLIST_POMS = true;\n \t}\n \tif(config.pomcp) {\n \t\tif(!LIST_POMS) {\n\t \t\tSystem.err.println(\"WARNING: POMCP needs the partially-observable moves to be listed. Adding LIST_POMS to game configuration\");\n\t \t\tLIST_POMS = true;\n \t\t}\n \t\tif(OBS_DISCARDS_IN_ROLLOUTS) {\n \t\t\tSystem.err.println(\"WARNING: POMCP already performs observable rollouts. Removing OBS_DISCARDS_IN_ROLLOUTS from game configuration\");\n \t\t\tOBS_DISCARDS_IN_ROLLOUTS = false;\n \t\t}\n \t}\n }\n \n}", "public interface GameStateConstants extends HexTypeConstants {\n\n int NPLAYERS = 4;\n \n int N_VERTICES = 54;\n int N_HEXES = 19;\n int N_EDGES = 72;\n int N_DEVCARDTYPES = 5;\n\n /**\n * The trade action contains 11 parts. All other action descriptions are smaller.\n */\n int ACTIONSIZE = 11;\n \n //board description\n int OFS_STARTING_PLAYER = 0;//the first player to place the first free settlement\n /** The player that \"controls\" the simulations, or the player whose belief we are tracking. This implementation is from only one perspective. */\n int OFS_OUR_PLAYER\t= OFS_STARTING_PLAYER \t+1;\n /**the first player to discard, such that it will be consistent with the JSettlers agent using the MCTS implementation**/\n int OFS_DISCARD_FIRST_PL\t= OFS_OUR_PLAYER \t+1;\n int OFS_NATURE_MOVE\t\t\t= OFS_DISCARD_FIRST_PL \t+1;\n int OFS_TURN = OFS_NATURE_MOVE \t\t+1;\n int OFS_FSMLEVEL = OFS_TURN \t\t+1;\n int OFS_FSMSTATE = OFS_FSMLEVEL \t+1;\n int OFS_FSMPLAYER = OFS_FSMSTATE \t+3;\n int OFS_NCARDSGONE = OFS_FSMPLAYER \t+3;\n int OFS_DICE \t\t= OFS_NCARDSGONE \t+1;\n int OFS_ROBBERPLACE = OFS_DICE \t\t+1;\n int OFS_LONGESTROAD_AT = OFS_ROBBERPLACE \t+1;\n int OFS_LARGESTARMY_AT = OFS_LONGESTROAD_AT \t+1;\n int OFS_LASTVERTEX = OFS_LARGESTARMY_AT \t+1;\n int OFS_VICTIM\t\t\t\t= OFS_LASTVERTEX \t+1;\n int OFS_MONO_RSS_CHOICE\t\t= OFS_VICTIM\t\t\t+1;\n int OFS_DEVCARDS_LEFT\t\t= OFS_MONO_RSS_CHOICE\t+1;\n int OFS_CURRENT_OFFER\t\t= OFS_DEVCARDS_LEFT \t+ N_DEVCARDTYPES;\n int OFS_NUMBER_OF_OFFERS = OFS_CURRENT_OFFER \t+ ACTIONSIZE;\n int OFS_EDGES = OFS_NUMBER_OF_OFFERS \t+1;\n int OFS_VERTICES = OFS_EDGES \t+ N_EDGES;\n \n //player information\n int OFS_SCORE = 0;\n int OFS_NSETTLEMENTS = OFS_SCORE\t\t\t\t+1;\n int OFS_NCITIES = OFS_NSETTLEMENTS\t\t+1;\n int OFS_NROADS = OFS_NCITIES\t\t\t+1;\n int OFS_PLAYERSLONGESTROAD = OFS_NROADS\t\t\t+1;\n int OFS_HASPLAYEDCARD = OFS_PLAYERSLONGESTROAD+1;\n int OFS_RESOURCES = OFS_HASPLAYEDCARD \t+1;\n int OFS_ACCESSTOPORT = OFS_RESOURCES \t+(NRESOURCES+1);\n int OFS_USEDCARDS = OFS_ACCESSTOPORT \t+(NRESOURCES+1);\n int OFS_OLDCARDS = OFS_USEDCARDS \t+N_DEVCARDTYPES;\n int OFS_NEWCARDS = OFS_OLDCARDS \t+N_DEVCARDTYPES + 1; //the last index is the total\n int PLAYERSTATESIZE\t\t\t= OFS_NEWCARDS \t+N_DEVCARDTYPES + 1; //the last index is the total\n \n int[] OFS_PLAYERDATA = { OFS_VERTICES+N_VERTICES,\n OFS_VERTICES+N_VERTICES + PLAYERSTATESIZE,\n OFS_VERTICES+N_VERTICES + 2*PLAYERSTATESIZE,\n OFS_VERTICES+N_VERTICES + 3*PLAYERSTATESIZE}; \n int STATESIZE = OFS_VERTICES+N_VERTICES + 4*PLAYERSTATESIZE;\n \n int S_GAME = 0;\n int S_START = 1;//the root node\n int S_SETTLEMENT1 = 2;\n int S_ROAD1 = 3;\n int S_SETTLEMENT2 = 4;\n int S_ROAD2 = 5;\n int S_BEFOREDICE = 6;\n int S_NORMAL = 7;\n int S_BUYCARD = 8;//nature choice of dealing the bought devcard\n int S_PAYTAX = 9;\n int S_FREEROAD1 = 10;\n int S_FREEROAD2 = 11;\n int S_ROBBERAT7 = 12;\n int S_NEGOTIATIONS\t\t\t= 13;\n int S_STEALING \t\t\t\t= 14;//nature choice of stealing resource after move robber or play knight\n int S_DICE_RESULT \t\t\t= 15;//nature choice of dice result\n int S_WIN_POSSIBILITY\t\t= 16;//nature choice if this player can win\n int S_MONOPOLY_EFFECT\t\t= 17;//nature choice for totals in case we are planning in the belief space\n int S_FINISHED = 100;\n \n// int A_NOTHING = 0; //there is always a legal option and nothing isn't one\n int A_BUILDSETTLEMENT = 1;\n int A_BUILDROAD = 2;\n int A_BUILDCITY = 3;\n int A_THROWDICE = 4;\n int A_ENDTURN = 5;\n int A_PORTTRADE = 6;\n int A_BUYCARD = 7;\n int A_PLAYCARD_KNIGHT = 8;\n int A_PLAYCARD_FREEROAD = 9;\n int A_PLAYCARD_FREERESOURCE = 10;\n int A_PLAYCARD_MONOPOLY = 11;\n// int A_PAYTAX_RANDOM = 12;//randomly sample from the options (uniform sampling)\n int A_PAYTAX \t\t\t\t= 13;\n int A_PLACEROBBER = 14;\n //trade actions below, last one includes the negotiations as one action and just executes the trade\n int A_OFFER \t\t= 15;\n int A_REJECT\t\t\t\t= 16;\n int A_ACCEPT\t\t\t\t= 17;\n int A_TRADE\t\t\t\t\t= 18;\n //nature actions (where chances are involved)\n int A_CHOOSE_MONO_TOTALS\t= 19;//nature choosing total monopolised after a player chose a resource type\n int A_CHOOSE_RESOURCE \t\t= 20;//nature choosing stolen resource (either after knight or robber at 7)\n int A_DEAL_DEVCARD \t\t\t= 21;//nature choosing the development card bought based on the card sequence \n int A_CHOOSE_DICE \t\t\t= 22;//nature choosing the dice result based on chances\n int A_WIN_GAME \t\t\t\t= 23;//nature choosing the current player to win the game\n int A_CONTINUE_GAME\t\t\t= 24;//nature choosing that this player didn't win the game (i.e. it doesn't have vp development cards)\n \n int VERTEX_EMPTY = 0;\n int VERTEX_TOOCLOSE = 1;\n int VERTEX_HASSETTLEMENT = 2; //+player number\n int VERTEX_HASCITY = 6; //+player number\n \n int EDGE_EMPTY = 0;\n int EDGE_OCCUPIED = 1; //+player number\n \n \n int CARD_KNIGHT = 0;\n int CARD_ONEPOINT = 1;\n int CARD_FREEROAD = 2;\n int CARD_FREERESOURCE = 3;\n int CARD_MONOPOLY = 4;\n \n int NCARDTYPES = 5;\n int NCARDS = 25;\n \n String[] resourceNames = {\"sheep\", \"wood\", \"clay\", \"wheat\", \"stone\"};\n String[] cardNames = {\"knight\", \"+1 point\", \"+2 road\", \"+2 res.\", \"monopoly\"};\n \n public final static Color[] playerColor = \n {\n Color.BLUE,\n Color.RED,\n Color.WHITE,\n Color.ORANGE,\n };\n \n}", "@JsonTypeInfo(use = Id.CLASS,\ninclude = JsonTypeInfo.As.PROPERTY,\nproperty = \"type\")\n@JsonSubTypes({\n\t@Type(value = UniformActionTypePdf.class),\n\t@Type(value = HumanActionTypePdf.class),\n})\npublic abstract class ActionTypePdf implements GameStateConstants{\n\n\t/**\n\t * @return the distribution given a set of legal types\n\t */\n\tpublic abstract Map<Integer,Double> getDist(ArrayList<Integer> legalTypes);\n}", "public class UniformActionTypePdf extends ActionTypePdf{\n\n\tpublic UniformActionTypePdf() {}\n\t\n\t@Override\n\tpublic Map<Integer, Double> getDist(ArrayList<Integer> legalTypes) {\n\t\tMap<Integer, Double> dist = new HashMap<Integer, Double>();\n\t\tfor(Integer i : legalTypes)\n\t\t\tdist.put(i, 1.0/legalTypes.size());\n\t\treturn dist;\n\t}\n\n}", "@JsonTypeInfo(use = Id.CLASS,\ninclude = JsonTypeInfo.As.PROPERTY,\nproperty = \"type\")\n@JsonSubTypes({\n\t@Type(value = NullSeedTrigger.class),\n\t@Type(value = CatanTypePDFSeedTrigger.class)\n})\npublic abstract class SeedTrigger {\n\t@JsonIgnore\n\tprotected MCTS mcts;\n\t@JsonIgnore\n\tprotected HashSet<Seeder> aliveSeeders = new HashSet<>();\n\t@JsonIgnore\n\tprotected boolean initialised = false;\n\t/**\n\t * Max number of seeders alive at one point.\n\t */\n\tpublic int maxSeederCount = 2;\n\t\n\t/**\n\t * Add a new node to the queue, and possibly start the evaluation thread\n\t * @param node\n\t */\n\tpublic abstract void addNode(TreeNode node, GameFactory factory);\n\t\n\t/**\n\t * e.g. clears queue(s), resets counters etc\n\t */\n\tpublic abstract void cleanUp();\n\t\n\t/**\n\t * Give access to the thread pool executor in MCTS and initialise fields\n\t * @param mcts\n\t */\n\tpublic void init(MCTS mcts){\n\t\tthis.mcts = mcts;\n\t\tinitialised = true;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[name-\" + this.getClass().getName() + \"; maxSeederCount-\" + maxSeederCount + \"]\";\n\t}\n}", "public class StandardNode extends TreeNode{\n\t\n\tprivate ArrayList<Key> children;\n\t/**\n\t * The possible actions.\n\t */\n\tprivate ArrayList<int[]> actions;\n\t\n\t/**\n\t * The probabilities of actions to be legal.\n\t */\n\tprivate ArrayList<Double> actionProbs;\n\t\n\t//stats on actions required if afterstates are not used\n\tpublic int[] childVisits;\n\tpublic double[][] wins;\n\tpublic int[] vloss;\n\t\n\t/**\n\t * The P value (probability of selecting each action given a policy) of each\n\t * action in the same order as the children are set. At the moment this is\n\t * also used as value initialisation\n\t */\n\tpublic AtomicDoubleArray pValue;\n\t\n\tpublic StandardNode(int[] state, int[] belief, boolean terminal, int cpn) {\n\t\tsuper(state, belief, terminal, cpn);\n\t}\n\t\n\t/**\n\t * Adds the edges to the node.\n\t * @param children\n\t */\n\tpublic synchronized void addChildren(ArrayList<Key> children, ArrayList<int[]> acts, ArrayList<Double> actionProbs){\n\t\tif(!isLeaf())\n\t\t\treturn;\n\t\tthis.actions = acts;\n\t\tthis.children = children;\n\t\tthis.actionProbs = actionProbs;\n\t\t//initialise the pValue with a uniform distribution\n\t\tdouble[] dist = new double[children.size()];\n\t\tArrays.fill(dist, 1.0/children.size());\n\t\tpValue = new AtomicDoubleArray(dist);\n\t\t//stats on actions required only if afterstates are not used\n\t\tchildVisits = new int[children.size()];\n\t\twins = new double[GameFactory.nMaxPlayers()][];\n\t\tfor(int i = 0; i < GameFactory.nMaxPlayers(); i++){\n\t\t\twins[i] = new double[children.size()];\n\t\t}\n\t\tvloss = new int[children.size()];\n\t\tsetLeaf(false);\n\t}\n\t\n\tpublic ArrayList<Key> getChildren(){\n\t\treturn this.children;\n\t}\n\t\n\tpublic ArrayList<int[]> getActions(){\n\t\treturn this.actions;\n\t}\n\t\n\tpublic ArrayList<Double> getActionProbs(){\n\t\treturn this.actionProbs;\n\t}\n\t\n\tpublic boolean canExpand(){\n\t\treturn true;\n\t}\n\t\n\t/**\n\t * Used only if afterstates are not used, otherwise use the standard state update\n\t * @param reward\n\t * @param k\n\t * @param nRollouts\n\t */\n\tpublic synchronized void update(double[] reward, Key k, int nRollouts) {\n\t\tif(k != null)\n\t\tfor(int idx = 0; idx < children.size(); idx++){\n\t\t\tif(children.get(idx).equals(k)){\n\t\t\t\tfor(int i =0; i < wins.length; i++)\n\t\t\t\t\twins[i][idx]+=reward[i];\n\t\t\t\tvloss[idx] = 0;\n\t\t\t\tchildVisits[idx]+=nRollouts;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tnVisits+=nRollouts;\n\t}\n\t\n}", "public abstract class TreeNode {\n\n\tprivate final int[] state;\n\tprivate final int[] belief;\n\t\n\tint nVisits;\n double[] wins;\n\tint vLoss;\n\tprivate final int currentPlayer;\n\tprivate boolean leaf = true;\n\tprivate final boolean terminal;\n\t/**\n\t * Field required for ISMCTS way of computing parentVisits when this node was legal\n\t */\n\tprivate int parentVisits;\n\t\n\t/**\n\t * Flag set when an external evaluation metric is used for seeding.\n\t */\n\tprivate boolean evaluated = false;\n\t\n\tpublic TreeNode(int[] state, int[] belief, boolean terminal, int cpn) {\n\t this.state = state;\n\t this.belief = belief;\n\t\tthis.terminal = terminal;\n\t\tcurrentPlayer = cpn;\n\t\tvLoss = 0;\n\t\tnVisits = 0;\n\t\tparentVisits = 0;\n\t wins = new double[GameFactory.nMaxPlayers()]; //TODO: find a way to set this value depending on the current game\n\t}\n\t\n\tpublic int getCurrentPlayer(){\n\t\treturn currentPlayer;\n\t}\n\t\n\t/**\n\t * @return a clone of the state\n\t */\n\tpublic int[] getState(){\n\t\treturn state.clone();\n\t}\n\t\n\tpublic boolean isLeaf(){\n\t\treturn leaf;\n\t}\n\t\n\tpublic void setLeaf(boolean leaf){\n\t\tthis.leaf = leaf;\n\t}\n\n\tpublic boolean isTerminal(){\n\t\treturn terminal;\n\t}\n\t\n\tpublic Key getKey(){\n\t\treturn new Key(state, belief);\n\t}\n\t\n\t/**\n\t * Update this node and remove the virtual loss.\n\t * \n\t * TODO: it remains to be seen if synchronising makes this too slow...\n\t * initial tests indicate this is a negligible increase, while it is\n\t * beneficial to synchronise the updates so that no results are lost\n\t */\n\tpublic synchronized void update(double[] reward, int nRollouts) {\n\t\tfor(int i = 0; i < wins.length; i++)\t\n\t\t\twins[i]+=reward[i];\n\t\tnVisits+=nRollouts;\n\t\tvLoss = 0;\n\t}\n\t\n\tpublic int getParentVisits() {\n\t\treturn parentVisits;\n\t}\n\t\n\tpublic void incrementParentVisits() {\n\t\tparentVisits++;\n\t}\n\t\n\tpublic double getWins(int pn) {\n\t\treturn wins[pn];\n\t}\n\t\n\tpublic int getnVisits() {\n\t\treturn nVisits;\n\t}\n\t\n\tpublic int getvLoss() {\n\t\treturn vLoss;\n\t}\n\t\n\tpublic void setEvaluated(boolean evaluated){\n\t\tthis.evaluated = evaluated;\n\t}\n\t\n\tpublic boolean isEvaluated(){\n\t\treturn evaluated;\n\t}\n\t\n\tpublic void incrementVLoss(){\n\t\tthis.vLoss++;\n\t}\n\t\n\t/**\n\t * Can this node be expanded?\n\t * \n\t * @return\n\t */\n\tpublic abstract boolean canExpand();\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif(obj instanceof TreeNode){\n\t\t\treturn Arrays.equals(state, ((TreeNode) obj).state);\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Arrays.hashCode(state);\n\t}\n\t\n}" ]
import java.util.ArrayList; import java.util.Map; import com.google.common.util.concurrent.AtomicDoubleArray; import mcts.game.GameFactory; import mcts.game.catan.Catan; import mcts.game.catan.CatanConfig; import mcts.game.catan.GameStateConstants; import mcts.game.catan.typepdf.ActionTypePdf; import mcts.game.catan.typepdf.UniformActionTypePdf; import mcts.seeder.SeedTrigger; import mcts.tree.node.StandardNode; import mcts.tree.node.TreeNode;
package mcts.seeder.pdf; /** * This uses the typed pdf to seed in the tree without launching new threads. * * @author sorinMD * */ public class CatanTypePDFSeedTrigger extends SeedTrigger implements GameStateConstants{ public ActionTypePdf pdf = new UniformActionTypePdf(); public CatanTypePDFSeedTrigger() { // TODO Auto-generated constructor stub } @Override public void addNode(TreeNode node, GameFactory factory) { //no need to start a new thread just for this. Also no need to track what was already evaluated as this should be pretty quick int task = getTaskIDFromState(node); if(task == -1) return; Catan game = (Catan) factory.getGame(node.getState()); ArrayList<Integer> types = game.listNormalActionTypes(); Map<Integer,Double> dist = pdf.getDist(types); //trades are A_TRADE in rollouts, but could be A_OFFER in tree, so handle this aspect here
if(((CatanConfig)factory.getConfig()).NEGOTIATIONS) {
2
rolandkrueger/user-microservice
service/src/test/java/info/rolandkrueger/userservice/service/AuthenticationListenerTest.java
[ "@SpringBootApplication\n@PropertySource(\"userservice.properties\")\npublic class UserMicroserviceApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(\n new Object[]{\n UserMicroserviceApplication.class,\n DevelopmentProfileConfiguration.class}\n , args);\n }\n}", "public class UserApiData extends AbstractBaseApiData<UserResource> implements UserDetails {\n private String username;\n private String password;\n private String email;\n private boolean enabled;\n private boolean accountNonLocked;\n private boolean accountNonExpired;\n private boolean credentialsNonExpired;\n private String rememberMeToken;\n private String registrationConfirmationToken;\n private LocalDate registrationDate;\n private LocalDateTime lastLogin;\n private List<AuthorityApiData> authorities;\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n\n public boolean isAccountNonLocked() {\n return accountNonLocked;\n }\n\n public void setAccountNonLocked(boolean accountNonLocked) {\n this.accountNonLocked = accountNonLocked;\n }\n\n public boolean isAccountNonExpired() {\n return accountNonExpired;\n }\n\n public void setAccountNonExpired(boolean accountNonExpired) {\n this.accountNonExpired = accountNonExpired;\n }\n\n public boolean isCredentialsNonExpired() {\n return credentialsNonExpired;\n }\n\n public void setCredentialsNonExpired(boolean credentialsNonExpired) {\n this.credentialsNonExpired = credentialsNonExpired;\n }\n\n public String getRememberMeToken() {\n return rememberMeToken;\n }\n\n public void setRememberMeToken(String rememberMeToken) {\n this.rememberMeToken = rememberMeToken;\n }\n\n public String getRegistrationConfirmationToken() {\n return registrationConfirmationToken;\n }\n\n public void setRegistrationConfirmationToken(String registrationConfirmationToken) {\n this.registrationConfirmationToken = registrationConfirmationToken;\n }\n\n public LocalDate getRegistrationDate() {\n return registrationDate;\n }\n\n public void setRegistrationDate(LocalDate registrationDate) {\n this.registrationDate = registrationDate;\n }\n\n public LocalDateTime getLastLogin() {\n return lastLogin;\n }\n\n public void setLastLogin(LocalDateTime lastLogin) {\n this.lastLogin = lastLogin;\n }\n\n public List<AuthorityApiData> getAuthorities() {\n if (authorities == null) {\n authorities = Lists.newArrayList();\n }\n return authorities;\n }\n\n public void setAuthorities(List<AuthorityApiData> authorities) {\n this.authorities = authorities;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(UserApiData.class)\n .add(\"username\", username)\n .toString();\n }\n\n @Override\n protected UserResource createNewResource(Link self) {\n return new UserResource(self, this);\n }\n}", "@Component\npublic class AuthenticationListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {\n\n private static final Logger LOG = LoggerFactory.getLogger(AuthenticationListener.class);\n\n private UserMicroserviceEndpointProvider endpointProvider;\n\n /**\n * Create a new AuthenticationListener with a specific {@link UserMicroserviceEndpointProvider}.\n *\n * @param endpointProvider an endpoint provider for the user micro-service so that the listener can access the service.\n */\n @Autowired\n public AuthenticationListener(UserMicroserviceEndpointProvider endpointProvider) {\n Preconditions.checkNotNull(endpointProvider);\n this.endpointProvider = endpointProvider;\n }\n\n /**\n * Will be called upon the successful login of a user, updates the user's status in the user micro-service. This\n * will update the date of the user's last login to the current timestamp and mark the user as logged in in the service.\n *\n * @param event event which indicates that a user has successfully signed in\n */\n @Override\n public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {\n Object principal = event.getAuthentication().getPrincipal();\n if (principal instanceof UserDetails) {\n UserDetails user = (UserDetails) principal;\n Optional<UserApiData> userForLogin = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint())\n .users()\n .search()\n .findUserForLogin(user.getUsername()).getData().stream().findFirst();\n if (!userForLogin.isPresent()) {\n LOG.warn(\"Received authentication success event for user '{}' but according to user service this user \" +\n \"is not active/does not exist.\", user.getUsername());\n } else {\n userForLogin.get().getResource().loggedIn();\n }\n }\n }\n}", "@Service\npublic class StaticEndpointProvider implements UserMicroserviceEndpointProvider {\n\n private String endpoint;\n\n protected StaticEndpointProvider() {\n }\n\n /**\n * Creates a new StaticEndpointProvider for the given static endpoint URL.\n *\n * @param endpoint static endpoint address for the user micro-service\n */\n public StaticEndpointProvider(String endpoint) {\n this.endpoint = endpoint;\n }\n\n /**\n * Returns the fixed user service endpoint address passed in through the constructor.\n */\n @Override\n public String getUserMicroserviceEndpoint() {\n return endpoint;\n }\n}", "public abstract class AbstractRestControllerTest {\n\n private final static String CONTEXT_PATH = \"http://localhost:\";\n\n private static UserService service;\n private static int port = 8080;\n\n protected static void setPort(int port) {\n AbstractRestControllerTest.port = port;\n }\n\n protected static UserService service() {\n if (service == null) {\n service = UserServiceAPI.init(CONTEXT_PATH + port);\n }\n return service;\n }\n\n @After\n public void tearDown(){\n deleteAllUsers();\n deleteAllAuthorities();\n }\n\n protected static void deleteAllUsers() {\n UsersResource users;\n do {\n users = service().users();\n users.getData().stream().forEach(user -> user.getResource().delete());\n } while (users.hasNext());\n }\n\n protected static void deleteAllAuthorities() {\n AuthoritiesResource authorities;\n do {\n authorities = service().authorities();\n authorities.getData().stream().forEach(authority -> authority.getResource().delete());\n } while (authorities.hasNext());\n }\n\n protected static AuthorityApiData createAuthority(String authority) {\n AuthorityApiData authorityApiData = new AuthorityApiData();\n authorityApiData.setAuthority(authority);\n authorityApiData.setDescription(\"The \" + authority + \" role\");\n return service().authorities().create(authorityApiData).getBody();\n }\n\n protected static UserApiData registerUser(String username, String password, String email) {\n ResponseEntity<UserRegistrationApiData> registrationResponse =\n service()\n .userRegistrations()\n .create(username, password, email);\n\n service()\n .userRegistrations()\n .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())\n .confirmRegistration();\n\n return service()\n .users()\n .search()\n .findByUsername(username).getData().stream().findFirst().get();\n }\n\n}" ]
import info.rolandkrueger.userservice.UserMicroserviceApplication; import info.rolandkrueger.userservice.api.model.UserApiData; import info.rolandkrueger.userservice.api.service.AuthenticationListener; import info.rolandkrueger.userservice.api.service.StaticEndpointProvider; import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue;
package info.rolandkrueger.userservice.service; /** * @author Roland Krüger */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = UserMicroserviceApplication.class) @WebIntegrationTest(randomPort = true) public class AuthenticationListenerTest extends AbstractRestControllerTest { private AuthenticationListener listener; @Value("${local.server.port}") private int port; @Before public void setUp() { setPort(port); deleteAllUsers(); deleteAllAuthorities(); listener = new AuthenticationListener(new StaticEndpointProvider("http://localhost:" + port)); registerUser("alice", "passw0rd", "[email protected]"); } @Test public void testAuthenticationSuccess() {
UserApiData user = new UserApiData();
1
mutualmobile/Barricade
app/src/androidTest/java/com/mutualmobile/barricade/sample/BarricadeActivityTest.java
[ "public class Barricade {\n static final String TAG = \"Barricade\";\n private static final String ROOT_DIRECTORY = \"barricade\";\n private static final long DEFAULT_DELAY = 150;\n private static Barricade instance;\n\n private IBarricadeConfig barricadeConfig;\n private AssetFileManager fileManager;\n private long delay = DEFAULT_DELAY;\n\n private boolean enabled = false;\n\n /**\n * @return The singleton instance of the Barricade\n */\n public static Barricade getInstance() {\n if (instance == null) {\n throw new IllegalStateException(\"Barricade not installed, install using Builder\");\n }\n return instance;\n }\n\n // Disable instance creation by using empty constructor\n private Barricade() {\n }\n\n private Barricade(AssetFileManager fileManager, IBarricadeConfig barricadeConfig, long delay, Application application) {\n this.barricadeConfig = barricadeConfig;\n this.fileManager = fileManager;\n this.delay = delay;\n\n if (application != null) {\n new BarricadeShakeListener(application);\n }\n }\n\n public boolean isEnabled() {\n return enabled;\n }\n\n /**\n * Builder class for Barricade\n */\n public static class Builder {\n private IBarricadeConfig barricadeConfig;\n private AssetFileManager fileManager;\n private long delay = DEFAULT_DELAY;\n private Application application;\n\n public Builder(Context context, IBarricadeConfig barricadeConfig) {\n this(barricadeConfig, new AndroidAssetFileManager(context));\n }\n\n public Builder(IBarricadeConfig barricadeConfig, AssetFileManager fileManager) {\n this.barricadeConfig = barricadeConfig;\n this.fileManager = fileManager;\n }\n\n public Builder enableShakeToStart(Application application) {\n this.application = application;\n return this;\n }\n\n public Builder setGlobalDelay(long delay) {\n this.delay = delay;\n return this;\n }\n\n /**\n * Create Barricade instance if not exist and return it\n * It should be called once in project, next call will be ignored\n *\n * @return Barricade instance\n */\n public Barricade install() {\n if (instance == null) {\n instance = new Barricade(fileManager, barricadeConfig, delay, application);\n } else {\n Logger.getLogger(TAG).info(\"Barricade already installed, install() will be ignored.\");\n }\n return instance;\n }\n }\n\n /**\n * Returns a barricaded response for an endpoint\n *\n * @param chain OkHttp Interceptor chain\n * @param endpoint Endpoint that is being hit\n * @return Barricaded response (if available), null otherwise\n */\n okhttp3.Response getResponse(Interceptor.Chain chain, String endpoint) {\n BarricadeResponse barricadeResponse = barricadeConfig.getResponseForEndpoint(endpoint);\n if (barricadeResponse == null) {\n return null;\n }\n String fileResponse = getResponseFromFile(endpoint, barricadeResponse.responseFileName);\n return new okhttp3.Response.Builder().code(barricadeResponse.statusCode).message(\"Barricade OK\")\n .request(chain.request())\n .protocol(Protocol.HTTP_1_0)\n .body(ResponseBody.create(MediaType.parse(barricadeResponse.contentType), fileResponse.getBytes()))\n .addHeader(\"content-type\", barricadeResponse.contentType)\n .build();\n }\n\n public HashMap<String, BarricadeResponseSet> getConfig() {\n return barricadeConfig.getConfigs();\n }\n\n public long getDelay() {\n return delay;\n }\n\n private String getResponseFromFile(String endpoint, String variant) {\n String fileName = ROOT_DIRECTORY + File.separator + endpoint + File.separator + variant;\n return fileManager.getContentsOfFileAsString(fileName);\n }\n\n /**\n * Change Barricade status\n *\n * @param enabled true to enable, false otherwise\n */\n public Barricade setEnabled(boolean enabled) {\n this.enabled = enabled;\n return this;\n }\n\n /**\n * Set delay for responses sent by Barricade\n *\n * @param delay Delay in milliseconds\n */\n public Barricade setDelay(long delay) {\n this.delay = delay;\n return this;\n }\n\n /**\n * Change response to be returned for an endpoint\n *\n * @param endPoint The endpoint whose response you want to change. Use BarricadeConfig$EndPoints\n * to\n * get endpoint strings rather than passing string directly\n * @param defaultIndex The index of the response you want to get for endPoint. Use\n * BarricadeConfig$Responses to get responses for an endpoint instead of passing an int directly\n */\n public Barricade setResponse(String endPoint, int defaultIndex) {\n if (getConfig().containsKey(endPoint)) {\n getConfig().get(endPoint).defaultIndex = defaultIndex;\n return this;\n } else {\n throw new IllegalArgumentException(endPoint + \" doesn't exist\");\n }\n }\n\n /**\n * Resets any configuration changes done at run-time\n */\n public void reset() {\n HashMap<String, BarricadeResponseSet> configs = getConfig();\n for (String key : configs.keySet()) {\n BarricadeResponseSet set = configs.get(key);\n set.defaultIndex = set.originalDefaultIndex;\n }\n this.delay = DEFAULT_DELAY;\n }\n\n /**\n * Launches the Barricade configuration UI\n *\n * @param context Activity context\n */\n public void launchConfigActivity(Context context) {\n Intent intent = new Intent(context, BarricadeActivity.class);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);\n } else {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n context.startActivity(intent);\n }\n}", "public class BarricadeActivity extends AppCompatActivity\n implements BarricadeEndpointsRVAdapter.EndpointClickedListener, BarricadeResponsesRVAdapter.EndpointResponseClickedListener {\n\n private HashMap<String, BarricadeResponseSet> barricadeConfig;\n\n private ActionBar actionBar;\n private RecyclerView endpointsRecyclerView;\n private RecyclerView responsesRecyclerView;\n\n private BarricadeEndpointsRVAdapter endpointsRVAdapter;\n private BarricadeResponsesRVAdapter responsesRVAdapter;\n private RelativeLayout container;\n\n @Override protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_barricade);\n\n initUi();\n barricadeConfig = Barricade.getInstance().getConfig();\n setEndpointsView();\n }\n\n private void initUi() {\n setSupportActionBar((Toolbar)findViewById(R.id.toolbar));\n actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n }\n endpointsRecyclerView = (RecyclerView) findViewById(R.id.endpoint_rv);\n responsesRecyclerView = (RecyclerView) findViewById(R.id.endpoint_responses_rv);\n\n endpointsRecyclerView.setLayoutManager(new LinearLayoutManager(this));\n responsesRecyclerView.setLayoutManager(new LinearLayoutManager(this));\n\n container = (RelativeLayout) findViewById(R.id.activity_barricade);\n }\n\n private void setEndpointsView() {\n setToolbarTitle(getString(R.string.title_activity));\n endpointsRVAdapter = new BarricadeEndpointsRVAdapter(barricadeConfig, this);\n endpointsRecyclerView.setAdapter(endpointsRVAdapter);\n endpointsRecyclerView.setVisibility(View.VISIBLE);\n responsesRecyclerView.setVisibility(View.GONE);\n }\n\n private void setResponsesView(String endpoint) {\n setToolbarTitle(endpoint);\n BarricadeResponseSet responseSet = barricadeConfig.get(endpoint);\n responsesRVAdapter = new BarricadeResponsesRVAdapter(endpoint, responseSet.responses, responseSet.defaultIndex, this);\n responsesRecyclerView.setAdapter(responsesRVAdapter);\n endpointsRecyclerView.setVisibility(View.GONE);\n responsesRecyclerView.setVisibility(View.VISIBLE);\n }\n\n private void setToolbarTitle(String title) {\n if (actionBar != null) {\n actionBar.setTitle(title);\n }\n }\n\n @Override public void onBackPressed() {\n if (endpointsRecyclerView.getVisibility() == View.GONE) {\n setEndpointsView();\n } else {\n super.onBackPressed();\n }\n }\n\n @Override public void onEndpointClicked(String endpoint) {\n setResponsesView(endpoint);\n }\n\n @Override public void onResponseClicked(String endpoint, int index) {\n barricadeConfig.get(endpoint).defaultIndex = index;\n setEndpointsView();\n }\n\n @Override public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n return super.onCreateOptionsMenu(menu);\n }\n\n @Override public boolean onOptionsItemSelected(MenuItem item) {\n int itemId = item.getItemId();\n if (itemId == android.R.id.home) {\n onBackPressed();\n return true;\n } else if (itemId == R.id.menu_delay) {\n showEditDialog();\n return true;\n } else if (itemId == R.id.menu_reset) {\n showResetDialog();\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n private void showEditDialog() {\n View dialogView =\n getLayoutInflater().inflate(R.layout.dialog_edit_global_delay, container, false);\n\n final EditText delayEditText = (EditText) dialogView.findViewById(R.id.delay_value_edittext);\n delayEditText.setText(String.format(Locale.US, \"%d\", Barricade.getInstance().getDelay()));\n\n new AlertDialog.Builder(this).setView(dialogView)\n .setTitle(R.string.edit_delay)\n .setPositiveButton(R.string.set, new DialogInterface.OnClickListener() {\n @Override public void onClick(DialogInterface dialogInterface, int i) {\n String value = delayEditText.getText().toString();\n if (value.isEmpty()) {\n delayEditText.setError(getString(R.string.required));\n } else {\n Barricade.getInstance().setDelay(Long.parseLong(value));\n Toast.makeText(BarricadeActivity.this, R.string.updated, Toast.LENGTH_LONG).show();\n }\n }\n })\n .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {\n @Override public void onClick(DialogInterface dialogInterface, int i) {\n\n }\n })\n .show();\n }\n\n private void showResetDialog() {\n new AlertDialog.Builder(this).setMessage(getString(R.string.reset_message))\n .setCancelable(true)\n .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {\n @Override public void onClick(DialogInterface dialogInterface, int i) {\n Barricade.getInstance().reset();\n endpointsRVAdapter.notifyDataSetChanged();\n }\n })\n .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {\n @Override public void onClick(DialogInterface dialogInterface, int i) {\n\n }\n })\n .create()\n .show();\n }\n}", "public class BarricadeResponse {\n public int statusCode;\n public String responseFileName;\n public String contentType;\n\n public BarricadeResponse(int statusCode, String responseFileName, String contentType) {\n this.statusCode = statusCode;\n this.responseFileName = responseFileName;\n this.contentType = contentType;\n }\n\n public BarricadeResponse(Response response) {\n this.statusCode = response.statusCode();\n this.responseFileName = response.fileName();\n this.contentType = response.type();\n }\n}", "public class BarricadeResponseSet {\n public List<BarricadeResponse> responses;\n public int defaultIndex;\n public int originalDefaultIndex;\n\n public BarricadeResponseSet(List<BarricadeResponse> responses, int defaultIndex) {\n this.responses = responses;\n this.defaultIndex = defaultIndex;\n this.originalDefaultIndex = defaultIndex;\n }\n}", "public class AndroidAssetFileManager implements AssetFileManager {\n private Context mApplicationContext;\n private static final String TAG = \"AndroidAssetFileManager\";\n\n public AndroidAssetFileManager(Context applicationContext) {\n mApplicationContext = applicationContext;\n }\n\n public String getContentsOfFileAsString(String fileName) {\n try {\n InputStream is = getContentsOfFileAsStream(fileName);\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n int aByte = is.read();\n while (aByte != -1) {\n bos.write(aByte);\n aByte = is.read();\n }\n return bos.toString(\"UTF-8\");\n } catch (IOException e) {\n Logger.getLogger(TAG).severe(e.getMessage());\n }\n return null;\n }\n\n @Override public InputStream getContentsOfFileAsStream(String fileName) {\n try {\n return mApplicationContext.getAssets().open(String.format(\"%s\", fileName));\n } catch (IOException e) {\n Logger.getLogger(TAG).severe(e.getMessage());\n }\n return null;\n }\n}", "public static RecyclerViewMatcher withRecyclerView(final int recyclerViewId) {\n return new RecyclerViewMatcher(recyclerViewId);\n}" ]
import androidx.test.InstrumentationRegistry; import androidx.test.espresso.Espresso; import androidx.test.espresso.contrib.RecyclerViewActions; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import com.mutualmobile.barricade.Barricade; import com.mutualmobile.barricade.BarricadeConfig; import com.mutualmobile.barricade.activity.BarricadeActivity; import com.mutualmobile.barricade.response.BarricadeResponse; import com.mutualmobile.barricade.response.BarricadeResponseSet; import com.mutualmobile.barricade.utils.AndroidAssetFileManager; import java.util.Map; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasDescendant; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static com.mutualmobile.barricade.sample.utils.RecyclerViewMatcher.withRecyclerView;
package com.mutualmobile.barricade.sample; /** * Contains Espresso tests for the Barricade Activity UI. We verify the response and it's corresponding response sets in the UI. Functionality of * delay and reset is verified as well */ @RunWith(AndroidJUnit4.class) @LargeTest public class BarricadeActivityTest { @Rule public ActivityTestRule<BarricadeActivity> activityTestRule = new ActivityTestRule<>(BarricadeActivity.class); private static Barricade barricade; @BeforeClass public static void setup() { barricade = new Barricade.Builder(BarricadeConfig.getInstance(), new AndroidAssetFileManager(InstrumentationRegistry.getTargetContext())). install(); } @Test public void verifyEndpoints() { int count = 0; for (String endpoint : barricade.getConfig().keySet()) { onView(withRecyclerView(com.mutualmobile.barricade.R.id.endpoint_rv).atPosition(count)).check(matches(hasDescendant(withText(endpoint)))); count++; } } @Test public void verifyResponsesForEndpoints() { int endpointCount = 0;
Map<String, BarricadeResponseSet> hashMap = barricade.getConfig();
3
turn/sorcerer
src/main/java/com/turn/sorcerer/pipeline/executable/impl/PipelineFactory.java
[ "public class SorcererInjector {\n\tprivate static final Logger logger =\n\t\t\tLoggerFactory.getLogger(SorcererInjector.class);\n\n\t// We use Guice as the underlying binder\n\tprivate Injector INJECTOR;\n\n\t/**\n\t * Singleton pattern. A single instance of Sorcerer runs per JVM.\n\t */\n\tprivate static SorcererInjector INSTANCE = new SorcererInjector();\n\n\tpublic static SorcererInjector get() {\n\t\treturn INSTANCE;\n\t}\n\n\t// Private constructor to prevent instantiation\n\tprivate SorcererInjector() {}\n\n\tprivate final TypeLiteral<Set<PipelineType>> setOfPipelines =\n\t\t\tnew TypeLiteral<Set<PipelineType>>() {};\n\n\t/**\n\t * Configure the SorcererInjector. Should be called once per instance of\n\t * Sorcerer.\n\t *\n\t * <p>\n\t * If the underlying injector is configured and created, this method will\n\t * log a warning and return without doing anything. Sorcerer currently does\n\t * not support reconfiguration.\n\t * </p>\n\t *\n\t * @param module SorcererAbstractModule defining the bindings\n\t */\n\tpublic void configure(SorcererAbstractModule module) {\n\n\t\tif (INJECTOR != null) {\n\t\t\tlogger.warn(\"Injector configuration method called but injector is already configured\");\n\t\t\treturn;\n\t\t}\n\n\t\tINJECTOR = Guice.createInjector(module);\n\t}\n\n\t/**\n\t * Provides the task type registered to a specific task name\n\t *\n\t * <p>\n\t * Uses the underlying injector to get the task type instance binding with\n\t * the provided task name. <b>If the binding is not found the method will\n\t * return null.</b> Therefore the client should handle the case if the\n\t * binding doesn't exist.\n\t * </p>\n\t *\n\t * @param name Name of task\n\t * @return Returns TaskType instance registered to the provided task name.\n\t * Returns null if no task type was found with the provided name.\n\t */\n\tpublic TaskType getTaskType(final String name){\n\t\ttry {\n\t\t\treturn INJECTOR.getInstance(\n\t\t\t\t\tKey.get(TaskType.class, Names.named(name)));\n\t\t} catch (ConfigurationException ce) {\n\t\t\tlogger.error(\"Injector could not get instance\", ce);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Provides a Task implementation instance of the task type\n\t *\n\t * <p>\n\t * Uses the underlying injector to get an instance of the Task\n\t * implementation that is registered to the provided task type. If no\n\t * binding is found for the task type, the method will return null.\n\t * This should never happen since Sorcerer does eager task type\n\t * reconciliation at initialization. However, it is possible (though\n\t * unsupported) that some unregistered task type was created outside of\n\t * Sorcerer. In any case, the client should handle the return value of\n\t * null if no Task implementation was found for the task type.\n\t * </p>\n\t *\n\t * @param type Task type\n\t * @return Returns a Task instance registered to the provided task name.\n\t * Returns null if no task implementation was found for the task type.\n\t */\n\tpublic Task getInstance(TaskType type) {\n\t\ttry {\n\t\t\treturn INJECTOR.getInstance(\n\t\t\t\t\tKey.get(Task.class, Names.named(type.getName())));\n\t\t} catch (ConfigurationException ce) {\n\t\t\tlogger.error(\"Injector could not get instance\", ce);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Provides the pipeline type registered to a specific task name\n\t *\n\t * <p>\n\t * Uses the underlying injector to get the pipeline type instance binding\n\t * with the provided pipeline name. <b>If the binding is not found the\n\t * method will return null.</b> Therefore the client should handle the case\n\t * if the binding doesn't exist.\n\t * </p>\n\t *\n\t * @param name Name of pipeline\n\t * @return Returns PipelineType instance registered to the provided\n\t * pipeline name\n\t */\n\tpublic PipelineType getPipelineType(final String name) {\n\t\ttry {\n\t\t\treturn INJECTOR.getInstance(\n\t\t\t\t\tKey.get(PipelineType.class, Names.named(name)));\n\t\t} catch (ConfigurationException ce) {\n\t\t\tlogger.error(\"Injector could not get instance\", ce);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Provides a Pipeline implementation instance of the pipeline type\n\t *\n\t * <p>\n\t * Uses the underlying injector to get an instance of the Pipeline\n\t * implementation that is registered to the provided pipeline type. If no\n\t * binding is found for the pipeline type, the method will return null.\n\t * This should never happen since Sorcerer does eager pipeline type\n\t * reconciliation at initialization. However, it is possible (though\n\t * unsupported) that some unregistered pipeline type was created outside of\n\t * Sorcerer. In any case, the client should handle the return value of\n\t * null if no Pipeline implementation was found for the pipeline type.\n\t * </p>\n\t *\n\t * @param type pipeline type\n\t * @return Returns a Pipeline instance registered to the provided pipeline\n\t * name. Returns null if no Pipeline implementation was found for the\n\t * pipeline type.\n\t */\n\tpublic Pipeline getInstance(PipelineType type) {\n\t\ttry {\n\t\t\treturn INJECTOR.getInstance(\n\t\t\t\t\tKey.get(Pipeline.class, Names.named(type.getName())));\n\t\t} catch (ConfigurationException ce) {\n\t\t\tlogger.error(\"Injector could not get instance\", ce);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Checks if a Pipeline implementation binding exists for a pipeline type\n\t */\n\tpublic boolean bindingExists(PipelineType type) {\n\t\treturn INJECTOR.getExistingBinding(\n\t\t\t\tKey.get(Pipeline.class, Names.named(type.getName()))\n\t\t) != null;\n\t}\n\n\t/**\n\t * Provides the set of pipeline types to be scheduled in the module\n\t */\n\tpublic Set<PipelineType> getPipelines() {\n\t\ttry {\n\t\t\treturn INJECTOR.getInstance(Key.get(setOfPipelines));\n\t\t} catch (ConfigurationException ce) {\n\t\t\tlogger.error(\"Injector could not get instance\", ce);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Provides the module type representing the current Sorcerer module\n\t */\n\tpublic ModuleType getModule() {\n\t\treturn INJECTOR.getInstance(ModuleType.class);\n\t}\n\n\t/**\n\t * Provides email information defined in the module\n\t */\n\tpublic EmailType getAdminEmail() {\n\t\treturn INJECTOR.getInstance(EmailType.class);\n\t}\n\n\t/**\n\t * Provides an instance of the storage layer\n\t */\n\tpublic StatusStorage getStorageInstance() {\n\t\treturn INJECTOR.getInstance(StatusStorage.class);\n\t}\n\n}", "public interface Pipeline {\n\n\t/**\n\t * Provides the current iteration number of a pipeline\n\t *\n\t * <p>\n\t * This method should be implemented to trigger the scheduling of a\n\t * pipeline based on the iteration number. Sorcerer will use the value\n\t * returned by this method to schedule pipelines. Each time a new iteration\n\t * number is provided by this method, Sorcerer will instantiate and\n\t * schedule a new pipeline.\n\t * </p>\n\t *\n\t * <p>\n\t * Note: This method will be called periodically (as defined by the\n\t * {@code interval} field of a pipeline configuration) and so it should\n\t * be stateless. Sorcerer instantiates a Pipeline instance using its\n\t * injector and then calls this method to generate the current iteration\n\t * number.\n\t * </p>\n\t *\n\t * @return Current iteration number\n\t */\n\tInteger getCurrentIterationNumber();\n\n\tInteger getPreviousIterationNumber(int curr, int prev);\n}", "public abstract class ExecutablePipeline {\n\tprotected final int iterationNum;\n\tprotected final PipelineType pipelineType;\n\n\tprotected Map<String, Boolean> taskCompletionMap;\n\n\t// Map representation of workflow graph\n\tprotected SetMultimap<String, TaskType> taskGraph;\n\n\t// This should never be used\n\tprivate ExecutablePipeline() {\n\t\tthis.iterationNum = -1;\n\t\tthis.pipelineType = null;\n\t}\n\n\tprotected ExecutablePipeline(int id, PipelineType pipelineType) {\n\t\tthis.iterationNum = id;\n\t\tthis.pipelineType = pipelineType;\n\n\t\tTaskType initTask = SorcererInjector.get().getTaskType(pipelineType.getInitTaskName());\n\n\t\tif (taskCompletionMap == null) {\n\t\t\ttaskCompletionMap = Maps.newConcurrentMap();\n\t\t}\n\t\tif (taskGraph == null) {\n\t\t\ttaskGraph = HashMultimap.create();\n\t\t\ttaskGraph.put(initTask.getName(), null);\n\t\t}\n\n\t\t// Initialize list of tasks in pipeline\n\t\tinitTask(initTask);\n\t\tupdatePipelineCompletion();\n\t}\n\n\tpublic String name() {\n\t\treturn pipelineType.getName();\n\t}\n\n\tpublic int getId() {\n\t\treturn iterationNum;\n\t}\n\n\t// recursive init task\n\tprivate void initTask(TaskType task) {\n\n\t\tif (task == null) {\n\t\t\treturn;\n\t\t}\n\n\t\ttaskCompletionMap.put(task.getName(), false);\n\n\t\tif (task.getNextTaskNames() == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (String nextTaskName : task.getNextTaskNames()) {\n\n\t\t\tif (nextTaskName == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tTaskType nextTask = SorcererInjector.get().getTaskType(nextTaskName);\n\t\t\ttaskGraph.put(nextTask.getName(), task);\n\n\t\t\tinitTask(nextTask);\n\t\t}\n\t}\n\n\tpublic void updateTaskAsComplete(TaskType task) {\n\t\ttaskCompletionMap.put(task.getName(), true);\n\t\tupdatePipelineCompletion();\n\t}\n\n\tpublic boolean isCompleted() {\n\t\treturn StatusManager.get().isPipelineComplete(this.pipelineType, this.iterationNum);\n\t}\n\n\tpublic Map<String, Boolean> getTaskCompletionMap() {\n\t\treturn taskCompletionMap;\n\t}\n\n\tpublic SetMultimap<String, TaskType> getTaskGraph() {\n\t\treturn taskGraph;\n\t}\n\n\tpublic String toString() {\n\t\treturn pipelineType.getName() + \":\" + iterationNum;\n\t}\n\n\tpublic abstract void updatePipelineCompletion();\n}", "public class CronPipeline implements Pipeline {\n\n\tprivate static final DateTimeFormatter dtf = DateTimeFormat.forPattern(\"yyMMdd\");\n\n\tprivate final CronExpression cronExp;\n\tprivate DateTime next;\n\tprivate int currIterNo;\n\n\tpublic CronPipeline(String cronString) {\n\t\tthis.cronExp = new CronExpression(cronString);\n\n\t\tnext = cronExp.getNextTimeAfter(DateTime.now());\n\n\t\tcurrIterNo = -1;\n\t}\n\n\t@Override\n\tpublic Integer getCurrentIterationNumber() {\n\t\tDateTime now = DateTime.now();\n\n\t\tif (now.isAfter(next)) {\n\t\t\tcurrIterNo = generateIterationNumber(now);\n\n\t\t\tnext = cronExp.getNextTimeAfter(now);\n\t\t}\n\n\t\treturn currIterNo;\n\t}\n\n\t@Override\n\tpublic Integer getPreviousIterationNumber(int curr, int prev) {\n\t\tDateTime currDate = getDateTime(curr);\n\t\tint currIterNo = getDayIterNo(curr);\n\n\t\tint iterationsLeft = prev;\n\n\t\twhile(iterationsLeft >= 0) {\n\n\t\t\tif (currIterNo - iterationsLeft > 0) {\n\t\t\t\treturn getIterationNumber(currDate, currIterNo - iterationsLeft);\n\t\t\t}\n\n\t\t\titerationsLeft -= currIterNo;\n\t\t\tcurrDate = new DateTime(currDate).minusDays(1);\n\t\t\tcurrIterNo = getLastIterNoForDate(currDate);\n\t\t}\n\n\t\treturn null;\n\n\t}\n\n\tprivate int generateIterationNumber(DateTime dt) {\n\t\treturn getIterationNumber(dt, getDayIterNoForDateTime(dt));\n\t}\n\n\tprivate int getIterationNumber(DateTime dt, int dayIterNo) {\n\t\tint year = dt.getYear();\n\t\tint month = dt.getMonthOfYear();\n\t\tint day = dt.getDayOfMonth();\n\n\t\treturn (((year % 100) * 10000) + (month * 100) + day) * 10000 + dayIterNo;\n\t}\n\n\tprivate DateTime getDateTime(int iterNo) {\n\t\treturn dtf.parseDateTime(String.valueOf(iterNo / 10000));\n\t}\n\n\tprivate int getDayIterNo(int iterNo) {\n\t\treturn iterNo % 10000;\n\t}\n\n\tprivate int getLastIterNoForDate(DateTime dt) {\n\t\tint iterNo = 0;\n\t\tDateTime _next = new DateTime()\n\t\t\t\t.withYear(dt.getYear())\n\t\t\t\t.withDayOfYear(dt.getDayOfYear())\n\t\t\t\t.withHourOfDay(0)\n\t\t\t\t.withMinuteOfHour(0)\n\t\t\t\t.withSecondOfMinute(0);\n\n\t\twhile(_next.getDayOfMonth() == dt.getDayOfMonth()) {\n\t\t\t_next = cronExp.getNextTimeAfter(_next);\n\t\t\titerNo++;\n\t\t}\n\n\t\treturn iterNo;\n\t}\n\n\tprivate int getDayIterNoForDateTime(DateTime dt) {\n\t\tint iterNo = 0;\n\t\tDateTime _next = new DateTime()\n\t\t\t\t.withYear(dt.getYear())\n\t\t\t\t.withDayOfYear(dt.getDayOfYear())\n\t\t\t\t.withHourOfDay(0)\n\t\t\t\t.withMinuteOfHour(0)\n\t\t\t\t.withSecondOfMinute(0);\n\n\t\twhile(_next.isBefore(dt)) {\n\t\t\t_next = cronExp.getNextTimeAfter(_next);\n\t\t\titerNo++;\n\t\t}\n\n\t\treturn iterNo;\n\t}\n}", "public class DefaultPipeline implements Pipeline {\n\n\tprivate final PipelineType type;\n\n\tpublic DefaultPipeline(PipelineType type) {\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic Integer getCurrentIterationNumber() {\n\t\treturn StatusManager.get().getCurrentIterationNumberForPipeline(type) + 1;\n\t}\n\n\t@Override\n\tpublic Integer getPreviousIterationNumber(int curr, int prev) {\n\t\treturn curr - prev;\n\t}\n}", "public class PipelineType {\n\tprivate String name;\n\n\tprivate String init;\n\n\tprivate Integer interval = 60;\n\n\tprivate Integer lookback = 0;\n\n\tprivate Integer threads = 0;\n\n\tprivate String cron;\n\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\tpublic String getInitTaskName() {\n\t\treturn this.init;\n\t}\n\n\tpublic Integer getInterval() {\n\t\treturn this.interval;\n\t}\n\n\tpublic Integer getLookback() {\n\t\treturn this.lookback;\n\t}\n\n\tpublic Integer getThreads() {\n\t\treturn this.threads;\n\t}\n\n\tpublic String getCronString() {\n\t\treturn this.cron;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn MoreObjects.toStringHelper(this)\n\t\t\t\t.add(\"name\", this.name)\n\t\t\t\t.add(\"init\", this.init)\n\t\t\t\t.toString();\n\t}\n\n\t/**\n\t * The name field is used as pipeline's unique identifier so we use it for hashing\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\treturn name.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\treturn o instanceof PipelineType\n\t\t\t\t&& this.getName().equals(((PipelineType) o).getName());\n\n\t}\n}" ]
import com.turn.sorcerer.injector.SorcererInjector; import com.turn.sorcerer.pipeline.Pipeline; import com.turn.sorcerer.pipeline.executable.ExecutablePipeline; import com.turn.sorcerer.pipeline.impl.CronPipeline; import com.turn.sorcerer.pipeline.impl.DefaultPipeline; import com.turn.sorcerer.pipeline.type.PipelineType; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (c) 2015, Turn Inc. All Rights Reserved. * Use of this source code is governed by a BSD-style license that can be found * in the LICENSE file. */ package com.turn.sorcerer.pipeline.executable.impl; /** * Class Description Here * * @author tshiou */ public class PipelineFactory { private static final Logger logger = LoggerFactory.getLogger(PipelineFactory.class); private static PipelineFactory INSTANCE = new PipelineFactory(); public static PipelineFactory get() { return INSTANCE; } private Table<String, Integer, ExecutablePipeline> pipelineInstances = HashBasedTable.create(); private PipelineFactory() { } public Pipeline getPipeline(PipelineType type) { if (type.getCronString() != null && type.getCronString().length() > 0) { return new CronPipeline(type.getCronString()); } if (SorcererInjector.get().bindingExists(type)) { return SorcererInjector.get().getInstance(type); }
return new DefaultPipeline(type);
4
Modbder/ThaumicBases
java/tb/init/TBTiles.java
[ "public class TileAuraLinker extends TileEntity implements IWandable,ITickable{\n\t\n\tpublic Coord3D linkCoord;\n\tpublic int syncTimer;\n\tpublic int instability;\n\tObject beam;\n\t@Override\n\tpublic void update() {\n\t\t\n\t\tif(syncTimer <= 0)\n\t\t{\n\t\t\tsyncTimer = 100;\n\t\t\tNBTTagCompound tg = new NBTTagCompound();\n\t\t\tif(linkCoord != null)\n\t\t\t{\n\t\t\t\ttg.setFloat(\"coordsX\", linkCoord.x);\n\t\t\t\ttg.setFloat(\"coordsY\", linkCoord.y);\n\t\t\t\ttg.setFloat(\"coordsZ\", linkCoord.z);\n\t\t\t}\n\t\t\ttg.setInteger(\"x\", pos.getX());\n\t\t\ttg.setInteger(\"y\", pos.getY());\n\t\t\ttg.setInteger(\"z\", pos.getZ());\n\t\t\tMiscUtils.syncTileEntity(tg, 0);\n\t\t}else\n\t\t\t--syncTimer;\n\t\t\n\t\tif(linkCoord != null)\n\t\t{\n\t\t\tint x = MathHelper.floor_double(linkCoord.x);\n\t\t\tint y = MathHelper.floor_double(linkCoord.y);\n\t\t\tint z = MathHelper.floor_double(linkCoord.z);\n\t\t\t\n\t\t\tif(this.worldObj.getTileEntity(new BlockPos(x, y, z)) instanceof TileAuraLinker && TileAuraLinker.class.cast(this.worldObj.getTileEntity(new BlockPos(x, y, z))).linkCoord == null)\n\t\t\t{\n\t\t\t\tdouble sX = linkCoord.x+0.5D;\n\t\t\t\tdouble sY = linkCoord.y+0.925D;\n\t\t\t\tdouble sZ = linkCoord.z+0.5D;\n\t\t\t\t\n\t\t\t\tdouble eX = pos.getX()+0.5D;\n\t\t\t\tdouble eY = pos.getY()+0.925D;\n\t\t\t\tdouble eZ = pos.getZ()+0.5D;\n\t\t\t\t\n\t\t\t\tint cX = pos.getX() / 16;\n\t\t\t\tint cZ = pos.getZ() / 16;\n\t\t\t\tint ecX = x / 16;\n\t\t\t\tint ecZ = z / 16;\n\t\t\t\t\n\t\t\t\tboolean same = cX == ecX && cZ == ecZ;\n\t\t\t\t\n\t\t\t\tif(this.worldObj.isRemote)\n\t\t\t\t\tbeam = Thaumcraft.proxy.getFX().beamBore(sX, sY, sZ, eX, eY, eZ, 1, same ? 0xff0000 : 0xffffff, true, 1, beam, 1);\n\t\t\t\t\n\t\t\t\tif(syncTimer % 10 == 0 && !this.worldObj.isRemote && !same && !this.worldObj.isBlockPowered(pos) && !this.worldObj.isBlockPowered(pos.down()))\n\t\t\t\t{\n\t\t\t\t\tint aPos = this.worldObj.rand.nextInt(Aspect.getPrimalAspects().size());\n\t\t\t\t\tAspect a = Aspect.getPrimalAspects().get(aPos);\n\t\t\t\t\tint aPullFrom = AuraHelper.getAura(worldObj, getPos(), a);\n\t\t\t\t\tBlockPos to = new BlockPos(x,y,z);\n\t\t\t\t\t\n\t\t\t\t\tif(!this.worldObj.isBlockPowered(to) && !this.worldObj.isBlockPowered(to.down()) && aPullFrom > 0 && AuraHelper.drainAura(worldObj, pos, a, 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tint pIndex = a == Aspect.AIR ? 1 : a == Aspect.WATER ? 2 : a == Aspect.EARTH ? 3 : a == Aspect.ENTROPY ? 5 : a == Aspect.ORDER ? 6 : a == Aspect.FIRE ? 4 : 0;\n\t\t\t\t\t\tboolean iB = instabilityCheck();\n\t\t\t\t\t\tif(iB)\n\t\t\t\t\t\t\tAuraHelper.addAura(worldObj, to, a, 1);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(iB)\n\t\t\t\t\t\t\tfor(int i = 0; i < 10; ++i)\n\t\t\t\t\t\t\t\tThaumcraft.proxy.getFX().sparkle((float)sX, (float)sY+0.1F, (float)sZ, 3, pIndex, -this.worldObj.rand.nextFloat());\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tfor(int i = 0; i < 10; ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat addition = this.worldObj.rand.nextFloat();\n\t\t\t\t\t\t\tThaumcraft.proxy.getFX().sparkle((float)eX, (float)eY+0.1F+addition, (float)eZ, 3, pIndex, addition);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(this.worldObj.rand.nextInt(100) > aPullFrom)\n\t\t\t\t\t\t\t++instability;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else\n\t\t\t{\n\t\t\t\tlinkCoord = null;\n\t\t\t\tbeam = null;\n\t\t\t}\n\t\t}else\n\t\t{\n\t\t\tinstability = 0;\n\t\t\tbeam = null;\n\t\t}\n\t}\n\t\n\tpublic boolean instabilityCheck()\n\t{\n\t\tif(instability > 0 && this.worldObj.rand.nextInt(50) <= this.instability)\n\t\t{\n\t\t\tint rnd = this.worldObj.rand.nextInt(this.instability);\n\t\t\tif(rnd == 49)\n\t\t\t{\n\t\t\t\tinstability -= explodeTransmitter();\n\t\t\t}else\n\t\t\t{\n\t\t\t\tif(rnd >= 45)\n\t\t\t\t{\n\t\t\t\t\tinstability -= harmTransmitter();\n\t\t\t\t}else\n\t\t\t\t{\n\t\t\t\t\tif(rnd >= 31)\n\t\t\t\t\t{\n\t\t\t\t\t\tinstability -= wisp();\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tif(rnd >= 20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tinstability -= zap();\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(rnd >= 10)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinstability -= fluxNode();\n\t\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tinstability -= fluxTransmission();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic int harmTransmitter()\n\t{\n\t\tint destroyed = 0;\n\t\tfor(Aspect a : Aspect.getPrimalAspects())\n\t\t{\n\t\t\tint current = AuraHelper.getAura(worldObj, getPos(), a);\n\t\t\tif(current > 0)\n\t\t\t{\n\t\t\t\tint reduced = this.worldObj.rand.nextInt(Math.min(current, 6));\n\t\t\t\tif(reduced > 0)\n\t\t\t\t\tAuraHelper.drainAura(worldObj, getPos(), a, reduced);\n\t\t\t\t\n\t\t\t\tdestroyed += reduced;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn destroyed;\n\t}\n\t\n\tpublic int zap()\n\t{\n\t\tint x = pos.getX();\n\t\tint y = pos.getY();\n\t\tint z = pos.getZ();\n\t\tList<EntityPlayer> players = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.fromBounds(x-5, y-6, z-5, x+5, y+4, z+5));\n\t\tif(!players.isEmpty())\n\t\t{\n\t\t\tEntityPlayer target = players.get(worldObj.rand.nextInt(players.size()));\n\t\t\ttarget.attackEntityFrom(DamageSource.magic, 4 + this.worldObj.rand.nextInt(4));\n\t\t\treturn 9;\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tpublic int wisp()\n\t{\n\t\tboolean side = this.worldObj.rand.nextBoolean();\n\t\tint x = side ? MathHelper.floor_double(linkCoord.x) : pos.getX();\n\t\tint y = side ? MathHelper.floor_double(linkCoord.y) : pos.getY();\n\t\tint z = side ? MathHelper.floor_double(linkCoord.z) : pos.getZ();\n\t\tArrayList<Aspect> aspects = new ArrayList<Aspect>();\n\t\tCollection<Aspect> pa = Aspect.aspects.values();\n\t\taspects.addAll(pa);\n\t\t\n\t\tEntityWisp wisp = new EntityWisp(worldObj);\n\t\twisp.setPositionAndRotation(x+0.5D, y-0.5D, z+0.5D, 0, 0);\n\t\twisp.setType(aspects.get(worldObj.rand.nextInt(aspects.size())).getTag());\n\t\tworldObj.spawnEntityInWorld(wisp);\n\t\t\n\t\treturn 9;\n\t}\n\t\n\tpublic int fluxNode()\n\t{\n\t\tAuraHelper.pollute(getWorld(), getPos(), 3, true);\n\t\treturn 5;\n\t}\n\t\n\tpublic int fluxTransmission()\n\t{\n\t\tAuraHelper.pollute(getWorld(), getPos(), 3, true);\n\t\treturn 3;\n\t}\n\t\n\tpublic int explodeTransmitter()\n\t{\n\t\tint x = MathHelper.floor_double(pos.getX());\n\t\tint y = MathHelper.floor_double(pos.getY());\n\t\tint z = MathHelper.floor_double(pos.getZ());\n\t\tthis.worldObj.setBlockToAir(pos);\n\t\tthis.worldObj.createExplosion(null, x+0.5D, y-0.5D, z+0.5D, 2, true);\n\t\treturn instability;\n\t}\n\t\n public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)\n {\n \tif(pkt.getNbtCompound().hasKey(\"coordsX\"))\n \t{\n \t\tlinkCoord = new Coord3D(pkt.getNbtCompound().getFloat(\"coordsX\"),pkt.getNbtCompound().getFloat(\"coordsY\"),pkt.getNbtCompound().getFloat(\"coordsZ\"));\n \t}else\n \t\tlinkCoord = null;\n }\n \n public void readFromNBT(NBTTagCompound tag)\n {\n super.readFromNBT(tag);\n \tif(tag.hasKey(\"coordsX\"))\n \t{\n \t\tlinkCoord = new Coord3D(tag.getFloat(\"coordsX\"),tag.getFloat(\"coordsY\"),tag.getFloat(\"coordsZ\"));\n \t}\n \tinstability = tag.getInteger(\"instability\");\n }\n \n public void writeToNBT(NBTTagCompound tag)\n {\n super.writeToNBT(tag);\n\t\tif(linkCoord != null)\n\t\t{\n\t\t\ttag.setFloat(\"coordsX\", linkCoord.x);\n\t\t\ttag.setFloat(\"coordsY\", linkCoord.y);\n\t\t\ttag.setFloat(\"coordsZ\", linkCoord.z);\n\t\t}\n\t\ttag.setInteger(\"instability\", instability);\n }\n\n\t@Override\n\tpublic boolean onWandRightClick(World paramWorld, ItemStack paramItemStack, EntityPlayer paramEntityPlayer,BlockPos paramBlockPos, EnumFacing paramEnumFacing) {\n\t\n\t\t\n\t\tparamEntityPlayer.swingItem();\n\t\tif(!paramItemStack.hasTagCompound())\n\t\t\tparamItemStack.setTagCompound(new NBTTagCompound());\n\t\t\n\t\tif(paramItemStack.getTagCompound().hasKey(\"linkCoordX\"))\n\t\t{\n\t\t\tfloat x = paramItemStack.getTagCompound().getFloat(\"linkCoordX\");\n\t\t\tfloat y = paramItemStack.getTagCompound().getFloat(\"linkCoordY\");\n\t\t\tfloat z = paramItemStack.getTagCompound().getFloat(\"linkCoordZ\");\n\t\t\tif(this.worldObj.getTileEntity(new BlockPos(MathHelper.floor_double(x), MathHelper.floor_double(y), MathHelper.floor_double(z))) instanceof TileAuraLinker)\n\t\t\t{\n\t\t\t\tTileAuraLinker tile = (TileAuraLinker) this.worldObj.getTileEntity(new BlockPos(MathHelper.floor_double(x), MathHelper.floor_double(y), MathHelper.floor_double(z)));\n\t\t\t\ttile.linkCoord = new Coord3D(pos.getX(),pos.getY(),pos.getZ());\n\t\t\t\tparamItemStack.getTagCompound().removeTag(\"linkCoordX\");\n\t\t\t\tparamItemStack.getTagCompound().removeTag(\"linkCoordY\");\n\t\t\t\tparamItemStack.getTagCompound().removeTag(\"linkCoordZ\");\n\t\t\t\tif(paramWorld.isRemote)\n\t\t\t\t\tparamEntityPlayer.addChatMessage(new ChatComponentText(StatCollector.translateToLocal(\"tb.txt.linkEstabilished\")));\n\t\t\t}\n\t\t}else\n\t\t{\n\t\t\tparamItemStack.getTagCompound().setFloat(\"linkCoordX\", pos.getX());\n\t\t\tparamItemStack.getTagCompound().setFloat(\"linkCoordY\", pos.getY());\n\t\t\tparamItemStack.getTagCompound().setFloat(\"linkCoordZ\", pos.getZ());\n\t\t\tif(paramWorld.isRemote)\n\t\t\t\tparamEntityPlayer.addChatMessage(new ChatComponentText(StatCollector.translateToLocal(\"tb.txt.linkStarted\")));\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void onUsingWandTick(ItemStack paramItemStack, EntityPlayer paramEntityPlayer, int paramInt) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void onWandStoppedUsing(ItemStack paramItemStack, World paramWorld, EntityPlayer paramEntityPlayer,\n\t\t\tint paramInt) {\n\t\t\n\t}\n\n}", "public class TileBraizer extends TileEntity implements ITickable\n{\n\tpublic int burnTime;\n\tpublic int uptime;\n\t\n public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)\n {\n \treturn oldState.getBlock() == newSate.getBlock() ? false : super.shouldRefresh(world, pos, oldState, newSate);\n }\n\t\n public void readFromNBT(NBTTagCompound tag)\n {\n super.readFromNBT(tag);\n burnTime = tag.getInteger(\"burnTime\");\n }\n \n public void writeToNBT(NBTTagCompound tag)\n {\n super.writeToNBT(tag);\n tag.setInteger(\"burnTime\", burnTime);\n }\n \n\t@SuppressWarnings({ \"rawtypes\" })\n\tpublic void update() \n\t{\n\t\t++uptime;\n\t\t\n\t\tif(burnTime > 0)\n\t\t{\n\t\t\t--burnTime;\n\t\t}else\n\t\t{\n\t\t\tif(EssentiaHandler.drainEssentia(this, Aspect.FIRE, null, 6, false, 6))\n\t\t\t{\n\t\t\t\tburnTime = 1600;\n\t\t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(1));\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!this.worldObj.isRemote)\n\t\t{\n\t\t\tif(burnTime <= 0)\n\t\t\t{\n\t\t\t\tint metadata = BlockStateMetadata.getBlockMetadata(worldObj, pos);\n\t\t\t\tif(metadata == 1)\n\t\t\t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(0));\n\t\t\t\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t\n\t\tif(!this.worldObj.isRemote)\n\t\t{\n\t\t\tList<EntityCreature> creatures = this.worldObj.getEntitiesWithinAABB(EntityCreature.class, AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX()+1, pos.getY()+1, pos.getZ()+1).expand(12, 6, 12));\n\t\t\t\n\t\t\tfor(EntityCreature c : creatures)\n\t\t\t{\n\t\t\t\tif(!(c instanceof IMob))\n\t\t\t\t\tcontinue;\n\n\t\t\t ArrayList entries = (ArrayList) c.tasks.taskEntries;\n\t\t\t \n\t\t\t EntityAIAvoidCampfire campfireAviodable = null;\n\t\t\t \n\t\t\t boolean hasTask = false;\n\t\t\t for (int i = 0; i < entries.size(); ++i)\n\t\t\t {\n\t\t\t \t EntityAITasks.EntityAITaskEntry task = (EntityAITaskEntry) entries.get(i);\n\t\t\t \t if ((task.action instanceof EntityAIAvoidCampfire)) \n\t\t\t \t {\n\t\t\t \t\t campfireAviodable = (EntityAIAvoidCampfire) task.action;\n\t\t\t \t\t hasTask = true;\n\t\t\t \t\t break;\n\t\t\t \t }\n\t\t\t }\n\t\t\t if(campfireAviodable == null)\n\t\t\t \t campfireAviodable = new EntityAIAvoidCampfire(c);\n\t\t\t \n\t\t\t campfireAviodable.isScared = true;\n\t\t\t campfireAviodable.scareTimer = 100;\n\t\t\t campfireAviodable.campfireX = pos.getX();\n\t\t\t campfireAviodable.campfireY = pos.getY();\n\t\t\t campfireAviodable.campfireZ = pos.getZ();\n\t\t\t \n\t\t\t if(!hasTask)\n\t\t\t \t c.tasks.addTask(1, campfireAviodable);\n\t\t\t}\n\t\t}\n\t}\n}", "public class TileCampfire extends TileEntity implements ITickable\n{\n\tpublic int burnTime;\n\tpublic int logTime;\n\tpublic int uptime;\n\tpublic boolean tainted;\n\tpublic int syncTimer;\n\t\n public void readFromNBT(NBTTagCompound tag)\n {\n super.readFromNBT(tag);\n burnTime = tag.getInteger(\"burnTime\");\n logTime = tag.getInteger(\"logTime\");\n tainted = tag.getBoolean(\"tainted\");\n }\n \n public void writeToNBT(NBTTagCompound tag)\n {\n super.writeToNBT(tag);\n tag.setInteger(\"burnTime\", burnTime);\n tag.setInteger(\"logTime\", logTime);\n tag.setBoolean(\"tainted\", tainted);\n }\n \n public boolean addLog(ItemStack log)\n {\n \tif(log == null)\n \t\treturn false;\n \t\n \tif(logTime > 0)\n \t\treturn false;\n \t\n \tif(log.getItem() == Item.getItemFromBlock(BlocksTC.log))\n \t{\n \t\tif(log.getItemDamage()%3==0)\n \t\t{\n \t\t\tlogTime = 1600*4;\n \t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(1));\n \t\t\tsyncTimer = 1;\n \t\t\treturn true;\n \t\t}\n \t}\n \t\n \tif(log.getItem() == Item.getItemFromBlock(BlocksTC.taintLog))\n \t{\n \t\tlogTime = 1600*8;\n \t\ttainted = true;\n \t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(1));\n \t\tsyncTimer = 1;\n \t\treturn true;\n \t}\n \t\n \tif(Block.getBlockFromItem(log.getItem()) instanceof BlockLog)\n \t{\n\t\t\tlogTime = 1600;\n\t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(1));\n\t\t\tsyncTimer = 1;\n\t\t\treturn true;\n \t}\n \t\n \tif(OreDictionary.getOreIDs(log).length > 0)\n \t{\n \t\tint[] ints = OreDictionary.getOreIDs(log);\n \t\tboolean isLog = false;\n \t\tfor(int i = 0; i < ints.length; ++i)\n \t\t{\n \t\t\tString str = OreDictionary.getOreName(ints[i]);\n \t\t\tif(str.equals(\"logWood\"))\n \t\t\t{\n \t\t\t\tisLog = true;\n \t\t\t\tbreak;\n \t\t\t}\n \t\t}\n \t\tif(isLog)\n \t\t{\n \t\t\tlogTime = 1600;\n \t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(1));\n \t\t\tsyncTimer = 1;\n \t\t\treturn true;\n \t\t}\n \t}\n \t\n \treturn false;\n }\n \n public boolean addFuel(ItemStack item)\n {\n \tif(item == null)\n \t\treturn false;\n \t\n \tif(logTime <= 0)\n \t\treturn false;\n \t\n \tif(burnTime > 0)\n \t\treturn false;\n \t\n \tint burnTime = TileEntityFurnace.getItemBurnTime(item);\n \t\n \tif(burnTime <= 0)\n \t\treturn false;\n \t\n \tthis.burnTime = burnTime;\n \tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(2));\n \t\n \tsyncTimer = 1;\n \t\n \treturn true;\n }\n \n public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)\n {\n \tboolean b = pkt.getNbtCompound().getBoolean(\"2\");\n \tif(tainted != b)\n \t{\n \t\tthis.worldObj.markBlockRangeForRenderUpdate(getPos().down().west().north(), getPos().up().east().south());\n \t\ttainted = b;\n \t}\n }\n \n public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)\n {\n \treturn oldState.getBlock() == newSate.getBlock() ? false : super.shouldRefresh(world, pos, oldState, newSate);\n }\n \n\t@SuppressWarnings({ \"rawtypes\" })\n\tpublic void update() \n\t{\n\t\tif(syncTimer <= 0)\n\t\t{\n\t\t\tsyncTimer = 100;\n\t\t\tNBTTagCompound tg = new NBTTagCompound();\n\t\t\ttg.setBoolean(\"2\", tainted);\n\t\t\ttg.setInteger(\"x\", this.pos.getX());\n\t\t\ttg.setInteger(\"y\", this.pos.getY());\n\t\t\ttg.setInteger(\"z\", this.pos.getZ());\n\t\t\tMiscUtils.syncTileEntity(tg, 0);\n\t\t}else\n\t\t\t--syncTimer;\n\t\t\n\t\t++uptime;\n\t\t\n\t\tif(burnTime > 0)\n\t\t{\n\t\t\t--burnTime;\n\t\t\t\n\t\t\tif(logTime > 0)\n\t\t\t\t--logTime;\n\t\t}\n\t\t\n\t\tif(!this.worldObj.isRemote)\n\t\t{\n\t\t\tif(burnTime <= 0)\n\t\t\t{\n\t\t\t\tint metadata = BlockStateMetadata.getBlockMetadata(worldObj, getPos());\n\t\t\t\tif(metadata == 2)\n\t\t\t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(1));\n\t\t\t\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif(logTime <= 0)\n\t\t\t{\n\t\t\t\tint metadata = BlockStateMetadata.getBlockMetadata(worldObj, getPos());\n\t\t\t\tif(metadata > 0)\n\t\t\t\t\tthis.worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos()).getBlock().getStateFromMeta(0));\n\t\t\t\ttainted = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t\n\t\tif(!this.worldObj.isRemote)\n\t\t{\n\t\t\tList<EntityLivingBase> creatures = this.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX()+1, pos.getY()+1, pos.getZ()+1).expand(12, 6, 12));\n\t\t\t\n\t\t\tfor(EntityLivingBase elb : creatures)\n\t\t\t{\n\t\t\t\tif(this.tainted && this.worldObj.rand.nextDouble() < 0.003D)\n\t\t\t\t\telb.addPotionEffect(new PotionEffect(PotionFluxTaint.instance.getId(),200,0,true,false));\n\t\t\t\t\n\t\t\t\tif(!(elb instanceof EntityCreature))\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tEntityCreature c = EntityCreature.class.cast(elb);\n\t\t\t\t\n\t\t\t\tif(!(c instanceof IMob))\n\t\t\t\t\tcontinue;\n\n\t\t\t ArrayList entries = (ArrayList) c.tasks.taskEntries;\n\t\t\t \n\t\t\t EntityAIAvoidCampfire campfireAviodable = null;\n\t\t\t \n\t\t\t boolean hasTask = false;\n\t\t\t for (int i = 0; i < entries.size(); ++i)\n\t\t\t {\n\t\t\t \t EntityAITasks.EntityAITaskEntry task = (EntityAITaskEntry) entries.get(i);\n\t\t\t \t if ((task.action instanceof EntityAIAvoidCampfire)) \n\t\t\t \t {\n\t\t\t \t\t campfireAviodable = (EntityAIAvoidCampfire) task.action;\n\t\t\t \t\t hasTask = true;\n\t\t\t \t\t break;\n\t\t\t \t }\n\t\t\t }\n\t\t\t if(campfireAviodable == null)\n\t\t\t \t campfireAviodable = new EntityAIAvoidCampfire(c);\n\t\t\t \n\t\t\t campfireAviodable.isScared = true;\n\t\t\t campfireAviodable.scareTimer = 100;\n\t\t\t campfireAviodable.campfireX = pos.getX();\n\t\t\t campfireAviodable.campfireY = pos.getY();\n\t\t\t campfireAviodable.campfireZ = pos.getZ();\n\t\t\t \n\t\t\t if(!hasTask)\n\t\t\t \t c.tasks.addTask(1, campfireAviodable);\n\t\t\t}\n\t\t}\n\t}\n}", "public class TileNodeManipulator extends TileEntity implements ITickable{\n\tpublic int workTime = 0;\n\tpublic EntityAuraNode node = null;\n\tpublic boolean firstTick = true;\n\tpublic int ticksExisted;\n\tObject beam;\n\t\n public void readFromNBT(NBTTagCompound tag)\n {\n super.readFromNBT(tag);\n workTime = tag.getInteger(\"workTime\");\n }\n\t\n public void writeToNBT(NBTTagCompound tag)\n {\n super.writeToNBT(tag);\n tag.setInteger(\"workTime\", workTime);\n }\n\t\n\t@Override\n\tpublic void update(){\n\t\t++ticksExisted;\n\t\tif(ticksExisted % 20 == 0)\n\t\t\tbeam = null;\n\t\tif((firstTick || ticksExisted % 20 == 0) && node == null)\n\t\t{\n\t\t\tList<Entity> nodes = TBUtils.castLst(this.worldObj.getEntitiesWithinAABB(EntityAuraNode.class, AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX(), pos.getY(), pos.getZ()).expand(3, 3, 3)));\n\t\t\tif(!nodes.isEmpty())\n\t\t\t\tnode = (EntityAuraNode) MiscUtils.getClosestEntity(nodes, pos.getX(), pos.getY(), pos.getZ());\n\t\t}\n\t\t\n\t\tif(node != null && (node.isDead || MathHelper.sqrt_double(node.getDistanceSq(getPos())) > 3))\n\t\t\tnode = null;\n\t\t\n\t\tif(node != null)\n\t\t{\n\t\t\tint meta = BlockStateMetadata.getBlockMetadata(worldObj, getPos());\n\t\t\tEnumEffect ee = EnumEffect.fromMetadata(meta);\n\t\t\tNodeType nt = NodeType.nodeTypes[node.getNodeType()];\n\t\t\tswitch(ee)\n\t\t\t{\n\t\t\t\tcase BRIGHTEN:\n\t\t\t\t{\n\t\t\t\t\tif(nt instanceof NTNormal)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(workTime > 20*60*20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\tnode.setNodeType(6);\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t++workTime;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase DESTRUCT:\n\t\t\t\t{\n\t\t\t\t\tint maxTimeRequired = nt instanceof NTAstral ? 1*60*20 : 2*60*20;\n\t\t\t\t\tif(workTime >= maxTimeRequired)\n\t\t\t\t\t{\n\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\tif(!(nt instanceof NTAstral))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnode.setDead();\n\t\t\t\t\t\t\tnode = null;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnode.setNodeType(0);\n\t\t\t\t\t\t\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\t++workTime;\n\t\t\t\t\t\tif(ticksExisted % 10 == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAspect asp = node.getAspect();\n\t\t\t\t\t\t\tAspectList al = AspectHelper.reduceToPrimals(new AspectList().add(asp,1));\n\t\t\t\t\t\t\tAspect a = al.getAspects()[this.worldObj.rand.nextInt(al.size())];\n\t\t\t\t\t\t\tEntityAspectOrb aspect = new EntityAspectOrb(worldObj, node.posX,node.posY,node.posZ, a, 1);\n\t\t\t\t\t\t\tif(!this.worldObj.isRemote)\n\t\t\t\t\t\t\t\tthis.worldObj.spawnEntityInWorld(aspect);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase EFFICIENCY:\n\t\t\t\t{\n\t\t\t\t\tif(this.worldObj.rand.nextDouble() < 0.05D)\n\t\t\t\t\t{\n\t\t\t\t\t\tAspect asp = node.getAspect();\n\t\t\t\t\t\tAspectList al = AspectHelper.reduceToPrimals(new AspectList().add(asp,1));\n\t\t\t\t\t\tAspect a = al.getAspects()[this.worldObj.rand.nextInt(al.size())];\n\t\t\t\t\t\tAuraHelper.addAura(getWorld(), node.getPosition(), a, 1+this.worldObj.rand.nextInt(5));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase HUNGER:\n\t\t\t\t{\n\t\t\t\t\tif(nt instanceof NTNormal)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(workTime > 5*60*20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\tnode.setNodeType(2);\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t++workTime;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase INSTABILITY:\n\t\t\t\t{\n\t\t\t\t\tif(nt instanceof NTNormal)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(workTime > 7*60*20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\tnode.setNodeType(5);\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t++workTime;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase PURITY:\n\t\t\t\t{\n\t\t\t\t\tif(nt instanceof NTNormal)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(workTime > 3*60*20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\tnode.setNodeType(3);\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t++workTime;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase SINISTER:\n\t\t\t\t{\n\t\t\t\t\tif(nt instanceof NTNormal)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(workTime > 6*60*20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\tnode.setNodeType(1);\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t++workTime;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase SPEED:\n\t\t\t\t{\n\t\t\t\t\tfor(int i = 0; i < 4; ++i)\n\t\t\t\t\t\tnode.onEntityUpdate();\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase STABILITY:\n\t\t\t\t{\n\t\t\t\t\tint maxTimeRequired = 0;\n\t\t\t\t\t\n\t\t\t\t\tif(nt instanceof NTDark)\n\t\t\t\t\t\tmaxTimeRequired = 2*60*20;\n\t\t\t\t\t\n\t\t\t\t\tif(nt instanceof NTHungry)\n\t\t\t\t\t\tmaxTimeRequired = 30*20;\n\t\t\t\t\t\n\t\t\t\t\tif(nt instanceof NTUnstable)\n\t\t\t\t\t\tmaxTimeRequired = 7*60*20;\n\t\t\t\t\t\n\t\t\t\t\tif(nt instanceof NTTaint)\n\t\t\t\t\t\tmaxTimeRequired = 3*60*20;\n\t\t\t\t\t\n\t\t\t\t\tif(nt instanceof NTAstral)\n\t\t\t\t\t\tmaxTimeRequired = 60*20;\n\t\t\t\t\t\n\t\t\t\t\tif(workTime >= maxTimeRequired)\n\t\t\t\t\t{\n\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(nt instanceof NTDark || nt instanceof NTUnstable || nt instanceof NTHungry || nt instanceof NTTaint || nt instanceof NTAstral)\n\t\t\t\t\t\t\tnode.setNodeType(0);\n\t\t\t\t\t}else\n\t\t\t\t\t\t++workTime;\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcase TAINT:\n\t\t\t\t{\n\t\t\t\t\tif(nt instanceof NTNormal)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(workTime > 6*60*20)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tworkTime = 0;\n\t\t\t\t\t\t\tnode.setNodeType(4);\n\t\t\t\t\t\t}else\n\t\t\t\t\t\t\t++workTime;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\n\t\t\t\tcase NONE:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif(!firstTick && this.worldObj.isRemote && ee != EnumEffect.NONE)\n\t\t\t\tbeam = Thaumcraft.proxy.getFX().beamBore(node.posX, node.posY, node.posZ, pos.getX()+0.5D, pos.getY()+0.5D, pos.getZ()+0.5D, 2, ee.getColor(), true, 0.5F, beam, 1);\n\t\t\n\t\t}\n\t\t\n\t\tif(firstTick)\n\t\t\tfirstTick = false;\n\t}\n\t\n public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)\n {\n \treturn oldState.getBlock() == newSate.getBlock() ? false : super.shouldRefresh(world, pos, oldState, newSate);\n }\n\t\n public enum EnumEffect\n {\n \tNONE, //Do nothing\n \tBRIGHTEN, //Turn into etherial\n \tDESTRUCT, //Destroy aspects and node, but create tons of aspect orbs\n \tEFFICIENCY, //Recharge aura with current aspect faster\n \tHUNGER, //Turn into Hungry\n \tINSTABILITY, //Turn into unstable\n \tPURITY, //Turn into pure\n \tSINISTER, //Turn into sinister\n \tSPEED, //+4 additional ticks each tick\n \tSTABILITY, //Turn onto normal\n \tTAINT; //Turn into tainted\n \t\n \tpublic static EnumEffect fromMetadata(int meta)\n \t{\n \t\treturn EnumEffect.values()[Math.min(EnumEffect.values().length-1, meta)];\n \t}\n \t\n \tpublic int getColor()\n \t{\n \t\treturn colors[ordinal()];\n \t}\n \t\n \tprivate static final int[] colors = new int[]{\n \t\t0xffffff,\n \t\t0xffffff,\n \t\t0x4e4756,\n \t\t0xd2d200,\n \t\t0xaf7c23,\n \t\t0x0b4d42,\n \t\t0xccc8f7,\n \t\t0x643c5b,\n \t\t0xeaeaea,\n \t\t0xd0e0f8,\n \t\t0x713496\n \t};\n }\n}", "public class TileOverchanter extends TileEntity implements IInventory, IWandable,ITickable{\n\n\tpublic ItemStack inventory;\n\t\n\tpublic int enchantingTime;\n\tpublic boolean xpAbsorbed;\n\tpublic boolean isEnchantingStarted;\n\tpublic int syncTimer;\n\tint ticksExisted;\n\t\n\tpublic Lightning renderedLightning;\n\t\n\t@Override\n\tpublic int getSizeInventory() {\n\t\treturn 1;\n\t}\n\t\n\tpublic void update() \n\t{\n\t\t++ticksExisted;\n\t\tif(syncTimer <= 0)\n\t\t{\n\t\t\tsyncTimer = 100;\n\t\t\tNBTTagCompound tg = new NBTTagCompound();\n\t\t\ttg.setInteger(\"0\", enchantingTime);\n\t\t\ttg.setBoolean(\"1\", xpAbsorbed);\n\t\t\ttg.setBoolean(\"2\", isEnchantingStarted);\n\t\t\ttg.setInteger(\"x\", this.pos.getX());\n\t\t\ttg.setInteger(\"y\", this.pos.getY());\n\t\t\ttg.setInteger(\"z\", this.pos.getZ());\n\t\t\tMiscUtils.syncTileEntity(tg, 0);\n\t\t}else\n\t\t\t--syncTimer;\n\t\t\n\t\tif(this.inventory == null)\n\t\t{\n\t\t\tisEnchantingStarted = false;\n\t\t\txpAbsorbed = false;\n\t\t\tenchantingTime = 0;\n\t\t\trenderedLightning = null;\n\t\t}else\n {\n \tif(this.isEnchantingStarted)\n \t{\n \t\tif(ticksExisted % 20 == 0)\n \t\t{\n \t\t\trenderedLightning = new Lightning(this.worldObj.rand, new Coord3D(0,0,0), new Coord3D(MathUtils.randomDouble(this.worldObj.rand)/50,MathUtils.randomDouble(this.worldObj.rand)/50,MathUtils.randomDouble(this.worldObj.rand)/50), 0.3F, 1,0,1);\n \t\t\tthis.worldObj.playSoundEffect(pos.getX(), pos.getY(), pos.getZ(), \"thaumcraft:infuserstart\", 1F, 1.0F);\n\t \t\tif(EssentiaHandler.drainEssentia(this, Aspect.ENERGY, null, 8, false, 8))\n\t \t\t{\n\t \t\t\t++enchantingTime;\n\t \t\t\tif(enchantingTime >= 16 && !this.xpAbsorbed)\n\t \t\t\t{\n\t \t\t\t\tList<EntityPlayer> players = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.fromBounds(pos.getX(), pos.getY(), pos.getZ(), pos.getX()+1, pos.getY()+1, pos.getZ()+1).expand(6, 3, 6));\n\t \t\t\t\tif(!players.isEmpty())\n\t \t\t\t\t{\n\t \t\t\t\t\tfor(int i = 0; i < players.size(); ++i)\n\t \t\t\t\t\t{\n\t \t\t\t\t\t\tEntityPlayer p = players.get(i);\n\t \t\t\t\t\t\tif(p.experienceLevel >= 30)\n\t \t\t\t\t\t\t{\n\t \t\t\t\t\t\t\tp.attackEntityFrom(DamageSource.magic, 8);\n\t \t\t\t\t\t\t\tthis.worldObj.playSoundEffect(p.posX,p.posY,p.posZ, \"thaumcraft:zap\", 1F, 1.0F);\n\t \t\t\t\t\t\t\tp.experienceLevel -= 30;\n\t \t\t\t\t\t\t\txpAbsorbed = true;\n\t \t\t\t\t\t\t\tbreak;\n\t \t\t\t\t\t\t}\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t}\n\t \t\t\t\n\t \t\t\tif(xpAbsorbed && enchantingTime >= 32)\n\t \t\t\t{\n\t \t\t\t\tint enchId = this.findEnchantment(inventory);\n\t \t\t\t\tNBTTagList nbttaglist = this.inventory.getEnchantmentTagList();\n\t \t\t\t\tfor(int i = 0; i < nbttaglist.tagCount(); ++i)\n\t \t\t\t\t{\n\t \t\t\t\t\tNBTTagCompound tag = nbttaglist.getCompoundTagAt(i);\n\t \t\t\t\t\tif(tag != null && Integer.valueOf(tag.getShort(\"id\"))==enchId)\n\t \t\t\t\t\t{\n\t \t\t\t\t\t\ttag.setShort(\"lvl\", (short) (Integer.valueOf(tag.getShort(\"lvl\"))+1));\n\t \t\t\t\t\t\tNBTTagCompound stackTag = MiscUtils.getStackTag(inventory);\n\t \t\t\t\t\t\tif(!stackTag.hasKey(\"overchants\"))\n\t \t\t\t\t\t\t{\n\t \t\t\t\t\t\t\tstackTag.setIntArray(\"overchants\", new int[]{enchId});\n\t \t\t\t\t\t\t}else\n\t \t\t\t\t\t\t{\n\t \t\t\t\t\t\t\tint[] arrayInt = stackTag.getIntArray(\"overchants\");\n\t \t\t\t\t\t\t\tint[] newArrayInt = new int[arrayInt.length+1];\n\t \t\t\t\t\t\t\tfor(int j = 0; j < arrayInt.length; ++j)\n\t \t\t\t\t\t\t\t{\n\t \t\t\t\t\t\t\t\tnewArrayInt[j] = arrayInt[j];\n\t \t\t\t\t\t\t\t}\n\t \t\t\t\t\t\t\tnewArrayInt[newArrayInt.length-1]=enchId;\n\t \t\t\t\t\t\t\t\n\t \t\t\t\t\t\t\tstackTag.setIntArray(\"overchants\", newArrayInt);\n\t \t\t\t\t\t\t}\n\t \t\t\t\t\t\tbreak;\n\t \t\t\t\t\t}\n\t \t\t\t\t}\n\t \t\t\t\tisEnchantingStarted = false;\n\t \t\t\t\txpAbsorbed = false;\n\t \t\t\t\tenchantingTime = 0;\n\t \t\t\t\trenderedLightning = null;\n\t \t\t\t\tthis.worldObj.playSoundEffect(pos.getX(), pos.getY(), pos.getZ(), \"thaumcraft:wand\", 1F, 1F);\n\t \t\t\t}\n\t \t\t\t\n\t \t\t}else\n\t \t\t{\n\t \t\t\t--enchantingTime;\n\t \t\t}\n \t\t}\n \t}\n }\n\t}\n\t\n\tpublic boolean canStartEnchanting()\n\t{\n\t\tif(!this.isEnchantingStarted)\n\t\t\tif(this.inventory != null)\n\t\t\t{\n\t\t\t\tif(this.inventory.getEnchantmentTagList() != null && this.inventory.getEnchantmentTagList().tagCount() > 0)\n\t\t\t\t{\n\t\t\t\t\tif(findEnchantment(inventory) != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic int findEnchantment(ItemStack enchanted)\n\t{\n\t\tNBTTagCompound stackTag = MiscUtils.getStackTag(inventory);\n\t\tLinkedHashMap<Integer,Integer> ench = (LinkedHashMap<Integer, Integer>) EnchantmentHelper.getEnchantments(enchanted);\n\t\tSet<Integer> keys = ench.keySet();\n\t\tIterator<Integer> $i = keys.iterator();\n\t\t\n\t\twhile($i.hasNext())\n\t\t{\n\t\t\tint i = $i.next();\n\t\t\tif(!stackTag.hasKey(\"overchants\"))\n\t\t\t{\n\t\t\t\treturn i;\n\t\t\t}\n\t\t\tint[] overchants = stackTag.getIntArray(\"overchants\");\n\t\t\tif(MathUtils.arrayContains(overchants, i))\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\treturn i;\n\t\t}\n\t\t\n\t\treturn -1;\n\t}\n\t\n public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)\n {\n \tenchantingTime = pkt.getNbtCompound().getInteger(\"0\");\n \txpAbsorbed = pkt.getNbtCompound().getBoolean(\"1\");\n \tisEnchantingStarted = pkt.getNbtCompound().getBoolean(\"2\");\n }\n\n\t@Override\n\tpublic ItemStack getStackInSlot(int slot) {\n\t\treturn inventory;\n\t}\n\n\t@Override\n\tpublic ItemStack decrStackSize(int slot, int num) {\n if (this.inventory != null)\n {\n ItemStack itemstack;\n\n if (this.inventory.stackSize <= num)\n {\n itemstack = this.inventory;\n this.inventory = null;\n this.markDirty();\n return itemstack;\n }\n\t\t\titemstack = this.inventory.splitStack(num);\n\n\t\t\tif (this.inventory.stackSize == 0)\n\t\t\t{\n\t\t\t this.inventory = null;\n\t\t\t}\n\n\t\t\tthis.markDirty();\n\t\t\treturn itemstack;\n }\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setInventorySlotContents(int slot, ItemStack stk) {\n\t\tinventory = stk;\n\t}\n\n\t@Override\n\tpublic int getInventoryStackLimit() {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic boolean isUseableByPlayer(EntityPlayer player) {\n\t\treturn player.dimension == this.worldObj.provider.getDimensionId() && !this.worldObj.isAirBlock(pos);\n\t}\n\n\t@Override\n\tpublic boolean isItemValidForSlot(int slot, ItemStack stk) {\n\t\treturn stk.hasTagCompound() && stk.getEnchantmentTagList() != null;\n\t}\n\t\n public void readFromNBT(NBTTagCompound tag)\n {\n super.readFromNBT(tag);\n \n enchantingTime = tag.getInteger(\"enchTime\");\n xpAbsorbed = tag.getBoolean(\"xpAbsorbed\");\n isEnchantingStarted = tag.getBoolean(\"enchStarted\");\n \n if(tag.hasKey(\"itm\"))\n \tinventory = ItemStack.loadItemStackFromNBT(tag.getCompoundTag(\"itm\"));\n }\n \n public void writeToNBT(NBTTagCompound tag)\n {\n super.writeToNBT(tag);\n \n tag.setInteger(\"enchTime\", enchantingTime);\n tag.setBoolean(\"xpAbsorbed\",xpAbsorbed);\n tag.setBoolean(\"enchStarted\", isEnchantingStarted);\n \n if(inventory != null)\n {\n \tNBTTagCompound t = new NBTTagCompound();\n \tinventory.writeToNBT(t);\n \ttag.setTag(\"itm\", t);\n }\n }\n \n\n\t@Override\n\tpublic boolean onWandRightClick(World paramWorld, ItemStack paramItemStack, EntityPlayer paramEntityPlayer, BlockPos paramBlockPos, EnumFacing paramEnumFacing)\n\t{\n\t\tif(canStartEnchanting())\n\t\t{\n\t\t\tisEnchantingStarted = true;\n\t\t\tparamEntityPlayer.swingItem();\n\t\t\tsyncTimer = 0;\n\t\t\tthis.worldObj.playSoundEffect(pos.getX(), pos.getY(), pos.getZ(), \"thaumcraft:craftstart\", 0.5F, 1.0F);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void onUsingWandTick(ItemStack wandstack, EntityPlayer player,\n\t\t\tint count) {\n\t}\n\n\t@Override\n\tpublic void onWandStoppedUsing(ItemStack wandstack, World world,\n\t\t\tEntityPlayer player, int count) {\n\t}\n\n\t@Override\n\tpublic String getName() {\n\t\treturn \"tb.overchanter\";\n\t}\n\n\t@Override\n\tpublic boolean hasCustomName() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic IChatComponent getDisplayName() {\n\t\treturn new ChatComponentText(getName());\n\t}\n\n\t@Override\n\tpublic void openInventory(EntityPlayer player) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void closeInventory(EntityPlayer player) {\n\t\t\n\t}\n\n\t@Override\n\tpublic int getField(int id) {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void setField(int id, int value) {\n\t\t\n\t}\n\n\t@Override\n\tpublic int getFieldCount() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tinventory = null;\n\t}\n\n\t@Override\n\tpublic ItemStack removeStackFromSlot(int index) {\n\t\treturn inventory;\n\t}\n\n\n}" ]
import net.minecraftforge.fml.common.registry.GameRegistry; import tb.common.tile.TileAuraLinker; import tb.common.tile.TileBraizer; import tb.common.tile.TileCampfire; import tb.common.tile.TileNodeManipulator; import tb.common.tile.TileOverchanter;
package tb.init; public class TBTiles { public static void setup() { GameRegistry.registerTileEntity(TileOverchanter.class, "tb.overchanter"); GameRegistry.registerTileEntity(TileCampfire.class, "tb.campfire");
GameRegistry.registerTileEntity(TileBraizer.class, "tb.brazier");
1
tavianator/sangria
sangria-listbinder/src/main/java/com/tavianator/sangria/listbinder/ListBinder.java
[ "public abstract class PotentialAnnotation {\n /**\n * A visitor interface to examine a {@link PotentialAnnotation}'s annotation, if it exists.\n *\n * @param <T> The type to return.\n * @author Tavian Barnes ([email protected])\n * @version 1.1\n * @since 1.1\n */\n public interface Visitor<T> {\n /**\n * Called when there is no annotation.\n *\n * @return Any value.\n */\n T visitNoAnnotation();\n\n /**\n * Called when an annotation type is stored.\n *\n * @param annotationType The annotation type.\n * @return Any value.\n */\n T visitAnnotationType(Class<? extends Annotation> annotationType);\n\n /**\n * Called when an annotation instance is stored.\n *\n * @param annotation The annotation instance.\n * @return Any value.\n */\n T visitAnnotationInstance(Annotation annotation);\n }\n\n private static final PotentialAnnotation NONE = new NoAnnotation();\n\n /**\n * @return A {@link PotentialAnnotation} with no annotation.\n */\n public static PotentialAnnotation none() {\n return NONE;\n }\n\n /**\n * Extract the annotation from a {@link Key}.\n *\n * @param key The {@link Key} whose annotation to use, if any.\n * @return A {@link PotentialAnnotation} with the annotation from {@code key}.\n * @since 1.2\n */\n public static PotentialAnnotation from(Key<?> key) {\n Annotation instance = key.getAnnotation();\n if (instance != null) {\n return none().annotatedWith(instance);\n }\n\n Class<? extends Annotation> type = key.getAnnotationType();\n if (type != null) {\n return none().annotatedWith(type);\n }\n\n return none();\n }\n\n private PotentialAnnotation() {\n }\n\n /**\n * Add an annotation.\n *\n * @param annotationType The annotation type to add.\n * @return A new {@link PotentialAnnotation} associated with the given annotation type.\n * @throws CreationException If an annotation is already present.\n */\n public PotentialAnnotation annotatedWith(Class<? extends Annotation> annotationType) {\n throw annotationAlreadyPresent();\n }\n\n /**\n * Add an annotation.\n *\n * @param annotation The annotation instance to add.\n * @return A new {@link PotentialAnnotation} associated with the given annotation instance.\n * @throws CreationException If an annotation is already present.\n */\n public PotentialAnnotation annotatedWith(Annotation annotation) {\n throw annotationAlreadyPresent();\n }\n\n private CreationException annotationAlreadyPresent() {\n Message message = new Message(\"An annotation was already present\");\n return new CreationException(Collections.singletonList(message));\n }\n\n /**\n * @return Whether an annotation is present.\n */\n public abstract boolean hasAnnotation();\n\n /**\n * Create a {@link Key} with the given type and the stored annotation.\n *\n * @param type The type of the key to create.\n * @param <T> The type of the key to create.\n * @return A {@link Key}.\n */\n public <T> Key<T> getKey(Class<T> type) {\n return getKey(TypeLiteral.get(type));\n }\n\n /**\n * Create a {@link Key} with the given type and the stored annotation.\n *\n * @param type The type of the key to create.\n * @param <T> The type of the key to create.\n * @return A {@link Key}.\n */\n public abstract <T> Key<T> getKey(TypeLiteral<T> type);\n\n /**\n * Accept a {@link Visitor}.\n *\n * @param visitor The visitor to accept.\n * @param <T> The type for the visitor to return.\n * @return The value produced by the visitor.\n */\n public abstract <T> T accept(Visitor<T> visitor);\n\n @Override\n public abstract boolean equals(Object o);\n\n @Override\n public abstract int hashCode();\n\n @Override\n public abstract String toString();\n\n /**\n * Implementation of {@link #none()}.\n */\n private static class NoAnnotation extends PotentialAnnotation {\n @Override\n public PotentialAnnotation annotatedWith(Class<? extends Annotation> annotationType) {\n return new AnnotationType(annotationType);\n }\n\n @Override\n public PotentialAnnotation annotatedWith(Annotation annotation) {\n return new AnnotationInstance(annotation);\n }\n\n @Override\n public boolean hasAnnotation() {\n return false;\n }\n\n @Override\n public <T> Key<T> getKey(TypeLiteral<T> type) {\n return Key.get(type);\n }\n\n @Override\n public <T> T accept(Visitor<T> visitor) {\n return visitor.visitNoAnnotation();\n }\n\n @Override\n public boolean equals(Object o) {\n return o == this || o instanceof NoAnnotation;\n }\n\n @Override\n public int hashCode() {\n return NoAnnotation.class.hashCode();\n }\n\n @Override\n public String toString() {\n return \"[no annotation]\";\n }\n }\n\n /**\n * Implementation of {@link #annotatedWith(Class)}.\n */\n private static class AnnotationType extends PotentialAnnotation {\n private final Class<? extends Annotation> annotationType;\n\n AnnotationType(Class<? extends Annotation> annotationType) {\n this.annotationType = annotationType;\n }\n\n @Override\n public boolean hasAnnotation() {\n return true;\n }\n\n @Override\n public <T> Key<T> getKey(TypeLiteral<T> type) {\n return Key.get(type, annotationType);\n }\n\n @Override\n public <T> T accept(Visitor<T> visitor) {\n return visitor.visitAnnotationType(annotationType);\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n } else if (!(o instanceof AnnotationType)) {\n return false;\n }\n\n AnnotationType other = (AnnotationType)o;\n return annotationType.equals(other.annotationType);\n }\n\n @Override\n public int hashCode() {\n return annotationType.hashCode();\n }\n\n @Override\n public String toString() {\n return \"@\" + annotationType.getCanonicalName();\n }\n }\n\n /**\n * Implementation of {@link #annotatedWith(Annotation)}.\n */\n private static class AnnotationInstance extends PotentialAnnotation {\n private final Annotation annotation;\n\n AnnotationInstance(Annotation annotation) {\n this.annotation = annotation;\n }\n\n @Override\n public boolean hasAnnotation() {\n return true;\n }\n\n @Override\n public <T> Key<T> getKey(TypeLiteral<T> type) {\n return Key.get(type, annotation);\n }\n\n @Override\n public <T> T accept(Visitor<T> visitor) {\n return visitor.visitAnnotationInstance(annotation);\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n } else if (!(o instanceof AnnotationInstance)) {\n return false;\n }\n\n AnnotationInstance other = (AnnotationInstance)o;\n return annotation.equals(other.annotation);\n }\n\n @Override\n public int hashCode() {\n return annotation.hashCode();\n }\n\n @Override\n public String toString() {\n return annotation.toString();\n }\n }\n}", "public class PrettyTypes {\n private PrettyTypes() {\n // Not for instantiating\n }\n\n /**\n * Format a message.\n *\n * @param message The format string.\n * @param args The format arguments, possibly containing {@link Class} or {@link Key} instances to be\n * pretty-printed.\n * @return A formatted message.\n * @see String#format(String, Object...)\n */\n public static String format(String message, Object... args) {\n // This is like Guice's internal Errors.format()\n Object[] prettyArgs = new Object[args.length];\n for (int i = 0; i < args.length; ++i) {\n Object arg = args[i];\n Object prettyArg;\n\n if (arg instanceof Class) {\n prettyArg = format((Class<?>)arg);\n } else if (arg instanceof Key) {\n prettyArg = format((Key<?>)arg);\n } else {\n prettyArg = arg;\n }\n\n prettyArgs[i] = prettyArg;\n }\n\n return String.format(message, prettyArgs);\n }\n\n private static String format(Class<?> type) {\n return type.getCanonicalName();\n }\n\n private static String format(Key<?> key) {\n StringBuilder builder = new StringBuilder(key.getTypeLiteral().toString());\n PotentialAnnotation annotation = PotentialAnnotation.from(key);\n if (annotation.hasAnnotation()) {\n builder.append(\" annotated with \")\n .append(annotation);\n }\n return builder.toString();\n }\n}", "public class Priority implements Comparable<Priority> {\n private static final Priority DEFAULT = new Priority(new int[0], 0);\n private static final Comparator<int[]> COMPARATOR = Ints.lexicographicalComparator();\n\n private final int[] weights;\n private final int seq;\n\n /**\n * @return The default priority, which comes before all other priorities.\n */\n public static Priority getDefault() {\n return DEFAULT;\n }\n\n /**\n * Create a {@link Priority} with the given sequence.\n *\n * @param weight The first value of the weight sequence.\n * @param weights An integer sequence. These sequences are sorted lexicographically, so {@code Priority.create(1)}\n * sorts before {@code Priority.create(1, 1)}, which sorts before {@code Priority.create(2)}.\n * @return A new {@link Priority}.\n */\n public static Priority create(int weight, int... weights) {\n int[] newWeights = new int[weights.length + 1];\n newWeights[0] = weight;\n System.arraycopy(weights, 0, newWeights, 1, weights.length);\n return new Priority(newWeights, 0);\n }\n\n private Priority(int[] weights, int seq) {\n this.weights = weights;\n this.seq = seq;\n }\n\n /**\n * @return Whether this priority originated in a call to {@link #getDefault()}.\n */\n public boolean isDefault() {\n return weights.length == 0;\n }\n\n /**\n * @return A new {@link Priority} which immediately follows this one, and which is distinct from all other\n * priorities obtained by {@link #create(int, int...)}.\n */\n public Priority next() {\n return new Priority(weights, seq + 1);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n } else if (!(obj instanceof Priority)) {\n return false;\n }\n\n Priority other = (Priority)obj;\n return Arrays.equals(weights, other.weights)\n && seq == other.seq;\n }\n\n @Override\n public int hashCode() {\n return Arrays.hashCode(weights) + seq;\n }\n\n @Override\n public int compareTo(Priority o) {\n return ComparisonChain.start()\n .compare(weights, o.weights, COMPARATOR)\n .compare(seq, o.seq)\n .result();\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n if (weights.length == 0) {\n builder.append(\"default priority\");\n } else {\n builder.append(\"priority [\");\n for (int i = 0; i < weights.length; ++i) {\n if (i != 0) {\n builder.append(\", \");\n }\n builder.append(weights[i]);\n }\n builder.append(\"]\");\n }\n if (seq != 0) {\n builder.append(\" + \")\n .append(seq);\n }\n return builder.toString();\n }\n}", "public class TypeLiterals {\n private TypeLiterals() {\n // Not for instantiating\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> TypeLiteral<List<T>> listOf(Class<T> type) {\n return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> TypeLiteral<List<T>> listOf(TypeLiteral<T> type) {\n return (TypeLiteral<List<T>>)TypeLiteral.get(Types.listOf(type.getType()));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> TypeLiteral<Set<T>> setOf(Class<T> type) {\n return (TypeLiteral<Set<T>>)TypeLiteral.get(Types.setOf(type));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> TypeLiteral<Set<T>> setOf(TypeLiteral<T> type) {\n return (TypeLiteral<Set<T>>)TypeLiteral.get(Types.setOf(type.getType()));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) {\n return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType, valueType));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <K, V> TypeLiteral<Map<K, V>> mapOf(Class<K> keyType, TypeLiteral<V> valueType) {\n return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType, valueType.getType()));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <K, V> TypeLiteral<Map<K, V>> mapOf(TypeLiteral<K> keyType, Class<V> valueType) {\n return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType.getType(), valueType));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <K, V> TypeLiteral<Map<K, V>> mapOf(TypeLiteral<K> keyType, TypeLiteral<V> valueType) {\n return (TypeLiteral<Map<K, V>>)TypeLiteral.get(Types.mapOf(keyType.getType(), valueType.getType()));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> TypeLiteral<Provider<T>> providerOf(Class<T> type) {\n // Can't use Types.providerOf() because we want to stick to JSR-330 Providers\n return (TypeLiteral<Provider<T>>)TypeLiteral.get(Types.newParameterizedType(Provider.class, type));\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> TypeLiteral<Provider<T>> providerOf(TypeLiteral<T> type) {\n // Can't use Types.providerOf() because we want to stick to JSR-330 Providers\n return (TypeLiteral<Provider<T>>)TypeLiteral.get(Types.newParameterizedType(Provider.class, type.getType()));\n }\n}", "public class UniqueAnnotations {\n private static final AtomicLong SEQUENCE = new AtomicLong();\n\n private UniqueAnnotations() {\n // Not for instantiating\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Qualifier\n @VisibleForTesting\n @interface UniqueAnnotation {\n long value();\n }\n\n /**\n * Actual implementation of {@link UniqueAnnotation}.\n */\n @SuppressWarnings(\"ClassExplicitlyAnnotation\")\n private static class UniqueAnnotationImpl implements UniqueAnnotation {\n private final long value;\n\n UniqueAnnotationImpl(long value) {\n this.value = value;\n }\n\n @Override\n public long value() {\n return value;\n }\n\n public Class<? extends Annotation> annotationType() {\n return UniqueAnnotation.class;\n }\n\n @Override\n public String toString() {\n return \"@\" + UniqueAnnotation.class.getName() + \"(value=\" + value + \")\";\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n } else if (!(obj instanceof UniqueAnnotation)) {\n return false;\n }\n\n UniqueAnnotation other = (UniqueAnnotation)obj;\n return value == other.value();\n }\n\n @Override\n public int hashCode() {\n return (127*\"value\".hashCode()) ^ Long.valueOf(value).hashCode();\n }\n }\n\n /**\n * @return An {@link Annotation} that will be unequal to every other annotation.\n */\n public static Annotation create() {\n return create(SEQUENCE.getAndIncrement());\n }\n\n @VisibleForTesting\n static Annotation create(long value) {\n return new UniqueAnnotationImpl(value);\n }\n}" ]
import java.lang.annotation.Annotation; import java.util.*; import javax.inject.Inject; import javax.inject.Provider; import com.google.common.base.Function; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.FluentIterable; import com.google.common.collect.ListMultimap; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.CreationException; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.multibindings.Multibinder; import com.google.inject.spi.Message; import com.google.inject.util.Types; import com.tavianator.sangria.core.PotentialAnnotation; import com.tavianator.sangria.core.PrettyTypes; import com.tavianator.sangria.core.Priority; import com.tavianator.sangria.core.TypeLiterals; import com.tavianator.sangria.core.UniqueAnnotations;
/**************************************************************************** * Sangria * * Copyright (C) 2014 Tavian Barnes <[email protected]> * * * * 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 com.tavianator.sangria.listbinder; /** * A multi-binder with guaranteed order. * * <p> * {@link ListBinder} is much like {@link Multibinder}, except it provides a guaranteed iteration order, and binds a * {@link List} instead of a {@link Set}. For example: * </p> * * <pre> * ListBinder&lt;String&gt; listBinder = ListBinder.build(binder(), String.class) * .withDefaultPriority(); * listBinder.addBinding().toInstance("a"); * listBinder.addBinding().toInstance("b"); * </pre> * * <p> * This will create a binding for a {@code List<String>}, which contains {@code "a"} followed by {@code "b"}. It also * creates a binding for {@code List<Provider<String>>} &mdash; this may be useful in more advanced cases to allow list * elements to be lazily loaded. * </p> * * <p>To add an annotation to the list binding, simply write this:</p> * * <pre> * ListBinder&lt;String&gt; listBinder = ListBinder.build(binder(), String.class) * .annotatedWith(Names.named("name")) * .withDefaultPriority(); * </pre> * * <p> * and the created binding will be {@code @Named("name") List<String>} instead. * </p> * * <p> * For large lists, it may be helpful to split up their specification across different modules. This is accomplished by * specifying <em>priorities</em> for the {@link ListBinder}s when they are created. For example: * </p> * * <pre> * // In some module * ListBinder&lt;String&gt; listBinder1 = ListBinder.build(binder(), String.class) * .withPriority(0); * listBinder1.addBinding().toInstance("a"); * listBinder1.addBinding().toInstance("b"); * * // ... some other module * ListBinder&lt;String&gt; listBinder2 = ListBinder.build(binder(), String.class) * .withPriority(1); * listBinder2.addBinding().toInstance("c"); * listBinder2.addBinding().toInstance("d"); * </pre> * * <p> * The generated list will contain {@code "a"}, {@code "b"}, {@code "c"}, {@code "d"}, in order. This happens because * the first {@link ListBinder} had a smaller priority, so its entries come first. For more information about the * priority system, see {@link Priority}. * </p> * * @param <T> The type of the list element. * @author Tavian Barnes ([email protected]) * @version 1.1 * @since 1.1 */ public class ListBinder<T> { private static final Class<?>[] SKIPPED_SOURCES = { ListBinder.class, BuilderImpl.class, }; private final Binder binder; private final Multibinder<ListElement<T>> multibinder; private final Multibinder<ListBinderErrors<T>> errorMultibinder; private final TypeLiteral<T> entryType; private final Key<List<T>> listKey; private final Key<List<Provider<T>>> listOfProvidersKey; private final Key<Set<ListElement<T>>> setKey; private final Key<Set<ListBinderErrors<T>>> errorSetKey; private final PotentialAnnotation potentialAnnotation;
private final Priority initialPriority;
2
MX-Futhark/hook-any-text
src/main/java/hextostring/convert/EncodingAgnosticConverter.java
[ "public class DebuggableDecodingAttempt {\n\n\tprivate DebuggableLineList attempt;\n\tprivate Charset encoding;\n\tprivate EvaluationResult encodingEvaluationResult;\n\tprivate boolean validEncoding = false;\n\n\tpublic DebuggableDecodingAttempt(DebuggableLineList attempt,\n\t\tCharset encoding) {\n\n\t\tthis.attempt = attempt;\n\t\tthis.encoding = encoding;\n\t}\n\n\t/**\n\t * Getter on the list of list attempted to be decoded.\n\t *\n\t * @return The list of list attempted to be decoded.\n\t */\n\tpublic DebuggableLineList getAttempt() {\n\t\treturn attempt;\n\t}\n\n\t/**\n\t * Getter on the encoding used to decode the list of lines.\n\t *\n\t * @return The encoding used to decode the list of lines.\n\t */\n\tpublic Charset getEncoding() {\n\t\treturn encoding;\n\t}\n\n\t/**\n\t * Getter on the evaluation result of the encoding used to decode the\n\t * list of lines.\n\t *\n\t * @return The evaluation result of the encoding used to decode the\n\t * list of lines.\n\t */\n\tpublic EvaluationResult getEncodingEvaluationResult() {\n\t\treturn encodingEvaluationResult;\n\t}\n\n\t/**\n\t * Setter on the evaluation result of the encoding used to decode the\n\t * list of lines.\n\t *\n\t * @param encodingEvaluationResult\n\t * \t\t\tThe evaluation result of the encoding used to decode the\n\t * \t\t\tlist of lines.\n\t */\n\tpublic void setEncodingEvaluationResult(\n\t\tEvaluationResult encodingEvaluationResult) {\n\t\tthis.encodingEvaluationResult = encodingEvaluationResult;\n\t}\n\n\t/**\n\t * Getter on whether or not the encoding was deemed valid for this\n\t * list of lines.\n\t *\n\t * @return True is the encoding was deemed valid for this list of lines.\n\t */\n\tpublic boolean isValidEncoding() {\n\t\treturn validEncoding;\n\t}\n\n\t/**\n\t * Setter on whether or not the encoding was deemed valid for this\n\t * list of lines.\n\t *\n\t * @param validEncoding\n\t * \t\t\tTrue is the encoding is deemed valid for this list of lines.\n\t */\n\tpublic void setValidEncoding(boolean validEncoding) {\n\t\tthis.validEncoding = validEncoding;\n\t}\n\n\t/**\n\t * Formats the attempt depending on the debugging flags.\n\t *\n\t * @param debuggingFlags\n\t * \t\t\tThe debugging flags used to format these lines.\n\t * @param converterStrictness\n\t * \t\t\tThe validity value below which a converted string is eliminated.\n\t * @return A string representing these lines, with or without debug traces.\n\t */\n\tpublic String toString(long debuggingFlags, int converterStrictness) {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_LIST_ENCODING) > 0) {\n\t\t\tsb.append(\"Encoding: \" + encoding.name() + \"\\n\");\n\t\t}\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_LIST_ENCODING_VALIDITY) > 0) {\n\t\t\tsb.append(\"Encoding validity: \");\n\t\t\tsb.append(encodingEvaluationResult.getMark() + \"\\n\");\n\n\t\t\tif ((debuggingFlags\n\t\t\t\t& DebuggingFlags.LINE_LIST_ENCODING_VALIDITY_DETAILS)\n\t\t\t\t== DebuggingFlags.LINE_LIST_ENCODING_VALIDITY_DETAILS) {\n\n\t\t\t\tsb.append(\"details:\\n\");\n\t\t\t\tsb.append(StringUtils.indent(\n\t\t\t\t\tencodingEvaluationResult.getDetails(),\n\t\t\t\t\t\"\\t\",\n\t\t\t\t\t1\n\t\t\t\t) + \"\\n\");\n\t\t\t}\n\t\t}\n\t\tsb.append(attempt.toString(debuggingFlags, converterStrictness));\n\n\t\treturn sb.toString();\n\t}\n\n}", "public class DebuggableDecodingAttemptList implements DebuggableStrings {\n\n\tprivate List<DebuggableDecodingAttempt> attempts = new LinkedList<>();\n\n\tpublic void addAttempt(DebuggableDecodingAttempt attempt) {\n\t\tattempts.add(attempt);\n\t}\n\n\t@Override\n\tpublic DebuggableLineList getDecorableList() {\n\t\tfor (DebuggableDecodingAttempt attempt : attempts) {\n\t\t\tif (attempt.isValidEncoding()) {\n\t\t\t\treturn attempt.getAttempt();\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String toString(long debuggingFlags, int converterStrictness) {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_LIST_ENCODING_REJECTED) > 0) {\n\t\t\tsb.append(\"Lines with detected encoding: \\n\");\n\t\t}\n\t\tfor (DebuggableDecodingAttempt attempt : attempts) {\n\t\t\tif (attempt.isValidEncoding()) {\n\t\t\t\tsb.append(\n\t\t\t\t\tattempt.toString(debuggingFlags, converterStrictness)\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_LIST_ENCODING_REJECTED) > 0) {\n\t\t\tsb.append(\"\\nFailed attempts at decoding: \\n\");\n\t\t\tfor (DebuggableDecodingAttempt attempt : attempts) {\n\t\t\t\tif (!attempt.isValidEncoding()) {\n\t\t\t\t\tsb.append(\n\t\t\t\t\t\tattempt.toString(debuggingFlags,converterStrictness)\n\t\t\t\t\t);\n\t\t\t\t\tsb.append(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sb.toString().trim();\n\t}\n\n}", "public class DebuggableLineList implements DebuggableStrings, DecorableList {\n\n\tprivate String hexInput;\n\tprivate String hexInputAfterHexReplacements;\n\tprivate String hexInputAfterStrReplacements;\n\tprivate List<DebuggableLine> lines = new LinkedList<>();\n\n\tprivate String decorationBefore = \"\";\n\tprivate String decorationBetween = \"\";\n\tprivate String decorationAfter = \"\";\n\n\tpublic DebuggableLineList(String hex) {\n\t\tthis.hexInput = hex;\n\t\tthis.hexInputAfterHexReplacements = hex;\n\t\tthis.hexInputAfterStrReplacements = hex;\n\t}\n\n\t@Override\n\tpublic DebuggableLineList getDecorableList() {\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a line to this group.\n\t *\n\t * @param line\n\t * \t\t\tThe line to add.\n\t */\n\tpublic void addLine(DebuggableLine line) {\n\t\tlines.add(line);\n\t}\n\n\t/**\n\t * Getter on the hex input from which these lines originate.\n\t *\n\t * @return The hex input from which these lines originate.\n\t */\n\tpublic String getHexInput() {\n\t\treturn hexInput;\n\t}\n\n\t/**\n\t * Getter on the hex input from which this line originates to which HEX2HEX\n\t * replacements were applied.\n\t *\n\t * @return The hex input from which this line originates to which HEX2HEX\n\t * \t\treplacements were applied.\n\t */\n\tpublic String getHexInputAfterHexReplacements() {\n\t\treturn hexInputAfterHexReplacements;\n\t}\n\n\t/**\n\t * Setter on the hex input from which this line originates to which HEX2HEX\n\t * replacements were applied.\n\t *\n\t * @param hexInputAfterHexReplacements\n\t * \t\t\tThe hex input from which this line originates to which HEX2HEX\n\t * \t\t\treplacements were applied.\n\t */\n\tpublic void setHexInputAfterHexReplacements(\n\t\tString hexInputAfterHexReplacements) {\n\n\t\tthis.hexInputAfterHexReplacements = hexInputAfterHexReplacements;\n\t\tsetHexInputAfterStrReplacements(hexInputAfterHexReplacements);\n\t}\n\n\t/**\n\t * Getter on the hex input from which this line originates to which HEX2HEX\n\t * & HEX2STR replacements were applied.\n\t *\n\t * @return The hex input from which this line originates to which HEX2HEX\n\t * \t\t& HEX2STR replacements were applied.\n\t */\n\tpublic String getHexInputAfterStrReplacements() {\n\t\treturn hexInputAfterStrReplacements;\n\t}\n\n\t/**\n\t * Setter on the hex input from which this line originates to which HEX2HEX\n\t * & HEX2STR replacements were applied.\n\t *\n\t * @param hexInputAfterStrReplacements\n\t * \t\t\tThe hex input from which this line originates to which HEX2HEX\n\t * \t\t\t& HEX2STR replacements were applied.\n\t */\n\tpublic void setHexInputAfterStrReplacements(\n\t\tString hexInputAfterStrReplacements) {\n\n\t\tthis.hexInputAfterStrReplacements = hexInputAfterStrReplacements;\n\t}\n\n\t/**\n\t * Getter on the lines of this group.\n\t *\n\t * @return The lines of this group.\n\t */\n\tpublic List<DebuggableLine> getLines() {\n\t\treturn lines;\n\t}\n\n\t/**\n\t * Getter on one line of this group.\n\t *\n\t * @param index\n\t * \t\t\tThe index of the line in the list.\n\t * @return The line in the list at the given index.\n\t */\n\tpublic DebuggableLine getLine(int index) {\n\t\treturn lines.get(index);\n\t}\n\n\t/**\n\t * Setter on the string put before these lines in the toString method.\n\t *\n\t * @param decorationBefore\n\t * \t\t\tThe string put before these lines in the toString method.\n\t */\n\t@Override\n\tpublic void setDecorationBefore(String decorationBefore) {\n\t\tthis.decorationBefore = decorationBefore;\n\t}\n\n\t/**\n\t * Setter on the string put between these lines in the toString method.\n\t *\n\t * @param decorationBetween\n\t * \t\t\tThe string put between these lines in the toString method.\n\t */\n\t@Override\n\tpublic void setDecorationBetween(String decorationBetween) {\n\t\tthis.decorationBetween = decorationBetween;\n\t}\n\n\t/**\n\t * Setter on the string put after these lines in the toString method.\n\t *\n\t * @param decorationAfter\n\t * \t\t\tThe string put after these lines in the toString method.\n\t */\n\t@Override\n\tpublic void setDecorationAfter(String decorationAfter) {\n\t\tthis.decorationAfter = decorationAfter;\n\t}\n\n\t/**\n\t * Setter on the strings decorating every line of this group.\n\t *\n\t * @param before\n\t * \t\t\tThe string put before every line in the toString method.\n\t * @param after\n\t * \t\t\tThe string put after every line in the toString method.\n\t */\n\t@Override\n\tpublic void setLinesDecorations(String before, String after) {\n\t\tfor (DebuggableLine line : lines) {\n\t\t\tline.setDecorationBefore(before);\n\t\t\tline.setDecorationAfter(after);\n\t\t}\n\t}\n\n\t/**\n\t * Getter on the sum of the validity of all converted strings in the list.\n\t *\n\t * @param filterUnder\n\t * \t\t\tThe threshold below which a line is not counted in the result.\n\t * @return The sum of the validity of all converted strings in the list.\n\t */\n\tpublic int getTotalValidity(int filterUnder) {\n\t\tint total = 0;\n\t\tfor (DebuggableLine line : lines) {\n\t\t\tint validity = line.getValidity();\n\t\t\tif(validity >= filterUnder) {\n\t\t\t\ttotal += validity;\n\t\t\t}\n\t\t}\n\t\treturn total;\n\t}\n\n\t@Override\n\tpublic String toString(long debuggingFlags, int converterStrictness) {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_LIST_HEX_INPUT) > 0) {\n\t\t\tsb.append(\"input: 0x\" + hexInput + \"\\n\");\n\t\t}\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_LIST_HEX_AFTER_HEX_REPL_INPUT)\n\t\t\t> 0) {\n\n\t\t\tsb.append(\"input after hex replacements: \\n0x\"\n\t\t\t\t+ hexInputAfterHexReplacements + \"\\n\");\n\t\t}\n\t\tif ((debuggingFlags\n\t\t\t& DebuggingFlags.LINE_LIST_HEX_AFTER_STR_REPL_INPUT)\n\t\t\t> 0) {\n\n\t\t\tsb.append(\"input after str replacements: \\n0x\"\n\t\t\t\t+ hexInputAfterStrReplacements + \"\\n\");\n\t\t}\n\n\t\tList<DebuggableLine> displayedLines;\n\t\tif ((debuggingFlags & DebuggingFlags.LINE_REJECTED) > 0) {\n\t\t\tdisplayedLines = lines;\n\t\t} else {\n\t\t\tdisplayedLines = new LinkedList<>();\n\t\t\tfor (DebuggableLine line : lines) {\n\t\t\t\tif (line.getValidity() >= converterStrictness) {\n\t\t\t\t\tdisplayedLines.add(line);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsb.append(decorationBefore);\n\t\tif (debuggingFlags > 0) {\n\t\t\tsb.append(\"\\n\");\n\t\t}\n\t\tif (displayedLines.size() > 0) {\n\t\t\tDebuggableLine lastDisplayedLine = displayedLines\n\t\t\t\t.get(displayedLines.size() - 1);\n\t\t\tfor (DebuggableLine line : displayedLines) {\n\t\t\t\tsb.append(line.toString(debuggingFlags));\n\t\t\t\tif (line != lastDisplayedLine) {\n\t\t\t\t\tsb.append(decorationBetween);\n\t\t\t\t}\n\t\t\t\tif (debuggingFlags > 0) {\n\t\t\t\t\tsb.append(\"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsb.append(decorationAfter);\n\n\t\tif (debuggingFlags > 0) {\n\t\t\tsb.append(\"\\n\");\n\t\t}\n\n\t\treturn sb.toString().trim();\n\t}\n\n}", "public interface DebuggableStrings {\n\n\t/**\n\t * Formats the lines depending on the debugging flags.\n\t *\n\t * @param debuggingFlags\n\t * \t\t\tThe debugging flags used to format these lines.\n\t * @param converterStrictness\n\t * \t\t\tThe validity value below which a converted string is eliminated.\n\t * @return A string representing these lines, with or without debug traces.\n\t */\n\tString toString(long debuggingFlags, int converterStrictness);\n\n\t/**\n\t * Provides a list of lines that can be formatted.\n\t *\n\t * @return A list of lines that can be formatted.\n\t */\n\tDecorableList getDecorableList();\n\n}", "public class EvaluationResult {\n\n\tprivate int mark;\n\tprivate String details;\n\n\tpublic EvaluationResult(int mark, String details) {\n\t\tthis.mark = mark;\n\t\tthis.details = details;\n\t}\n\n\t/**\n\t * Getter on the mark obtained by the object.\n\t *\n\t * @return the mark obtained by the object.\n\t */\n\tpublic int getMark() {\n\t\treturn mark;\n\t}\n\n\t/**\n\t * Getter on the details of the evaluation.\n\t *\n\t * @return the details of the evaluation.\n\t */\n\tpublic String getDetails() {\n\t\treturn details;\n\t}\n\n}", "public class EvaluatorFactory {\n\n\tprivate static StringEvaluator stringEvaluatorInstance =\n\t\tnew JapaneseStringEvaluator();\n\n\tprivate static EncodingEvaluator encodingEvaluatorInstance =\n\t\tnew EncodingEvaluator();\n\n\tpublic static StringEvaluator getStringEvaluatorInstance() {\n\t\treturn stringEvaluatorInstance;\n\t}\n\n\tpublic static EncodingEvaluator getEncodingEvaluatorInstance() {\n\t\treturn encodingEvaluatorInstance;\n\t}\n\n}", "public class EncodingEvaluator implements Evaluator<DebuggableLineList> {\n\n\t// The threshold below which a line extracted from the hex data\n\t// is not considered in the encoding detection algorithm.\n\tpublic static int LINE_VALIDITY_THRESHOLD = 0;\n\n\t@Override\n\tpublic EvaluationResult evaluate(DebuggableLineList lines) {\n\t\tint mark = lines.getTotalValidity(LINE_VALIDITY_THRESHOLD);\n\t\tString details =\n\t\t\t\"Total validity of strings for elements with validity > \"\n\t\t\t+ LINE_VALIDITY_THRESHOLD + \" : \" + mark;\n\t\treturn new EvaluationResult(mark, details);\n\t}\n\n}", "public class Replacements\n\timplements TableData<Replacement>, Serializable {\n\n\t/**\n\t * Backward-compatible with 0.7.0\n\t */\n\tprivate static final long serialVersionUID = 00000000007000000L;\n\n\tprivate List<Replacement> orderedReplacements;\n\tprivate Map<ReplacementType, List<Replacement>> replacementsByType;\n\n\tpublic Replacements() {\n\t\torderedReplacements = new ArrayList<>();\n\t\treplacementsByType = new HashMap<>();\n\t\tfor (ReplacementType type : ReplacementType.values()) {\n\t\t\treplacementsByType.put(type, new LinkedList<Replacement>());\n\t\t}\n\t}\n\n\t/**\n\t * Getter on a replacement by its index.\n\t *\n\t * @param index\n\t * \t\t\tThe index of the replacement.\n\t * @return The replacement at the specified index.\n\t */\n\t@Override\n\tpublic Replacement get(int index) {\n\t\treturn orderedReplacements.get(index);\n\t}\n\n\t/**\n\t * Getter on the replacements.\n\t *\n\t * @return The replacements.\n\t */\n\t@Override\n\tpublic List<Replacement> getAll() {\n\t\treturn new ArrayList<Replacement>(orderedReplacements);\n\t}\n\n\t/**\n\t * Adds a replacement at the end of the list.\n\t *\n\t * @param r\n\t * \t\t\tThe replacement to add.\n\t */\n\t@Override\n\tpublic void add(Replacement r) {\n\t\torderedReplacements.add(r);\n\t\treplacementsByType.get(r.getType()).add(r);\n\t}\n\n\t/**\n\t * Removes a replacement at the specified index.\n\t *\n\t * @param index\n\t * \t\t\tThe index of the replacement to remove.\n\t */\n\t@Override\n\tpublic void remove(int index) {\n\t\tReplacement deleted = orderedReplacements.remove(index);\n\t\treplacementsByType.get(deleted.getType()).remove(deleted);\n\t}\n\n\t/**\n\t * Empties the list.\n\t */\n\tpublic void clear() {\n\t\torderedReplacements.clear();\n\t\tfor (ReplacementType type : replacementsByType.keySet()) {\n\t\t\treplacementsByType.get(type).clear();\n\t\t}\n\t}\n\n\t/**\n\t * Get all replacements of a specified type.\n\t *\n\t * @param type\n\t * \t\t\tThe type of the replacements.\n\t * @return All replacements of a specified type.\n\t */\n\tpublic List<Replacement> getByType(ReplacementType type) {\n\t\treturn replacementsByType.get(type);\n\t}\n\n\t/**\n\t * Setter on the type of a replacement.\n\t *\n\t * @param r\n\t * \t\t\tThe replacement to modify.\n\t * @param type\n\t * \t\t\tThe new type of the replacement.\n\t */\n\tpublic void setType(Replacement r, ReplacementType type) {\n\t\tfor (ReplacementType previoustType : replacementsByType.keySet()) {\n\t\t\treplacementsByType.get(previoustType).remove(r);\n\t\t}\n\t\treplacementsByType.get(type).add(r);\n\t\tr.setType(type);\n\t}\n\n\t/**\n\t * Applies all the replacements of a given type.\n\t *\n\t * @param s\n\t * \t\t\tThe string to which replacements are applied.\n\t * @param type\n\t * \t\t\tThe type of the replacements to use.\n\t * @return The string to which replacements were applied.\n\t */\n\tpublic String apply(String s, ReplacementType type) {\n\t\tString res = new String(s);\n\t\tfor (Replacement r : replacementsByType.get(type)) {\n\t\t\tres = r.apply(res);\n\t\t}\n\t\treturn res;\n\t}\n\n}", "public class Charsets implements ValueClass {\n\n\t// Charsets used in Japanese games\n\t@CommandLineValue(\n\t\tvalue = \"sjis\",\n\t\tshortcut = \"j\",\n\t\tdescription = \"Shift JIS\"\n\t)\n\tpublic static final Charset SHIFT_JIS = Charset.forName(\"Shift_JIS\");\n\t@CommandLineValue(\n\t\tvalue = \"utf16-le\",\n\t\tshortcut = \"l\",\n\t\tdescription = \"UTF16 Little Endian\"\n\t)\n\tpublic static final Charset UTF16_LE = Charset.forName(\"UTF-16LE\");\n\t@CommandLineValue(\n\t\tvalue = \"utf16-be\",\n\t\tshortcut = \"b\",\n\t\tdescription = \"UTF16 Bid Endian\"\n\t)\n\tpublic static final Charset UTF16_BE = Charset.forName(\"UTF-16BE\");\n\t// also used for test files\n\t@CommandLineValue(\n\t\tvalue = \"utf8\",\n\t\tshortcut = \"u\",\n\t\tdescription = \"UTF8\"\n\t)\n\tpublic static final Charset UTF8 = Charset.forName(\"UTF-8\");\n\n\t// not a charset, used for automatic recognition\n\t@CommandLineValue(\n\t\tvalue = \"detect\",\n\t\tshortcut = \"d\",\n\t\tdescription = \"Detect the right encoding among the other ones\"\n\t)\n\tpublic static final Charset DETECT = CharsetAutodetect.getInstance();\n\n\tpublic static final Charset[] ALL_CHARSETS = getAllCharsets();\n\n\tpublic static Charset getValidCharset(String charsetName) {\n\t\tfor (Charset cs : ALL_CHARSETS) {\n\t\t\tif (cs.name().equals(charsetName)) {\n\t\t\t\treturn cs;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate static Charset[] getAllCharsets() {\n\n\t\tList<Field> charsetFields = ReflectionUtils.getAnnotatedFields(\n\t\t\tCharsets.class,\n\t\t\tCommandLineValue.class\n\t\t);\n\t\tCharset[] allCharsets = new Charset[charsetFields.size()];\n\t\tint eltCounter = 0;\n\t\tfor (Field charsetField : charsetFields) {\n\t\t\ttry {\n\t\t\t\tallCharsets[eltCounter++] = (Charset) charsetField.get(null);\n\t\t\t} catch (IllegalArgumentException | IllegalAccessException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn allCharsets;\n\t}\n\n}" ]
import hextostring.debug.DebuggableDecodingAttempt; import hextostring.debug.DebuggableDecodingAttemptList; import hextostring.debug.DebuggableLineList; import hextostring.debug.DebuggableStrings; import hextostring.evaluate.EvaluationResult; import hextostring.evaluate.EvaluatorFactory; import hextostring.evaluate.encoding.EncodingEvaluator; import hextostring.replacement.Replacements; import hextostring.utils.Charsets;
package hextostring.convert; /** * Converter choosing the right encoding by itself. * * @author Maxime PIA */ public class EncodingAgnosticConverter implements Converter { private AbstractConverter[] converters = { (AbstractConverter) ConverterFactory.getConverterInstance(Charsets.SHIFT_JIS, null), (AbstractConverter) ConverterFactory.getConverterInstance(Charsets.UTF16_BE, null), (AbstractConverter) ConverterFactory.getConverterInstance(Charsets.UTF16_LE, null), (AbstractConverter) ConverterFactory.getConverterInstance(Charsets.UTF8, null) }; private EncodingEvaluator encodingEvaluator = EvaluatorFactory.getEncodingEvaluatorInstance(); @Override public DebuggableStrings convert(String hex) { boolean encodingFound = false; int maxValidity = 0; DebuggableDecodingAttemptList allAttempts = new DebuggableDecodingAttemptList(); DebuggableDecodingAttempt validAttempt = null; for (AbstractConverter c : converters) { DebuggableLineList lines = c.convert(hex); DebuggableDecodingAttempt currentAttempt = new DebuggableDecodingAttempt(lines, c.getCharset());
EvaluationResult encodingEvaluationResult =
4
mokies/ratelimitj
ratelimitj-aerospike/src/test/java/es/moki/aerospike/request/AerospikeSlidingWindowRequestRateLimiterPerformanceTest.java
[ "public class AerospikeClientFactory {\n\n public static AerospikeClient getAerospikeClient() {\n\n Policy readPolicy = new Policy();\n readPolicy.maxRetries = 1;\n readPolicy.readModeAP = ReadModeAP.ONE;\n readPolicy.replica = Replica.MASTER_PROLES;\n readPolicy.sleepBetweenRetries = 5;\n readPolicy.totalTimeout = 1000;\n readPolicy.sendKey = true;\n\n WritePolicy writePolicy = new WritePolicy();\n writePolicy.maxRetries = 2;\n writePolicy.readModeAP = ReadModeAP.ALL;\n writePolicy.replica = Replica.MASTER_PROLES;\n writePolicy.sleepBetweenRetries = 5;\n writePolicy.commitLevel = CommitLevel.COMMIT_ALL;\n writePolicy.totalTimeout = 10000;\n writePolicy.sendKey = true;\n\n ClientPolicy clientPolicy = new ClientPolicy();\n clientPolicy.maxConnsPerNode = 1;\n clientPolicy.readPolicyDefault = readPolicy;\n clientPolicy.writePolicyDefault = writePolicy;\n clientPolicy.failIfNotConnected = true;\n clientPolicy.timeout = 30000;\n clientPolicy.threadPool = Executors.newFixedThreadPool(1);\n\n AerospikeClient aerospikeClient = new AerospikeClient(clientPolicy,\n new Host(\"127.0.0.1\", 3000));\n return aerospikeClient;\n }\n}", "public class AerospikeContext {\n\n public final AerospikeClient aerospikeClient;\n\n public final String setName;\n\n public final String nameSpace;\n\n public AerospikeContext(AerospikeClient aerospikeClient, String setName, String nameSpace) {\n this.aerospikeClient = requireNonNull(aerospikeClient, \"aerospike client can not be null\");\n this.setName = requireNonNull(setName, \"set name can not be null\");\n this.nameSpace = requireNonNull(nameSpace, \"set name can not be null\");\n }\n\n}", "@ParametersAreNonnullByDefault\n@ThreadSafe\npublic class AerospikeSlidingWindowRateLimiter implements RequestRateLimiter {\n\n private static final Logger LOG = LoggerFactory.getLogger(AerospikeSlidingWindowRateLimiter.class);\n private static final String BIN_NAME = \"rate_limit\";\n\n private final AerospikeContext aerospikeContext;\n private final DefaultRequestLimitRulesSupplier rulesSupplier;\n private final TimeSupplier timeSupplier;\n\n public AerospikeSlidingWindowRateLimiter(AerospikeContext aerospikeContext,Set<RequestLimitRule> rules){\n this(aerospikeContext,rules,new SystemTimeSupplier());\n }\n\n public AerospikeSlidingWindowRateLimiter(AerospikeContext aerospikeContext, Set<RequestLimitRule> rules, TimeSupplier timeSupplier) {\n this.aerospikeContext = requireNonNull(aerospikeContext, \"aerospikeContext can not be null\");\n requireNonNull(rules, \"rules can not be null\");\n if (rules.isEmpty()) {\n throw new IllegalArgumentException(\"at least one rule must be provided\");\n }\n this.timeSupplier = requireNonNull(timeSupplier, \"time supplier can not be null\");\n this.rulesSupplier = new DefaultRequestLimitRulesSupplier(rules);\n }\n\n @Override\n public boolean overLimitWhenIncremented(String key) {\n return overLimitWhenIncremented(key, 1);\n }\n\n @Override\n public boolean overLimitWhenIncremented(String key, int weight) {\n return eqOrGeLimit(key, weight, true);\n }\n\n @Override\n public boolean geLimitWhenIncremented(String key) {\n return geLimitWhenIncremented(key, 1);\n }\n\n @Override\n public boolean geLimitWhenIncremented(String key, int weight) {\n return eqOrGeLimit(key, weight, false);\n }\n\n\n @Override\n public boolean resetLimit(String key) {\n return aerospikeContext.aerospikeClient.delete(aerospikeContext.aerospikeClient.getWritePolicyDefault(),\n new Key(aerospikeContext.nameSpace,aerospikeContext.setName,key)) ;\n }\n\n private Map<String, Long> getMap(final String userKey) {\n AerospikeClient aerospikeClient = aerospikeContext.aerospikeClient;\n final Key key = new Key(aerospikeContext.nameSpace,aerospikeContext.setName,userKey);\n final Record record = aerospikeContext.aerospikeClient.get(aerospikeClient.getReadPolicyDefault(),key);\n\n return record != null ? (Map<String, Long>)record.getMap(BIN_NAME): new HashMap<>();\n }\n\n private boolean eqOrGeLimit(String key, int weight, boolean strictlyGreater) {\n\n final long now = timeSupplier.get();\n final Set<RequestLimitRule> rules = rulesSupplier.getRules(key);\n final int longestDuration = rules.stream().map(RequestLimitRule::getDurationSeconds).reduce(Integer::max).orElse(0);\n List<SavedKey> savedKeys = new ArrayList<>(rules.size());\n\n Map<String, Long> asKeyMap = getMap(key);\n boolean geLimit = false;\n Map<SavedKey,List<Operation>> savedKeyListMap = new HashMap<>();\n for (RequestLimitRule rule : rules) {\n\n SavedKey savedKey = new SavedKey(now, rule.getDurationSeconds(), rule.getPrecisionSeconds());\n savedKeys.add(savedKey);\n\n Long oldTs = asKeyMap.get(savedKey.tsKey);\n\n oldTs = oldTs != null ? oldTs : savedKey.trimBefore;\n\n if (oldTs > now) {\n // don't write in the past\n return true;\n }\n\n\n\n // compute no of requests in given window;\n long curr = 0L;\n for (long block = savedKey.trimBefore; block <= savedKey.blockId; block++) {\n String bkey = savedKey.countKey + block;\n curr = curr + asKeyMap.getOrDefault(bkey,0L);\n }\n\n\n // discover what needs to be cleaned up\n List<Value> keyNeedToDeleted = new ArrayList<>();\n long trim = Math.min(savedKey.trimBefore, oldTs + savedKey.blocks);\n\n for (long oldBlock = oldTs; oldBlock <= trim - 1; oldBlock++) {\n keyNeedToDeleted.add(new StringValue(savedKey.countKey + oldBlock));\n }\n\n\n if(!keyNeedToDeleted.isEmpty()){\n Operation operation = MapOperation.removeByKeyList(BIN_NAME,keyNeedToDeleted, MapReturnType.NONE);\n List<Operation> operations = savedKeyListMap.getOrDefault(savedKey,new ArrayList<>());\n operations.add(operation);\n savedKeyListMap.put(savedKey,operations);\n }\n\n\n // check our limits\n long count = coalesce(curr, 0L) + weight;\n if (count > rule.getLimit()) {\n return true; // over limit, don't record request\n } else if (!strictlyGreater && count == rule.getLimit()) {\n geLimit = true; // at limit, do record request\n }\n Operation operation = MapOperation.increment(MapPolicy.Default,BIN_NAME,Value.get(savedKey.countKey + savedKey.blockId),Value.get(weight));\n List<Operation> operations = savedKeyListMap.getOrDefault(savedKey,new ArrayList<>());\n operations.add(operation);\n savedKeyListMap.put(savedKey,operations);\n }\n\n // there is enough resources, update the counts and delete map key\n AerospikeClient aerospikeClient = aerospikeContext.aerospikeClient;\n final WritePolicy updationWritePolicy = new WritePolicy(\n aerospikeContext.aerospikeClient.getWritePolicyDefault());\n updationWritePolicy.recordExistsAction = RecordExistsAction.UPDATE;\n updationWritePolicy.expiration = longestDuration;\n for (SavedKey savedKey : savedKeys) {\n //update the current timestamp, count, and bucket count and delete key\n LOG.debug(\"Update key {},{}\",key,savedKey);\n List<Operation> operations = savedKeyListMap.getOrDefault(savedKey,new ArrayList<>());\n\n operations.add(MapOperation.put(MapPolicy.Default,BIN_NAME,Value.get(savedKey.tsKey),Value.get(savedKey.trimBefore)));\n\n Operation[] operationArray = new Operation[operations.size()];\n\n operationArray = operations.toArray(operationArray);\n\n aerospikeClient.operate(updationWritePolicy,new Key(aerospikeContext.nameSpace,aerospikeContext.setName,key),operationArray);\n }\n return geLimit;\n }\n\n\n}", "@ParametersAreNonnullByDefault\npublic class RequestLimitRule {\n\n private final int durationSeconds;\n private final long limit;\n private final int precision;\n private final String name;\n private final Set<String> keys;\n\n private RequestLimitRule(int durationSeconds, long limit, int precision) {\n this(durationSeconds, limit, precision, null);\n }\n\n private RequestLimitRule(int durationSeconds, long limit, int precision, String name) {\n this(durationSeconds, limit, precision, name, null);\n }\n\n private RequestLimitRule(int durationSeconds, long limit, int precision, String name, Set<String> keys) {\n this.durationSeconds = durationSeconds;\n this.limit = limit;\n this.precision = precision;\n this.name = name;\n this.keys = keys;\n }\n\n private static void checkDuration(Duration duration) {\n requireNonNull(duration, \"duration can not be null\");\n if (Duration.ofSeconds(1).compareTo(duration) > 0) {\n throw new IllegalArgumentException(\"duration must be great than 1 second\");\n }\n }\n\n /**\n * Initialise a request rate limit. Imagine the whole duration window as being one large bucket with a single count.\n *\n * @param duration The time the limit will be applied over. The duration must be greater than 1 second.\n * @param limit A number representing the maximum operations that can be performed in the given duration.\n * @return A limit rule.\n */\n public static RequestLimitRule of(Duration duration, long limit) {\n checkDuration(duration);\n if (limit < 0) {\n throw new IllegalArgumentException(\"limit must be greater than zero.\");\n }\n int durationSeconds = (int) duration.getSeconds();\n return new RequestLimitRule(durationSeconds, limit, durationSeconds);\n }\n\n /**\n * Controls (approximate) sliding window precision. A lower duration increases precision and minimises the Thundering herd problem - https://en.wikipedia.org/wiki/Thundering_herd_problem\n *\n * @param precision Defines the time precision that will be used to approximate the sliding window. The precision must be greater than 1 second.\n * @return a limit rule\n */\n public RequestLimitRule withPrecision(Duration precision) {\n checkDuration(precision);\n return new RequestLimitRule(this.durationSeconds, this.limit, (int) precision.getSeconds(), this.name, this.keys);\n }\n\n /**\n * Applies a name to the rate limit that is useful for metrics.\n *\n * @param name Defines a descriptive name for the rule limit.\n * @return a limit rule\n */\n public RequestLimitRule withName(String name) {\n return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, name, this.keys);\n }\n\n /**\n * Applies a key to the rate limit that defines to which keys, the rule applies, empty for any unmatched key.\n *\n * @param keys Defines a set of keys to which the rule applies.\n * @return a limit rule\n */\n public RequestLimitRule matchingKeys(String... keys) {\n Set<String> keySet = keys.length > 0 ? new HashSet<>(Arrays.asList(keys)) : null;\n return matchingKeys(keySet);\n }\n\n /**\n * Applies a key to the rate limit that defines to which keys, the rule applies, null for any unmatched key.\n *\n * @param keys Defines a set of keys to which the rule applies.\n * @return a limit rule\n */\n public RequestLimitRule matchingKeys(Set<String> keys) {\n return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, this.name, keys);\n }\n\n /**\n * @return The limits duration in seconds.\n */\n public int getDurationSeconds() {\n return durationSeconds;\n }\n\n /**\n * @return The limits precision in seconds.\n */\n public int getPrecisionSeconds() {\n return precision;\n }\n\n /**\n * @return The name.\n */\n public String getName() {\n return name;\n }\n\n /**\n * @return The limit.\n */\n public long getLimit() {\n return limit;\n }\n\n /**\n * @return The keys.\n */\n @Nullable\n public Set<String> getKeys() {\n return keys;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || !(o instanceof RequestLimitRule)) {\n return false;\n }\n RequestLimitRule that = (RequestLimitRule) o;\n return durationSeconds == that.durationSeconds\n && limit == that.limit\n && Objects.equals(precision, that.precision)\n && Objects.equals(name, that.name)\n && Objects.equals(keys, that.keys);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(durationSeconds, limit, precision, name, keys);\n }\n}", "public interface RequestRateLimiter {\n\n /**\n * Determine if the given key, after incrementing by one, has exceeded the configured rate limit.\n * @param key key.\n * @return {@code true} if the key is over the limit, otherwise {@code false}\n */\n boolean overLimitWhenIncremented(String key);\n\n /**\n * Determine if the given key, after incrementing by the given weight, has exceeded the configured rate limit.\n * @param key key.\n * @param weight A variable weight.\n * @return {@code true} if the key has exceeded the limit, otherwise {@code false} .\n */\n boolean overLimitWhenIncremented(String key, int weight);\n\n /**\n * Determine if the given key, after incrementing by one, is &gt;= the configured rate limit.\n * @param key key.\n * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} .\n */\n boolean geLimitWhenIncremented(String key);\n\n /**\n * Determine if the given key, after incrementing by the given weight, is &gt;= the configured rate limit.\n * @param key key.\n * @param weight A variable weight.\n * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} .\n */\n boolean geLimitWhenIncremented(String key, int weight);\n\n// /**\n// * Determine if the given key has exceeded the configured rate limit.\n// * @param key key.\n// * @return {@code true} if the key is over the limit, otherwise {@code false}\n// */\n// boolean isOverLimit(String key);\n//\n// /**\n// * Determine if the given key is &gt;= the configured rate limit.\n// * @param key key.\n// * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} .\n// */\n// boolean isGeLimit(String key);\n\n /**\n * Resets the accumulated rate for the given key.\n * @param key key.\n * @return {@code true} if the key existed, otherwise {@code false} .\n */\n boolean resetLimit(String key);\n}", "public interface TimeSupplier {\n\n @Deprecated\n CompletionStage<Long> getAsync();\n\n Mono<Long> getReactive();\n\n /**\n * Get unix time in seconds\n * @return unix time seconds\n */\n long get();\n}", "public abstract class AbstractSyncRequestRateLimiterPerformanceTest {\n\n private final Logger log = LoggerFactory.getLogger(this.getClass());\n\n private final TimeBanditSupplier timeBandit = new TimeBanditSupplier();\n\n protected abstract RequestRateLimiter getRateLimiter(Set<RequestLimitRule> rules, TimeSupplier timeSupplier);\n\n @Test\n void shouldLimitDualWindowSyncTimed() {\n\n Stopwatch watch = Stopwatch.createStarted();\n\n ImmutableSet<RequestLimitRule> rules =\n ImmutableSet.of(RequestLimitRule.of(Duration.ofSeconds(2), 100), RequestLimitRule.of(Duration.ofSeconds(10), 100));\n RequestRateLimiter requestRateLimiter = getRateLimiter(rules, timeBandit);\n Random rand = new Random();\n\n int total = 10_000;\n IntStream.rangeClosed(1, total).map(i -> rand.nextInt(128)).forEach(value -> {\n timeBandit.addUnixTimeMilliSeconds(200L);\n requestRateLimiter.overLimitWhenIncremented(\"ip:127.0.0.\" + value);\n });\n\n double transactionsPerSecond = Math.ceil((double) total / watch.elapsed(TimeUnit.MILLISECONDS) * 1000);\n\n log.info(\"total time {} checks {}/sec\", watch.stop(), NumberFormat.getNumberInstance(Locale.US).format(transactionsPerSecond));\n }\n\n}" ]
import com.aerospike.client.AerospikeClient; import es.moki.aerospike.extensions.AerospikeClientFactory; import es.moki.ratelimitj.aerospike.request.AerospikeContext; import es.moki.ratelimitj.aerospike.request.AerospikeSlidingWindowRateLimiter; import es.moki.ratelimitj.core.limiter.request.RequestLimitRule; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.time.TimeSupplier; import es.moki.ratelimitj.test.limiter.request.AbstractSyncRequestRateLimiterPerformanceTest; import java.util.Set; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll;
package es.moki.aerospike.request; public class AerospikeSlidingWindowRequestRateLimiterPerformanceTest extends AbstractSyncRequestRateLimiterPerformanceTest { private static AerospikeContext aerospikeContext; @AfterAll static void afterAll() { aerospikeContext.aerospikeClient.close(); } @BeforeAll static void beforeAll() {
AerospikeClient aerospikeClient = AerospikeClientFactory.getAerospikeClient();
0
larusba/neo4j-jdbc
neo4j-jdbc-http/src/main/java/org/neo4j/jdbc/http/HttpNeo4jConnection.java
[ "public class CypherExecutor {\n\n\t/**\n\t * URL of the transaction endpoint.\n\t */\n\tfinal String transactionUrl;\n\n\t/**\n\t * If we are in https or not.\n\t */\n\tprivate Boolean secure;\n\n\t/**\n\t * Autocommit transaction.\n\t * Must be null at creation time.\n\t * Initiation of this property is made by its setter, that is called from the constructor.\n\t */\n\tprivate Boolean autoCommit;\n\n\t/**\n\t * The http client.\n\t */\n\tprivate CloseableHttpClient http;\n\n\t/**\n\t * URL of the current transaction.\n\t */\n\tprivate String currentTransactionUrl;\n\n\t/**\n\t * Jackson mapper object.\n\t */\n\tprivate static final ObjectMapper mapper = new ObjectMapper();\n\n\tprivate static final String DB_DATA_TRANSACTION = \"/db/data/transaction\";\n\n\tstatic {\n\t\tmapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, true);\n\t}\n\n\t/**\n\t * Default constructor.\n\t *\n\t * @param host Hostname of the Neo4j instance.\n\t * @param port HTTP port of the Neo4j instance.\n\t * @param secure\t If the connection used SSL.\n\t * @param properties Properties of the url connection.\n\t * @throws SQLException sqlexception\n\t */\n\tpublic CypherExecutor(String host, Integer port, Boolean secure, Properties properties) throws SQLException {\n\t\tthis.secure = secure;\n\n\t\t// Create the http client builder\n\t\tHttpClientBuilder builder = HttpClients.custom();\n\n\t\t// Adding authentication to the http client if needed\n\t\tCredentialsProvider credentialsProvider = getCredentialsProvider(host, port, properties);\n\t\tif (credentialsProvider != null)\n\t\t\tbuilder.setDefaultCredentialsProvider(credentialsProvider);\n\n\t\t// Setting user-agent\n\t\tString userAgent = properties.getProperty(\"useragent\");\n\t\tbuilder.setUserAgent(\"Neo4j JDBC Driver\" + (userAgent != null ? \" via \"+userAgent : \"\"));\n\t\t// Create the http client\n\t\tthis.http = builder.build();\n\n\t\t// Create the url endpoint\n\t\tthis.transactionUrl = createTransactionUrl(host, port, this.secure);\n\n\t\t// Setting autocommit\n\t\tthis.setAutoCommit(Boolean.valueOf(properties.getProperty(\"autoCommit\", \"true\")));\n\t}\n\n\tprivate String createTransactionUrl(String host, Integer port, Boolean secure) throws SQLException {\n\t\ttry {\n\t\t\tif(secure)\n\t\t\t\treturn new URL(\"https\", host, port, DB_DATA_TRANSACTION).toString();\n\t\t\telse\n\t\t\t\treturn new URL(\"http\", host, port, DB_DATA_TRANSACTION).toString();\n\t\t} catch (MalformedURLException e) {\n\t\t\tthrow new SQLException(\"Invalid server URL\", e);\n\t\t}\n\t}\n\n\tprivate CredentialsProvider getCredentialsProvider(String host, Integer port, Properties properties) {\n\t\tif (properties.containsKey(\"password\")) {\n\t\t\tString user = properties.getProperty(\"user\", properties.getProperty(\"username\", \"neo4j\"));\n\t\t\tCredentialsProvider credsProvider = new BasicCredentialsProvider();\n\t\t\tUsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, properties.getProperty(\"password\"));\n\t\t\tcredsProvider.setCredentials(new AuthScope(host, port), credentials);\n\t\t\treturn credsProvider;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Execute a list of cypher queries.\n\t *\n\t * @param queries List of cypher query object\n\t * @return the response for these queries\n\t * @throws SQLException sqlexception\n\t */\n\tpublic Neo4jResponse executeQueries(List<Neo4jStatement> queries) throws SQLException {\n\t\t// Prepare the headers query\n\t\tHttpPost request = new HttpPost(currentTransactionUrl);\n\n\t\t// Prepare body request\n\t\tStringEntity requestEntity = new StringEntity(Neo4jStatement.toJson(queries, mapper), ContentType.APPLICATION_JSON);\n\t\trequest.setEntity(requestEntity);\n\n\t\t// Make the request\n\t\treturn this.executeHttpRequest(request);\n\t}\n\n\t/**\n\t * Execute a cypher query.\n\t *\n\t * @param query Cypher query object.\n\t * @return the response for this query\n\t * @throws SQLException sqlexception\n\t */\n\tpublic Neo4jResponse executeQuery(Neo4jStatement query) throws SQLException {\n\t\tList<Neo4jStatement> queries = new ArrayList<>();\n\t\tqueries.add(query);\n\t\treturn this.executeQueries(queries);\n\t}\n\n\t/**\n\t * Commit the current transaction.\n\t *\n\t * @throws SQLException sqlexception\n\t */\n\tpublic void commit() throws SQLException {\n\t\tif (this.getOpenTransactionId() > 0) {\n\t\t\tHttpPost request = new HttpPost(currentTransactionUrl + \"/commit\");\n\t\t\tNeo4jResponse response = this.executeHttpRequest(request);\n\t\t\tif (response.hasErrors()) {\n\t\t\t\tthrow new SQLException(response.displayErrors());\n\t\t\t}\n\t\t\tthis.currentTransactionUrl = this.transactionUrl;\n\t\t}\n\t}\n\n\t/**\n\t * Rollback the current transaction.\n\t *\n\t * @throws SQLException if there is no transaction to rollback\n\t */\n\tpublic void rollback() throws SQLException {\n\t\tif (this.getOpenTransactionId() > 0) {\n\t\t\t// Prepare the request\n\t\t\tHttpDelete request = new HttpDelete(currentTransactionUrl);\n\t\t\tNeo4jResponse response = this.executeHttpRequest(request);\n\t\t\tif (response.getCode() != 200 & response.hasErrors()) {\n\t\t\t\tthrow new SQLException(response.displayErrors());\n\t\t\t}\n\t\t\tthis.currentTransactionUrl = this.transactionUrl;\n\t\t}\n\t}\n\n\t/**\n\t * Getter for AutoCommit.\n\t *\n\t * @return true if statement are automatically committed\n\t */\n\tpublic Boolean getAutoCommit() {\n\t\treturn autoCommit;\n\t}\n\n\t/**\n\t * Setter for autocommit.\n\t *\n\t * @param autoCommit enable/disable autocommit\n\t * @throws SQLException sqlexception\n\t */\n\tpublic void setAutoCommit(Boolean autoCommit) throws SQLException {\n\t\t// we only do something if there is a change\n\t\tif (this.autoCommit != autoCommit) {\n\n\t\t\tif (autoCommit) {\n\t\t\t\t// Check if a transaction is currently opened before\n\t\t\t\t// If so, we commit it\n\t\t\t\tif (getOpenTransactionId() > 0) {\n\t\t\t\t\tthis.commit();\n\t\t\t\t}\n\t\t\t\tthis.autoCommit = Boolean.TRUE;\n\t\t\t\tthis.currentTransactionUrl = this.transactionUrl + \"/commit\";\n\t\t\t} else {\n\t\t\t\tthis.autoCommit = Boolean.FALSE;\n\t\t\t\tthis.currentTransactionUrl = this.transactionUrl;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve the Neo4j version from the server.\n\t *\n\t * @return A string that represent the neo4j server version\n\t */\n\tpublic String getServerVersion() {\n\t\tString result = null;\n\n\t\t// Prepare the headers query\n\t\tHttpGet request = new HttpGet(this.transactionUrl.replace(DB_DATA_TRANSACTION, \"/db/manage/server/version\"));\n\n\t\t// Adding default headers to the request\n\t\tfor (Header header : this.getDefaultHeaders()) {\n\t\t\trequest.addHeader(header.getName(), header.getValue());\n\t\t}\n\n\t\t// Make the request\n\t\ttry (CloseableHttpResponse response = http.execute(request)) {\n\t\t\ttry (InputStream is = response.getEntity().getContent()) {\n\t\t\t\tMap body = mapper.readValue(is, Map.class);\n\t\t\t\tif (body.get(\"version\") != null) {\n\t\t\t\t\tresult = (String) body.get(\"version\");\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tresult = \"Unknown\";\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Close all thing in this object.\n\t * @throws SQLException sqlexception\n\t */\n\n\tpublic void close() throws SQLException {\n\t\ttry {\n\t\t\thttp.close();\n\t\t} catch (IOException e) {\n\t\t\tthrow new SQLException(e);\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve the transaction id from an url.\n\t *\n\t * @param url An url\n\t * @return The transaction id if there is an opened transaction, <code>-1</code> otherwise\n\t */\n\tInteger getTransactionId(String url) {\n\t\tInteger transactId = -1;\n\t\tif (url != null && url.contains(transactionUrl)) {\n\t\t\tString[] tab = url.split(\"/\");\n\t\t\tString last = tab[tab.length - 1];\n\t\t\ttry {\n\t\t\t\ttransactId = Integer.valueOf(last);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\ttransactId = -1;\n\t\t\t}\n\t\t}\n\t\treturn transactId;\n\t}\n\n\t/**\n\t * Retrieve the current transaction id.\n\t *\n\t * @return The transaction id, or <code>-1</code> if there is no transaction.\n\t */\n\tpublic Integer getOpenTransactionId() {\n\t\treturn getTransactionId(this.currentTransactionUrl);\n\t}\n\n\t/**\n\t * Give the default http client default header for Neo4j API.\n\t *\n\t * @return List of default headers.\n\t */\n\tprivate Header[] getDefaultHeaders() {\n\t\tHeader[] headers = new Header[2];\n\t\theaders[0] = new BasicHeader(\"Accept\", ContentType.APPLICATION_JSON.toString());\n\t\theaders[1] = new BasicHeader(\"X-Stream\", \"true\");\n\n\t\treturn headers;\n\t}\n\n\t/**\n\t * Execute the http client request.\n\t *\n\t * @param request The request to make\n\t */\n\tprivate Neo4jResponse executeHttpRequest(HttpRequestBase request) throws SQLException {\n\t\tNeo4jResponse result;\n\n\t\t// Adding default headers to the request\n\t\tfor (Header header : this.getDefaultHeaders()) {\n\t\t\trequest.addHeader(header.getName(), header.getValue());\n\t\t}\n\n\t\t// Make the request\n\t\ttry (CloseableHttpResponse response = http.execute(request)) {\n\t\t\tresult = new Neo4jResponse(response, mapper);\n\t\t\tif(!getAutoCommit()) {\n\t\t\t\tif (result.hasErrors()) {\n\t\t\t\t\t// The transaction *was* rolled back server-side. Whether a transaction existed or not before, it should\n\t\t\t\t\t// now be considered rolled back on this side as well.\n\t\t\t\t\tthis.currentTransactionUrl = this.transactionUrl;\n\t\t\t\t} else if (result.getLocation() != null) {\n\t\t\t\t\t// Here we reconstruct the location in case of a proxy, but in this case you should redirect write queries to the master.\n\t\t\t\t\tInteger transactionId = this.getTransactionId(result.getLocation());\n\t\t\t\t\tthis.currentTransactionUrl = this.transactionUrl + \"/\" + transactionId;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tthrow new SQLException(e);\n\t\t}\n\n\t\treturn result;\n\t}\n\n}", "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic class Neo4jResponse {\n\n\t/**\n\t * HTTP code\n\t */\n\tprivate Integer code;\n\n\t/**\n\t * Transaction url receive in case of a ne one.\n\t */\n\tprivate String location;\n\n\t/**\n\t * List of query result.\n\t */\n\tprivate List<Neo4jResult> results;\n\n\t/**\n\t * List of Neo4j error.\n\t */\n\tprivate List<SQLException> errors;\n\n\t/**\n\t * Construct the object directly from the HttpResponse.\n\t *\n\t * @param response Http response\n\t * @param mapper Jackson object mapper\n\t * @throws SQLException sqlexception\n\t */\n\tpublic Neo4jResponse(HttpResponse response, ObjectMapper mapper) throws SQLException {\n\t\t// Parse response headers\n\t\tif (response.getStatusLine() != null) {\n\n\t\t\tsaveCodeAndLocation(response);\n\n\t\t\t// Parsing the body\n\t\t\tHttpEntity json = response.getEntity();\n\t\t\tif (json != null) {\n\t\t\t\ttry (InputStream is = json.getContent()) {\n\t\t\t\t\tMap body = mapper.readValue(is, Map.class);\n\n\t\t\t\t\t// Error parsing\n\t\t\t\t\tparseErrors(body);\n\n\t\t\t\t\t// Data parsing\n\t\t\t\t\tparseData(body);\n\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tthrow new SQLException(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tthrow new SQLException(\"Receive request without status code ...\");\n\t\t}\n\t}\n\t\n\t/**\n\t * @return the code\n\t */\n\tpublic Integer getCode() {\n\t\treturn this.code;\n\t}\n\t\n\t/**\n\t * @return the location\n\t */\n\tpublic String getLocation() {\n\t\treturn this.location;\n\t}\n\t\n\t/**\n\t * @return the results\n\t */\n\tpublic List<Neo4jResult> getResults() {\n\t\treturn this.results;\n\t}\n\t\n\t/**\n\t * @return the first result\n\t */\n\tpublic Neo4jResult getFirstResult() {\n\t\tif (this.results != null && !this.results.isEmpty())\n\t\t\treturn this.results.get(0);\n\t\telse\n\t\t\treturn null;\n\t}\n\t\n\t/**\n\t * @return the errors\n\t */\n\tpublic List<SQLException> getErrors() {\n\t\treturn this.errors;\n\t}\n\n\t/**\n\t * Is this response has errors ?\n\t * @return true is there're errors\n\t */\n\tpublic boolean hasErrors() {\n\t\tBoolean hasErrors = Boolean.FALSE;\n\t\tif (this.errors != null && !this.errors.isEmpty()) {\n\t\t\thasErrors = Boolean.TRUE;\n\t\t}\n\t\treturn hasErrors;\n\t}\n\n\t/**\n\t * Has this response at least one result set ?\n\t * @return true is there're result sets\n\t */\n\tpublic boolean hasResultSets() {\n\t\tBoolean hasResultSets = Boolean.FALSE;\n\t\tif (this.results != null && !this.results.isEmpty()) {\n\t\t\tfor (int i = 0; i < this.results.size() && !hasResultSets; i++) {\n\t\t\t\tNeo4jResult result = this.results.get(i);\n\t\t\t\tif ((result.getColumns() != null && result.getColumns().size() > 0) || (result.getRows() != null && result.getRows().size() > 0)) {\n\t\t\t\t hasResultSets = Boolean.TRUE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn hasResultSets;\n\t}\n\n\t/**\n\t * Transform the error list to a string for display purpose.\n\t * @return A String with all errors\n\t */\n\tpublic String displayErrors() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif (hasErrors()) {\n\t\t\tsb.append(\"Some errors occurred : \\n\");\n\t\t\tfor (SQLException error : errors) {\n\t\t\t\tsb.append(\"[\").append(error.getSQLState()).append(\"]\").append(\":\").append(error.getMessage()).append(\"\\n\");\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tprivate void saveCodeAndLocation(HttpResponse response) {\n\t\t// Save the http code\n\t\tthis.code = response.getStatusLine().getStatusCode();\n\n\t\t// If status code is 201, then we retrieve the Location header to keep the transaction url.\n\t\tif (this.code == HttpStatus.SC_CREATED) {\n\t\t\tthis.location = response.getFirstHeader(\"Location\").getValue();\n\t\t}\n\t}\n\n\tprivate void parseErrors(Map body) {\n\t\tthis.errors = new ArrayList<>();\n\t\tfor (Map<String, String> error : (List<Map<String, String>>) body.get(\"errors\")) {\n\t\t\tString message = \"\";\n\t\t\tString errorCode = \"\";\n\t\t\tif(error.get(\"message\") != null) {\n\t\t\t\tmessage = error.get(\"message\");\n\t\t\t}\n\t\t\tif(error.get(\"code\") != null) {\n\t\t\t\terrorCode = error.get(\"code\");\n\t\t\t}\n\t\t\terrors.add(new SQLException(message, errorCode));\n\t\t}\n\t}\n\n\tprivate void parseData(Map body) {\n\t\t// Data parsing\n\t\tthis.results = new ArrayList<>();\n\t\tif (body.containsKey(\"results\")) {\n\t\t\tfor (Map map : (List<Map>) body.get(\"results\")) {\n\t\t\t\tresults.add(new Neo4jResult(map));\n\t\t\t}\n\t\t}\n\t}\n\n}", "public class Neo4jStatement {\n\n\t/**\n\t * Cypher query.\n\t */\n\tpublic final String statement;\n\n\t/**\n\t * Params of the cypher query.\n\t */\n\tpublic final Map<String, Object> parameters;\n\n\t/**\n\t * Do we need to include stats with the query ?\n\t */\n\tpublic final Boolean includeStats;\n\n\t/**\n\t * Default constructor.\n\t *\n\t * @param statement Cypher query\n\t * @param parameters List of named params for the cypher query\n\t * @param includeStats Do we need to include stats\n\t * @throws SQLException sqlexception\n\t */\n\tpublic Neo4jStatement(String statement, Map<String, Object> parameters, Boolean includeStats) throws SQLException {\n\t\tif (statement != null && !\"\".equals(statement)) {\n\t\t\tthis.statement = statement;\n\t\t} else {\n\t\t\tthrow new SQLException(\"Creating a NULL query\");\n\t\t}\n\t\tif (parameters != null) {\n\t\t\tthis.parameters = parameters;\n\t\t} else {\n\t\t\tthis.parameters = new HashMap<>();\n\t\t}\n\t\tif (includeStats != null) {\n\t\t\tthis.includeStats = includeStats;\n\t\t} else {\n\t\t\tthis.includeStats = Boolean.FALSE;\n\t\t}\n\t}\n\n\t/**\n\t * Escape method for cypher queries.\n\t *\n\t * @param query Cypher query\n\t * @return ...\n\t */\n\tpublic static String escapeQuery(String query) {\n\t\treturn query.replace('\\\"', '\\'').replace('\\n', ' ');\n\t}\n\n\t/**\n\t * Convert the list of query to a JSON compatible with Neo4j endpoint.\n\t *\n\t * @param queries List of cypher queries.\n\t * @param mapper mapper\n\t * @return The JSON string that correspond to the body of the API call\n\t * @throws SQLException sqlexception\n\t */\n\tpublic static String toJson(List<Neo4jStatement> queries, ObjectMapper mapper) throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\ttry {\n\t\t\tsb.append(\"{\\\"statements\\\":\");\n\t\t\tsb.append(mapper.writeValueAsString(queries));\n\t\t\tsb.append(\"}\");\n\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new SQLException(\"Can't convert Cypher statement(s) into JSON\", e);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * Getter for Statements.\n\t * We escape the string for the API.\n\t * \n\t * @return the statement\n\t */\n\tpublic String getStatement() {\n\t\treturn escapeQuery(statement);\n\t}\n\n}", "public abstract class Neo4jConnectionImpl implements Neo4jConnection {\n\t/**\n\t * JDBC Url used for this connection\n\t */\n\tprivate String url;\n\n\t/**\n\t * JDBC driver properties\n\t */\n\tprivate Properties properties;\n\n\t/**\n\t * Is the connection is in readonly mode ?\n\t */\n\tprivate boolean readOnly = false;\n\n\t/**\n\t * Holdability of the connection\n\t */\n\tprivate int holdability;\n\n\tprotected static final String FASTEST_STATEMENT = \"RETURN 1\";\n\n\t/**\n\t * Default constructor with properties.\n\t *\n\t * @param properties driver properties\n\t * @param url connection url\n\t * @param defaultHoldability connection holdability\n\t */\n\tprotected Neo4jConnectionImpl(Properties properties, String url, int defaultHoldability) {\n\t\tthis.url = url;\n\t\tthis.properties = properties;\n\t\tthis.holdability = defaultHoldability;\n\t}\n\n\tpublic static boolean hasDebug(Properties properties) {\n\t\treturn \"true\".equalsIgnoreCase(properties.getProperty(\"debug\", \"false\"));\n\t}\n\n\t/**\n\t * Get the connection url.\n\t *\n\t * @return String the connection url\n\t */\n\tpublic String getUrl() {\n\t\treturn url;\n\t}\n\n\t/**\n\t * Get the properties for this connection.\n\t *\n\t * @return Properties the properties for this connection\n\t */\n\tpublic Properties getProperties() {\n\t\treturn properties;\n\t}\n\n\t/**\n\t * Get the user of this connection.\n\t *\n\t * @return String\n\t */\n\tpublic String getUserName() {\n\t\treturn properties.getProperty(\"user\");\n\t}\n\n\t/**\n\t * Get the flattening sample rows (-1 if no flattening).\n\t *\n\t * @return int\n\t */\n\tpublic int getFlattening() {\n\t\tString flatten = properties.getProperty(\"flatten\");\n\t\treturn flatten == null ? 0 : Integer.parseInt(flatten);\n\t}\n\n\t/*---------------------------------------*/\n\t/* Some useful check method */\n\t/*---------------------------------------*/\n\n\t/**\n\t * Check if this connection is closed or not.\n\t * If it's closed, then we throw a SQLException, otherwise we do nothing.\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkClosed() throws SQLException {\n\t\tif (this.isClosed()) {\n\t\t\tthrow new SQLException(\"Connection already closed\");\n\t\t}\n\t}\n\n\t/**\n\t * Method to check if we are into autocommit mode.\n\t * If we do, then it throw an exception.\n\t * This method is for using into commit and rollback method.\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkAutoCommit() throws SQLException {\n\t\tif (this.getAutoCommit()) {\n\t\t\tthrow new SQLException(\"Cannot commit when in autocommit\");\n\t\t}\n\t}\n\n\t/**\n\t * Check if can execute the query into the current mode (ie. readonly or not).\n\t * If we can't an SQLException is throw.\n\t *\n\t * @param query Cypher query\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkReadOnly(String query) throws SQLException {\n\t\tif (isReadOnly() && isMutating(query)) {\n\t\t\tthrow new SQLException(\"Mutating Query in readonly mode: \" + query);\n\t\t}\n\t}\n\n\t/**\n\t * Detect some cypher keyword to know if this query mutated the graph.\n\t * /!\\ This not enough now due to procedure procedure.\n\t *\n\t * @param query Cypher query\n\t * @return\n\t */\n\tprivate boolean isMutating(String query) {\n\t\treturn query.matches(\"(?is).*\\\\b(create|relate|delete|set)\\\\b.*\");\n\t}\n\n\t/**\n\t * Check if the holdability parameter conform to specification.\n\t * If it doesn't, we throw an exception.\n\t * {@link java.sql.Connection#setHoldability(int)}\n\t *\n\t * @param resultSetHoldability The holdability value to check\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkHoldabilityParams(int resultSetHoldability) throws SQLException {\n\t\t// @formatter:off\n\t\tif( resultSetHoldability != Neo4jResultSet.HOLD_CURSORS_OVER_COMMIT &&\n\t\t\tresultSetHoldability != Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT\n\t\t){\n\t\t\tthrow new SQLFeatureNotSupportedException();\n\t\t}\n\t\t// @formatter:on\n\t}\n\n\t/**\n\t * Check if the concurrency parameter conform to specification.\n\t * If it doesn't, we throw an exception.\n\t *\n\t * @param resultSetConcurrency The concurrency value to check\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkConcurrencyParams(int resultSetConcurrency) throws SQLException {\n\t\t// @formatter:off\n\t\tif( resultSetConcurrency != Neo4jResultSet.CONCUR_UPDATABLE &&\n\t\t\tresultSetConcurrency != Neo4jResultSet.CONCUR_READ_ONLY\n\t\t){\n\t\t\tthrow new SQLFeatureNotSupportedException();\n\t\t}\n\t\t// @formatter:on\n\t}\n\n\t/**\n\t * Check if the resultset type parameter conform to specification.\n\t * If it doesn't, we throw an exception.\n\t *\n\t * @param resultSetType The concurrency value to check\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkTypeParams(int resultSetType) throws SQLException {\n\t\t// @formatter:off\n\t\tif( resultSetType != Neo4jResultSet.TYPE_FORWARD_ONLY &&\n\t\t\tresultSetType != Neo4jResultSet.TYPE_SCROLL_INSENSITIVE &&\n\t\t\tresultSetType != Neo4jResultSet.TYPE_SCROLL_SENSITIVE\n\t\t){\n\t\t\tthrow new SQLFeatureNotSupportedException();\n\t\t}\n\t\t// @formatter:on\n\t}\n\n\t/**\n\t * Check if the transaction isolation level parameter conform to specification.\n\t * If it doesn't, we throw an exception.\n\t *\n\t * @param level The transaction isolation level value to check\n\t * @throws SQLException sqlexception\n\t */\n\tprotected void checkTransactionIsolation(int level) throws SQLException {\n\t\t// @formatter:off\n\t\tint[] invalid = {\n\t\t\tTRANSACTION_NONE,\n\t\t\tTRANSACTION_READ_COMMITTED,\n\t\t\tTRANSACTION_READ_UNCOMMITTED,\n\t\t\tTRANSACTION_REPEATABLE_READ,\n\t\t\tTRANSACTION_SERIALIZABLE\n\t\t};\n\n\t\tif(!Arrays.asList(invalid).contains(level)){\n\t\t\tthrow new SQLException();\n\t\t}\n\t\t// @formatter:on\n\t}\n\n\t/**\n\t * Check if the auto generated keys parameter conform to specification.\n\t * If it doesn't, we throw an exception.\n\t *\n\t * @param autoGeneratedKeys the auto generated keys value to check\n\t * @throws SQLException sqlexception\n\t */\n\tprivate void checkAutoGeneratedKeys(int autoGeneratedKeys) throws SQLException {\n\t\t// @formatter:off\n\t\tif( autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS &&\n\t\t\t\tautoGeneratedKeys != Statement.NO_GENERATED_KEYS\n\t\t\t\t){\n\t\t\tthrow new SQLException();\n\t\t}\n\t\t// @formatter:on\n\t}\n\n\t/*------------------------------------*/\n\t/* Default implementation */\n\t/*------------------------------------*/\n\n\t@Override public void setReadOnly(boolean readOnly) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.readOnly = readOnly;\n\t}\n\n\t@Override public boolean isReadOnly() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn this.readOnly;\n\t}\n\n\t@Override public void setHoldability(int holdability) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.checkHoldabilityParams(holdability);\n\t\tthis.holdability = holdability;\n\t}\n\n\t@Override public int getHoldability() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn this.holdability;\n\t}\n\n\t/**\n\t * Default implementation of setCatalog.\n\t * Neo4j doesn't implement catalog feature, so we do nothing to avoid some tools exception.\n\t */\n\t@Override public void setCatalog(String catalog) throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn;\n\t}\n\n\t/**\n\t * Default implementation of getCatalog.\n\t * Neo4j doesn't implement catalog feature, so return <code>null</code> (@see {@link java.sql.Connection#getCatalog})\n\t */\n\t@Override public String getCatalog() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn null;\n\t}\n\n\t/**\n\t * Default implementation of getTransactionIsolation.\n\t */\n\t@Override public int getTransactionIsolation() throws SQLException {\n\t\tthis.checkClosed();\n\t\treturn TRANSACTION_READ_COMMITTED;\n\t}\n\n\t/**\n\t * Default implementation of setTransactionIsolation.\n\t */\n\t@Override public void setTransactionIsolation(int level) throws SQLException {\n\t\tthis.checkClosed();\n\t\tthis.checkTransactionIsolation(level);\n\t\tif (level != TRANSACTION_READ_COMMITTED) {\n\t\t\tthrow new SQLException(\"Unsupported isolation level\");\n\t\t}\n\t}\n\n\t/**\n\t * Default implementation of preparedStatement(String, int).\n\t * We're just ignoring the autoGeneratedKeys param.\n\t */\n\t@Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {\n\t\tthis.checkAutoGeneratedKeys(autoGeneratedKeys);\n\t\treturn prepareStatement(sql);\n\t}\n\n\t/**\n\t * Default implementation of nativeSQL.\n\t * Here we should implement some hacks for JDBC tools if needed.\n\t * This method must be used before running a query.\n\t */\n\t@Override public String nativeSQL(String sql) throws SQLException {\n\t\treturn sql;\n\t}\n\n\t@Override public <T> T unwrap(Class<T> iface) throws SQLException {\n\t\treturn org.neo4j.jdbc.Wrapper.unwrap(iface, this);\n\t}\n\n\t@Override public boolean isWrapperFor(Class<?> iface) throws SQLException {\n\t\treturn org.neo4j.jdbc.Wrapper.isWrapperFor(iface, this.getClass());\n\t}\n\n\t@Override public SQLWarning getWarnings() throws SQLException {\n\t\tcheckClosed();\n\t\treturn null;\n\t}\n\n\t@Override public void clearWarnings() throws SQLException {\n\t\tcheckClosed();\n\t}\n\n\t@Override public String getSchema() throws SQLException {\n\t\tcheckClosed();\n\t\treturn null;\n\t}\n\n\t/*---------------------------------*/\n\t/* Not implemented yet */\n\t/*---------------------------------*/\n\n\t@Override public java.sql.CallableStatement prepareCall(String sql) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Map<String, Class<?>> getTypeMap() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Savepoint setSavepoint() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Savepoint setSavepoint(String name) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void rollback(Savepoint savepoint) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void releaseSavepoint(Savepoint savepoint) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Clob createClob() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Blob createBlob() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public NClob createNClob() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public SQLXML createSQLXML() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setClientInfo(String name, String value) throws SQLClientInfoException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setClientInfo(Properties properties) throws SQLClientInfoException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public String getClientInfo(String name) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Properties getClientInfo() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Neo4jArray createArrayOf(String typeName, Object[] elements) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setSchema(String schema) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void abort(Executor executor) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n\t@Override public int getNetworkTimeout() throws SQLException {\n\t\tthrow ExceptionBuilder.buildUnsupportedOperationException();\n\t}\n\n}", "public class ExceptionBuilder {\n\n\tprivate ExceptionBuilder() {}\n\n\t/**\n\t * An <code>UnsupportedOperationException</code> exception builder that retrueve it's caller to make\n\t * a not yet implemented exception with method and class name.\n\t *\n\t * @return an UnsupportedOperationException\n\t */\n\tpublic static UnsupportedOperationException buildUnsupportedOperationException() {\n\t\tStackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();\n\t\tif (stackTraceElements.length > 2) {\n\t\t\tStackTraceElement caller = stackTraceElements[2];\n\n\t\t\tStringBuilder sb = new StringBuilder().append(\"Method \").append(caller.getMethodName()).append(\" in class \").append(caller.getClassName())\n\t\t\t\t\t.append(\" is not yet implemented.\");\n\n\t\t\treturn new UnsupportedOperationException(sb.toString());\n\t\t} else {\n\t\t\treturn new UnsupportedOperationException(\"Not yet implemented.\");\n\t\t}\n\t}\n}", "public class Neo4jJdbcRuntimeException extends RuntimeException {\n\tpublic Neo4jJdbcRuntimeException (Throwable t) {\n\t\tsuper(t);\n\t}\n}", "public class TimeLimitedCodeBlock {\n\n\tprivate TimeLimitedCodeBlock () {}\n\n\t/**\n\t * This method is used to run a specific <code>Runnable</code> for at most a <code>timeout</code> period of time.\n\t * If a <code>timeout</code> of 0 is set then no timeout will be applied.\n\t *\n\t * @param runnable The runnable to run\n\t * @param timeout The maximum time a run should last\n\t * @param timeUnit The <code>TimeUnit</code> unit for the timeout\n\t * @throws Neo4jJdbcRuntimeException Any exception thrown by the runnable wrapped.\n\t */\n\tpublic static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) {\n\t\tExecutorService executor = Executors.newSingleThreadExecutor();\n\t\tFuture future = executor.submit(runnable);\n\t\texecutor.shutdown();\n\t\ttry {\n\t\t\tif (timeout == 0) {\n\t\t\t\tfuture.get();\n\t\t\t} else {\n\t\t\t\tfuture.get(timeout, timeUnit);\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tfuture.cancel(true);\n\t\t\tthrow new Neo4jJdbcRuntimeException(e);\n\t\t}\n\t}\n\n}" ]
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.neo4j.jdbc.*; import org.neo4j.jdbc.http.driver.CypherExecutor; import org.neo4j.jdbc.http.driver.Neo4jResponse; import org.neo4j.jdbc.http.driver.Neo4jStatement; import org.neo4j.jdbc.impl.Neo4jConnectionImpl; import org.neo4j.jdbc.utils.ExceptionBuilder; import org.neo4j.jdbc.utils.Neo4jJdbcRuntimeException; import org.neo4j.jdbc.utils.TimeLimitedCodeBlock; import java.sql.PreparedStatement; import java.sql.SQLException;
/* * Copyright (c) 2016 LARUS Business Automation [http://www.larus-ba.it] * <p> * This file is part of the "LARUS Integration Framework for Neo4j". * <p> * The "LARUS Integration Framework for Neo4j" is 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. * <p> * Created on 15/4/2016 */ package org.neo4j.jdbc.http; public class HttpNeo4jConnection extends Neo4jConnectionImpl implements Loggable { CypherExecutor executor; private boolean isClosed = false; private boolean debug = false; private int debugLevel; /** * Default constructor. * * @param host Hostname of the Neo4j instance. * @param port HTTP port of the Neo4j instance. * @param secure Secure * @param properties Properties of the url connection. * @param url Url * @throws SQLException sqlexption */ public HttpNeo4jConnection(String host, Integer port, Boolean secure, Properties properties, String url) throws SQLException { super(properties, url, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT); this.executor = new CypherExecutor(host, port, secure, properties); } /** * Execute a cypher query. * * @param queries List of cypher queries * @param parameters Parameter of the cypher queries (match by index) * @param stats Do we need to include stats ? * @return ... * @throws SQLException sqlexception */ public Neo4jResponse executeQueries(final List<String> queries, List<Map<String, Object>> parameters, Boolean stats) throws SQLException { checkClosed(); if(queries.size() != parameters.size()) { throw new SQLException("Query and parameter list haven't the same cardinality"); }
List<Neo4jStatement> neo4jStatements = new ArrayList<>();
2