answer
stringlengths
17
10.2M
package net.minecraftforge.client; import java.util.HashMap; import java.util.Random; import java.util.TreeSet; import javax.imageio.ImageIO; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.PixelFormat; import cpw.mods.fml.client.FMLClientHandler; import net.minecraft.client.Minecraft; import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.client.texturepacks.ITexturePack; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderEngine; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.TextureLoadEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.common.IArmorTextureProvider; import net.minecraftforge.common.MinecraftForge; import static net.minecraftforge.client.IItemRenderer.ItemRenderType.*; import static net.minecraftforge.client.IItemRenderer.ItemRendererHelper.*; public class ForgeHooksClient { static RenderEngine engine() { return FMLClientHandler.instance().getClient().renderEngine; } @Deprecated //Deprecated in 1.5.1, move to the more detailed one below. @SuppressWarnings("deprecation") public static String getArmorTexture(ItemStack armor, String _default) { String result = null; if (armor.getItem() instanceof IArmorTextureProvider) { result = ((IArmorTextureProvider)armor.getItem()).getArmorTextureFile(armor); } return result != null ? result : _default; } public static String getArmorTexture(Entity entity, ItemStack armor, String _default, int slot, int layer) { String result = armor.getItem().getArmorTexture(armor, entity, slot, layer); return result != null ? result : _default; } public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks) { IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY); if (customRenderer == null) { return false; } if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION)) { GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F); } if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING)) { GL11.glTranslatef(0.0F, -bobing, 0.0F); } boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D); engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png"); Block block = (item.itemID < Block.blocksList.length ? Block.blocksList[item.itemID] : null); if (is3D || (block != null && RenderBlocks.renderItemIn3d(block.getRenderType()))) { int renderType = (block != null ? block.getRenderType() : 1); float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F); if (RenderItem.renderInFrame) { GL11.glScalef(1.25F, 1.25F, 1.25F); GL11.glTranslatef(0.0F, 0.05F, 0.0F); GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); } GL11.glScalef(scale, scale, scale); int size = item.stackSize; int count = (size > 40 ? 5 : (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1)))); for(int j = 0; j < count; j++) { GL11.glPushMatrix(); if (j > 0) { GL11.glTranslatef( ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale, ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale, ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale); } customRenderer.renderItem(ENTITY, item, renderBlocks, entity); GL11.glPopMatrix(); } } else { GL11.glScalef(0.5F, 0.5F, 0.5F); customRenderer.renderItem(ENTITY, item, renderBlocks, entity); } return true; } public static boolean renderInventoryItem(RenderBlocks renderBlocks, RenderEngine engine, ItemStack item, boolean inColor, float zLevel, float x, float y) { IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, INVENTORY); if (customRenderer == null) { return false; } engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png"); if (customRenderer.shouldUseRenderHelper(INVENTORY, item, INVENTORY_BLOCK)) { GL11.glPushMatrix(); GL11.glTranslatef(x - 2, y + 3, -3.0F + zLevel); GL11.glScalef(10F, 10F, 10F); GL11.glTranslatef(1.0F, 0.5F, 1.0F); GL11.glScalef(1.0F, 1.0F, -1F); GL11.glRotatef(210F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45F, 0.0F, 1.0F, 0.0F); if(inColor) { int color = Item.itemsList[item.itemID].getColorFromItemStack(item, 0); float r = (float)(color >> 16 & 0xff) / 255F; float g = (float)(color >> 8 & 0xff) / 255F; float b = (float)(color & 0xff) / 255F; GL11.glColor4f(r, g, b, 1.0F); } GL11.glRotatef(-90F, 0.0F, 1.0F, 0.0F); renderBlocks.useInventoryTint = inColor; customRenderer.renderItem(INVENTORY, item, renderBlocks); renderBlocks.useInventoryTint = true; GL11.glPopMatrix(); } else { GL11.glDisable(GL11.GL_LIGHTING); GL11.glPushMatrix(); GL11.glTranslatef(x, y, -3.0F + zLevel); if (inColor) { int color = Item.itemsList[item.itemID].getColorFromItemStack(item, 0); float r = (float)(color >> 16 & 255) / 255.0F; float g = (float)(color >> 8 & 255) / 255.0F; float b = (float)(color & 255) / 255.0F; GL11.glColor4f(r, g, b, 1.0F); } customRenderer.renderItem(INVENTORY, item, renderBlocks); GL11.glPopMatrix(); GL11.glEnable(GL11.GL_LIGHTING); } return true; } @Deprecated public static void renderEquippedItem(IItemRenderer customRenderer, RenderBlocks renderBlocks, EntityLiving entity, ItemStack item) { renderEquippedItem(ItemRenderType.EQUIPPED, customRenderer, renderBlocks, entity, item); } public static void renderEquippedItem(ItemRenderType type, IItemRenderer customRenderer, RenderBlocks renderBlocks, EntityLiving entity, ItemStack item) { if (customRenderer.shouldUseRenderHelper(type, item, EQUIPPED_BLOCK)) { GL11.glPushMatrix(); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); customRenderer.renderItem(type, item, renderBlocks, entity); GL11.glPopMatrix(); } else { GL11.glPushMatrix(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glTranslatef(0.0F, -0.3F, 0.0F); GL11.glScalef(1.5F, 1.5F, 1.5F); GL11.glRotatef(50.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F); GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F); customRenderer.renderItem(type, item, renderBlocks, entity); GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); } } //Optifine Helper Functions u.u, these are here specifically for Optifine //Note: When using Optfine, these methods are invoked using reflection, which //incurs a major performance penalty. public static void orientBedCamera(Minecraft mc, EntityLiving entity) { int x = MathHelper.floor_double(entity.posX); int y = MathHelper.floor_double(entity.posY); int z = MathHelper.floor_double(entity.posZ); Block block = Block.blocksList[mc.theWorld.getBlockId(x, y, z)]; if (block != null && block.isBed(mc.theWorld, x, y, z, entity)) { int var12 = block.getBedDirection(mc.theWorld, x, y, z); GL11.glRotatef((float)(var12 * 90), 0.0F, 1.0F, 0.0F); } } public static boolean onDrawBlockHighlight(RenderGlobal context, EntityPlayer player, MovingObjectPosition target, int subID, ItemStack currentItem, float partialTicks) { return MinecraftForge.EVENT_BUS.post(new DrawBlockHighlightEvent(context, player, target, subID, currentItem, partialTicks)); } public static void dispatchRenderLast(RenderGlobal context, float partialTicks) { MinecraftForge.EVENT_BUS.post(new RenderWorldLastEvent(context, partialTicks)); } public static void onTextureLoad(String texture, ITexturePack pack) { MinecraftForge.EVENT_BUS.post(new TextureLoadEvent(texture, pack)); } public static void onTextureStitchedPre(TextureMap map) { MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Pre(map)); } public static void onTextureStitchedPost(TextureMap map) { MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Post(map)); } /** * This is added for Optifine's convenience. And to explode if a ModMaker is developing. * @param texture */ public static void onTextureLoadPre(String texture) { if (Tessellator.renderingWorldRenderer) { String msg = String.format("Warning: Texture %s not preloaded, will cause render glitches!", texture); System.out.println(msg); if (Tessellator.class.getPackage() != null) { if (Tessellator.class.getPackage().getName().startsWith("net.minecraft.")) { Minecraft mc = FMLClientHandler.instance().getClient(); if (mc.ingameGUI != null) { mc.ingameGUI.getChatGUI().printChatMessage(msg); } } } } } static int renderPass = -1; public static void setRenderPass(int pass) { renderPass = pass; } public static ModelBiped getArmorModel(EntityLiving entityLiving, ItemStack itemStack, int slotID, ModelBiped _default) { ModelBiped modelbiped = itemStack.getItem().getArmorModel(entityLiving, itemStack, slotID); return modelbiped == null ? _default : modelbiped; } static int stencilBits = 0; public static void createDisplay() throws LWJGLException { ImageIO.setUseCache(false); //Disable on-disc stream cache should speed up texture pack reloading. PixelFormat format = new PixelFormat().withDepthBits(24); try { //TODO: Figure out how to determine the max bits. Display.create(format.withStencilBits(8)); stencilBits = 8; } catch(LWJGLException e) { Display.create(format); stencilBits = 0; } } }
package com.tisawesomeness.minecord.util; import java.awt.Color; import java.time.OffsetDateTime; import java.util.regex.Pattern; import org.apache.commons.lang3.ArrayUtils; import com.tisawesomeness.minecord.Bot; import com.tisawesomeness.minecord.Config; import com.tisawesomeness.minecord.database.Database; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.SelfUser; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.User; public class MessageUtils { public static final String dateHelp = "In [date], you may define a date, time, and timezone." + "\n" + "Dates are `mm/dd` or `mm/dd/yyyy`" + "\n" + "Date Examples:" + "\n" + "`9/25`" + " | " + "`2/29/2012`" + " | " + "`5/15 8:30`" + " | " + "`3/2/06 2:47:32`" + " | " + "`9:00 PM`" + " | " + "`12/25/12 12:00 AM EST`" + " | " + "`5:22 CST`"; public static long ownerID; public static TextChannel logChannel; public static int totalChance; /** * Formats a message to look more fancy using an embed. Pass null in any argument (except color) to remove that aspect of the message. * @param title The title or header of the message. * @param url A URL that the title goes to when clicked. Only works if title is not null. * @param body The main body of the message. * @param color The color of the embed. Discord markdown formatting and newline are supported. * @param thumb The URL of the thumbnail. * @return A MessageEmbed representing the message. You can add additional info (e.g. fields) by passing this variable into a new EmbedBuilder. */ public static MessageEmbed embedMessage(String title, String url, String body, Color color) { EmbedBuilder eb = new EmbedBuilder(); if (title != null) eb.setTitle(title, url); eb.setDescription(body); eb.setColor(color); eb = addFooter(eb); return eb.build(); } /** * Formats an image to look more fancy using an embed. * @param title The title or header. * @param url The URL of the image. * @param color The color of the embed. Discord markdown formatting and newline are supported. * @return A MessageEmbed representing the message. You can add additional info (e.g. fields) by passing this variable into a new EmbedBuilder. */ public static MessageEmbed embedImage(String title, String url, Color color) { EmbedBuilder eb = new EmbedBuilder(); if (title != null) {eb.setAuthor(title, null, null);} eb.setImage(url); eb.setColor(color); eb = addFooter(eb); return eb.build(); } public static EmbedBuilder addFooter(EmbedBuilder eb) { int rand = (int) (Math.random() * MessageUtils.totalChance); int i = -1; while (rand >= 0) { i++; rand -= Config.getAnnouncements().get(i).getChance(); } String announcement = Config.getAnnouncements().get(i).getText(); if (Config.getOwner().equals("0")) { return eb.setFooter(announcement); } User owner = Bot.shardManager.retrieveUserById(Config.getOwner()).complete(); return eb.setFooter(announcement, owner.getAvatarUrl()); } /** * Returns one of 16 random colors public static Color randomColor() { final Color[] colors = new Color[]{ new Color(0, 0, 0), new Color(0, 0, 170), new Color(0, 170, 0), new Color(0, 170, 170), new Color(170, 0, 0), new Color(170, 0, 170), new Color(255, 170, 0), new Color(170, 170, 170), new Color(85, 85, 85), new Color(85, 85, 255), new Color(85, 255, 85), new Color(85, 255, 255), new Color(255, 85, 85), new Color(255, 85, 255), new Color(255, 255, 85), new Color(255, 255, 255) }; return colors[new Random().nextInt(colors.length)]; } */ /** * Parses boolean arguments. * @param search The string array to search through. * @param include A string that also means true. * @return The first index of the boolean argument. Returns -1 if not found. */ public static int parseBoolean(String[] search, String include) { String[] words = new String[]{"true", "yes", "allow", include}; for (String word : words) { int index = ArrayUtils.indexOf(search, word); if (index > -1) { return index; } } return -1; } /** * Logs a message to the logging channel. */ public static void log(String m) { if (!Config.getLogChannel().equals("0")) { logChannel.sendMessage(m).queue(); } } /** * Logs a message to the logging channel. */ public static void log(Message m) { if (!Config.getLogChannel().equals("0")) { logChannel.sendMessage(m).queue(); } } /** * Logs a message to the logging channel. */ public static void log(MessageEmbed m) { if (!Config.getLogChannel().equals("0")) { EmbedBuilder eb = new EmbedBuilder(m); eb.setTimestamp(OffsetDateTime.now()); logChannel.sendMessage(eb.build()).queue(); } } /** * Gets the command-useful content of a message, keeping the name and arguments and purging the prefix and mention. */ public static String[] getContent(Message m, long id, SelfUser su) { String content = m.getContentRaw(); if (m.getContentRaw().startsWith(Database.getPrefix(id))) { return content.replaceFirst(Pattern.quote(Database.getPrefix(id)), "").split(" "); } else if (content.replaceFirst("@!", "@").startsWith(su.getAsMention())) { String[] args = content.split(" "); return ArrayUtils.removeElement(args, args[0]); } else { return null; } } public static String dateErrorString(long id, String cmd) { return ":x: Improperly formatted date. " + "At least a date or time is required. " + "Do `" + Database.getPrefix(id) + cmd + "` for more info."; } }
package com.valkryst.VTerminal.misc; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.valkryst.VTerminal.AsciiCharacter; import com.valkryst.VTerminal.font.Font; import lombok.Getter; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Objects; import java.util.concurrent.TimeUnit; public class ColoredImageCache { /** The cache. */ private final Cache<Integer, BufferedImage> cachedImages; /** The font of the character images. */ @Getter private final Font font; /** * Constructs a new ColoredImageCache. * * @param font * The font. * * @throws NullPointerException * If the font is null. */ public ColoredImageCache(final Font font) { Objects.requireNonNull(font); this.font = font; cachedImages = Caffeine.newBuilder() .initialCapacity(100) .maximumSize(10_000) .expireAfterAccess(5, TimeUnit.MINUTES) .build(); } /** * Constructs a new ColoredImageCache. * * @param font * The font. * * @param maxCacheSize * The maximum number of images to save in the cache. * * @throws NullPointerException * If the font is null. */ public ColoredImageCache(final Font font, final int maxCacheSize) { Objects.requireNonNull(font); this.font = font; cachedImages = Caffeine.newBuilder() .initialCapacity(100) .maximumSize(maxCacheSize) .expireAfterAccess(5, TimeUnit.MINUTES) .build(); } @Override public int hashCode() { return Objects.hash(cachedImages); } /** * Retrieves a character image from the cache. * * If no image could be found, then one is created, inserted into * the cache, and then returned. * * @param character * The character. * * @return * The character image. * * @throws NullPointerException * If the character is null. */ public BufferedImage retrieveFromCache(final AsciiCharacter character) { Objects.requireNonNull(character); final int hashCode = Objects.hash(character.getCharacter(), character.getBackgroundColor(), character.getForegroundColor()); BufferedImage image = cachedImages.getIfPresent(hashCode); if (image == null) { image = applyColorSwap(character, font); cachedImages.put(hashCode, image); } return image; } /** * Gets a character image for a character and applies the back/foreground * colors to it. * * @param font * The font to retrieve the base character image from. * * @return * The character image. * * @throws NullPointerException * If the character is null. */ private static BufferedImage applyColorSwap(final AsciiCharacter character, final Font font) { Objects.requireNonNull(character); BufferedImage image; try { image = cloneImage(font.getCharacterImage(character.getCharacter())); } catch (final NullPointerException e) { System.err.println("Couldn't display '" + character.getCharacter() + "', represented by the decimal + (int) character.getCharacter() +"."); System.err.println("When this error occurs, it means that the font being used does not contain a sprite" + " for the character being used."); System.err.println("Defaulting to the '?' sprite.\n"); image = cloneImage(font.getCharacterImage('?')); } final int backgroundRGB = character.getBackgroundColor().getRGB(); final int foregroundRGB = character.getForegroundColor().getRGB(); for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = image.getRGB(x, y); int alpha = (pixel >> 24) & 0xff; int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; boolean isTransparent = alpha != 255; isTransparent &= red == 0; isTransparent &= green == 0; isTransparent &= blue == 0; if (isTransparent) { image.setRGB(x, y, backgroundRGB); } else { image.setRGB(x, y, foregroundRGB); } } } return image; } /** * Makes a clone of an image. * * @param image * The image. * * @return * The clone image. * * @throws NullPointerException * If the image is null. */ private static BufferedImage cloneImage(final BufferedImage image) { Objects.requireNonNull(image); final BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType()); final Graphics g = newImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return newImage; } }
package com.xruby.runtime.builtin; import antlr.RecognitionException; import antlr.TokenStreamException; import com.xruby.runtime.lang.*; import com.xruby.compiler.*; import com.xruby.compiler.codegen.*; import com.xruby.runtime.value.*; import com.xruby.runtime.javasupport.JavaClass; import java.io.*; import java.util.jar.*; import java.util.*; import java.util.regex.Pattern; //TODO imcomplete class Kernel_eval extends RubyVarArgMethod { static RubyValue eval(RubyString program_text, RubyBinding binding) { RubyCompiler compiler = new RubyCompiler(binding, false); try { CompilationResults codes = compiler.compile(new StringReader(program_text.toString())); RubyProgram p = codes.getRubyProgram(); if (null != binding) { return p.invoke(binding.getSelf(), binding.getVariables(), binding.getBlock(), binding.getScope()); } else { return p.invoke(); } } catch (RecognitionException e) { throw new RubyException(e.toString()); } catch (TokenStreamException e) { throw new RubyException(e.toString()); } catch (CompilerException e) { throw new RubyException(e.toString()); } catch (InstantiationException e) { throw new RubyException(e.toString()); } catch (IllegalAccessException e) { throw new RubyException(e.toString()); } } protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString program_text = (RubyString)args.get(0); RubyBinding binding = null; if (args.get(1) instanceof RubyBinding) { binding = (RubyBinding)args.get(1); } return eval(program_text, binding); } } class Kernel_binding extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { //compiler will do the magic and insert Binding object return args.get(0); } } class Kernel_puts extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { for (RubyValue arg : args) { if (ObjectFactory.nilValue == arg) { System.out.print("nil\n"); } else if (arg instanceof RubyString){ RubyString value = (RubyString)arg; value.appendString("\n"); System.out.print(value.toString()); } else { RubyValue str = RubyAPI.callPublicMethod(arg, null, null, CommonRubyID.toSID); RubyString value = (RubyString)str; value.appendString("\n"); System.out.print(value.toString()); } } return ObjectFactory.nilValue; } } class Kernel_print extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { return _run(GlobalVariables.get("$stdout"), args, block); } protected RubyValue _run(RubyValue receiver, RubyArray args, RubyBlock block) { // if no argument given, print `$_' if (null == args) { args = new RubyArray(GlobalVariables.get("$_")); } for (int i = 0; i < args.size(); ++i) { // insert the output field separator($,) if not nil if (i > 0 && GlobalVariables.get("$,") != ObjectFactory.nilValue) { RubyAPI.callPublicOneArgMethod(receiver, GlobalVariables.get("$,"), null, "write"); } if (args.get(i) == ObjectFactory.nilValue) { RubyAPI.callPublicOneArgMethod(receiver, ObjectFactory.createString("nil"), null, "write"); } else { RubyAPI.callPublicOneArgMethod(receiver, args.get(i), null, "write"); } } // if the output record separator($\) is not nil, it will be appended to the output. if ( GlobalVariables.get("$\\") != ObjectFactory.nilValue) { RubyAPI.callPublicOneArgMethod(receiver, GlobalVariables.get("$\\"), null, "write"); } return ObjectFactory.nilValue; } } class Kernel_printf extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { Object[] raw_args = new Object[args.size() - 1]; for (int i = 1; i < args.size(); ++i) { Object v = args.get(i); if (v instanceof RubyFixnum) { raw_args[i - 1] = new Integer(((RubyFixnum)v).intValue()); } else if (args.get(i) instanceof RubyString) { raw_args[i - 1] = args.get(i); } else { raw_args[i - 1] = v; } } String fmt = ((RubyString)args.get(0)).toString(); System.out.printf(fmt, raw_args); return ObjectFactory.nilValue; } } class Kernel_p extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null != args) { for (RubyValue arg : args) { RubyValue str = RubyAPI.callPublicMethod(arg, null, null, CommonRubyID.inspectID); RubyString value = (RubyString)str; value.appendString("\n"); System.out.print(value.toString()); } } return ObjectFactory.nilValue; } } class Kernel_class extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { return receiver.getRubyClass(); } } class Kernel_operator_case_equal extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (receiver == arg) { return ObjectFactory.trueValue; } else { return RubyAPI.callPublicOneArgMethod(receiver, arg, block, "=="); } } } class Kernel_method_missing extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubySymbol method_name = (RubySymbol)args.get(0); throw new RubyException(RubyRuntime.NoMethodErrorClass, "undefined method '" + method_name.toString()+ "' for " + receiver.getRubyClass().getName()); } } class Kernel_raise extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == args) { //With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. RubyValue v = GlobalVariables.get("$!"); if (ObjectFactory.nilValue != v) { throw new RubyException((RubyClass)v, ""); } else { throw new RubyException(RubyRuntime.RuntimeErrorClass, ""); } } else if (1 == args.size() && (args.get(0) instanceof RubyString)) { //With a single String argument, raises a RuntimeError with the string as a message. throw new RubyException(RubyRuntime.RuntimeErrorClass, ((RubyString)args.get(0)).toString()); } else if (args.get(0) instanceof RubyExceptionValue) { //Otherwise, the first parameter should be the name of an Exception class //(or an object that returns an Exception when sent exception). The optional second //parameter sets the message associated with the exception, and the third parameter //is an array of callback information. RubyExceptionValue v = (RubyExceptionValue)args.get(0); v.setMessage(1 == args.size() ? "" : ((RubyString)args.get(1)).toString()); throw new RubyException(v); } else { RubyClass v = (RubyClass)args.get(0); throw new RubyException(v, 1 == args.size() ? "" : ((RubyString)args.get(1)).toString()); } } } class JarLoader extends ClassLoader { public RubyProgram load(File filename) { JarFile jar = null; try { jar = new JarFile(filename); return _load(jar); } catch (IOException e) { return null; } catch (InstantiationException e) { return null; } catch (IllegalAccessException e) { return null; } finally { if (null != jar) { try { jar.close(); } catch (IOException e) { } } } } private RubyProgram _load(JarFile jar) throws IOException, InstantiationException, IllegalAccessException { RubyProgram p = null; for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) { JarEntry entry = e.nextElement(); if (!entry.getName().endsWith(".class")) { continue; } BufferedInputStream stream = new BufferedInputStream(jar.getInputStream(entry)); byte[] buffer = new byte[(int)entry.getSize()]; stream.read(buffer); Class c = defineClass(NameFactory.filename2classname(entry.getName()), buffer, 0, buffer.length); if (entry.getName().endsWith("main.class")) {//FIXME better error checking p = (RubyProgram)c.newInstance(); } } return p; } } class Kernel_require extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { RubyString required_file = (RubyString)arg; File filename = NameFactory.find_corresponding_jar_file(required_file.toString(), null);//TODO search $: if (null == filename) { throw new RubyException(RubyRuntime.LoadErrorClass, "no such file to load -- " + required_file); } JarLoader jarloader = new JarLoader(); RubyProgram p = jarloader.load(filename); if (null == p) { throw new RubyException(RubyRuntime.LoadErrorClass, "no such file to load -- " + required_file); } p.invoke(); return ObjectFactory.trueValue; } } class Kernel_require_java extends RubyOneArgMethod { private static Pattern packagePattern = Pattern.compile("\\."); protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { RubyString className = (RubyString)arg; try { Class clazz = Class.forName(className.toString()); String[] names = packagePattern.split(className.toString()); String name = names[names.length - 1]; JavaClass jClazz = new JavaClass(clazz); //TODO: The naming mechanism is not quite appropriate RubyAPI.setTopLevelConstant(jClazz, name); RubyAPI.setTopLevelConstant(jClazz, className.toString()); } catch (ClassNotFoundException e) { throw new RubyException("Couldn't find class " + className.toString()); } return ObjectFactory.trueValue; } } class Kernel_load extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { throw new RubyException("not implemented!"); /* * Loads and executes the Ruby program in the file aFileName. * If the filename does not resolve to an absolute path, the * file is searched for in the library directories listed in $:. * If the optional wrap parameter is true, the loaded script will * be executed under an anonymous module, protecting the calling * program's global namespace. Any local variables in the loaded * file will not be propagated to the loading environment. */ } } class Kernel_to_s extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { String className = receiver.getRubyClass().getName(); return ObjectFactory.createString("#<" + className + ":0x" + Integer.toHexString(receiver.hashCode()) + "x>"); } } class Kernel_lambda extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { block.setCreatedByLambda(); return ObjectFactory.createProc(block); } } class Kernel_loop extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == block) { throw new RubyException(RubyRuntime.LocalJumpErrorClass, "in `loop': no block given"); } for (;;) { RubyValue v = block.invoke(receiver, args); if (block.breakedOrReturned()) { return v; } } } } class Kernel_open extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyString filename = (RubyString)args.get(0); RubyIO io; if (args.size() <= 1) { io = ObjectFactory.createFile(filename.toString(), "r"); } else { RubyString mode = (RubyString)args.get(1); io = ObjectFactory.createFile(filename.toString(), mode.toString()); } if (null == block) { return io; } else { RubyValue v = block.invoke(receiver, new RubyArray(io)); io.close(); return v; } } } class Kernel_kind_of extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (RubyAPI.isKindOf(arg, receiver)) { return ObjectFactory.trueValue; } else { return ObjectFactory.falseValue; } } } class Kernel_instance_of extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (RubyAPI.isInstanceOf(arg, receiver)) { return ObjectFactory.trueValue; } else { return ObjectFactory.falseValue; } } } class Kernel_respond_to extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { assertArgNumberAtLeast(args, 1); boolean include_private = (ObjectFactory.trueValue == args.get(1)); RubyID mid = StringMap.intern(convertToString(args.get(0))); if (hasMethod(receiver, mid, include_private)) { return ObjectFactory.trueValue; } else { return ObjectFactory.falseValue; } } private boolean hasMethod(RubyValue receiver, RubyID mid, boolean include_private) { if (include_private) { return (null != receiver.findMethod(mid)); } else { return (null != receiver.findPublicMethod(mid)); } } } class Kernel_send extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (args.size() < 1) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "no method name given"); } RubyValue method_name = args.remove(0); RubyID mid = StringMap.intern(convertToString(method_name)); if (args.size() == 0) { return RubyAPI.callMethod(receiver, null, block, mid); } else if (args.size() == 1) { return RubyAPI.callOneArgMethod(receiver, args.get(0), block, mid); } else { return RubyAPI.callMethod(receiver, args, block, mid); } } } class Kernel_method extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { String method_name = convertToString(arg); RubyID mid = StringMap.intern(method_name); RubyMethod m = receiver.findMethod(mid); if (null == m) { throw new RubyException(RubyRuntime.NameErrorClass, "public method '" + method_name + "' can not be found in '" + receiver.getRubyClass().getName() + "'"); } return ObjectFactory.createMethod(receiver, method_name, m); } } class Kernel_methods extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { RubyArray a = new RubyArray(); receiver.collectMethodNames(a); return a; } } class Kernel_caller extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { int skip = 1; if (null != args) { skip = ((RubyFixnum)args.get(0)).intValue(); } return FrameManager.caller(skip); } } class Kernel_at_exit extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { if (null == block) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "called without a block"); } AtExitBlocks.registerBlock(block); return ObjectFactory.createProc(block); } } class Kernel_gsub extends String_gsub { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (!(GlobalVariables.get("$_") instanceof RubyString)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "$_ value need to be String (" + GlobalVariables.get("$LAST_READ_LINE").getRubyClass().getName() + " given)"); } GlobalVariables.set(super.run(GlobalVariables.get("$_"), args, block), "$_"); return GlobalVariables.get("$_"); } } class Kernel_gsub_danger extends String_gsub_danger { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (!(GlobalVariables.get("$_") instanceof RubyString)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "$_ value need to be String (" + GlobalVariables.get("$_").getRubyClass().getName() + " given)"); } RubyValue r = super.run(GlobalVariables.get("$_"), args, block); if (r != ObjectFactory.nilValue) { GlobalVariables.set(r, "$_"); } return r; } } class Kernel_throw extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { assertArgNumberAtLeast(args, 1); if (!(args.get(0) instanceof RubySymbol)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, args.get(0).toString() + " is not a symbol"); } RubySymbol s = (RubySymbol)args.get(0); RubyExceptionValueForThrow e = new RubyExceptionValueForThrow(s, args.get(1)); throw new RubyException(e); } } class Kernel_catch extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { if (!(arg instanceof RubySymbol)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, arg.toString() + " is not a symbol"); } try { block.invoke(receiver, null); } catch (RubyException e) { Object ev = e.getRubyValue(); if (ev instanceof RubyExceptionValueForThrow) { RubyExceptionValueForThrow v = (RubyExceptionValueForThrow)ev; if (v.isSameSymbol((RubySymbol)arg)) { return v.getReturnValue(); } } throw e; } return ObjectFactory.nilValue; } } class Kernel_untrace_var extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { assertArgNumberAtLeast(args, 1); if (!(args.get(0) instanceof RubySymbol)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, args.get(0).toString() + " is not a symbol"); } String name = ((RubySymbol)args.get(0)).toString(); RubyValue v = args.get(1); if (v == ObjectFactory.nilValue) { GlobalVariables.removeAllTraceProc(name); } else if (v instanceof RubyProc) { GlobalVariables.removeTraceProc(name, (RubyProc)v); } return ObjectFactory.nilValue; } } class Kernel_trace_var extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { assertArgNumberAtLeast(args, 1); if (!(args.get(0) instanceof RubySymbol)) { throw new RubyException(RubyRuntime.ArgumentErrorClass, args.get(0).toString() + " is not a symbol"); } String name = ((RubySymbol)args.get(0)).toString(); RubyValue v = args.get(1); if (v instanceof RubyProc) { GlobalVariables.addTraceProc(name, (RubyProc)v); } else if (null != block) { GlobalVariables.addTraceProc(name, ObjectFactory.createProc(block)); } else { throw new RubyException(RubyRuntime.ArgumentErrorClass, "tried to create Proc object without a block"); } return ObjectFactory.nilValue; } } class Kernel_block_given extends RubyNoArgMethod { protected RubyValue run(RubyValue receiver, RubyBlock block) { if (null == block) { return ObjectFactory.falseValue; } else { return ObjectFactory.trueValue; } } } class Kernel_gets extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = null; try { s = in.readLine(); } catch (IOException e) { } GlobalVariables.set((null == s ? ObjectFactory.nilValue : ObjectFactory.createString(s)), "$_"); return GlobalVariables.get("$_"); } } class Kernel_instance_eval extends RubyVarArgMethod { protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block) { if (null == args && null == block) { throw new RubyException(RubyRuntime.ArgumentErrorClass, "block not supplied"); } if (null != args) { RubyString program_text = (RubyString)args.get(0); RubyBinding binding = new RubyBinding(); binding.setScope((RubyModule)receiver); binding.setSelf(receiver); return Kernel_eval.eval(program_text, binding); } else { block.setSelf(receiver); return block.invoke(receiver, null); } } } class Kernel_Float extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { return RubyTypesUtil.convertToFloat(arg); } } class Kernel_Integer extends RubyOneArgMethod { protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block) { return RubyTypesUtil.convertToFixnum(arg); } } public class KernelModuleBuilder { public static void initialize() { RubyModule m = RubyRuntime.KernelModule; m.defineMethod("class", new Kernel_class()); RubyMethod raise = new Kernel_raise(); m.defineMethod("raise", raise); m.defineMethod("fail", raise); m.defineMethod("===", new Kernel_operator_case_equal()); m.defineMethod("to_s", new Kernel_to_s()); m.defineMethod("loop", new Kernel_loop()); m.defineMethod("open", new Kernel_open()); m.defineMethod("kind_of?", new Kernel_kind_of()); m.defineMethod("instance_of?", new Kernel_instance_of()); m.defineMethod("respond_to?", new Kernel_respond_to()); RubyMethod send = new Kernel_send(); m.defineMethod("send", send); m.defineMethod("__send__", send); m.defineMethod("instance_eval", new Kernel_instance_eval()); m.defineMethod("method", new Kernel_method()); m.defineMethod("methods", new Kernel_methods()); m.defineMethod("caller", new Kernel_caller()); m.defineMethod("throw", new Kernel_throw()); m.defineMethod("catch", new Kernel_catch()); m.defineMethod("untrace_var", new Kernel_untrace_var()); m.defineMethod("trace_var", new Kernel_trace_var()); RubyMethod block_given = new Kernel_block_given(); m.defineMethod("iterator?", block_given); m.defineMethod("block_given?", block_given); m.defineMethod("Float", new Kernel_Float()); m.defineMethod("Integer", new Kernel_Integer()); //TODO Create a method wrapper so that following methods can be instantiated only once m.getSingletonClass().defineMethod("puts", new Kernel_puts()); m.getSingletonClass().defineMethod("print", new Kernel_print()); m.getSingletonClass().defineMethod("printf", new Kernel_printf()); m.getSingletonClass().defineMethod("p", new Kernel_p()); m.getSingletonClass().defineMethod("gets", new Kernel_gets()); m.setAccessPrivate(); m.defineMethod("puts", new Kernel_puts()); m.defineMethod("print", new Kernel_print()); m.defineMethod("printf", new Kernel_printf()); m.defineMethod("p", new Kernel_p()); m.defineMethod("gets", new Kernel_gets()); m.defineMethod("binding", new Kernel_binding()); m.defineMethod("method_missing", new Kernel_method_missing()); m.defineMethod("eval", new Kernel_eval()); m.defineMethod("require", new Kernel_require()); m.defineMethod("require_java", new Kernel_require_java()); m.defineMethod("load", new Kernel_load()); RubyMethod lambda = new Kernel_lambda(); m.defineMethod("lambda", lambda); m.defineMethod("proc", lambda); m.defineMethod("at_exit", new Kernel_at_exit()); m.defineMethod("gsub", new Kernel_gsub()); m.defineMethod("gsub!", new Kernel_gsub_danger()); m.defineMethod("sub", new Kernel_gsub());//TODO sub != gsub m.setAccessPublic(); RubyRuntime.ObjectClass.includeModule(m); } }
package com.intellij.ide.plugins; import com.intellij.CommonBundle; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.cl.IdeaClassLoader; import com.intellij.ide.plugins.cl.PluginClassLoader; import com.intellij.ide.startup.StartupActionScriptManager; import com.intellij.idea.IdeaApplication; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.impl.PluginsFacade; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.*; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.JDOMUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.graph.CachingSemiGraph; import com.intellij.util.graph.DFSTBuilder; import com.intellij.util.graph.Graph; import com.intellij.util.graph.GraphGenerator; import com.intellij.util.text.StringTokenizer; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import sun.reflect.Reflection; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * @author mike */ @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) // No logger is loaded at this time so we have to use these. public class PluginManager { @SuppressWarnings({"NonConstantLogger"}) //Logger is lasy-initialized in order not to use it outside the appClassLoader private static Logger ourLogger = null; @NonNls public static final String AREA_IDEA_PROJECT = "IDEA_PROJECT"; @NonNls public static final String AREA_IDEA_MODULE = "IDEA_MODULE"; private static Logger getLogger() { if (ourLogger == null) { ourLogger = Logger.getInstance("#com.intellij.ide.plugins.PluginManager"); } return ourLogger; } // these fields are accessed via Reflection, so their names must not be changed by the obfuscator // do not make them private cause in this case they will be scrambled static String[] ourArguments; static String ourMainClass; static String ourMethodName; private static class Facade extends PluginsFacade { public IdeaPluginDescriptor getPlugin(PluginId id) { return PluginManager.getPlugin(id); } public IdeaPluginDescriptor[] getPlugins() { return PluginManager.getPlugins(); } } private static IdeaPluginDescriptorImpl[] ourPlugins; private static Map<String, PluginId> ourPluginClasses; public static void main(final String[] args, final String mainClass, final String methodName) { main(args, mainClass, methodName, new ArrayList<URL>()); } public static void main(final String[] args, final String mainClass, final String methodName, List<URL> classpathElements) { ourArguments = args; ourMainClass = mainClass; ourMethodName = methodName; final PluginManager pluginManager = new PluginManager(); pluginManager.bootstrap(classpathElements); } /** * do not call this method during bootstrap, should be called in a copy of PluginManager, loaded by IdeaClassLoader */ public synchronized static IdeaPluginDescriptor[] getPlugins() { if (ourPlugins == null) { initializePlugins(); } return ourPlugins; } private static void initializePlugins() { if (!shouldLoadPlugins()) { ourPlugins = new IdeaPluginDescriptorImpl[0]; return; } configureExtensions(); final IdeaPluginDescriptorImpl[] pluginDescriptors = loadDescriptors(); final Map<PluginId, IdeaPluginDescriptor> idToDescriptorMap = new HashMap<PluginId, IdeaPluginDescriptor>(); for (final IdeaPluginDescriptor descriptor : pluginDescriptors) { idToDescriptorMap.put(descriptor.getPluginId(), descriptor); } // sort descriptors according to plugin dependencies Arrays.sort(pluginDescriptors, getPluginDescriptorComparator(idToDescriptorMap)); final Class callerClass = Reflection.getCallerClass(1); final ClassLoader parentLoader = callerClass.getClassLoader(); for (final IdeaPluginDescriptorImpl pluginDescriptor : pluginDescriptors) { final List<File> classPath = pluginDescriptor.getClassPath(); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final ClassLoader[] parentLoaders = dependentPluginIds.length > 0 ? getParentLoaders(idToDescriptorMap, dependentPluginIds) : new ClassLoader[]{parentLoader}; final IdeaClassLoader pluginClassLoader = createPluginClassLoader(classPath.toArray(new File[classPath.size()]), pluginDescriptor.getPluginId(), parentLoaders, pluginDescriptor.getPath()); pluginDescriptor.setLoader(pluginClassLoader); pluginDescriptor.registerExtensions(); } ourPlugins = pluginDescriptors; } private static void configureExtensions() { final List<Element> extensionPoints = new ArrayList<Element>(); final List<Element> extensions = new ArrayList<Element>(); try { final Document stdExtensions = JDOMUtil.loadDocument(PluginManager.class.getResourceAsStream("/standard-extensions.xml")); final Element root = stdExtensions.getRootElement(); final List<Element> epRoots = JDOMUtil.getChildrenFromAllNamespaces(root, "extensionPoints"); for (Element epRoot : epRoots) { for (Object o : epRoot.getChildren()) { extensionPoints.add((Element)o); } } final List<Element> extensionRoots = JDOMUtil.getChildrenFromAllNamespaces(root, "extensions"); for (Element extRoot : extensionRoots) { for (Object o : extRoot.getChildren()) { extensions.add((Element)o); } } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Extensions.setLogProvider(new IdeaLogProvider()); Extensions.registerAreaClass(AREA_IDEA_PROJECT, null); Extensions.registerAreaClass(AREA_IDEA_MODULE, AREA_IDEA_PROJECT); Extensions.getRootArea().registerAreaExtensionsAndPoints(RootPluginDescriptor.INSTANCE, extensionPoints, extensions); Extensions.getRootArea().getExtensionPoint(Extensions.AREA_LISTENER_EXTENSION_POINT).registerExtension(new AreaListener() { public void areaCreated(String areaClass, AreaInstance areaInstance) { if (AREA_IDEA_PROJECT.equals(areaClass) || AREA_IDEA_MODULE.equals(areaClass)) { final ExtensionsArea area = Extensions.getArea(areaInstance); area.registerAreaExtensionsAndPoints(RootPluginDescriptor.INSTANCE, extensionPoints, extensions); } } public void areaDisposing(String areaClass, AreaInstance areaInstance) { } }, LoadingOrder.FIRST); } public static boolean shouldLoadPlugins() { try { // no plugins during bootstrap Class.forName("com.intellij.openapi.extensions.Extensions"); } catch (ClassNotFoundException e) { return false; } //noinspection HardCodedStringLiteral final String loadPlugins = System.getProperty("idea.load.plugins"); return loadPlugins == null || Boolean.TRUE.toString().equals(loadPlugins); } public static boolean shouldLoadPlugin(IdeaPluginDescriptor descriptor) { //noinspection HardCodedStringLiteral final String loadPluginCategory = System.getProperty("idea.load.plugins.category"); return loadPluginCategory == null || loadPluginCategory.equals(descriptor.getCategory()); } private static Comparator<IdeaPluginDescriptor> getPluginDescriptorComparator(Map<PluginId, IdeaPluginDescriptor> idToDescriptorMap) { final Graph<PluginId> graph = createPluginIdGraph(idToDescriptorMap); final DFSTBuilder<PluginId> builder = new DFSTBuilder<PluginId>(graph); /* if (!builder.isAcyclic()) { final Pair<String,String> circularDependency = builder.getCircularDependency(); throw new Exception("Cyclic dependencies between plugins are not allowed: \"" + circularDependency.getFirst() + "\" and \"" + circularDependency.getSecond() + ""); } */ final Comparator<PluginId> idComparator = builder.comparator(); return new Comparator<IdeaPluginDescriptor>() { public int compare(IdeaPluginDescriptor o1, IdeaPluginDescriptor o2) { return idComparator.compare(o1.getPluginId(), o2.getPluginId()); } }; } private static Graph<PluginId> createPluginIdGraph(final Map<PluginId, IdeaPluginDescriptor> idToDescriptorMap) { final PluginId[] ids = idToDescriptorMap.keySet().toArray(new PluginId[idToDescriptorMap.size()]); return GraphGenerator.create(CachingSemiGraph.create(new GraphGenerator.SemiGraph<PluginId>() { public Collection<PluginId> getNodes() { return Arrays.asList(ids); } public Iterator<PluginId> getIn(PluginId pluginId) { final IdeaPluginDescriptor descriptor = idToDescriptorMap.get(pluginId); return Arrays.asList(descriptor.getDependentPluginIds()).iterator(); } })); } private static ClassLoader[] getParentLoaders(Map<PluginId, IdeaPluginDescriptor> idToDescriptorMap, PluginId[] pluginIds) { if (ApplicationManager.getApplication().isUnitTestMode()) return new ClassLoader[0]; final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(); for (final PluginId id : pluginIds) { IdeaPluginDescriptor pluginDescriptor = idToDescriptorMap.get(id); if (pluginDescriptor == null) { getLogger().assertTrue(false, "Plugin not found: " + id); return null; } final ClassLoader loader = pluginDescriptor.getPluginClassLoader(); if (loader == null) { getLogger().assertTrue(false, "Plugin class loader should be initialized for plugin " + id); } classLoaders.add(loader); } return classLoaders.toArray(new ClassLoader[classLoaders.size()]); } /** * Called via reflection */ protected static void start() { try { //noinspection HardCodedStringLiteral ThreadGroup threadGroup = new ThreadGroup("Idea Thread Group") { public void uncaughtException(Thread t, Throwable e) { getLogger().error(e); } }; Runnable runnable = new Runnable() { public void run() { try { PluginsFacade.INSTANCE = new Facade(); Class aClass = Class.forName(ourMainClass); final Method method = aClass.getDeclaredMethod(ourMethodName, (ArrayUtil.EMPTY_STRING_ARRAY).getClass()); method.setAccessible(true); method.invoke(null, new Object[]{ourArguments}); } catch (Exception e) { e.printStackTrace(); getLogger().error(e); } } }; //noinspection HardCodedStringLiteral new Thread(threadGroup, runnable, "Idea Main Thread").start(); } catch (Exception e) { getLogger().error(e); } } private static IdeaPluginDescriptorImpl[] loadDescriptors() { if (isLoadingOfExternalPluginsDisabled()) { return IdeaPluginDescriptorImpl.EMPTY_ARRAY; } final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); loadDescriptors(PathManager.getPluginsPath(), result); loadDescriptors(PathManager.getPreinstalledPluginsPath(), result); if (Boolean.valueOf(System.getProperty(IdeaApplication.IDEA_IS_INTERNAL_PROPERTY)).booleanValue()) { loadDescriptorsFromClassPath(result); } String errorMessage = filterBadPlugins(result); IdeaPluginDescriptorImpl[] pluginDescriptors = result.toArray(new IdeaPluginDescriptorImpl[result.size()]); try { Arrays.sort(pluginDescriptors, new PluginDescriptorComparator(pluginDescriptors)); } catch (Exception e) { errorMessage = IdeBundle.message("error.plugins.were.not.loaded", e.getMessage()); pluginDescriptors = IdeaPluginDescriptorImpl.EMPTY_ARRAY; } if (errorMessage != null) { JOptionPane.showMessageDialog(null, errorMessage, IdeBundle.message("title.plugin.error"), JOptionPane.ERROR_MESSAGE); } return pluginDescriptors; } @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) private static void loadDescriptorsFromClassPath(final List<IdeaPluginDescriptorImpl> result) { try { final String homePath = PathManager.getHomePath(); final ClassLoader classLoader = PluginManager.class.getClassLoader(); final Class<? extends ClassLoader> aClass = classLoader.getClass(); if (!aClass.getName().equals(IdeaClassLoader.class.getName())) return; final ArrayList<URL> urls = (ArrayList<URL>)aClass.getDeclaredMethod("getUrls").invoke(classLoader); for (URL url : urls) { final String protocol = url.getProtocol(); if ("file".equals(protocol)) { final File file = new File(url.getFile()); final String canonicalPath = file.getCanonicalPath(); if (!canonicalPath.startsWith(homePath) || canonicalPath.endsWith(".jar")) continue; final IdeaPluginDescriptorImpl pluginDescriptor = loadDescriptor(file); if (pluginDescriptor != null && !result.contains(pluginDescriptor)) { result.add(pluginDescriptor); } } } } catch (Exception e) { System.err.println("Error loading plugins from classpath:"); e.printStackTrace(); } } private static String filterBadPlugins(List<IdeaPluginDescriptorImpl> result) { final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap = new HashMap<PluginId, IdeaPluginDescriptorImpl>(); final StringBuffer message = new StringBuffer(); boolean pluginsWithoutIdFound = false; for (Iterator<IdeaPluginDescriptorImpl> it = result.iterator(); it.hasNext();) { final IdeaPluginDescriptorImpl descriptor = it.next(); final PluginId id = descriptor.getPluginId(); if (idToDescriptorMap.containsKey(id)) { if (message.length() > 0) { message.append("\n"); } message.append(IdeBundle.message("message.duplicate.plugin.id")); message.append(id); it.remove(); } else { idToDescriptorMap.put(id, descriptor); } } for (Iterator<IdeaPluginDescriptorImpl> it = result.iterator(); it.hasNext();) { final IdeaPluginDescriptor pluginDescriptor = it.next(); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); for (final PluginId dependentPluginId : dependentPluginIds) { if (!idToDescriptorMap.containsKey(dependentPluginId)) { if (message.length() > 0) { message.append("\n"); } message.append(IdeBundle.message("error.required.plugin.not.found", pluginDescriptor.getPluginId(), dependentPluginId)); it.remove(); break; } } } if (pluginsWithoutIdFound) { if (message.length() > 0) { message.append("\n"); } message.append(IdeBundle.message("error.plugins.without.id.found")); } if (message.length() > 0) { message.insert(0, IdeBundle.message("error.problems.found.loading.plugins")); return message.toString(); } for (Iterator<IdeaPluginDescriptorImpl> iterator = result.iterator(); iterator.hasNext();) { IdeaPluginDescriptor descriptor = iterator.next(); if (!shouldLoadPlugins() || !shouldLoadPlugin(descriptor)) { iterator.remove(); } } return null; } private static void loadDescriptors(String pluginsPath, List<IdeaPluginDescriptorImpl> result) { final File pluginsHome = new File(pluginsPath); final File[] files = pluginsHome.listFiles(); if (files != null) { for (File file : files) { final IdeaPluginDescriptorImpl descriptor = loadDescriptor(file); if (descriptor != null && !result.contains(descriptor)) { result.add(descriptor); } } } } @SuppressWarnings({"HardCodedStringLiteral"}) private static IdeaPluginDescriptorImpl loadDescriptor(final File file) { IdeaPluginDescriptorImpl descriptor = null; if (file.isDirectory()) { File descriptorFile = new File(file, "META-INF" + File.separator + "plugin.xml"); if (descriptorFile.exists()) { descriptor = new IdeaPluginDescriptorImpl(file); try { descriptor.readExternal(JDOMUtil.loadDocument(descriptorFile).getRootElement()); } catch (Exception e) { System.err.println("Cannot load: " + descriptorFile.getAbsolutePath()); e.printStackTrace(); } } else { File libDir = new File(file, "lib"); if (!libDir.isDirectory()) { return null; } final File[] files = libDir.listFiles(); if (files == null || files.length == 0) { return null; } for (final File f : files) { if (!f.isFile()) { continue; } final String lowercasedName = f.getName().toLowerCase(); if (lowercasedName.endsWith(".jar") || lowercasedName.endsWith(".zip")) { IdeaPluginDescriptorImpl descriptor1 = loadDescriptorFromJar(f); if (descriptor1 != null) { if (descriptor != null) { getLogger().info("Cannot load " + file + " because two or more plugin.xml's detected"); return null; } descriptor = descriptor1; descriptor.setPath(file); } } } } } else if (file.getName().endsWith(".jar")) { descriptor = loadDescriptorFromJar(file); } return descriptor; } private static IdeaPluginDescriptorImpl loadDescriptorFromJar(File file) { IdeaPluginDescriptorImpl descriptor = null; try { ZipFile zipFile = new ZipFile(file); try { //noinspection HardCodedStringLiteral final ZipEntry entry = zipFile.getEntry("META-INF/plugin.xml"); if (entry != null) { descriptor = new IdeaPluginDescriptorImpl(file); final InputStream inputStream = zipFile.getInputStream(entry); final Element rootElement = JDOMUtil.loadDocument(inputStream).getRootElement(); inputStream.close(); descriptor.readExternal(rootElement); } } finally { zipFile.close(); } } catch (Exception e) { getLogger().info("Cannot load " + file, e); } return descriptor; } @SuppressWarnings({"HardCodedStringLiteral"}) protected void bootstrap(List<URL> classpathElements) { IdeaClassLoader newClassLoader = initClassloader(classpathElements); try { final Class mainClass = Class.forName(getClass().getName(), true, newClassLoader); Field field = mainClass.getDeclaredField("ourMainClass"); field.setAccessible(true); field.set(null, ourMainClass); field = mainClass.getDeclaredField("ourMethodName"); field.setAccessible(true); field.set(null, ourMethodName); field = mainClass.getDeclaredField("ourArguments"); field.setAccessible(true); field.set(null, ourArguments); final Method startMethod = mainClass.getDeclaredMethod("start"); startMethod.setAccessible(true); startMethod.invoke(null, ArrayUtil.EMPTY_OBJECT_ARRAY); } catch (Exception e) { Logger logger = getLogger(); if (logger == null) { e.printStackTrace(System.err); } else { logger.error(e); } } } public IdeaClassLoader initClassloader(final List<URL> classpathElements) { PathManager.loadProperties(); try { addParentClasspath(classpathElements); addIDEALibraries(classpathElements); addAdditionalClassPath(classpathElements); } catch (IllegalArgumentException e) { JOptionPane .showMessageDialog(JOptionPane.getRootFrame(), e.getMessage(), CommonBundle.getErrorTitle(), JOptionPane.INFORMATION_MESSAGE); System.exit(1); } catch (MalformedURLException e) { JOptionPane .showMessageDialog(JOptionPane.getRootFrame(), e.getMessage(), CommonBundle.getErrorTitle(), JOptionPane.INFORMATION_MESSAGE); System.exit(1); } IdeaClassLoader newClassLoader = null; try { newClassLoader = new IdeaClassLoader(classpathElements, null); // prepare plugins if (!isLoadingOfExternalPluginsDisabled()) { PluginInstaller.initPluginClasses(); StartupActionScriptManager.executeActionScript(); } Thread.currentThread().setContextClassLoader(newClassLoader); } catch (Exception e) { Logger logger = getLogger(); if (logger == null) { e.printStackTrace(System.err); } else { logger.error(e); } } return newClassLoader; } private static IdeaClassLoader createPluginClassLoader(final File[] classPath, final PluginId pluginId, final ClassLoader[] parentLoaders, File pluginRoot) { if (ApplicationManager.getApplication().isUnitTestMode()) return null; try { final List<URL> urls = new ArrayList<URL>(classPath.length); for (File aClassPath : classPath) { final File file = aClassPath.getCanonicalFile(); // it is critical not to have "." and ".." in classpath elements urls.add(file.toURL()); } return new PluginClassLoader(urls, parentLoaders, pluginId, pluginRoot); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private void addParentClasspath(List<URL> aClasspathElements) throws MalformedURLException { final ClassLoader loader = getClass().getClassLoader(); if (loader instanceof URLClassLoader) { URLClassLoader urlClassLoader = (URLClassLoader)loader; aClasspathElements.addAll(Arrays.asList(urlClassLoader.getURLs())); } else { try { Class antClassLoaderClass = Class.forName("org.apache.tools.ant.AntClassLoader"); if (antClassLoaderClass.isInstance(loader) || loader.getClass().getName().equals("org.apache.tools.ant.AntClassLoader") || loader.getClass().getName().equals("org.apache.tools.ant.loader.AntClassLoader2")) { //noinspection HardCodedStringLiteral final String classpath = (String)antClassLoaderClass.getDeclaredMethod("getClasspath", ArrayUtil.EMPTY_CLASS_ARRAY).invoke(loader, ArrayUtil.EMPTY_OBJECT_ARRAY); final StringTokenizer tokenizer = new StringTokenizer(classpath, File.separator, false); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); aClasspathElements.add(new File(token).toURL()); } } else { getLogger().error("Unknown classloader: " + loader.getClass().getName()); } } catch (ClassCastException e) { getLogger().error("Unknown classloader [CCE]: " + e.getMessage()); } catch (ClassNotFoundException e) { getLogger().error("Unknown classloader [CNFE]: " + loader.getClass().getName()); } catch (NoSuchMethodException e) { getLogger().error("Unknown classloader [NSME]: " + e.getMessage()); } catch (IllegalAccessException e) { getLogger().error("Unknown classloader [IAE]: " + e.getMessage()); } catch (InvocationTargetException e) { getLogger().error("Unknown classloader [ITE]: " + e.getMessage()); } } } private void addIDEALibraries(List<URL> classpathElements) { final String ideaHomePath = PathManager.getHomePath(); addAllFromLibFolder(ideaHomePath, classpathElements); } @SuppressWarnings({"HardCodedStringLiteral"}) public static void addAllFromLibFolder(final String aFolderPath, List<URL> classPath) { try { final Class<PluginManager> aClass = PluginManager.class; final String selfRoot = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"); final URL selfRootUrl = new File(selfRoot).getAbsoluteFile().toURL(); classPath.add(selfRootUrl); final File libFolder = new File(aFolderPath + File.separator + "lib"); addLibraries(classPath, libFolder, selfRootUrl); final File antLib = new File(new File(libFolder, "ant"), "lib"); addLibraries(classPath, antLib, selfRootUrl); } catch (MalformedURLException e) { getLogger().error(e); } } private static void addLibraries(List<URL> classPath, File fromDir, final URL selfRootUrl) throws MalformedURLException { final File[] files = fromDir.listFiles(); if (files != null) { for (final File file : files) { if (!isJarOrZip(file)) { continue; } final URL url = file.toURL(); if (selfRootUrl.equals(url)) { continue; } classPath.add(url); } } } @SuppressWarnings({"HardCodedStringLiteral"}) private static boolean isJarOrZip(File file) { if (file.isDirectory()) { return false; } final String name = file.getName().toLowerCase(); return name.endsWith(".jar") || name.endsWith(".zip"); } private void addAdditionalClassPath(List<URL> classPath) { try { //noinspection HardCodedStringLiteral final StringTokenizer tokenizer = new StringTokenizer(System.getProperty("idea.additional.classpath", ""), File.pathSeparator, false); while (tokenizer.hasMoreTokens()) { String pathItem = tokenizer.nextToken(); classPath.add(new File(pathItem).toURL()); } } catch (MalformedURLException e) { getLogger().error(e); } } @SuppressWarnings({"HardCodedStringLiteral"}) private static boolean isLoadingOfExternalPluginsDisabled() { return !"true".equalsIgnoreCase(System.getProperty("idea.plugins.load", "true")); } public static boolean isPluginInstalled(PluginId id) { return (getPlugin(id) != null); } public static IdeaPluginDescriptor getPlugin(PluginId id) { final IdeaPluginDescriptor[] plugins = getPlugins(); for (final IdeaPluginDescriptor plugin : plugins) { if (Comparing.equal(id, plugin.getPluginId())) { return plugin; } } return null; } public static void addPluginClass(String className, PluginId pluginId) { if (ourPluginClasses == null) { ourPluginClasses = new HashMap<String, PluginId>(); } ourPluginClasses.put(className, pluginId); } public static boolean isPluginClass(String className) { return getPluginByClassName(className) != null; } @Nullable public static PluginId getPluginByClassName(String className) { return ourPluginClasses != null ? ourPluginClasses.get(className) : null; } private static class IdeaLogProvider implements LogProvider { public void error(String message) { getLogger().error(message); } public void error(String message, Throwable t) { getLogger().error(message, t); } public void error(Throwable t) { getLogger().error(t); } public void warn(String message) { getLogger().info(message); } public void warn(String message, Throwable t) { getLogger().info(message, t); } public void warn(Throwable t) { getLogger().info(t); } } }
package peergos.shared.messaging; import jsinterop.annotations.*; import peergos.shared.*; import peergos.shared.crypto.*; import peergos.shared.crypto.hash.*; import peergos.shared.display.*; import peergos.shared.messaging.messages.*; import peergos.shared.user.*; import peergos.shared.user.fs.*; import peergos.shared.util.*; import java.nio.file.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.stream.*; public class ChatController { public static final String SHARED_CHAT_STATE = "peergos-chat-state.cbor"; public static final String SHARED_MSG_LOG = "peergos-chat-messages.cborstream"; public static final String SHARED_MSG_LOG_INDEX = "peergos-chat-messages.index.bin"; public static final String PRIVATE_CHAT_STATE = "private-chat-state.cbor"; public final String chatUuid; public final MessageStore store; public final PrivateChatState privateChatState; private final Chat state; private final FileWrapper root; // includes the version that the state above was derived from private final LRUCache<MessageRef, MessageEnvelope> cache; private final Hasher hasher; private final UserContext context; public ChatController(String chatUuid, Chat state, MessageStore store, PrivateChatState privateChatState, FileWrapper root, LRUCache<MessageRef, MessageEnvelope> cache, UserContext context) { this.chatUuid = chatUuid; this.state = state; this.store = store; this.privateChatState = privateChatState; this.root = root; this.cache = cache; this.hasher = context.crypto.hasher; this.context = context; } public Member host() { return state.host(); } public Member getMember(String username) { return state.getMember(username); } @JsMethod public String getUsername(Id author) { return state.getMember(author).username; } @JsMethod public Set<String> getMemberNames() { return state.members.values().stream() .filter(m -> !m.removed) .filter(m -> ! privateChatState.deletedMembers.contains(m.username)) .map(m -> m.username) .collect(Collectors.toSet()); } @JsMethod public Set<String> getPendingMemberNames() { return state.members.values().stream() .filter(m -> !m.removed) .filter(m -> m.chatIdentity.isEmpty()) .map(m -> m.username) .collect(Collectors.toSet()); } public ChatController with(PrivateChatState priv) { return new ChatController(chatUuid, state, store, priv, root, cache, context); } @JsMethod public Set<String> deletedMemberNames() { return privateChatState.deletedMembers; } @JsMethod public List<MessageEnvelope> getRecent() { return state.getRecent(); } @JsMethod public CompletableFuture<MessageEnvelope> getMessageFromRef(MessageRef ref, int sourceIndex) { MessageEnvelope cached = cache.get(ref); if (cached != null) return Futures.of(cached); // Try 100 message prior to reference source first, then try previous chunks return store.getMessages(Math.max(0, sourceIndex - 100), sourceIndex) .thenCompose(allSigned -> Futures.findFirst(allSigned, s -> hashMessage(s.msg) .thenApply(h -> h.equals(ref) ? Optional.of(s.msg) : Optional.empty()))) .thenCompose(resOpt -> resOpt.map(Futures::of) .orElseGet(() -> getMessageFromRef(ref, sourceIndex - 100))); } @JsMethod public CompletableFuture<MessageRef> generateHash(MessageEnvelope m) { byte[] raw = m.serialize(); return hasher.bareHash(raw) .thenApply(MessageRef::new); } private CompletableFuture<MessageRef> hashMessage(MessageEnvelope m) { return generateHash(m) .thenApply(r -> { cache.put(r, m); return r; }); } @JsMethod public CompletableFuture<List<MessageEnvelope>> getMessages(int from, int to) { return store.getMessages(from, to) .thenApply(signed -> signed.stream().map(s -> s.msg).collect(Collectors.toList())); } @JsMethod public CompletableFuture<ChatController> sendMessage(Message message) { return applyAndCommit(chat -> chat.sendMessage(message, privateChatState.chatIdentity, context.signer, store, context.network.dhtClient, context.crypto), context.username); } @JsMethod public String getGroupProperty(String key) { return state.groupState.get(key).value; } @JsMethod public String getTitle() { return state.getTitle(); } @JsMethod public Set<String> getAdmins() { return state.getAdmins(); } @JsMethod public boolean isAdmin() { return state.getAdmins().contains(state.host().username); } private ChatController withState(Chat c) { return new ChatController(chatUuid, c, store, privateChatState, root, cache, context); } private ChatController withStore(MessageStore newStore) { return new ChatController(chatUuid, state, newStore, privateChatState, root, cache, context); } private ChatController withRoot(FileWrapper root) { return new ChatController(chatUuid, state, store, privateChatState, root, cache, context); } public CompletableFuture<ChatController> join(SigningPrivateKeyAndPublicHash identity) { OwnerProof chatId = OwnerProof.build(identity, privateChatState.chatIdentity.publicKeyHash); return applyAndCommit(chat -> chat.join(state.host(), chatId, privateChatState.chatIdPublic, identity, store, context.network.dhtClient, context.crypto), context.username); } @JsMethod public CompletableFuture<ChatController> addAdmin(String username) { Set<String> admins = new TreeSet<>(state.getAdmins()); if (! admins.isEmpty() && ! admins.contains(state.host().username)) throw new IllegalStateException("Only admins can modify the admin list!"); admins.add(username); SetGroupState msg = new SetGroupState(GroupProperty.ADMINS_STATE_KEY, admins.stream().collect(Collectors.joining(","))); return sendMessage(msg); } @JsMethod public CompletableFuture<ChatController> removeAdmin(String username) { Set<String> admins = new TreeSet<>(state.getAdmins()); if (! admins.contains(state.host().username)) throw new IllegalStateException("Only admins can modify the admin list!"); admins.remove(username); if (admins.isEmpty()) throw new IllegalStateException("A chat must always have at least 1 admin"); SetGroupState msg = new SetGroupState(GroupProperty.ADMINS_STATE_KEY, admins.stream().collect(Collectors.joining(","))); return sendMessage(msg); } public CompletableFuture<ChatController> invite(List<String> usernames, List<PublicKeyHash> identities) { return applyAndCommit(chat -> chat.inviteMembers(usernames, identities, privateChatState.chatIdentity, context.signer, store, context.network.dhtClient, context.crypto), context.username); } public CompletableFuture<ChatController> mergeMessages(String username, MessageStore mirrorStore) { Member mirrorHost = state.getMember(username); return applyAndCommit(chat -> chat.merge(chatUuid, mirrorHost.id, context.signer, mirrorStore, context.network.dhtClient, context.crypto), username); } private CompletableFuture<Snapshot> copyFile(FileWrapper dir, Path sourcePath, String mirrorUsername, Snapshot v, Committer c) { // Try copying file from source first, and then fallback to mirror we are currently merging return Futures.asyncExceptionally(() -> context.getByPath(sourcePath.toString(), v) .thenApply(Optional::get), t -> context.getByPath(Paths.get(mirrorUsername).resolve(sourcePath.subpath(1, sourcePath.getNameCount())).toString(), v) .thenApply(Optional::get)) .thenCompose(f -> f.getInputStream(f.version.get(f.writer()).props, context.network, context.crypto, x -> {}) .thenCompose(r -> dir.uploadFileSection(v, c, f.getName(), r, false, 0, f.getSize(), Optional.empty(), false, false, context.network, context.crypto, x -> {}, context.crypto.random.randomBytes(RelativeCapability.MAP_KEY_LENGTH)))); } private Path getChatMediaDir(ChatController current) { return Paths.get(Messenger.MESSAGING_BASE_DIR, current.chatUuid, "shared", "media"); } private CompletableFuture<Snapshot> mirrorMedia(FileRef ref, ChatController chat, String currentMirrorUsername, Snapshot in, Committer committer) { if (currentMirrorUsername.equals(context.username)) return Futures.of(in); Path mediaDir = getChatMediaDir(chat); Path sourcePath = Paths.get(ref.path); Path chatRelativePath = sourcePath.subpath(1 + mediaDir.getNameCount(), sourcePath.getNameCount()); Path ourCopy = mediaDir.resolve(chatRelativePath); Path parent = ourCopy.getParent(); List<String> mediaFileParentPath = IntStream.range(0, parent.getNameCount()) .mapToObj(i -> parent.getName(i).toString()) .collect(Collectors.toList()); return context.getByPath(context.username, in) .thenApply(Optional::get) .thenCompose(home -> home.getOrMkdirs(mediaFileParentPath, false, context.network, context.crypto, in, committer)) .thenCompose(dir -> copyFile(dir.right, sourcePath, currentMirrorUsername, dir.left, committer)); } private CompletableFuture<Snapshot> overwriteState(FileWrapper root, Chat c, Snapshot v, Committer com) { byte[] raw = c.serialize(); return root.getDescendentByPath("shared/"+ SHARED_CHAT_STATE, context.crypto.hasher, context.network) .thenCompose(file -> file.get().overwriteFile(AsyncReader.build(raw), raw.length, context.network, context.crypto, x -> {}, v, com)); } private CompletableFuture<ChatController> applyAndCommit(Function<Chat, CompletableFuture<ChatUpdate>> modifier, String mirrorUsername) { NetworkAccess network = context.network; return network.synchronizer.applyComplexComputation(context.signer.publicKeyHash, root.signingPair(), (s, c) -> root.getUpdated(s, network) .thenCompose(updated -> updated.getChild("shared", hasher, network) .thenCompose(sharedDir -> getChatState(sharedDir.get(), network, context.crypto)) .thenCompose(chatState -> modifier.apply(chatState) .thenCompose(u -> commitUpdate(u, mirrorUsername, s, c))))) .thenApply(res -> res.right); } private CompletableFuture<Pair<Snapshot, ChatController>> commitUpdate(ChatUpdate u, String mirrorUsername, Snapshot in, Committer c) { if (u.isEmpty() && u.state.equals(state)) return Futures.of(new Pair<>(in, this)); // 1. rotate access control // 2. copy media // 3. commit any new private state // 4. append messages // 5. commit state file boolean noRemovals = u.toRevokeAccess.isEmpty(); return (noRemovals ? Futures.of(in) : store.revokeAccess(u.toRevokeAccess, in, c)) .thenCompose(s -> Futures.reduceAll(u.mediaToCopy, s, (v, f) -> mirrorMedia(f, this, mirrorUsername, v, c), (a, b) -> a.merge(b)) .thenCompose(s2 -> root.getUpdated(s2, context.network) .thenCompose(base -> commitPrivateState(u.priv, base, context.network, context.crypto, s2, c) .thenCompose(s3 -> base.getUpdated(s3, context.network)))) .thenCompose(base -> (noRemovals ? Futures.of(store) : getChatMessageStore(base, context)) .thenCompose(newStore -> newStore.addMessages(base.version, c, state.host().messagesMergedUpto, u.newMessages)) .thenCompose(s4 -> overwriteState(base, u.state, s4, c))) .thenCompose(s5 -> root.getUpdated(s5, context.network) .thenCompose(newRoot -> getChatMessageStore(newRoot, context) .thenApply(newStore -> new Pair<>(s5, withState(u.state).withRoot(newRoot).withStore(newStore)))))); } private static CompletableFuture<Snapshot> commitPrivateState(Optional<PrivateChatState> priv, FileWrapper chatRoot, NetworkAccess network, Crypto crypto, Snapshot in, Committer c) { if (priv.isEmpty()) return Futures.of(in); byte[] rawPrivateChatState = priv.get().serialize(); return chatRoot.uploadFileSection(in, c, ChatController.PRIVATE_CHAT_STATE, AsyncReader.build(rawPrivateChatState), false, 0, rawPrivateChatState.length, Optional.empty(), true, true, network, crypto, x -> {}, crypto.random.randomBytes(32)); } private static CompletableFuture<Pair<FileWrapper, FileWrapper>> getSharedLogAndIndex(FileWrapper chatRoot, Hasher hasher, NetworkAccess network) { return chatRoot.getDescendentByPath("shared/" + SHARED_MSG_LOG, hasher, network) .thenCompose(msgFile -> chatRoot.getDescendentByPath("shared/" + SHARED_MSG_LOG_INDEX, hasher, network) .thenApply(index -> new Pair<>(msgFile.get(), index.get()))); } public static CompletableFuture<MessageStore> getChatMessageStore(FileWrapper chatRoot, UserContext context) { Path chatRootPath = Messenger.getChatPath(context.username, chatRoot.getName()); return getSharedLogAndIndex(chatRoot, context.crypto.hasher, context.network) .thenApply(files -> new FileBackedMessageStore(files.left, files.right, context, chatRootPath.resolve("shared"), () -> context.getByPath(chatRootPath) .thenApply(Optional::get) .thenCompose(d -> getSharedLogAndIndex(d, context.crypto.hasher, context.network)))); } public static CompletableFuture<Chat> getChatState(FileWrapper chatSharedDir, NetworkAccess network, Crypto crypto) { return chatSharedDir.getChild(SHARED_CHAT_STATE, crypto.hasher, network) .thenCompose(chatStateOpt -> Serialize.parse(chatStateOpt.get(), Chat::fromCbor, network, crypto)); } private static CompletableFuture<PrivateChatState> getPrivateChatState(FileWrapper chatRoot, NetworkAccess network, Crypto crypto) { return chatRoot.getChild(PRIVATE_CHAT_STATE, crypto.hasher, network) .thenCompose(priv -> Serialize.parse(priv.get(), PrivateChatState::fromCbor, network, crypto)); } public static CompletableFuture<ChatController> getChatController(FileWrapper chatRoot, UserContext context, LRUCache<MessageRef, MessageEnvelope> cache) { return chatRoot.getChild("shared", context.crypto.hasher, context.network) .thenCompose(sharedDir -> getChatState(sharedDir.get(), context.network, context.crypto)) .thenCompose(chat -> getPrivateChatState(chatRoot, context.network, context.crypto) .thenCompose(priv -> getChatMessageStore(chatRoot, context) .thenApply(msgStore -> new ChatController(chatRoot.getName(), chat, msgStore, priv, chatRoot, cache, context)))); } }
package pl.edu.agh.megamud.module; import java.sql.SQLException; import pl.edu.agh.megamud.GameServer; import pl.edu.agh.megamud.base.Controller; import pl.edu.agh.megamud.base.Creature; import pl.edu.agh.megamud.base.CyclicBehaviour; import pl.edu.agh.megamud.base.DatabaseModule; import pl.edu.agh.megamud.base.Location; import pl.edu.agh.megamud.base.SimpleItem; import pl.edu.agh.megamud.base.itemtype.HealItem; import pl.edu.agh.megamud.base.itemtype.Weapon; import pl.edu.agh.megamud.dao.Attribute; import pl.edu.agh.megamud.dao.LocationItem; import pl.edu.agh.megamud.dao.base.LocationBase; import pl.edu.agh.megamud.mechanix.CommandHit; import pl.edu.agh.megamud.world.AggressiveSentry; import pl.edu.agh.megamud.world.CaveInitializer; import pl.edu.agh.megamud.world.Chochlik; import pl.edu.agh.megamud.world.CommandAskOldman; import pl.edu.agh.megamud.world.CreatureFactory; import pl.edu.agh.megamud.world.Oldman; import pl.edu.agh.megamud.world.Sentry; /** * Abstraction of a in-server module. A module loads locations, NPCs, new items * etc. * * @author Tomasz */ public class DefaultModule extends DatabaseModule { public String getId() { return "default"; } public String getDescription() { return "Default game module."; } private void prepareAttributes() throws SQLException { // AttributeBase.createDao().deleteBuilder().delete(); Attribute.insertIfNotExists(Attribute.STRENGTH); Attribute.insertIfNotExists(Attribute.DEXTERITY); Attribute.insertIfNotExists(Attribute.DAMAGE); Attribute.insertIfNotExists(Attribute.HEAL); } private void clearLocations() throws SQLException { LocationBase.createDao().deleteBuilder().delete(); LocationItem.createDao().deleteBuilder().delete(); } protected void init() { try { clearLocations(); prepareAttributes(); CaveInitializer.init(this.getId()); } catch (SQLException e) { e.printStackTrace(); } super.init(); // Commands installCommands(); Weapon sword = new Weapon("sword", "little rusty sword"); sword.giveTo(GameServer.getInstance().getLocation( CaveInitializer.B2.getName())); sword.initAtribute(Attribute.findByName(Attribute.DAMAGE)); sword.setAttribute(Attribute.DAMAGE, 3L); HealItem potion1 = new HealItem("potion", "small potion"); potion1.giveTo(GameServer.getInstance().getLocation(CaveInitializer.B1.getName())); potion1.initAtribute(Attribute.findByName(Attribute.HEAL)); potion1.setAttribute(Attribute.HEAL, 30L); new CyclicBehaviour(GameServer.getInstance().getLocation( CaveInitializer.C7), 1000L) { protected void action() { Location location = (Location) owner; if (location.getItems().containsKey("apple")) return; SimpleItem it = new SimpleItem("apple", "Precious, golden apple."); it.giveTo(location); } }.init(); Oldman oldman = new Oldman(); CommandAskOldman askOldman = new CommandAskOldman(oldman); GameServer.getInstance().getStartLocation().addCommand(askOldman); installNPC(oldman, new Creature("Oldman").setLevel(100).setHp(1000), GameServer.getInstance().getStartLocation()); installNPC(new Chochlik(), new Creature("Chochlik").setLevel(100) .setHp(666), GameServer.getInstance().getLocation(CaveInitializer.B3)); installRespawningNPC( new Sentry(), CreatureFactory.RAT, GameServer.getInstance().getLocation(CaveInitializer.B2)); installRespawningNPC( new AggressiveSentry(), CreatureFactory.RAT, GameServer.getInstance().getLocation(CaveInitializer.D3)); installRespawningNPC( new AggressiveSentry(), CreatureFactory.RAT, GameServer.getInstance().getLocation(CaveInitializer.E1)); installRespawningNPC( new AggressiveSentry(), CreatureFactory.RAT, GameServer.getInstance().getLocation(CaveInitializer.D5)); installRespawningNPC( new Sentry(), CreatureFactory.RAT, GameServer.getInstance().getLocation(CaveInitializer.C6)); installRespawningNPC( new Sentry(), CreatureFactory.RAT, GameServer.getInstance().getLocation(CaveInitializer.D1)); } private void installCommands() { installCommand(new CommandUse()); installCommand(new CommandEquip()); installCommand(new CommandHit()); installCommand(new CommandUnequip()); installCommand(new CommandExit()); installCommand(new CommandGoto()); installCommand(new CommandHelp()); installCommand(new CommandInfo()); installCommand(new CommandLogin()); installCommand(new CommandLook()); installCommand(new CommandTake()); installCommand(new CommandGive()); installCommand(new CommandDrop()); installCommand(new CommandSay()); installCommand(new CommandKill()); } public void onNewController(Controller c) { findCommands("login").get(0).installTo(c); findCommands("exit").get(0).installTo(c); findCommands("help").get(0).installTo(c); findCommands("kill").get(0).installTo(c); } public void onKillController(Controller c) { findCommands("login").get(0).uninstallFrom(c); findCommands("exit").get(0).uninstallFrom(c); findCommands("help").get(0).uninstallFrom(c); findCommands("kill").get(0).uninstallFrom(c); } public void onNewCreature(Creature c) { Controller d = c.getController(); findCommands("login").get(0).uninstallFrom(d); findCommands("info").get(0).installTo(d); findCommands(CommandEquip.commandString).get(0).installTo(d); findCommands(CommandUse.commandString).get(0).installTo(d); findCommands(CommandUnequip.commandString).get(0).installTo(d); findCommands(CommandHit.commandString).get(0).installTo(d); findCommands("take").get(0).installTo(d); findCommands("drop").get(0).installTo(d); findCommands("give").get(0).installTo(d); findCommands("look").get(0).installTo(d); findCommands("goto").get(0).installTo(d); findCommands("say").get(0).installTo(d); } public void onKillCreature(Creature c) { Controller d = c.getController(); if (d == null) return; findCommands("info").get(0).uninstallFrom(d); findCommands("login").get(0).installTo(d); findCommands(CommandEquip.commandString).get(0).uninstallFrom(d); findCommands(CommandUnequip.commandString).get(0).uninstallFrom(d); findCommands(CommandHit.commandString).get(0).uninstallFrom(d); findCommands("take").get(0).uninstallFrom(d); findCommands("drop").get(0).uninstallFrom(d); findCommands("give").get(0).uninstallFrom(d); findCommands("look").get(0).uninstallFrom(d); findCommands("goto").get(0).uninstallFrom(d); findCommands("say").get(0).uninstallFrom(d); } }
public class RepairDroid { public RepairDroid (boolean debug) { _debug = debug; } public void printGrid () { } private boolean _debug; }
package model; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.eclipse.egit.github.core.Label; import ui.LabelTreeItem; public class TurboLabel implements Listable, LabelTreeItem { public TurboLabel(String name) { setName(name); setColour("000000"); } public TurboLabel(Label label) { assert label != null; String labelName = label.getName(); String[] tokens = null; if (labelName.contains("\\.")) { tokens = labelName.split("\\."); setGroup(tokens[0]); setName(tokens[1]); setExclusive(true); } else if (labelName.contains("\\-")) { tokens = labelName.split("\\-"); setGroup(tokens[0]); setName(tokens[1]); setExclusive(false); } else { setName(labelName); } setColour(label.getColor()); } public Label toGhLabel() { Label ghLabel = new Label(); ghLabel.setName(toGhName()); ghLabel.setColor(getColour()); return ghLabel; } public String toGhName() { String groupDelimiter = isExclusive ? "." : "-"; String groupPrefix = getGroup() == null ? "" : getGroup() + groupDelimiter; String groupAppended = groupPrefix + getName(); return groupAppended; } public static List<Label> toGhLabels(List<TurboLabel> turboLabels) { List<Label> ghLabels = new ArrayList<Label>(); if (turboLabels == null) return ghLabels; for (TurboLabel turboLabel : turboLabels) { Label label = new Label(); label.setName(turboLabel.getName()); ghLabels.add(label); } return ghLabels; } private StringProperty name = new SimpleStringProperty(); public final String getName() {return name.get();} public final void setName(String value) {name.set(value);} public StringProperty nameProperty() {return name;} private StringProperty colour = new SimpleStringProperty(); public final String getColour() {return colour.get();} public final void setColour(String value) {colour.set(value);} public StringProperty colourProperty() {return colour;} private StringProperty group = new SimpleStringProperty(); public final String getGroup() {return group.get();} public final void setGroup(String value) {group.set(value);} public StringProperty groupProperty() {return group;} private boolean isExclusive; // exclusive: "." non-exclusive: "-" @Override public String getListName() { return getName(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TurboLabel other = (TurboLabel) obj; if (name == null) { if (other.name != null) return false; } else if (!getName().equals(other.getName())) return false; return true; } @Override public String toString() { return getGroup() + "/" + getName() + "/" + getColour(); } public String getValue() { return getName(); } public void setValue(String value) { setName(value); } public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { if (getGroup() != null) { this.isExclusive = isExclusive; } } }
package orwell.proxy.robot; import lejos.mf.common.UnitMessage; import lejos.mf.common.UnitMessageType; import org.easymock.TestSubject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import orwell.proxy.mock.MockedCamera; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @RunWith(PowerMockRunner.class) public class TankTest { final static Logger logback = LoggerFactory.getLogger(TankTest.class); @TestSubject private Tank tank; @Before public void setUp() { logback.info("IN"); tank = new Tank("BtName", "BtId", new MockedCamera(), "Image"); logback.info("OUT"); } @Test /** * 1. Tank reads an RFID value: first read of ServerRobotState is not null * 2. Nothing happens: second read of ServerRobotState is null * 3. Tank reads a Color value: third read of ServerRobotState is not null */ public void testGetAndClearZmqServerRobotState() { logback.info("IN"); UnitMessage unitMessage = new UnitMessage(UnitMessageType.Rfid, "123"); tank.receivedNewMessage(unitMessage); assertNotNull(tank.getAndClearZmqServerRobotStateBytes()); assertNull(tank.getAndClearZmqServerRobotStateBytes()); unitMessage = new UnitMessage(UnitMessageType.Colour, "2"); tank.receivedNewMessage(unitMessage); assertNotNull(tank.getAndClearZmqServerRobotStateBytes()); logback.info("OUT"); } @After public void tearDown() { } }
// Exporter.java package loci.plugins; import ij.*; import ij.gui.GenericDialog; import ij.io.FileInfo; import ij.io.SaveDialog; import ij.process.*; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.*; import loci.formats.*; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; public class Exporter { // -- Fields -- /** Current stack. */ private ImagePlus imp; private LociExporter plugin; // -- Constructor -- public Exporter(LociExporter plugin, ImagePlus imp) { this.plugin = plugin; this.imp = imp; } // -- Exporter API methods -- /** Executes the plugin. */ public void run(ImageProcessor ip) { String outfile = null; if (plugin.arg != null && plugin.arg.startsWith("outfile=")) { outfile = Macro.getValue(plugin.arg, "outfile", null); plugin.arg = null; } if (outfile == null) { String options = Macro.getOptions(); if (options != null) { String save = Macro.getValue(options, "save", null); if (save != null) outfile = save; } } if (outfile == null || outfile.length() == 0) { // open a dialog prompting for the filename to save SaveDialog sd = new SaveDialog("LOCI Bio-Formats Exporter", "", ""); String dir = sd.getDirectory(); String name = sd.getFileName(); if (dir == null || name == null) return; outfile = new File(dir, name).getAbsolutePath(); if (outfile == null) return; } try { IFormatWriter w = new ImageWriter().getWriter(outfile); FileInfo fi = imp.getOriginalFileInfo(); String xml = fi == null ? null : fi.description == null ? null : fi.description.indexOf("xml") == -1 ? null : fi.description; MetadataStore store = MetadataTools.createOMEXMLMetadata(xml); if (store == null) IJ.error("OME-Java library not found."); else if (store instanceof MetadataRetrieve) { if (xml == null) { store.createRoot(); int ptype = 0; int channels = 1; switch (imp.getType()) { case ImagePlus.GRAY8: case ImagePlus.COLOR_256: ptype = FormatTools.UINT8; break; case ImagePlus.COLOR_RGB: channels = 3; ptype = FormatTools.UINT8; break; case ImagePlus.GRAY16: ptype = FormatTools.UINT16; break; case ImagePlus.GRAY32: ptype = FormatTools.FLOAT; break; } store.setPixelsSizeX(new Integer(imp.getWidth()), 0, 0); store.setPixelsSizeY(new Integer(imp.getHeight()), 0, 0); store.setPixelsSizeZ(new Integer(imp.getNSlices()), 0, 0); store.setPixelsSizeC(new Integer(channels*imp.getNChannels()), 0, 0); store.setPixelsSizeT(new Integer(imp.getNFrames()), 0, 0); store.setPixelsPixelType(FormatTools.getPixelTypeString(ptype), 0, 0); store.setPixelsBigEndian(Boolean.FALSE, 0, 0); store.setPixelsDimensionOrder("XYCZT", 0, 0); } // NB: This handles a known deficiency in Image5D. // getStackSize() on an Image5D ImagePlus will always return the // number of slices, not the total number of planes. if (imp.getStackSize() != imp.getNChannels() * imp.getNSlices() * imp.getNFrames()) { IJ.showMessageWithCancel("Bio-Formats Exporter Warning", "The number of planes in the stack (" + imp.getStackSize() + ") does not match the number of expected planes (" + (imp.getNChannels() * imp.getNSlices() * imp.getNFrames()) + ")." + "\nThis is probably because you are exporting from an Image5D " + "window.\nIf you select 'OK', only " + imp.getStackSize() + " planes will be exported. If you wish to export all of the " + "planes,\nselect 'Cancel' and convert the Image5D window " + "to a stack."); store.setPixelsSizeZ(new Integer(imp.getStackSize()), 0, 0); store.setPixelsSizeC(new Integer(1), 0, 0); store.setPixelsSizeT(new Integer(1), 0, 0); } w.setMetadataRetrieve((MetadataRetrieve) store); } w.setId(outfile); // prompt for options String[] codecs = w.getCompressionTypes(); ImageProcessor proc = imp.getStack().getProcessor(1); Image firstImage = proc.createImage(); firstImage = AWTImageTools.makeBuffered(firstImage, proc.getColorModel()); int thisType = AWTImageTools.getPixelType((BufferedImage) firstImage); if (proc instanceof ColorProcessor) { thisType = FormatTools.UINT8; } boolean notSupportedType = !w.isSupportedType(thisType); if (notSupportedType) { IJ.error("Pixel type (" + FormatTools.getPixelTypeString(thisType) + ") not supported by this format."); } if (codecs != null && codecs.length > 1) { GenericDialog gd = new GenericDialog("LOCI Bio-Formats Exporter Options"); if (codecs != null) { gd.addChoice("Compression type: ", codecs, codecs[0]); } gd.showDialog(); if (gd.wasCanceled()) return; if (codecs != null) w.setCompression(gd.getNextChoice()); } // convert and save slices Class c = null; try { c = Class.forName("ij.CompositeImage"); } catch (ClassNotFoundException e) { } boolean fakeRGB = imp.getClass().equals(c); int n = fakeRGB ? imp.getNChannels() : 1; ImageStack is = imp.getStack(); int size = is.getSize(); boolean doStack = w.canDoStacks() && size > 1; int start = doStack ? 0 : imp.getCurrentSlice() - 1; int end = doStack ? size : start + 1; for (int i=start; i<end; i+=n) { if (doStack) { IJ.showStatus("Saving plane " + (i + 1) + "/" + size); IJ.showProgress((double) (i + 1) / size); } else IJ.showStatus("Saving image"); proc = is.getProcessor(i + 1); BufferedImage img = null; int x = proc.getWidth(); int y = proc.getHeight(); if (proc instanceof ByteProcessor) { if (fakeRGB) { byte[][] b = new byte[n][]; for (int j=0; j<n; j++) { b[j] = (byte[]) is.getProcessor(i + j + 1).getPixels(); } img = AWTImageTools.makeImage(b, x, y); } else { byte[] b = (byte[]) proc.getPixels(); img = AWTImageTools.makeImage(b, x, y); } } else if (proc instanceof ShortProcessor) { if (fakeRGB) { short[][] s = new short[n][]; for (int j=0; j<n; j++) { s[j] = (short[]) is.getProcessor(i + j + 1).getPixels(); } img = AWTImageTools.makeImage(s, x, y); } else { short[] s = (short[]) proc.getPixels(); img = AWTImageTools.makeImage(s, x, y); } } else if (proc instanceof FloatProcessor) { if (fakeRGB) { float[][] f = new float[n][]; for (int j=0; j<n; j++) { f[j] = (float[]) is.getProcessor(i + j + 1).getPixels(); } img = AWTImageTools.makeImage(f, x, y); } else { float[] b = (float[]) proc.getPixels(); img = AWTImageTools.makeImage(b, x, y); } } else if (proc instanceof ColorProcessor) { byte[][] pix = new byte[3][x*y]; ((ColorProcessor) proc).getRGB(pix[0], pix[1], pix[2]); img = AWTImageTools.makeImage(pix, x, y); } if (notSupportedType) { IJ.error("Pixel type not supported by this format."); } else w.saveImage(img, i == end - 1); } } catch (FormatException e) { e.printStackTrace(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(buf)); IJ.error(e.getMessage() + ":\n" + buf.toString()); } catch (IOException e) { e.printStackTrace(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(buf)); IJ.error(e.getMessage() + ":\n" + buf.toString()); } } }
package duro.runtime; import java.io.Serializable; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; public class InteractionHistory { public static class Interaction implements Serializable { private static final long serialVersionUID = 1L; public final String interfaceId; public final Instruction instruction; public final Object output; public Interaction(String interfaceId, Instruction instruction, Object output) { this.interfaceId = interfaceId; this.instruction = instruction; this.output = output; } } private int initialSize; private List<Interaction> interactions; private Hashtable<String, Integer> tracks = new Hashtable<String, Integer>(); public InteractionHistory(List<Interaction> interactions) { this.interactions = interactions; initialSize = interactions.size(); } public boolean hasNewInteractions() { return initialSize < interactions.size(); } public List<Interaction> getNewInteractions() { return new ArrayList<Interaction>(interactions.subList(initialSize, interactions.size())); } public void append(String interfaceId, Instruction instruction, Object output) { interactions.add(new Interaction(interfaceId, instruction, output)); tracks.put(interfaceId, interactions.size() - 1); } public Object nextOutputFor(String interfaceId, int opcode) { tracks.putIfAbsent(interfaceId, -1); int trackIndex = tracks.get(interfaceId); for(int i = trackIndex + 1; i < interactions.size(); i++) { Interaction interaction = interactions.get(i); if(interaction.instruction.opcode == opcode && interaction.interfaceId.equals(interfaceId)) { tracks.put(interfaceId, i); return interaction.output; } } return null; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.Period; import java.time.YearMonth; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.time.temporal.WeekFields; import java.util.Locale; import java.util.Objects; import javax.swing.*; public final class MainPanel extends JPanel { public final Dimension size = new Dimension(40, 26); public final JLabel yearMonthLabel = new JLabel("", SwingConstants.CENTER); public final JList<LocalDate> monthList = new JList<LocalDate>() { @Override public void updateUI() { setCellRenderer(null); super.updateUI(); setLayoutOrientation(JList.HORIZONTAL_WRAP); setVisibleRowCount(CalendarViewListModel.ROW_COUNT); // ensure 6 rows in the list setFixedCellWidth(size.width); setFixedCellHeight(size.height); setCellRenderer(new CalendarListRenderer()); getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); } }; public final LocalDate realLocalDate = LocalDate.now(ZoneId.systemDefault()); private LocalDate currentLocalDate; public LocalDate getCurrentLocalDate() { return currentLocalDate; } private MainPanel() { super(); installActions(); JButton prev = new JButton("<"); prev.addActionListener(e -> updateMonthView(getCurrentLocalDate().minusMonths(1))); JButton next = new JButton(">"); next.addActionListener(e -> updateMonthView(getCurrentLocalDate().plusMonths(1))); JPanel yearMonthPanel = new JPanel(new BorderLayout()); yearMonthPanel.add(yearMonthLabel); yearMonthPanel.add(prev, BorderLayout.WEST); yearMonthPanel.add(next, BorderLayout.EAST); DefaultListModel<DayOfWeek> weekModel = new DefaultListModel<>(); DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek(); for (int i = 0; i < DayOfWeek.values().length; i++) { weekModel.add(i, firstDayOfWeek.plus(i)); } JList<DayOfWeek> header = new JList<DayOfWeek>(weekModel) { @Override public void updateUI() { setCellRenderer(null); super.updateUI(); ListCellRenderer<? super DayOfWeek> renderer = getCellRenderer(); setCellRenderer((list, value, index, isSelected, cellHasFocus) -> { JLabel c = (JLabel) renderer.getListCellRendererComponent(list, value, index, false, false); c.setHorizontalAlignment(SwingConstants.CENTER); // String s = value.getDisplayName(TextStyle.SHORT_STANDALONE, l); // c.setText(s.substring(0, Math.min(2, s.length()))); c.setText(value.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.getDefault())); c.setBackground(new Color(0xDC_DC_DC)); return c; }); getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); setLayoutOrientation(JList.HORIZONTAL_WRAP); setVisibleRowCount(0); setFixedCellWidth(size.width); setFixedCellHeight(size.height); } }; updateMonthView(realLocalDate); JScrollPane scroll = new JScrollPane(monthList); scroll.setColumnHeaderView(header); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JLabel label = new JLabel(" ", SwingConstants.CENTER); monthList.getSelectionModel().addListSelectionListener(e -> { ListSelectionModel lsm = (ListSelectionModel) e.getSource(); if (lsm.isSelectionEmpty()) { label.setText(" "); } else { ListModel<LocalDate> model = monthList.getModel(); LocalDate from = model.getElementAt(lsm.getMinSelectionIndex()); LocalDate to = model.getElementAt(lsm.getMaxSelectionIndex()); label.setText(Period.between(from, to).toString()); } }); Box box = Box.createVerticalBox(); box.add(yearMonthPanel); box.add(Box.createVerticalStrut(2)); box.add(scroll); box.add(label); add(box); setPreferredSize(new Dimension(320, 240)); } private void installActions() { InputMap im = monthList.getInputMap(JComponent.WHEN_FOCUSED); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "selectNextIndex"); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "selectPreviousIndex"); ActionMap am = monthList.getActionMap(); am.put("selectPreviousIndex", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { int index = monthList.getLeadSelectionIndex(); if (index > 0) { monthList.setSelectedIndex(index - 1); } else { LocalDate d = monthList.getModel().getElementAt(0).minusDays(1); updateMonthView(getCurrentLocalDate().minusMonths(1)); monthList.setSelectedValue(d, false); } } }); am.put("selectNextIndex", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { int index = monthList.getLeadSelectionIndex(); if (index < monthList.getModel().getSize() - 1) { monthList.setSelectedIndex(index + 1); } else { LocalDate d = monthList.getModel().getElementAt(monthList.getModel().getSize() - 1).plusDays(1); updateMonthView(getCurrentLocalDate().plusMonths(1)); monthList.setSelectedValue(d, false); } } }); Action selectPreviousRow = am.get("selectPreviousRow"); am.put("selectPreviousRow", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { int index = monthList.getLeadSelectionIndex(); int weekLength = DayOfWeek.values().length; if (index < weekLength) { LocalDate d = monthList.getModel().getElementAt(index).minusDays(weekLength); updateMonthView(getCurrentLocalDate().minusMonths(1)); monthList.setSelectedValue(d, false); } else { selectPreviousRow.actionPerformed(e); } } }); Action selectNextRow = am.get("selectNextRow"); am.put("selectNextRow", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { int index = monthList.getLeadSelectionIndex(); int weekLength = DayOfWeek.values().length; if (index > monthList.getModel().getSize() - weekLength) { LocalDate d = monthList.getModel().getElementAt(index).plusDays(weekLength); updateMonthView(getCurrentLocalDate().plusMonths(1)); monthList.setSelectedValue(d, false); } else { selectNextRow.actionPerformed(e); } } }); } public void updateMonthView(LocalDate localDate) { currentLocalDate = localDate; yearMonthLabel.setText(localDate.format(DateTimeFormatter.ofPattern("yyyy / MM").withLocale(Locale.getDefault()))); monthList.setModel(new CalendarViewListModel(localDate)); } private class CalendarListRenderer implements ListCellRenderer<LocalDate> { private final ListCellRenderer<? super LocalDate> renderer = new DefaultListCellRenderer(); @Override public Component getListCellRendererComponent(JList<? extends LocalDate> list, LocalDate value, int index, boolean isSelected, boolean cellHasFocus) { JLabel l = (JLabel) renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); l.setOpaque(true); l.setHorizontalAlignment(SwingConstants.CENTER); l.setText(Objects.toString(value.getDayOfMonth())); Color fgc = l.getForeground(); if (YearMonth.from(value).equals(YearMonth.from(getCurrentLocalDate()))) { DayOfWeek dow = value.getDayOfWeek(); if (value.isEqual(realLocalDate)) { fgc = new Color(0x64_FF_64); } else if (dow == DayOfWeek.SUNDAY) { fgc = new Color(0xFF_64_64); } else if (dow == DayOfWeek.SATURDAY) { fgc = new Color(0x64_64_FF); } } else { fgc = Color.GRAY; } l.setForeground(isSelected ? l.getForeground() : fgc); return l; } } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class CalendarViewListModel extends AbstractListModel<LocalDate> { public static final int ROW_COUNT = 6; private final LocalDate startDate; protected CalendarViewListModel(LocalDate date) { super(); LocalDate firstDayOfMonth = YearMonth.from(date).atDay(1); WeekFields weekFields = WeekFields.of(Locale.getDefault()); int fdmDow = firstDayOfMonth.get(weekFields.dayOfWeek()) - 1; startDate = firstDayOfMonth.minusDays(fdmDow); } @Override public int getSize() { return DayOfWeek.values().length * ROW_COUNT; } @Override public LocalDate getElementAt(int index) { return startDate.plusDays(index); } }
package org.objectweb.proactive.core; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * <p> * UniqueID is a unique object identifier across all jvm. It is made of a unique VMID combined * with a unique UID on that VM. * </p><p> * The UniqueID is used to identify object globally, even in case of migration. * </p> * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * */ public class UniqueID implements java.io.Serializable, Comparable { private java.rmi.server.UID id; private java.rmi.dgc.VMID vmID; //the Unique ID of the JVM private static java.rmi.dgc.VMID uniqueVMID = new java.rmi.dgc.VMID(); protected static Logger logger = ProActiveLogger.getLogger(Loggers.CORE); // Optim private transient String cachedShortString; private transient String cachedCanonString; /** * Creates a new UniqueID */ public UniqueID() { this.id = new java.rmi.server.UID(); this.vmID = uniqueVMID; } /** * Returns the VMID of the current VM in which this class has been loaded. * @return the VMID of the current VM */ public static java.rmi.dgc.VMID getCurrentVMID() { return uniqueVMID; } /** * Returns the VMID of this UniqueID. Note that the VMID of one UniqueID may differ * from the local VMID (that one can get using <code>getCurrentVMID()</code> in case * this UniqueID is attached to an object that has migrated. * @return the VMID part of this UniqueID */ public java.rmi.dgc.VMID getVMID() { return vmID; } /** * Returns the UID part of this UniqueID. * @return the UID part of this UniqueID */ public java.rmi.server.UID getUID() { return id; } /** * Returns a string representation of this UniqueID. * @return a string representation of this UniqueID */ @Override public String toString() { if (logger.isDebugEnabled()) { return shortString(); } else { return getCanonString(); } } public String shortString() { if (this.cachedShortString == null) { this.cachedShortString = "" + Math.abs(this.getCanonString().hashCode() % 100000); } return this.cachedShortString; } public String getCanonString() { if (this.cachedCanonString == null) { this.cachedCanonString = "" + id + " " + vmID; } return this.cachedCanonString; } public int compareTo(Object o) { UniqueID u = (UniqueID) o; return getCanonString().compareTo(u.getCanonString()); } /** * Overrides hashCode to take into account the two part of this UniqueID. * @return the hashcode of this object */ @Override public int hashCode() { return id.hashCode() + vmID.hashCode(); } /** * Overrides equals to take into account the two part of this UniqueID. * @return the true if and only if o is an UniqueID equals to this UniqueID */ @Override public boolean equals(Object o) { //System.out.println("Now checking for equality"); if (o instanceof UniqueID) { return ((id.equals(((UniqueID) o).id)) && (vmID.equals(((UniqueID) o).vmID))); } else { return false; } } /** * for debug purpose */ public void echo() { logger.info("UniqueID The Id is " + id + " and the address is " + vmID); } }
package be.ugent.service; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.google.gson.Gson; import be.ugent.Authentication; import be.ugent.dao.PatientDao; import be.ugent.entitity.Patient; @Path("/PatientService") public class PatientService { PatientDao patientDao = new PatientDao(); @GET @Path("/patients") @Produces({ MediaType.APPLICATION_JSON }) public Response getUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName, @HeaderParam("Authorization") String header) { if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } // System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName); Patient retrieved = patientDao.getPatient(firstName, lastName); retrieved.setPassword(""); return Response.ok(retrieved+"").build(); } @GET @Path("/advice") @Produces({ MediaType.TEXT_PLAIN }) public Response getAdvice(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) { if(!Authentication.isAuthorized(header)){ return Response.status(403).build(); } // System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName); Patient retrieved = patientDao.getPatienFromId(patientID); return Response.ok().entity(retrieved.getAdvice()+"").build(); } @GET @Path("/login") @Produces({ MediaType.APPLICATION_JSON }) public Response login(@HeaderParam("Authorization") String header) { //if(!Authentication.isAuthorized(header)){ // return Response.status(403).build(); // System.out.println("User ingelogd met email:"+patientDao.getPatientFromHeader(header)); Patient retrieved = patientDao.getPatientFromHeader(header); retrieved.setPassword(""); return Response.ok(retrieved+"").build(); } @POST @Path("/patients/hello") @Consumes({MediaType.TEXT_PLAIN}) public Response hello(String user){ System.out.println("Hello "+user); return Response.ok("Hello "+user).build(); } @PUT @Path("/patients") @Consumes(MediaType.APPLICATION_JSON) public Response addUser(String user){ System.out.println("pat: "+user); System.out.println("Patient requested to add: "+user.toString()); Gson gson = new Gson(); Patient toAdd = gson.fromJson(user, Patient.class); if(toAdd.getPatientID()==0){ PatientDao patientDao = new PatientDao(); toAdd.setPatientID(patientDao.getNewId()); } JSONObject userJSON = null; try { userJSON = new JSONObject(user); toAdd.setRelation(""+userJSON.get("relation")); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return Response.status(417).build(); } // System.out.println("Patient to add:"+toAdd); if(patientDao.storePatient(toAdd)){ //return patient successfully created return Response.status(201).entity(patientDao.getPatienFromId(toAdd.getPatientID()+"")).build(); }else{ //return record was already in database, or was wrong format return Response.status(409).build(); } } @POST @Path("/patients/update") @Consumes(MediaType.APPLICATION_JSON) public Response changeUser(String user){ System.out.println("Patient requested to change: "+user.toString()); Gson gson = new Gson(); Patient toAdd = gson.fromJson(user, Patient.class); if(toAdd.getPatientID()<=0){ return Response.status(404).build(); } JSONObject userJSON = null; try { userJSON = new JSONObject(user); toAdd.setRelation(""+userJSON.get("relation")); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // System.out.println("Patient to add:"+toAdd); if(patientDao.updatePatient(toAdd)){ //return patient successfully created return Response.status(202).entity(toAdd.getPatientID()).build(); }else{ //return record was already in database, or was wrong format return Response.status(409).build(); } } }
package com.jetbrains.python.psi.resolve; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ProcessingContext; import com.intellij.util.containers.HashSet; import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyImportResolver; import com.jetbrains.python.psi.types.PyType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author yole */ public class ResolveImportUtil { /** Name of the __init__.py special file. */ @NonNls public static final String INIT_PY = "__init__.py"; @NonNls public static final String PY_SUFFIX = ".py"; private ResolveImportUtil() { } private static final ThreadLocal<Set> myBeingImported = new ThreadLocal<Set>() { @Override protected Set initialValue() { return new HashSet(); } }; /** * Resolves a reference in an import statement into whatever object it refers to. * @param importRef a reference within an import element. * @return the object importRef refers to, or null. */ @Nullable public static PsiElement resolveImportReference(final PyReferenceExpression importRef) { if (importRef == null) return null; // fail fast final String referencedName = importRef.getReferencedName(); if (referencedName == null) return null; PyReferenceExpression source = null; if (importRef.getParent() instanceof PyImportElement) { PyImportElement parent = (PyImportElement) importRef.getParent(); if (parent.getParent() instanceof PyFromImportStatement) { PyFromImportStatement stmt = (PyFromImportStatement) parent.getParent(); source = stmt.getImportSource(); if (source == null) return null; } } PsiElement result; if (source != null) { result = resolvePythonImport2(source, referencedName); } else result = resolvePythonImport2(importRef, null); if (result != null) { return result; } return resolveForeignImport(importRef, resolveImportReference(source)); } /* * Finds a named submodule file/dir under given root. */ @Nullable private static PsiElement matchToFile(String name, PsiManager manager, VirtualFile root_file) { VirtualFile child_file = root_file.findChild(name); if (child_file != null) { if (name.equals(child_file.getName())) { VirtualFile initpy = child_file.findChild(INIT_PY); if (initpy != null) { PsiFile initfile = manager.findFile(initpy); if (initfile != null) { initfile.putCopyableUserData(PyFile.KEY_IS_DIRECTORY, Boolean.TRUE); // we really resolved to the dir return initfile; } } } } return null; } /** * Resolves either <tt>import foo</tt> or <tt>from foo import bar</tt>. * @param importRef refers to the name of the module being imported (the <tt>foo</tt>). * @param referencedName the name imported from the module (the <tt>bar</tt> in <tt>import from</tt>), or null (for just <tt>import foo</tt>). * @return element the name resolves to, or null. */ @Nullable public static PsiElement resolvePythonImport2(final PyReferenceExpression importRef, final String referencedName) { if (! importRef.isValid()) return null; // we often catch a reparse while in a process of resolution final String the_name = referencedName != null? referencedName : importRef.getName(); Set being_imported = myBeingImported.get(); PsiFile containing_file = importRef.getContainingFile(); PsiElement last_resolved = null; List<PyReferenceExpression> ref_path = PyResolveUtil.unwindQualifiers(importRef); // join path to form the FQN: (a, b, c) -> a.b.c. StringBuffer pathbuf = new StringBuffer(); for (PyQualifiedExpression pathelt : ref_path) pathbuf.append(pathelt.getName()).append("."); if (referencedName != null) pathbuf.append(referencedName); final String import_fqname = pathbuf.toString(); if (being_imported.contains(import_fqname)) return null; // already trying this path, unable to recurse try { being_imported.add(import_fqname); // mark // resolve qualifiers Iterator<PyReferenceExpression> it = ref_path.iterator(); if (ref_path.size() > 1) { // it was a qualified name if (it.hasNext()) { last_resolved = it.next().resolve(); // our topmost qualifier, not ourselves for certain } else return null; // topmost qualifier not found while (it.hasNext()) { last_resolved = resolveChild(last_resolved, it.next().getName(), containing_file, true); if (last_resolved == null) return null; // anything in the chain unresolved means that the whole chain fails } if (referencedName != null) { return resolveChild(last_resolved, referencedName, containing_file, false); } else return last_resolved; } // non-qualified name if (referencedName != null) { return resolveChild(importRef.resolve(), referencedName, containing_file, false); // the importRef.resolve() does not recurse infinitely because we're asked to resolve referencedName, not importRef itself } // unqualified import can be found: // in the same dir PsiElement root_elt = resolveInRoots(importRef, the_name); if (root_elt != null) return root_elt; } finally { being_imported.remove(import_fqname); // unmark } return null; // not resolved by any means } public static void visitRoots(final PsiElement elt, @NotNull final SdkRootVisitor visitor) { // real search final Module module = ModuleUtil.findModuleForPsiElement(elt); if (module != null) { // TODO: implement a proper module-like approach in PyCharm for "project's dirs on pythonpath", minding proper search order // Module-based approach works only in the IDEA plugin. ModuleRootManager rootManager = ModuleRootManager.getInstance(module); // look in module sources boolean source_entries_missing = true; for (ContentEntry entry: rootManager.getContentEntries()) { VirtualFile root_file = entry.getFile(); if (!visitor.visitRoot(root_file)) return; for (VirtualFile folder : entry.getSourceFolderFiles()) { source_entries_missing = false; if (!visitor.visitRoot(folder)) return; } } if (source_entries_missing) { // fallback for a case without any source entries: use project root VirtualFile project_root = module.getProject().getBaseDir(); if (!visitor.visitRoot(project_root)) return; } // else look in SDK roots rootManager.processOrder(new SdkRootVisitingPolicy(visitor), null); } else { // no module, another way to look in SDK roots final PsiFile elt_psifile = elt.getContainingFile(); if (elt_psifile != null) { // formality final VirtualFile elt_vfile = elt_psifile.getVirtualFile(); if (elt_vfile != null) { // reality for (OrderEntry entry: ProjectRootManager.getInstance(elt.getProject()).getFileIndex().getOrderEntriesForFile(elt_vfile)) { if (!visitGivenRoots(entry.getFiles(OrderRootType.SOURCES), visitor)) break; if (!visitGivenRoots(entry.getFiles(OrderRootType.CLASSES), visitor)) break; } } } } } private static boolean visitGivenRoots(final VirtualFile[] roots, SdkRootVisitor visitor) { for (VirtualFile root: roots) { if (! visitor.visitRoot(root)) return false; } return true; } // TODO: rewrite using visitRoots /** * Looks for a name among element's module's roots; if there's no module, then among project's roots. * @param elt PSI element that defines the module and/or the project. * @param refName module name to be found among roots. * @return a PsiFile, a child of a root. */ @Nullable public static PsiElement resolveInRoots(@NotNull final PsiElement elt, final String refName) { // NOTE: a quick and ditry temporary fix for "current dir" root path, which is assumed to be present first (but may be not). PsiFile pfile = elt.getContainingFile(); VirtualFile vfile = pfile.getVirtualFile(); if (vfile == null) { // we're probably within a copy, e.g. for completion; get the real thing pfile = pfile.getOriginalFile(); } if (pfile != null) { PsiDirectory pdir = pfile.getContainingDirectory(); if (pdir != null) { PsiElement child_elt = resolveChild(pdir, refName, pfile, true); if (child_elt != null) return child_elt; } } // real search final Module module = ModuleUtil.findModuleForPsiElement(elt); if (module != null) { // TODO: implement a proper module-like approach in PyCharm for "project's dirs on pythonpath", minding proper search order // Module-based approach works only in the IDEA plugin. ModuleRootManager rootManager = ModuleRootManager.getInstance(module); // look in module sources boolean source_entries_missing = true; for (ContentEntry entry: rootManager.getContentEntries()) { VirtualFile root_file = entry.getFile(); PsiElement ret = matchToFile(refName, elt.getManager(), root_file); if (ret != null) return ret; for (VirtualFile folder : entry.getSourceFolderFiles()) { source_entries_missing = false; ret = matchToFile(refName, elt.getManager(), folder); if (ret != null) return ret; } } if (source_entries_missing) { // fallback for a case without any source entries: use project root VirtualFile project_root = module.getProject().getBaseDir(); PsiElement ret = matchToFile(refName, elt.getManager(), project_root); if (ret != null) return ret; } // else look in SDK roots LookupRootVisitor visitor = new LookupRootVisitor(refName, elt.getManager()); rootManager.processOrder(new SdkRootVisitingPolicy(visitor), null); return visitor.getResult(); } else { // no module, another way to look in SDK roots try { final PsiFile elt_psifile = elt.getContainingFile(); if (elt_psifile != null) { // formality final VirtualFile elt_vfile = elt_psifile.getVirtualFile(); if (elt_vfile != null) { // reality for (OrderEntry entry: ProjectRootManager.getInstance(elt.getProject()).getFileIndex().getOrderEntriesForFile(elt_vfile ) ) { PsiElement root_elt = resolveWithinRoots(entry.getFiles(OrderRootType.SOURCES), refName, elt.getProject()); if (root_elt != null) return root_elt; } } } } catch (NullPointerException ex) { // NOTE: not beautiful return null; // any cut corners might result in an NPE; resolution fails, but not the IDE. } } return null; // nothing matched } @Nullable private static PsiElement resolveForeignImport(final PyReferenceExpression importRef, final PsiElement importFrom) { for(PyImportResolver resolver: Extensions.getExtensions(PyImportResolver.EP_NAME)) { PsiElement result = resolver.resolveImportReference(importRef, importFrom); if (result != null) { return result; } } return null; } @Nullable private static PsiElement resolveWithinRoots(final VirtualFile[] roots, final String referencedName, final Project project) { for(VirtualFile contentRoot: roots) { PsiElement result = resolveWithinRoot(contentRoot, referencedName, project); if (result != null) return result; } return null; } /** Tries to find referencedName under a root. @param root where to look for the referenced name. @param referencedName which name to look for. @param project Project to use. @return the element the referencedName resolves to, or null. */ @Nullable private static PsiElement resolveWithinRoot(final VirtualFile root, final String referencedName, final Project project) { final PsiManager psi_mgr = PsiManager.getInstance(project); final VirtualFile childFile = root.findChild(referencedName + PY_SUFFIX); if (childFile != null) { return psi_mgr.findFile(childFile); } final VirtualFile childDir = root.findChild(referencedName); if (childDir != null) { return psi_mgr.findDirectory(childDir); } return null; } interface SdkRootVisitor { /** * @param root what we're visiting. * @return false when visiting must stop. */ boolean visitRoot(VirtualFile root); } static class LookupRootVisitor implements SdkRootVisitor { String name; PsiManager psimgr; PsiElement result; public LookupRootVisitor(String name, PsiManager psimgr) { this.name = name; this.psimgr = psimgr; this.result = null; } public boolean visitRoot(final VirtualFile root) { if (result != null) return false; final VirtualFile childFile = root.findChild(name + PY_SUFFIX); if (childFile != null) { result = psimgr.findFile(childFile); return (result == null); } final VirtualFile childDir = root.findChild(name); if (childDir != null) { result = psimgr.findDirectory(childDir); return (result == null); } return true; } public PsiElement getResult() { return result; } } static class CollectingRootVisitor implements SdkRootVisitor { Set<String> result; PsiManager psimgr; static String cutExt(String name) { return name.substring(0, Math.max(name.length() - PY_SUFFIX.length(), 0)); } public CollectingRootVisitor(PsiManager psimgr) { result = new HashSet<String>(); this.psimgr = psimgr; } public boolean visitRoot(final VirtualFile root) { for (VirtualFile vfile : root.getChildren()) { if (vfile.getName().endsWith(PY_SUFFIX)) { PsiFile pfile = psimgr.findFile(vfile); if (pfile != null) result.add(cutExt(pfile.getName())); } else if (vfile.isDirectory() && (vfile.findChild(INIT_PY) != null)) { PsiDirectory pdir = psimgr.findDirectory(vfile); if (pdir != null) result.add(pdir.getName()); } } return true; // continue forever } public Collection<String> getResult() { return result; } } /** Tries to find referencedName under the parent element. Used to resolve any names that look imported. Parent might happen to be a PyFile(__init__.py), then it is treated <i>both</i> as a file and as ist base dir. For details of this ugly magic, see {@link com.jetbrains.python.psi.impl.PyReferenceExpressionImpl#resolve()}. @param parent element under which to look for referenced name. @param referencedName which name to look for. @param containingFile where we're in. @param fileOnly if true, considers only a PsiFile child as a valid result; non-file hits are ignored. @return the element the referencedName resolves to, or null. @todo: Honor module's __all__ value. @todo: Honor package's __path__ value (hard). */ @Nullable public static PsiElement resolveChild(final PsiElement parent, final String referencedName, final PsiFile containingFile, boolean fileOnly) { PsiDirectory dir = null; PsiElement ret = null; ResolveProcessor processor = null; if (parent instanceof PyFile) { boolean is_dir = (parent.getCopyableUserData(PyFile.KEY_IS_DIRECTORY) == Boolean.TRUE); PyFile pfparent = (PyFile)parent; if (! is_dir) { // look for name in the file: processor = new ResolveProcessor(referencedName); //ret = PyResolveUtil.treeWalkUp(processor, parent, null, importRef); ret = PyResolveUtil.treeCrawlUp(processor, true, parent); if (ret != null) return ret; } else { // the file was a fake __init__.py covering a reference to dir dir = pfparent.getContainingDirectory(); } } else if (parent instanceof PsiDirectory) { dir = (PsiDirectory)parent; } else if (parent instanceof PsiDirectoryContainer) { final PsiDirectoryContainer container = (PsiDirectoryContainer)parent; for(PsiDirectory childDir: container.getDirectories()) { final PsiElement result = resolveInDirectory(referencedName, containingFile, childDir, processor); if (fileOnly && ! (result instanceof PsiFile) && ! (result instanceof PsiDirectory)) return null; if (result != null) return result; } } if (dir != null) { final PsiElement result = resolveInDirectory(referencedName, containingFile, dir, processor); if (fileOnly && ! (result instanceof PsiFile) && ! (result instanceof PsiDirectory)) return null; return result; } return ret; } @Nullable private static PsiElement resolveInDirectory(final String referencedName, final PsiFile containingFile, final PsiDirectory dir, ResolveProcessor processor) { final PsiFile file = dir.findFile(referencedName + PY_SUFFIX); if (file != null) return file; final PsiDirectory subdir = dir.findSubdirectory(referencedName); if (subdir != null) return subdir; else { // not a subdir, not a file; could be a name in parent/__init__.py final PsiFile initPy = dir.findFile(INIT_PY); if (initPy == containingFile) return null; // don't dive into the file we're in if (initPy != null) { if (processor == null) processor = new ResolveProcessor(referencedName); // should not normally happen return PyResolveUtil.treeCrawlUp(processor, true, initPy);//PyResolveUtil.treeWalkUp(processor, initPy, null, importRef); } } return null; } private static void addImportedNames(PyImportElement[] import_elts, Collection<String> names_already) { if (import_elts != null && names_already != null) { for (PyImportElement ielt : import_elts) { String s; PyReferenceExpression ref = ielt.getImportReference(); if (ref != null) { s = ref.getReferencedName(); if (s != null) names_already.add(s); } } } } /** * Finds reasonable names to import to complete a patrial name. * @param partial_ref reference containing the partial name. * @return an array of names ready for getVariants(). */ public static Object[] suggestImportVariants(final PyReferenceExpression partial_ref) { List<Object> variants = new ArrayList<Object>(); if (partial_ref == null) return variants.toArray(); // are we in "import _" or "from foo import _"? PyFromImportStatement from_import = PsiTreeUtil.getParentOfType(partial_ref, PyFromImportStatement.class); if (from_import != null && partial_ref.getParent() != from_import) { // in "from foo import _" PyReferenceExpression src = from_import.getImportSource(); if (src != null) { PsiElement mod_candidate = src.resolve(); if (mod_candidate instanceof PyExpression) { final Set<String> names_already = new java.util.HashSet<String>(); // don't propose already imported items addImportedNames(from_import.getImportElements(), names_already); // collect what's within module file final VariantsProcessor processor = new VariantsProcessor(new PyResolveUtil.FilterNameNotIn(names_already)); PyResolveUtil.treeCrawlUp(processor, true, mod_candidate); variants.addAll(processor.getResultList()); // try to collect submodules PyExpression module = (PyExpression)mod_candidate; PyType qualifierType = module.getType(); if (qualifierType != null) { ProcessingContext ctx = new ProcessingContext(); for (Object ex : variants) { // just in case: file's definitions shadow submodules if (ex instanceof PyReferenceExpression) { names_already.add(((PyReferenceExpression)ex).getReferencedName()); } } // collect submodules ctx.put(PyType.CTX_NAMES, names_already); Collections.addAll(variants, qualifierType.getCompletionVariants(partial_ref, ctx)); } return variants.toArray(); } } } // in "import _" or "from _ import" // don't propose already imported names final Set<String> names_already = new java.util.HashSet<String>(); if (from_import != null) addImportedNames(from_import.getImportElements(), names_already); else { PyImportStatement import_stmt = PsiTreeUtil.getParentOfType(partial_ref, PyImportStatement.class); if (import_stmt != null) { addImportedNames(import_stmt.getImportElements(), names_already); } } // look in builtins DataContext dataContext = DataManager.getInstance().getDataContext(); // look at current dir final VirtualFile pfile = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext); if (pfile != null) { VirtualFile pdir = pfile.getParent(); if (pdir != null) { for (VirtualFile a_file : pdir.getChildren()) { if (a_file != pfile) { if (a_file.isDirectory()) { if (a_file.findChild(INIT_PY) != null) { final String name = a_file.getName(); if (PyUtil.isIdentifier(name) && !names_already.contains(name)) variants.add(name); } } else { // plain file String fname = a_file.getName(); if (fname.endsWith(PY_SUFFIX)) { final String name = fname.substring(0, fname.length() - PY_SUFFIX.length()); if (PyUtil.isIdentifier(name) && !names_already.contains(name)) variants.add(name); } } } } } } // look in SDK final CollectingRootVisitor visitor = new CollectingRootVisitor(partial_ref.getManager()); final Module module = ModuleUtil.findModuleForPsiElement(partial_ref); if (module != null) { ModuleRootManager.getInstance(module).processOrder(new SdkRootVisitingPolicy(visitor), null); for (String name : visitor.getResult()) { if (PyUtil.isIdentifier(name) && !names_already.contains(name)) variants.add(name); // to thwart stuff like "__phello__.foo" } } return variants.toArray(new Object[variants.size()]); } /** * Tries to find roots that contain given vfile, and among them the root that contains at the smallest depth. */ private static class PathChoosingVisitor implements SdkRootVisitor { private final VirtualFile myFile; private String myFname; private String myResult = null; private int myDots = Integer.MAX_VALUE; // how many dots in the path private PathChoosingVisitor(VirtualFile file) { myFile = file; myFname = file.getPath(); // cut off the ext int pos = myFname.lastIndexOf('.'); if (pos > 0) myFname = myFname.substring(0, pos); // cut off the final __init__ if it's there; we want imports directly from a module pos = myFname.lastIndexOf(PyNames.INIT); if (pos > 0) myFname = myFname.substring(0, pos-1); // pos-1 also cuts the '/' that came before "__init__" } public boolean visitRoot(VirtualFile root) { // does it ever fit? String root_name = root.getPath()+"/"; if (myFname.startsWith(root_name)) { String bet = myFname.substring(root_name.length()).replace('/', '.'); // "/usr/share/python/foo/bar" -> "foo.bar" // count the dots int dots = 0; for (int i = 0; i < bet.length(); i += 1) if (bet.charAt(i) == '.') dots += 1; // a better variant? if (dots < myDots) { myDots = dots; myResult = bet; } } return true; // visit all roots } public String getResult() { return myResult; } } /** * Looks for a way to import given file. * @param foothold an element in the file to import to (maybe the file itself); used to determine module, roots, etc. * @param vfile file which importable name we want to find. * @return a possibly qualified name under which the file may be imported, or null. If there's more than one way (overlapping roots), * the name with fewest qualifiers is selected. */ @Nullable public static String findShortestImportableName(PsiElement foothold, VirtualFile vfile) { PathChoosingVisitor visitor = new PathChoosingVisitor(vfile); visitRoots(foothold, visitor); return visitor.getResult(); } private static class SdkRootVisitingPolicy extends RootPolicy<PsiElement> { private final SdkRootVisitor myVisitor; public SdkRootVisitingPolicy(SdkRootVisitor visitor) { myVisitor = visitor; } @Nullable public PsiElement visitJdkOrderEntry(final JdkOrderEntry jdkOrderEntry, final PsiElement value) { if (value != null) return value; // for chaining in processOrder() visitGivenRoots(jdkOrderEntry.getRootFiles(OrderRootType.SOURCES), myVisitor); visitGivenRoots(jdkOrderEntry.getRootFiles(OrderRootType.CLASSES), myVisitor); return null; } @Nullable @Override public PsiElement visitLibraryOrderEntry(LibraryOrderEntry libraryOrderEntry, PsiElement value) { if (value != null) return value; // for chaining in processOrder() visitGivenRoots(libraryOrderEntry.getRootFiles(OrderRootType.SOURCES), myVisitor); visitGivenRoots(libraryOrderEntry.getRootFiles(OrderRootType.CLASSES), myVisitor); return null; } } }
package org.c4sg.service; import org.c4sg.dto.UserDTO; import org.c4sg.entity.User; import java.util.List; public interface UserService { List<UserDTO> findAll(); List<UserDTO> findActiveUsers(); UserDTO findById(int id); UserDTO findByEmail(String email); List<User> findDevelopers(); UserDTO saveUser(UserDTO userDTO); void deleteUser(Integer id); List<UserDTO> search(String userName, String firstName, String lastName); List<UserDTO> getApplicants(Integer projectId); String getAvatarUploadPath(Integer userId); String getResumeUploadPath(Integer userId); }
package radlab.rain.workload.rubis; import java.util.Arrays; import java.util.Calendar; import java.util.concurrent.atomic.AtomicInteger; //import java.util.concurrent.Semaphore; import java.util.Date; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpStatus; import radlab.rain.util.HttpTransport; import radlab.rain.workload.rubis.model.RubisCategory; import radlab.rain.workload.rubis.model.RubisComment; import radlab.rain.workload.rubis.model.RubisItem; import radlab.rain.workload.rubis.model.RubisRegion; import radlab.rain.workload.rubis.model.RubisUser; import radlab.rain.workload.rubis.util.DiscreteDistribution; /** * Collection of RUBiS utilities. * * @author Marco Guazzone (marco.guazzone@gmail.com) */ public final class RubisUtility { public static final int ANONYMOUS_USER_ID = -1; public static final int INVALID_CATEGORY_ID = -1; public static final int INVALID_REGION_ID = -1; public static final int INVALID_ITEM_ID = -1; public static final int INVALID_OPERATION_ID = -1; public static final int MILLISECS_PER_DAY = 1000*60*60*24; private static final char[] ALNUM_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; ///< The set of alphanumeric characters private static final String[] COMMENTS = {"This is a very bad comment. Stay away from this seller!!", "This is a comment below average. I don't recommend this user!!", "This is a neutral comment. It is neither a good or a bad seller!!", "This is a comment above average. You can trust this seller even if it is not the best deal!!", "This is an excellent comment. You can make really great deals with this seller!!"}; ///< Descriptions associated to comment ratings private static final int[] COMMENT_RATINGS = {-5, // Bad -3, // Below average 0, // Neutral 3, // Average 5 /* Excellent */ }; ///< Possible comment ratings private static final int MIN_USER_ID = 1; ///< Mininum value for user IDs private static final int MIN_ITEM_ID = 1; ///< Mininum value for item IDs private static final int MIN_REGION_ID = 1; ///< Mininum value for region IDs private static final int MIN_CATEGORY_ID = 1; ///< Mininum value for category IDs private static AtomicInteger _userId; private static AtomicInteger _itemId; // private static Semaphore _userLock = new Semaphore(1, true); // private static Semaphore _itemLock = new Semaphore(1, true); private Random _rng = null; private RubisConfiguration _conf = null; private DiscreteDistribution _catDistr = null; ///< Probability distribution for generating random categories private Pattern _pageRegex = Pattern.compile("^.*?[&?]page=(\\d+).*?(?:[&?]page=(\\d+).*?)?$"); private static int nextUserId() { return _userId.incrementAndGet(); } private static int lastUserId() { return _userId.get(); } private static int nextItemId() { return _itemId.incrementAndGet(); } private static int lastItemId() { return _itemId.get(); } // private static void lockUsers() throws InterruptedException // _userLock.acquire(); // private static void unlockUsers() // _userLock.release(); // private static void lockItems() throws InterruptedException // _itemLock.acquire(); // private static void unlockItems() // _itemLock.release(); private static synchronized void initUserId(int numPreloadUsers) { _userId = new AtomicInteger(MIN_USER_ID+numPreloadUsers-1); } private static synchronized void initItemId(int numPreloadItems) { _itemId = new AtomicInteger(MIN_ITEM_ID+numPreloadItems-1); } public RubisUtility() { } public RubisUtility(Random rng, RubisConfiguration conf) { this._rng = rng; this._conf = conf; initUserId(this._conf.getNumOfPreloadedUsers()); initItemId(this._conf.getTotalActiveItems()+this._conf.getNumOfOldItems()); int nc = this._conf.getCategories().size(); if (nc > 0) { double[] catProbs = new double[nc]; for (int i = 0; i < nc; ++i) { catProbs[i] = this._conf.getNumOfItemsPerCategory(i) / ((double) this._conf.getTotalActiveItems()); } this._catDistr = new DiscreteDistribution(catProbs); } } public void setRandomGenerator(Random rng) { this._rng = rng; } public Random getRandomGenerator() { return this._rng; } public void setConfiguration(RubisConfiguration conf) { this._conf = conf; initUserId(this._conf.getNumOfPreloadedUsers()); } public RubisConfiguration getConfiguration() { return this._conf; } public boolean isAnonymousUser(RubisUser user) { return this.isAnonymousUser(user.id); } public boolean isAnonymousUser(int userId) { return ANONYMOUS_USER_ID == userId; } public boolean isLoggedUser(RubisUser user) { return !this.isLoggedUser(user.id); } public boolean isLoggedUser(int userId) { return !this.isAnonymousUser(userId); } public boolean isValidUser(RubisUser user) { return null != user && MIN_USER_ID <= user.id; } public boolean isValidItem(RubisItem item) { return null != item && MIN_ITEM_ID <= item.id; } public boolean isValidCategory(RubisCategory category) { return null != category && MIN_CATEGORY_ID <= category.id; } public boolean isValidRegion(RubisRegion region) { return null != region && MIN_REGION_ID <= region.id; } public boolean checkHttpResponse(HttpTransport httpTransport, String response) { if (response.length() == 0 || HttpStatus.SC_OK != httpTransport.getStatusCode() || -1 != response.indexOf("ERROR")) { return false; } return true; } /** * Creates a new RUBiS user object. * * @return an instance of RubisUser. */ public RubisUser newUser() { return this.getUser(nextUserId()); } /** * Generate a random RUBiS user among the ones already preloaded. * * @return an instance of RubisUser. */ public RubisUser generateUser() { // Only generate a user among the ones that have been already preloaded in the DB int userId = this._rng.nextInt(this._conf.getNumOfPreloadedUsers()-MIN_USER_ID)+MIN_USER_ID; return this.getUser(userId); } /** * Get the RUBiS user associated to the given identifier. * * @param id The user identifier. * @return an instance of RubisUser. */ public RubisUser getUser(int id) { RubisUser user = new RubisUser(); user.id = id; user.firstname = "Great" + user.id; user.lastname = "User" + user.id; user.nickname = "user" + user.id; user.email = user.firstname + "." + user.lastname + "@rubis.com"; user.password = "password" + user.id; user.region = this.generateRegion().id; Calendar cal = Calendar.getInstance(); user.creationDate = cal.getTime(); return user; } /** * Creates a new RUBiS item. * * @return an instance of RubisItem. */ public RubisItem newItem(int loggedUserId) { return this.getItem(nextItemId(), loggedUserId); } /** * Generate a random RUBiS item among the ones already preloaded. * * @return an instance of RubisItem. */ public RubisItem generateItem(int loggedUserId) { // Only generate an item among the active and old ones int itemId = this._rng.nextInt(this._conf.getTotalActiveItems()+this._conf.getNumOfOldItems()-MIN_ITEM_ID)+MIN_ITEM_ID; return this.getItem(itemId, loggedUserId); } /** * Get the RUBiS item associated to the given identifier. * * @param id The item identifier. * @return an instance of RubisItem. */ public RubisItem getItem(int id, int loggedUserId) { RubisItem item = new RubisItem(); item.id = id; item.name = "RUBiS automatically generated item #" + item.id; item.description = this.generateText(1, this._conf.getMaxItemDescriptionLength()); item.initialPrice = this._rng.nextInt((int) Math.round(this._conf.getMaxItemInitialPrice()))+1; if (this._rng.nextInt(this._conf.getTotalActiveItems()) < (this._conf.getPercentageOfUniqueItems()*this._conf.getTotalActiveItems()/100.0)) { item.quantity = 1; } else { item.quantity = this._rng.nextInt(this._conf.getMaxItemQuantity())+1; } if (this._rng.nextInt(this._conf.getTotalActiveItems()) < (this._conf.getPercentageOfItemsReserve()*this._conf.getTotalActiveItems()/100.0)) { item.reservePrice = this._rng.nextInt((int) Math.round(this._conf.getMaxItemBaseReservePrice()))+item.initialPrice; } else { item.reservePrice = 0; } if (this._rng.nextInt(this._conf.getTotalActiveItems()) < (this._conf.getPercentageOfItemsBuyNow()*this._conf.getTotalActiveItems()/100.0)) { item.buyNow = this._rng.nextInt((int) Math.round(this._conf.getMaxItemBaseBuyNowPrice()))+item.initialPrice+item.reservePrice; } else { item.buyNow = 0; } item.nbOfBids = 0; item.maxBid = 0; Calendar cal = Calendar.getInstance(); item.startDate = cal.getTime(); cal.add(Calendar.DAY_OF_MONTH, this._rng.nextInt(this._conf.getMaxItemDuration())+1); item.endDate = cal.getTime(); item.seller = loggedUserId; item.category = this.generateCategory().id; return item; } public RubisCategory generateCategory() { // return this.getCategory(this._rng.nextInt(this._conf.getCategories().size()-MIN_CATEGORY_ID)+MIN_CATEGORY_ID); return this.getCategory(this._catDistr.nextInt(this._rng)+MIN_CATEGORY_ID); } public RubisCategory getCategory(int id) { RubisCategory category = new RubisCategory(); category.id = id; category.name = this._conf.getCategories().get(category.id-MIN_CATEGORY_ID); return category; } public RubisRegion generateRegion() { return this.getRegion(this._rng.nextInt(this._conf.getRegions().size()-MIN_REGION_ID)+MIN_REGION_ID); } public RubisRegion getRegion(int id) { RubisRegion region = new RubisRegion(); region.id = id; region.name = this._conf.getRegions().get(region.id); return region; } public RubisComment generateComment(int fromUserId, int toUserId, int itemId) { return getComment(fromUserId, toUserId, itemId, COMMENT_RATINGS[this._rng.nextInt(COMMENT_RATINGS.length)]); } public RubisComment getComment(int fromUserId, int toUserId, int itemId, int rating) { RubisComment comment = new RubisComment(); comment.fromUserId = fromUserId; comment.toUserId = toUserId; comment.itemId = itemId; int rateIdx = Arrays.binarySearch(COMMENT_RATINGS, rating); comment.rating = COMMENT_RATINGS[rateIdx]; comment.comment = this.generateText(1, this._conf.getMaxCommentLength()-COMMENTS[rateIdx].length()-System.lineSeparator().length()) + System.lineSeparator() + COMMENTS[rateIdx]; Calendar cal = Calendar.getInstance(); comment.date = cal.getTime(); return comment; } /** * Parses the given HTML text to find an item identifier. * * @param html The HTML string where to look for the item identifier. * @return The found item identifier, or INVALID_ITEM_ID if * no item identifier is found. If more than one item is found, returns the * one picked at random. * * This method is based on the edu.rice.rubis.client.UserSession#extractItemIdFromHTML. */ public int findItemIdInHtml(String html) { if (html == null) { return INVALID_ITEM_ID; } // Count number of itemId int count = 0; int keyIdx = html.indexOf("itemId="); while (keyIdx != -1) { ++count; keyIdx = html.indexOf("itemId=", keyIdx + 7); // 7 equals to "itemId=" } if (count == 0) { return INVALID_ITEM_ID; } // Choose randomly an item count = this._rng.nextInt(count) + 1; keyIdx = -7; while (count > 0) { keyIdx = html.indexOf("itemId=", keyIdx + 7); // 7 equals to itemId= --count; } int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('\"', keyIdx + 7)); lastIdx = minIndex(lastIdx, html.indexOf('?', keyIdx + 7)); lastIdx = minIndex(lastIdx, html.indexOf('&', keyIdx + 7)); lastIdx = minIndex(lastIdx, html.indexOf('>', keyIdx + 7)); String str = html.substring(keyIdx + 7, lastIdx); return Integer.parseInt(str); } /** * Parses the given HTML text to find the value of the given parameter. * * @param html The HTML string where to look for the parameter. * @param paramName The name of the parameter to look for. * @return The value of the parameter as a string, or null if * no parameter is found. * * This method is based on the edu.rice.rubis.client.UserSession#extractIntFromHTML * and edu.rice.rubis.client.UserSession#extractFloatFromHTML. */ public String findParamInHtml(String html, String paramName) { if (html == null) { return null; } // Look for the parameter // int paramIdx = html.indexOf(paramName); // if (paramIdx == -1) // return null; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('=', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('\"', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('?', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('&', paramIdx + paramName.length())); // lastIdx = minIndex(lastIdx, html.indexOf('>', paramIdx + paramName.length())); // return html.substring(paramIdx + paramName.length(), lastIdx); Pattern p = Pattern.compile("^.*?[&?]" + paramName + "=([^\"?&]*).+$"); Matcher m = p.matcher(html); if (m.matches()) { return m.group(1); } return null; } /** * Parses the given HTML text to find the value of the given form parameter. * * @param html The HTML string where to look for the form parameter. * @param paramName The name of the form parameter to look for. * @return The value of the form parameter as a string, or null if * no parameter is found. * * This method is based on the edu.rice.rubis.client.UserSession#extractIntFromHTML * and edu.rice.rubis.client.UserSession#extractFloatFromHTML. */ public String findFormParamInHtml(String html, String paramName) { if (html == null) { return null; } // Look for the parameter // String key = "name=" + paramName + " value="; // int keyIdx = html.indexOf(key); // if (keyIdx == -1) // return null; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('=', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('\"', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('?', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('&', keyIdx + key.length())); // lastIdx = minIndex(lastIdx, html.indexOf('>', keyIdx + key.length())); // return html.substring(keyIdx + key.length(), lastIdx); Pattern p = Pattern.compile("^.*?<(?i:input)\\s+(?:.+\\s)?(?i:name)=" + paramName + "\\s+(?:.+\\s)?(?i:value)=([^\"?&>]+).+$"); Matcher m = p.matcher(html); if (m.matches()) { return m.group(1); } return null; } /** * Parses the given HTML text to find the page value. * * @param html The HTML string where to look for the item identifier. * @return The page value. * * This method is based on the edu.rice.rubis.client.UserSession#extractPageFromHTML */ public int findPageInHtml(String html) { if (html == null) { return 0; } // int firstPageIdx = html.indexOf("&page="); // if (firstPageIdx == -1) // return 0; // int secondPageIdx = html.indexOf("&page=", firstPageIdx + 6); // 6 equals to &page= // int chosenIdx = 0; // if (secondPageIdx == -1) // chosenIdx = firstPageIdx; // First or last page => go to next or previous page // else // // Choose randomly a page (previous or next) // if (this._rng.nextInt(100000) < 50000) // chosenIdx = firstPageIdx; // else // chosenIdx = secondPageIdx; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('\"', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('?', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('&', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('>', chosenIdx + 6)); // String str = html.substring(chosenIdx + 6, lastIdx); // return Integer.parseInt(str); ////Pattern p = Pattern.compile("^.*?[&?]page=([^\"?&]*).*(?:[&?]page=([^\"?&]*).*)?$"); //Pattern p = Pattern.compile("^.*?[&?]page=(\\d+).*?(?:[&?]page=(\\d+).*?)?$"); Matcher m = _pageRegex.matcher(html); if (m.matches()) { if (m.groupCount() == 2 && m.group(2) != null) { // Choose randomly a page (previous or next) if (this._rng.nextInt(100000) < 50000) { return Integer.parseInt(m.group(1)); } return Integer.parseInt(m.group(2)); } // First or last page => go to next or previous page return (m.group(1) != null) ? Integer.parseInt(m.group(1)) : 0; } return 0; } /** * Get the number of days between the two input dates. * * @param from The first date * @param to The second date * @return The number of days between from and to. * A negative number means that the second date is earlier then the first * date. */ public int getDaysBetween(Date from, Date to) { Calendar cal = Calendar.getInstance(); cal.setTime(from); long fromTs = cal.getTimeInMillis(); cal.setTime(to); long toTs = cal.getTimeInMillis(); //long diffTs = Math.abs(toTs-fromTs); long diffTs = toTs-fromTs; return Math.round(diffTs/MILLISECS_PER_DAY); } public Date addDays(Date date, int n) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, n); return cal.getTime(); } /** * Internal method that returns the min between ix1 and ix2 if ix2 is not * equal to -1. * * @param ix1 The first index * @param ix2 The second index to compare with ix1 * @return ix2 if (ix2 < ix1 and ix2!=-1) else ix1 */ private static int minIndex(int ix1, int ix2) { if (ix2 == -1) { return ix1; } if (ix1 <= ix2) { return ix1; } return ix2; } /** * Generates a random text. * * @param minLen The minimum length of the text. * @param maxLen The maximum length of the text. * @return The generated text. */ private String generateText(int minLen, int maxLen) { int len = minLen+this._rng.nextInt(maxLen-minLen+1); StringBuilder buf = new StringBuilder(len); int left = len; while (left > 0) { if (buf.length() > 0) { buf.append(' '); --left; } String word = this.generateWord(1, left < this._conf.getMaxWordLength() ? left : this._conf.getMaxWordLength()); buf.append(word); left -= word.length(); } return buf.toString(); } /** * Generates a random word. * * @param minLen The minimum length of the word. * @param maxLen The maximum length of the word. * @return The generated word. */ private String generateWord(int minLen, int maxLen) { if (minLen > maxLen) { return ""; } int len = minLen+this._rng.nextInt(maxLen-minLen+1); char[] buf = new char[len]; for (int i = 0; i < len; ++i) { int j = this._rng.nextInt(ALNUM_CHARS.length); buf[i] = ALNUM_CHARS[j]; } return new String(buf); } }
package net.gcdc; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.util.Arrays; import net.gcdc.geonetworking.Address; import net.gcdc.geonetworking.BtpPacket; import net.gcdc.geonetworking.BtpSocket; import net.gcdc.geonetworking.Destination; import net.gcdc.geonetworking.GeonetData; import net.gcdc.geonetworking.GeonetStation; import net.gcdc.geonetworking.LinkLayer; import net.gcdc.geonetworking.LinkLayerUdpToEthernet; import net.gcdc.geonetworking.LongPositionVector; import net.gcdc.geonetworking.MacAddress; import net.gcdc.geonetworking.Optional; import net.gcdc.geonetworking.Position; import net.gcdc.geonetworking.PositionProvider; import net.gcdc.geonetworking.StationConfig; import net.gcdc.geonetworking.TrafficClass; import net.gcdc.geonetworking.UpperProtocolType; import net.gcdc.geonetworking.gpsdclient.GpsdClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.threeten.bp.Instant; public class BtpUdpClient { private final static Logger logger = LoggerFactory.getLogger(BtpUdpClient.class); private final static String usage = "Usage: java -cp gn.jar BtpClient --local-udp2eth-port <local-port> --remote-udp2eth-address <udp-to-ethernet-remote-host-and-port> --local-data-port <port> --remote-data-address <host:port> --gpsd-server <host:port> --mac-address <xx:xx:xx:xx:xx:xx>" + "\n" + "BTP ports: 2001 (CAM), 2002 (DENM), 2003 (MAP), 2004 (SPAT)."; public static void main(String[] args) throws IOException { if (args.length < 7) { System.err.println(usage); System.exit(1); } int localUdp2EthPort = 0; InetSocketAddress remoteUdp2EthAddress = null; int localDataPort = 0; InetSocketAddress remoteDataAddress = null; int localDataCamPort = 0; InetSocketAddress remoteDataCamAddress = null; int localDataIclcmPort = 0; InetSocketAddress remoteDataIclcmAddress = null; boolean hasEthernetHeader = false; PositionProvider positionProvider = null; short btpDestinationPort = (short) 2001; // CAM hasEthernetHeader = true; MacAddress macAddress = new MacAddress(0); for (int arg = 0; arg < args.length; arg += 2) { if (args[arg].startsWith("--local-udp2eth-port")) { localUdp2EthPort = Integer.parseInt(args[arg + 1]); } else if (args[arg].startsWith("--remote-udp2eth-address")) { String[] hostPort = args[arg + 1].split(":"); if (hostPort.length != 2) { System.err.println("Bad udp2eth host:port.\n" + usage); System.exit(1); } remoteUdp2EthAddress = new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1])); } else if (args[arg].startsWith("--local-data-port")) { localDataPort = Integer.parseInt(args[arg + 1]); } else if (args[arg].startsWith("--remote-data-address")) { String[] hostPort = args[arg + 1].split(":"); if (hostPort.length != 2) { System.err.println("Bad DATA host:port.\n" + usage); System.exit(1); } remoteDataAddress = new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1])); } else if (args[arg].startsWith("--local-data-cam-port")) { localDataCamPort = Integer.parseInt(args[arg + 1]); } else if (args[arg].startsWith("--remote-data-cam-address")) { String[] hostPort = args[arg + 1].split(":"); if (hostPort.length != 2) { System.err.println("Bad DATA host:port.\n" + usage); System.exit(1); } remoteDataCamAddress = new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1])); } else if (args[arg].startsWith("--local-data-iclcm-port")) { localDataIclcmPort = Integer.parseInt(args[arg + 1]); } else if (args[arg].startsWith("--remote-data-iclcm-address")) { String[] hostPort = args[arg + 1].split(":"); if (hostPort.length != 2) { System.err.println("Bad DATA host:port.\n" + usage); System.exit(1); } remoteDataIclcmAddress = new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1])); } else if (args[arg].startsWith("--position")) { String[] latLon = args[arg + 1].split(","); if (latLon.length != 2) { System.err.println("Bad lat,lon.\n" + usage); System.exit(1); } final double lat = Double.parseDouble(latLon[0]); final double lon = Double.parseDouble(latLon[1]); final boolean isPositionConfident = true; // Let's say we know it. positionProvider = new PositionProvider() { final Optional<Address> emptyAddress = Optional.empty(); @Override public LongPositionVector getLatestPosition() { return new LongPositionVector(emptyAddress, Instant.now(), new Position(lat, lon), isPositionConfident, 0, 0); } }; } else if (args[arg].startsWith("--gpsd-server")) { String[] hostPort = args[arg + 1].split(":"); if (hostPort.length != 2) { System.err.println("Bad gpsd host:port.\n" + usage); System.exit(1); } positionProvider = new GpsdClient( new InetSocketAddress(hostPort[0], Integer.parseInt(hostPort[1]))).startClient(); } else if (args[arg].startsWith("--mac-address")) { macAddress = new MacAddress(MacAddress.parseFromString(args[arg + 1])); } else { throw new IllegalArgumentException("Unrecognized argument: " + args[arg]); } } runSenderAndReceiver(localUdp2EthPort, remoteUdp2EthAddress, localDataPort, remoteDataAddress, localDataCamPort, remoteDataCamAddress, localDataIclcmPort, remoteDataIclcmAddress, hasEthernetHeader, positionProvider, btpDestinationPort, macAddress); } public static void runSenderAndReceiver( final int localUdp2EthPort, final SocketAddress remoteUdp2EthAddress, final int localDataPort, final InetSocketAddress remoteDataAddress, final int localDataCamPort, final InetSocketAddress remoteDataCamAddress, final int localDataIclcmPort, final InetSocketAddress remoteDataIclcmAddress, final boolean hasEthernetHeader, final PositionProvider positionProvider, final short btpDestinationPort, final MacAddress macAddress ) throws SocketException { LinkLayer linkLayer = new LinkLayerUdpToEthernet(localUdp2EthPort, remoteUdp2EthAddress, hasEthernetHeader); StationConfig config = new StationConfig(); final GeonetStation station = new GeonetStation(config, linkLayer, positionProvider, macAddress); new Thread(station).start(); // This is ugly API, sorry... station.startBecon(); final BtpSocket socket = BtpSocket.on(station); final Runnable senderData = new Runnable() { @Override public void run() { int length = 4096; byte[] buffer = new byte[length]; DatagramPacket udpPacket = new DatagramPacket(buffer, length); try (DatagramSocket udpSocket = new DatagramSocket(localDataPort);){ while (true) { udpSocket.receive(udpPacket); byte[] gnPayload = Arrays.copyOfRange(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getOffset() + udpPacket.getLength()); logger.info("Sending GN message of size {}", gnPayload.length); Optional<TrafficClass> emptyTrafficClass = Optional.empty(); Optional<LongPositionVector> emptySender = Optional.empty(); station.send(new GeonetData( UpperProtocolType.BTP_B, Destination.singleHop(), emptyTrafficClass, emptySender, gnPayload )); } } catch (IOException e) { e.printStackTrace(); } } }; final Runnable senderCam = new Runnable() { @Override public void run() { int length = 4096; byte[] buffer = new byte[length]; DatagramPacket udpPacket = new DatagramPacket(buffer, length); try (DatagramSocket udpSocket = new DatagramSocket(localDataCamPort);){ while (true) { udpSocket.receive(udpPacket); short btpDestinationPort = (short) 2001; byte[] btpPayload = Arrays.copyOfRange(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getOffset() + udpPacket.getLength()); logger.info("Sending BTP CAM message of size {} to BTP port {}", btpPayload.length, btpDestinationPort); socket.send(BtpPacket.singleHop(btpPayload, btpDestinationPort)); } } catch (IOException e) { e.printStackTrace(); } } }; final Runnable senderIclcm = new Runnable() { @Override public void run() { int length = 4096; byte[] buffer = new byte[length]; DatagramPacket udpPacket = new DatagramPacket(buffer, length); try (DatagramSocket udpSocket = new DatagramSocket(localDataIclcmPort);){ while (true) { udpSocket.receive(udpPacket); short btpDestinationPort = (short) 2010; byte[] btpPayload = Arrays.copyOfRange(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getOffset() + udpPacket.getLength()); logger.info("Sending BTP i-CLCM message of size {} to BTP port {}", btpPayload.length, btpDestinationPort); socket.send(BtpPacket.singleHop(btpPayload, btpDestinationPort)); } } catch (IOException e) { e.printStackTrace(); } } }; Runnable receiver = new Runnable() { @Override public void run() { int length = 4096; byte[] buffer = new byte[length]; DatagramPacket udpPacket = new DatagramPacket(buffer, length); udpPacket.setPort(remoteDataAddress.getPort()); udpPacket.setAddress(remoteDataAddress.getAddress()); byte[] bufferCam = new byte[length]; DatagramPacket udpPacketCam = new DatagramPacket(bufferCam, length); if (remoteDataCamAddress != null) { udpPacketCam.setPort(remoteDataCamAddress.getPort()); udpPacketCam.setAddress(remoteDataCamAddress.getAddress()); } byte[] bufferIclcm = new byte[length]; DatagramPacket udpPacketIclcm = new DatagramPacket(bufferIclcm, length); if (remoteDataIclcmAddress != null) { udpPacketIclcm.setPort(remoteDataIclcmAddress.getPort()); udpPacketIclcm.setAddress(remoteDataIclcmAddress.getAddress()); } try (DatagramSocket udpSocket = new DatagramSocket();){ while(true) { try { GeonetData gnData = station.receive(); System.arraycopy(gnData.payload, 0, buffer, 0, gnData.payload.length); udpPacket.setLength(gnData.payload.length); udpSocket.send(udpPacket); BtpPacket packet = BtpPacket.fromGeonetData(gnData); if (packet.destinationPort() == 2001 && remoteDataCamAddress != null) { System.arraycopy(packet.payload(), 0, bufferCam, 0, packet.payload().length); udpPacketCam.setLength(packet.payload().length); udpSocket.send(udpPacketCam); } else if (packet.destinationPort() == 2010 && remoteDataIclcmAddress != null) { System.arraycopy(packet.payload(), 0, bufferIclcm, 0, packet.payload().length); udpPacketIclcm.setLength(packet.payload().length); udpSocket.send(udpPacketIclcm); } logger.debug("Received BTP message of size {} to BTP port {}", packet.payload().length, packet.destinationPort()); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } }; new Thread(senderData).start(); if (localDataCamPort != 0) { new Thread(senderCam).start(); } if (localDataIclcmPort != 0) { new Thread(senderIclcm).start(); } new Thread(receiver).start(); } }
package com.grilledmonkey.grilledui; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.util.Log; import com.grilledmonkey.grilledui.abstracts.GrilledActivity; import com.grilledmonkey.grilledui.adapters.SectionAdapter; import com.grilledmonkey.grilledui.fragments.SectionListFragment; /** * * @author Aux * */ public class SectionActivity extends GrilledActivity { private static final String ARG_SECTION_ID = "sectionId"; private static final String ARG_SECTION_FRAGMENT = "fragment"; private static final int WRONG_SECTION_ID = -1; private boolean hasTwoPanes = false; private FragmentManager fm; private SectionAdapter sectionAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(needsAutoInit()) { initSections(); } } private void initSections() { initSections(R.layout.gui__activity_section_list); } private void initSections(int layout) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if(extras != null) { int sectionId = extras.getInt(ARG_SECTION_ID, WRONG_SECTION_ID); String fragment = extras.getString(ARG_SECTION_FRAGMENT); if(sectionId != WRONG_SECTION_ID && !TextUtils.isEmpty(fragment)) { // TODO Handle phone version here Log.w("SSS", "Section: " + sectionId + " | Fragment: " + fragment); } } fm = getSupportFragmentManager(); sectionAdapter = createSectionAdapter(fm); setContentView(layout); if(findViewById(R.id.section_detail_container) != null) { hasTwoPanes = true; // TODO Anything to do here? ((SectionListFragment)fm.findFragmentById(R.id.section_list)).setActivateOnItemClick(true); } } public void onSectionSelected(int position) { Fragment fragment = sectionAdapter.getItem(position); if(hasTwoPanes) { // TODO R.id.section_detail_container should user changeable fm.beginTransaction().replace(R.id.section_detail_container, fragment).commit(); } else { Intent intent = new Intent(this, this.getClass()); intent.putExtra(ARG_SECTION_ID, position); intent.putExtra(ARG_SECTION_FRAGMENT, fragment.getClass().getName()); startActivity(intent); } } public boolean hasTwoPanes() { return(hasTwoPanes); } @Override public SectionAdapter getSectionAdapter() { return(sectionAdapter); } @Override public SectionAdapter createSectionAdapter(FragmentManager fm) { return(new SectionAdapter(fm)); } }
package com.qiniu.android.netdiag; import android.os.Process; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public final class EnvInfo { public static class CpuInfo{ public final float total; public final float current; public CpuInfo(float total, float current) { this.total = total; this.current = current; } } public static CpuInfo cpuInfo() { BufferedReader reader = null; long work1, total1, work2, total2; try { reader = new BufferedReader(new FileReader("/proc/stat")); String[] sa = reader.readLine().split("[ ]+", 9); work1 = Long.parseLong(sa[1]) + Long.parseLong(sa[2]) + Long.parseLong(sa[3]); total1 = work1 + Long.parseLong(sa[4]) + Long.parseLong(sa[5]) + Long.parseLong(sa[6]) + Long.parseLong(sa[7]); } catch (IOException e) { e.printStackTrace(); return new CpuInfo(0, 0); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } reader = null; long workP1; try { reader = new BufferedReader(new FileReader("/proc/" + Process.myPid() + "/stat")); String[] sa = reader.readLine().split("[ ]+", 18); workP1 = Long.parseLong(sa[13]) + Long.parseLong(sa[14]) + Long.parseLong(sa[15]) + Long.parseLong(sa[16]); reader.close(); } catch (IOException e) { e.printStackTrace(); return new CpuInfo(0, 0); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } reader = null; try { reader = new BufferedReader(new FileReader("/proc/stat")); String[] sa = reader.readLine().split("[ ]+", 9); work2 = Long.parseLong(sa[1]) + Long.parseLong(sa[2]) + Long.parseLong(sa[3]); total2 = work2 + Long.parseLong(sa[4]) + Long.parseLong(sa[5]) + Long.parseLong(sa[6]) + Long.parseLong(sa[7]); } catch (IOException e) { e.printStackTrace(); return new CpuInfo(0, 0); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } reader = null; long workP2; try { reader = new BufferedReader(new FileReader("/proc/" + Process.myPid() + "/stat")); String[] sa = reader.readLine().split("[ ]+", 18); workP2 = Long.parseLong(sa[13]) + Long.parseLong(sa[14]) + Long.parseLong(sa[15]) + Long.parseLong(sa[16]); reader.close(); } catch (IOException e) { e.printStackTrace(); return new CpuInfo(0, 0); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } long t = total2 -total1; float percent = (work2 - work1)*100/(float)t; float currentPercent = (workP2-workP1)*100/(float)t; if (percent < 0 || percent> 100){ return new CpuInfo(0, 0); } return new CpuInfo(percent, currentPercent); } public static class MemInfo{ public final int total; public final int free; public final int cached; public MemInfo(int total, int free, int cached) { this.total = total; this.free = free; this.cached = cached; } public MemInfo(){ this(0,0,0); } } public static MemInfo memInfo(){ BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("/proc/meminfo")); } catch (FileNotFoundException e) { e.printStackTrace(); return new MemInfo(); } int total = 0; int free = 0; int cached = 0; try { String s = reader.readLine(); while (s != null) { if (s.startsWith("MemTotal:")) { total = Integer.parseInt(s.split("[ ]+", 3)[1]); } else if (s.startsWith("MemFree:")) free = Integer.parseInt(s.split("[ ]+", 3)[1]); else if (s.startsWith("Cached:")){ cached = Integer.parseInt(s.split("[ ]+", 3)[1]); } s = reader.readLine(); } }catch (Exception e){ return new MemInfo(); }finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return new MemInfo(total, free, cached); } }
package com.tylersuehr.library; import android.content.Context; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.PorterDuff; import android.support.v4.view.ViewCompat; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.RelativeLayout; import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager; import com.tylersuehr.library.data.Chip; import com.tylersuehr.library.data.ChipDataSource; import com.tylersuehr.library.data.ListChipDataSource; import java.util.List; public class ChipsInput extends MaxHeightScrollView implements FilterableChipsAdapter.OnFilteredChipClickListener { private static final String TAG = "CHIPS_INPUT"; /* Stores and manages all our chips */ private ChipDataSource chipDataSource; /* Stores the mutable properties of our ChipsInput (XML attrs) */ private ChipOptions chipOptions; /* Allows user to type text into the ChipsInput */ private ChipEditText chipsEditText; /* Displays selected chips and chips EditText */ private RecyclerView chipsRecycler; private ChipsAdapter chipsAdapter; /* Displays filtered chips */ private FilterableRecyclerView filterableRecyclerView; private FilterableChipsAdapter filterableChipsAdapter; public ChipsInput(Context context) { this(context, null); } public ChipsInput(Context c, AttributeSet attrs) { super(c, attrs); this.chipOptions = new ChipOptions(c, attrs); this.chipDataSource = new ListChipDataSource(); // Inflate the view inflate(c, R.layout.chips_input_view, this); // Setup the chips recycler view this.chipsAdapter = new ChipsAdapter(this); this.chipsRecycler = findViewById(R.id.chips_recycler); this.chipsRecycler.setLayoutManager(ChipsLayoutManager.newBuilder(c) .setOrientation(ChipsLayoutManager.HORIZONTAL).build()); this.chipsRecycler.setNestedScrollingEnabled(false); this.chipsRecycler.setAdapter(chipsAdapter); } @Override public void onFilteredChipClick(Chip chip) { // Hide the filterable recycler this.filterableRecyclerView.fadeOut(); // Clear the input and refresh the chips recycler this.chipsEditText.setText(""); this.chipsAdapter.notifyDataSetChanged(); // Close the software keyboard hideKeyboard(); } /** * Sets and stores a list of filterable chips on the data source. * @param chips List of {@link Chip} */ public void setFilterableChipList(List<? extends Chip> chips) { this.chipDataSource.setFilterableChips(chips); // Setup the filterable recycler when new filterable data has been set createAndSetupFilterableRecyclerView(); } ChipDataSource getChipDataSource() { return chipDataSource; } ChipOptions getChipOptions() { return chipOptions; } RecyclerView getChipsRecyclerView() { return chipsRecycler; } /** * Lazy loads the input for the user to enter chip titles. * @return {@link EditText} */ ChipEditText getThemedChipsEditText() { if (chipsEditText == null) { this.chipsEditText = new ChipEditText(getContext()); this.chipsEditText.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT )); int padding = Utils.dp(8); this.chipsEditText.setPadding(padding, padding, padding, padding); // Setup the chips options for the input this.chipsEditText.setBackgroundResource(android.R.color.transparent); if (chipOptions.textColorHint != null) { this.chipsEditText.setHintTextColor(chipOptions.textColorHint); } if (chipOptions.textColor != null) { this.chipsEditText.setTextColor(chipOptions.textColor); } this.chipsEditText.setHint(chipOptions.hint); // Prevent fullscreen on landscape this.chipsEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE); this.chipsEditText.setPrivateImeOptions("nm"); // No suggestions this.chipsEditText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER|InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); // Listen to text changes this.chipsEditText.addTextChangedListener(new ChipInputTextChangedHandler()); } return chipsEditText; } /** * Creates a new {@link ChipView} with its theme set from properties defined * in {@link #chipOptions}. * @return {@link ChipView} */ ChipView getThemedChipView() { int padding = Utils.dp(4); ChipView chipView = new ChipView.Builder(getContext()) .titleTextColor(chipOptions.chipLabelColor) .hasAvatarIcon(chipOptions.hasAvatarIcon) .deletable(chipOptions.chipDeletable) .deleteIcon(chipOptions.chipDeleteIcon) .deleteIconColor(chipOptions.chipDeleteIconColor) .backgroundColor(chipOptions.chipBackgroundColor) .build(); chipView.setPadding(padding, padding, padding, padding); return chipView; } /** * Creates a new {@link DetailedChipView} with its theme set from properties * defined in {@link #chipOptions}. * @param chip {@link Chip} * @return {@link DetailedChipView} */ DetailedChipView getThemedDetailedChipView(Chip chip) { return new DetailedChipView.Builder(getContext()) .chip(chip) .textColor(chipOptions.detailedChipTextColor) .backgroundColor(chipOptions.detailedChipBackgroundColor) .deleteIconColor(chipOptions.detailedChipDeleteIconColor) .build(); } /** * Creates a new filterable recycler, sets up its properties from the chip options, * creates a new filterable adapter for the recycler, and adds it as a child view to * the root ViewGroup. */ private void createAndSetupFilterableRecyclerView() { // Create a new filterable recycler view this.filterableRecyclerView = new FilterableRecyclerView(getContext()); // Set the filterable properties from the options this.filterableRecyclerView.setBackgroundColor(Color.WHITE); ViewCompat.setElevation(filterableRecyclerView, 4f); if (chipOptions.filterableListBackgroundColor != null) { this.filterableRecyclerView.getBackground().setColorFilter( chipOptions.filterableListBackgroundColor.getDefaultColor(), PorterDuff.Mode.SRC_ATOP); } // Create and set the filterable chips adapter this.filterableChipsAdapter = new FilterableChipsAdapter(getContext(), this, chipOptions, chipDataSource); this.filterableRecyclerView.setAdapter(this, filterableChipsAdapter); // To show our filterable recycler view, we need to make sure our ChipsInput has already // been displayed on the screen so we can access its root view getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Get the root view of the ChipsInput ViewGroup rootView = (ViewGroup)getRootView(); // Create the layout params for our filterable recycler view RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( Utils.getWindowWidth(getContext()), ViewGroup.LayoutParams.MATCH_PARENT ); lp.addRule(RelativeLayout.ALIGN_PARENT_TOP); lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { lp.bottomMargin = Utils.getNavBarHeight(getContext()); } // Add the filterable recycler to our root with the specified layout params rootView.addView(filterableRecyclerView, lp); // Remove the view tree listener getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } /** * Hides the software keyboard from the chips edit text. */ private void hideKeyboard() { ((InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(chipsEditText.getWindowToken(), 0); } /** * Implementation of {@link TextWatcher} that handles two things for us: * (1) Hides the filterable recycler if the user removes all the text from input. * (2) Tells the filterable recycler to filter the chips when the user enters text. */ private final class ChipInputTextChangedHandler implements TextWatcher { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (filterableRecyclerView != null) { // Hide the filterable recycler if there is no filter. // Filter the recycler if there is a filter if (TextUtils.isEmpty(s)) { filterableRecyclerView.fadeOut(); } else { filterableRecyclerView.filterChips(s); } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) {} } }
package edu.pdx.cs410J.grader; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.jar.Attributes; import java.util.stream.Collectors; public class Submit { private static final PrintWriter out = new PrintWriter(System.out, true); private static final PrintWriter err = new PrintWriter(System.err, true); /** * The grader's email address */ private static final String TA_EMAIL = "sjavata@gmail.com"; /** * A URL containing a list of files that should not be submitted */ private static final String NO_SUBMIT_LIST_URL = "http: private static final String PROJECT_NAMES_LIST_URL = "http: ///////////////////// Instance Fields ////////////////////////// /** * The name of the project being submitted */ private String projName = null; /** * The name of the user (student) submits the project */ private String userName = null; /** * The submitter's email address */ private String userEmail = null; /** * The submitter's user id */ private String userId = null; /** * The name of the SMTP server that is used to send email */ private String serverName = "mailhost.cs.pdx.edu"; /** * A comment describing the project */ private String comment = null; /** * Should the execution of this program be logged? */ private boolean debug = false; /** * Should the generated jar file be saved? */ private boolean saveJar = false; /** * The time at which the project was submitted */ private Date submitTime = null; /** * The names of the files to be submitted */ private Set<String> fileNames = new HashSet<>(); /////////////////////// Constructors ///////////////////////// /** * Creates a new <code>Submit</code> program */ public Submit() { } ///////////////////// Instance Methods /////////////////////// /** * Sets the name of the SMTP server that is used to send emails */ public void setServerName(String serverName) { this.serverName = serverName; } /** * Sets whether or not the progress of the submission should be logged. */ public void setDebug(boolean debug) { this.debug = debug; } /** * Sets whether or not the jar file generated by the submission * should be saved. */ public void setSaveJar(boolean saveJar) { this.saveJar = saveJar; } /** * Sets the comment for this submission */ public void setComment(String comment) { this.comment = comment; } /** * Sets the name of project being submitted */ public void setProjectName(String projName) { this.projName = projName; } /** * Sets the name of the user who is submitting the project */ public void setUserName(String userName) { this.userName = userName; } /** * Sets the id of the user who is submitting the project */ public void setUserId(String userId) { this.userId = userId; } /** * Sets the email address of the user who is submitting the project */ public void setUserEmail(String userEmail) { this.userEmail = userEmail; } /** * Adds the file with the given name to the list of files to be * submitted. */ public void addFile(String fileName) { this.fileNames.add(fileName); } public void validate() { validateProjectName(); if (projName == null) { throw new IllegalStateException("Missing project name"); } if (userName == null) { throw new IllegalStateException("Missing student name"); } if (userId == null) { throw new IllegalStateException("Missing login id"); } if (userEmail == null) { throw new IllegalStateException("Missing email address"); } else { // Make sure user's email is okay try { new InternetAddress(userEmail); } catch (AddressException ex) { String s = "Invalid email address: " + userEmail; IllegalStateException ex2 = new IllegalStateException(s); ex2.initCause(ex); throw ex2; } } } private void validateProjectName() { List<String> validProjectNames = fetchListOfValidProjectNames(); if (!validProjectNames.contains(projName)) { String message = "\"" + projName + "\" is not in the list of valid project names: " + validProjectNames; throw new IllegalStateException(message); } } private List<String> fetchListOfValidProjectNames() { return fetchListOfStringsFromUrl(PROJECT_NAMES_LIST_URL); } public boolean submit(boolean verify) throws IOException, MessagingException { // Recursively search the source directory for .java files Set<File> sourceFiles = searchForSourceFiles(fileNames); db(sourceFiles.size() + " source files found"); if (sourceFiles.size() == 0) { String s = "No source files were found."; throw new IllegalStateException(s); } else if (sourceFiles.size() < 3) { String s = "Too few source files were submitted. 3 or more must be submitted."; throw new IllegalStateException(s); } // Verify submission with user if (verify && !verifySubmission(sourceFiles)) { // User does not want to submit return false; } // Timestamp this.submitTime = new Date(); // Create a temporary jar file to hold the source files File jarFile = makeJarFileWith(sourceFiles); // Send the jar file as an email attachment to the TA mailTA(jarFile, sourceFiles); // Send a receipt to the user mailReceipt(sourceFiles); return true; } /** * Prints debugging output. */ private void db(String s) { if (this.debug) { err.println("++ " + s); } } /** * Searches for the files given on the command line. Ignores files * that do not end in .java, or that appear on the "no submit" list. * Files must reside in a directory named * edu/pdx/cs410J/<studentId>. */ private Set<File> searchForSourceFiles(Set<String> fileNames) { List<String> noSubmit = fetchListOfFilesThatCanNotBeSubmitted(); // Files should be sorted by name SortedSet<File> files = new TreeSet<>((o1, o2) -> o1.toString().compareTo(o2.toString())); for (String fileName : fileNames) { File file = new File(fileName); file = file.getAbsoluteFile(); // Full path // Does the file exist? if (!file.exists()) { err.println("** Not submitting file " + fileName + " because it does not exist"); continue; } // Is the file on the "no submit" list? String name = file.getName(); if (noSubmit.contains(name)) { err.println("** Not submitting file " + fileName + " because it is on the \"no submit\" list"); continue; } // Does the file name end in .java? if (!name.endsWith(".java")) { err.println("** No submitting file " + fileName + " because does end in \".java\""); continue; } // Verify that file is in the correct directory. File parent = file.getParentFile(); if (parent == null || !parent.getName().equals(userId)) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("cs410J")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "cs410J" + File.separator + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("pdx")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "pdx" + File.separator + "cs410J" + File.separator + userId); continue; } parent = parent.getParentFile(); if (parent == null || !parent.getName().equals("edu")) { err.println("** Not submitting file " + fileName + ": it does not reside in a directory named " + "edu" + File.separator + "pdx" + File.separator + "cs410J" + File.separator + userId); continue; } // We like this file files.add(file); } return files; } private List<String> fetchListOfFilesThatCanNotBeSubmitted() { return fetchListOfStringsFromUrl(NO_SUBMIT_LIST_URL); } private List<String> fetchListOfStringsFromUrl(String listUrl) { List<String> noSubmit = new ArrayList<>(); try { URL url = new URL(listUrl); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); while (br.ready()) { noSubmit.add(br.readLine().trim()); } } catch (MalformedURLException ex) { err.println("** WARNING: Cannot access " + listUrl + ": " + ex.getMessage()); } catch (IOException ex) { err.println("** WARNING: Problems while reading " + listUrl + ": " + ex.getMessage()); } return noSubmit; } /** * Prints a summary of what is about to be submitted and prompts the * user to verify that it is correct. * * @return <code>true</code> if the user wants to submit */ private boolean verifySubmission(Set<File> sourceFiles) { // Print out what is going to be submitted out.print("\n" + userName); out.print("'s submission for "); out.println(projName); for (File file : sourceFiles) { out.println(" " + file); } if (comment != null) { out.println("\nComment: " + comment + "\n\n"); } out.println("A receipt will be sent to: " + userEmail + "\n"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); while (true) { out.print("Do you wish to continue with the submission? (yes/no) "); out.flush(); try { String line = in.readLine().trim(); switch (line) { case "yes": return true; case "no": return false; default: err.println("** Please enter yes or no"); break; } } catch (IOException ex) { err.println("** Exception while reading from System.in: " + ex); } } } /** * Returns the name of a <code>File</code> relative to the source * directory. */ private String getRelativeName(File file) { // We already know that the file is in the correct directory return "edu/pdx/cs410J/" + userId + "/" + file.getName(); } /** * Creates a Jar file that contains the source files. The Jar File * is temporary and is deleted when the program exits. */ private File makeJarFileWith(Set<File> sourceFiles) throws IOException { String jarFileName = userName.replace(' ', '_') + "-TEMP"; File jarFile = File.createTempFile(jarFileName, ".jar"); if (!saveJar) { jarFile.deleteOnExit(); } else { out.println("Saving temporary Jar file: " + jarFile); } db("Created Jar file: " + jarFile); Map<File, String> sourceFilesWithNames = sourceFiles.stream().collect(Collectors.toMap(file -> file, this::getRelativeName)); return new JarMaker(sourceFilesWithNames, jarFile, getManifestEntries()).makeJar(); } private Map<Attributes.Name, String> getManifestEntries() { Map<Attributes.Name, String> manifestEntries = new HashMap<>(); manifestEntries.put(ManifestAttributes.USER_NAME, userName); manifestEntries.put(ManifestAttributes.USER_ID, userId); manifestEntries.put(ManifestAttributes.USER_EMAIL, userEmail); manifestEntries.put(ManifestAttributes.PROJECT_NAME, projName); manifestEntries.put(ManifestAttributes.SUBMISSION_COMMENT, comment); manifestEntries.put(ManifestAttributes.SUBMISSION_TIME, ManifestAttributes.formatSubmissionTime(submitTime)); return manifestEntries; } /** * Sends the Jar file to the TA as a MIME attachment. Also includes * a textual summary of the contents of the Jar file. */ private void mailTA(File jarFile, Set<File> sourceFiles) throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(), TA_EMAIL, "CS410J-SUBMIT " + userName + "'s " + projName); MimeBodyPart textPart = createTextPartOfTAEmail(sourceFiles); MimeBodyPart filePart = createJarAttachment(jarFile); Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(filePart); message.setContent(mp); out.println("Submitting project to Grader"); Transport.send(message); } private MimeBodyPart createJarAttachment(File jarFile) throws MessagingException { // Now attach the Jar file DataSource ds = new FileDataSource(jarFile); DataHandler dh = new DataHandler(ds); MimeBodyPart filePart = new MimeBodyPart(); String jarFileTitle = userName.replace(' ', '_') + ".jar"; filePart.setDataHandler(dh); filePart.setFileName(jarFileTitle); filePart.setDescription(userName + "'s " + projName); return filePart; } private MimeBodyPart createTextPartOfTAEmail(Set<File> sourceFiles) throws MessagingException { // Create the text portion of the message StringBuilder text = new StringBuilder(); text.append("Student name: ").append(userName).append(" (").append(userEmail).append(")\n"); text.append("Project name: ").append(projName).append("\n"); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); text.append("Submitted on: ").append(df.format(submitTime)).append("\n"); if (comment != null) { text.append("\nComment: ").append(comment).append("\n\n"); } text.append("Contents:\n"); for (File file : sourceFiles) { text.append(" ").append(getRelativeName(file)).append("\n"); } text.append("\n\n"); MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(text.toString(), "text/plain"); // Try not to display text as separate attachment textPart.setDisposition("inline"); return textPart; } private MimeMessage newEmailTo(Session session, String recipient, String subject) throws MessagingException { // Make a new email message MimeMessage message = new MimeMessage(session); InternetAddress[] to = {new InternetAddress(recipient)}; message.setRecipients(Message.RecipientType.TO, to); message.setSubject(subject); return message; } private Session newEmailSession() { // Obtain a Session for sending email Properties props = new Properties(); props.put("mail.smtp.host", serverName); db("Establishing session on " + serverName); Session session = Session.getDefaultInstance(props, null); session.setDebug(this.debug); return session; } /** * Sends a email to the user as a receipt of the submission. */ private void mailReceipt(Set<File> sourceFiles) throws MessagingException { MimeMessage message = newEmailTo(newEmailSession(), userEmail, "CS410J " + projName + " submission"); // Create the contents of the message DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); StringBuilder text = new StringBuilder(); text.append("On ").append(df.format(submitTime)).append("\n"); text.append(userName).append(" (").append(userEmail).append(")\n"); text.append("submitted the following files for ").append(projName).append(":\n"); for (File file : sourceFiles) { text.append(" ").append(file.getAbsolutePath()).append("\n"); } if (comment != null) { text.append("\nComment: ").append(comment).append("\n\n"); } text.append("\n\n"); text.append("Have a nice day."); // Add the text to the message and send it message.setText(text.toString()); message.setDisposition("inline"); out.println("Sending receipt to you"); Transport.send(message); } ///////////////////////// Main Program /////////////////////////// /** * Prints usage information about this program. */ private static void usage(String s) { err.println("\n** " + s + "\n"); err.println("usage: java Submit [options] args file+"); err.println(" args are (in this order):"); err.println(" project What project is being submitted (Project1, Project2, etc.)"); err.println(" student Who is submitting the project?"); err.println(" loginId UNIX login id"); err.println(" email Student's email address"); err.println(" file Java source file to submit"); err.println(" options are (options may appear in any order):"); err.println(" -savejar Saves temporary Jar file"); err.println(" -smtp serverName Name of SMTP server"); err.println(" -verbose Log debugging output"); err.println(" -comment comment Info for the Grader"); err.println(""); err.println("Submits Java source code to the CS410J grader."); System.exit(1); } /** * Parses the command line, finds the source files, prompts the user * to verify whether or not the settings are correct, and then sends * an email to the Grader. */ public static void main(String[] args) throws IOException, MessagingException { Submit submit = new Submit(); // Parse the command line for (int i = 0; i < args.length; i++) { // Check for options first if (args[i].equals("-smtp")) { if (++i >= args.length) { usage("No SMTP server specified"); } submit.setServerName(args[i]); } else if (args[i].equals("-verbose")) { submit.setDebug(true); } else if (args[i].equals("-savejar")) { submit.setSaveJar(true); } else if (args[i].equals("-comment")) { if (++i >= args.length) { usage("No comment specified"); } submit.setComment(args[i]); } else if (submit.projName == null) { submit.setProjectName(args[i]); } else if (submit.userName == null) { submit.setUserName(args[i]); } else if (submit.userId == null) { submit.setUserId(args[i]); } else if (submit.userEmail == null) { submit.setUserEmail(args[i]); } else { // The name of a source file submit.addFile(args[i]); } } boolean submitted; try { // Make sure that user entered enough information submit.validate(); submit.db("Command line successfully parsed."); submitted = submit.submit(true); } catch (IllegalStateException ex) { usage(ex.getMessage()); return; } // All done. if (submitted) { out.println(submit.projName + " submitted successfully. Thank you."); } else { out.println(submit.projName + " not submitted."); } } static class ManifestAttributes { public static final Attributes.Name USER_NAME = new Attributes.Name("Submitter-User-Name"); public static final Attributes.Name USER_ID = new Attributes.Name("Submitter-User-Id"); public static final Attributes.Name USER_EMAIL = new Attributes.Name("Submitter-Email"); public static final Attributes.Name PROJECT_NAME = new Attributes.Name("Project-Name"); public static final Attributes.Name SUBMISSION_TIME = new Attributes.Name("Submission-Time"); public static final Attributes.Name SUBMISSION_COMMENT = new Attributes.Name("Submission-Comment"); public static String formatSubmissionTime(Date submitTime) { DateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); return format.format(submitTime); } } }
package de.dakror.factory.game.entity.machine; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import de.dakror.factory.game.Game; import de.dakror.factory.game.entity.Entity; import de.dakror.factory.game.entity.item.Item; import de.dakror.factory.game.entity.item.ItemType; import de.dakror.factory.game.entity.item.Items; import de.dakror.factory.game.entity.machine.tube.Tube; import de.dakror.factory.game.world.Block; import de.dakror.factory.game.world.World.Cause; import de.dakror.factory.ui.ItemList; import de.dakror.factory.util.Filter; import de.dakror.factory.util.TubePoint; import de.dakror.gamesetup.ui.ClickEvent; import de.dakror.gamesetup.ui.Container.DefaultContainer; /** * @author Dakror */ public abstract class Machine extends Entity { public static final int REQUEST_SPEED = 40; protected String name; protected ArrayList<TubePoint> points = new ArrayList<>(); protected ArrayList<Filter> inputFilters = new ArrayList<>(); protected ArrayList<Filter> outputFilters = new ArrayList<>(); protected Items items; protected boolean running = true; protected boolean drawFrame = true; protected boolean working = false; protected boolean outputSameMaterial = true; public boolean forceGuiToStay = false; protected int speed, requested, tick, startTick; public DefaultContainer container; public Machine(float x, float y, int width, int height) { super(x * Block.SIZE, y * Block.SIZE, width * Block.SIZE, height * Block.SIZE); items = new Items(); requested = 0; container = new DefaultContainer(); addClickEvent(new ClickEvent() { @Override public void trigger() { if (Game.currentGame.worldActiveMachine == null || !Game.currentGame.worldActiveMachine.forceGuiToStay) Game.currentGame.worldActiveMachine = Machine.this; } }); } @Override public void draw(Graphics2D g) { Color c = g.getColor(); g.setColor(Color.black); if (drawFrame) g.drawRect(x, y, width, height); g.setColor(c); if (this instanceof Tube) drawIcon(g); } public void drawAbove(Graphics2D g) { if (!(this instanceof Tube)) { Color c = g.getColor(); for (TubePoint p : points) { g.setColor(Color.white); g.fillRect(x + p.x * Block.SIZE + 4, y + p.y * Block.SIZE + 4, Block.SIZE - 8, Block.SIZE - 8); g.setColor(p.in ? Color.blue : Color.red); if (p.horizontal) g.fillRect(x + p.x * Block.SIZE + 8, y + p.y * Block.SIZE + (p.up ? 4 : Block.SIZE - 8), Block.SIZE - 16, 4); else g.fillRect(x + p.x * Block.SIZE + (p.up ? 4 : Block.SIZE - 8), y + p.y * Block.SIZE + 8, 4, Block.SIZE - 16); } g.setColor(c); drawIcon(g); } if (state != 0) { Color c = g.getColor(); g.setColor(Color.darkGray); g.drawRect(x, y, width - 1, height - 1); g.setColor(c); } } public void drawGUI(Graphics2D g) { container.draw(g); } public BufferedImage getImage() { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bi.getGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Machine m = (Machine) clone(); m.x = 0; m.y = 0; drawIcon(g); return bi; } protected abstract void drawIcon(Graphics2D g); @Override protected void tick(int tick) { this.tick = tick; if (inputFilters.size() > 0) { if (!working) { if (tick % REQUEST_SPEED == 0 && items.getLength(outputFilters) > 0 && Game.world.isTube(x + points.get(1).x * Block.SIZE, y + points.get(1).y * Block.SIZE + Block.SIZE)) { ItemType it = items.getFilled().get(0); Item item = new Item(x + points.get(1).x * Block.SIZE, y + points.get(1).y * Block.SIZE, it); Game.world.addEntity(item); items.add(it, -1); if (items.getLength() == 0) Game.world.dispatchEntityUpdate(Cause.MACHINE_DONE, this); } if (items.getLength(inputFilters) == inputFilters.size()) { requested = 0; working = true; startTick = tick; } } if (working && (tick - startTick) % speed == 0 && startTick != tick) { for (ItemType t : items.getFilled(inputFilters)) { if (t.hasMaterial() && outputSameMaterial) { for (Filter f : outputFilters) { if (f.c != null) { items.add(ItemType.getItemsByCategories(t.getMaterial(), f.c)[0], 1); } } } items.set(t, 0); } for (Filter f : outputFilters) if (f.c == null) items.add(f.t, 1); working = false; } } } @Override protected void onReachTarget() {} @Override public void mouseReleased(MouseEvent e) { if (contains2(e.getPoint()) && e.getButton() == MouseEvent.BUTTON3 && (Game.currentGame.worldActiveMachine == null || !Game.currentGame.worldActiveMachine.forceGuiToStay)) { for (Entity e1 : Game.world.getEntities()) if (e1 instanceof Item && getArea().intersects(e1.getArea())) return; dead = true; } if (!dead) super.mouseReleased(e); } public ArrayList<TubePoint> getTubePoints() { return points; } public void placeTubePoints() { for (TubePoint tp : points) Game.world.getEntities().add(new Tube(x / Block.SIZE + tp.x, y / Block.SIZE + tp.y)); running = true; } public String getName() { return name; } public Items getItems() { return items; } @Override public void onRemoval() { if (this instanceof Tube) return; for (Entity e : Game.world.getEntities()) { if (e instanceof Tube && getArea().contains(e.getArea())) e.setDead(true); } if (Game.currentGame.getActiveLayer() instanceof ItemList) Game.currentGame.removeLayer(Game.currentGame.getActiveLayer()); } public boolean isRunning() { return running; } public boolean isWorking() { return working; } @Override public void onReachPathNode() {} public boolean matchesFilters(ItemType t) { if (inputFilters.size() == 0) return true; for (Filter f : inputFilters) if (t.matchesFilter(f)) return true; return false; } public boolean matchSameFilters(ItemType t, ItemType t2) { if (inputFilters.size() == 0) return false; for (Filter f : inputFilters) if (t.matchesFilter(f) && t2.matchesFilter(f)) return true; return false; } public boolean wantsItem(ItemType t) { if (working || items.getLength(outputFilters) > 0) return false; if (inputFilters.size() == 0) return true; if (!matchesFilters(t)) return false; int amount = 0; Filter filter = null; for (Filter f : inputFilters) { if (t.matchesFilter(f) && (filter == null || (f.c == filter.c && f.t == filter.t))) { filter = f; amount++; } } return items.get(t) + 1 <= amount; } @Override public void onEntityUpdate(Cause cause, Object source) {} @Override public JSONObject getData() throws Exception { JSONObject o = new JSONObject(); o.put("c", getClass().getName().replace("de.dakror.factory.game.entity.", "")); o.put("x", x); o.put("y", y); o.put("i", items.getData()); o.put("w", working); o.put("r", running); JSONArray is = new JSONArray(); for (Filter f : inputFilters) is.put(f.getData()); o.put("is", is); JSONArray os = new JSONArray(); for (Filter f : outputFilters) is.put(f.getData()); o.put("os", os); o.put("sT", startTick); return o; } @Override public void setData(JSONObject data) {} public boolean hasInputFilters() { return inputFilters.size() > 0; } }
package verification.platu.logicAnalysis; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Stack; import javax.swing.JOptionPane; import lpn.parser.LhpnFile; import lpn.parser.Transition; import main.Gui; import verification.platu.MDD.MDT; import verification.platu.MDD.Mdd; import verification.platu.MDD.mddNode; import verification.platu.common.IndexObjMap; import verification.platu.lpn.LPNTranRelation; import verification.platu.lpn.LpnTranList; import verification.platu.main.Options; import verification.platu.partialOrders.DependentSet; import verification.platu.partialOrders.DependentSetComparator; import verification.platu.partialOrders.LpnTransitionPair; import verification.platu.partialOrders.StaticSets; import verification.platu.project.PrjState; import verification.platu.stategraph.State; import verification.platu.stategraph.StateGraph; import verification.timed_state_exploration.zoneProject.EventSet; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.StateSet; public class Analysis { private LinkedList<Transition> traceCex; protected Mdd mddMgr = null; private HashMap<LpnTransitionPair, HashSet<LpnTransitionPair>> cachedNecessarySets = new HashMap<LpnTransitionPair, HashSet<LpnTransitionPair>>(); private String PORdebugFileName; private FileWriter PORdebugFileStream; private BufferedWriter PORdebugBufferedWriter; public Analysis(StateGraph[] lpnList, State[] initStateArray, LPNTranRelation lpnTranRelation, String method) { traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); if (method.equals("dfs")) { //if (Options.getPOR().equals("off")) { //this.search_dfs(lpnList, initStateArray); //this.search_dfs_mdd_1(lpnList, initStateArray); //this.search_dfs_mdd_2(lpnList, initStateArray); //else // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); } else if (method.equals("bfs")==true) this.search_bfs(lpnList, initStateArray); else if (method == "dfs_noDisabling") //this.search_dfs_noDisabling(lpnList, initStateArray); this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * This constructor performs dfs. * @param lpnList */ public Analysis(StateGraph[] lpnList){ traceCex = new LinkedList<Transition>(); mddMgr = new Mdd(lpnList.length); // if (method.equals("dfs")) { // //if (Options.getPOR().equals("off")) { // this.search_dfs(lpnList, initStateArray, applyPOR); // //this.search_dfs_mdd_1(lpnList, initStateArray); // //this.search_dfs_mdd_2(lpnList, initStateArray); // //else // // this.search_dfs_por(lpnList, initStateArray, lpnTranRelation, "state"); // else if (method.equals("bfs")==true) // this.search_bfs(lpnList, initStateArray); // else if (method == "dfs_noDisabling") // //this.search_dfs_noDisabling(lpnList, initStateArray); // this.search_dfs_noDisabling_fireOrder(lpnList, initStateArray); } /** * Recursively find all reachable project states. */ int iterations = 0; int stack_depth = 0; int max_stack_depth = 0; public void search_recursive(final StateGraph[] lpnList, final State[] curPrjState, final ArrayList<LinkedList<Transition>> enabledList, HashSet<PrjState> stateTrace) { int lpnCnt = lpnList.length; HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); stack_depth++; if (stack_depth > max_stack_depth) max_stack_depth = stack_depth; iterations++; if (iterations % 50000 == 0) System.out.println("iterations: " + iterations + ", # of prjStates found: " + prjStateSet.size() + ", max_stack_depth: " + max_stack_depth); for (int index = 0; index < lpnCnt; index++) { LinkedList<Transition> curEnabledSet = enabledList.get(index); if (curEnabledSet == null) continue; for (Transition firedTran : curEnabledSet) { // while(curEnabledSet.size() != 0) { // LPNTran firedTran = curEnabledSet.removeFirst(); // TODO: (check) Not sure if lpnList[index] is correct State[] nextStateArray = lpnList[index].fire(lpnList, curPrjState, firedTran, null, null); // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. PrjState nextPrjState = new PrjState(nextStateArray); if (stateTrace.contains(nextPrjState) == true) ;// System.out.println("found a cycle"); if (prjStateSet.add(nextPrjState) == false) { continue; } // Get the list of enabled transition sets, and call // findsg_recursive. ArrayList<LinkedList<Transition>> nextEnabledList = new ArrayList<LinkedList<Transition>>(); for (int i = 0; i < lpnCnt; i++) { if (curPrjState[i] != nextStateArray[i]) { StateGraph Lpn_tmp = lpnList[i]; nextEnabledList.add(i, Lpn_tmp.getEnabled(nextStateArray[i]));// firedTran, // enabledList.get(i), // false)); } else { nextEnabledList.add(i, enabledList.get(i)); } } stateTrace.add(nextPrjState); search_recursive(lpnList, nextStateArray, nextEnabledList, stateTrace); stateTrace.remove(nextPrjState); } } } /** * An iterative implement of findsg_recursive(). * * @param sgList * @param start * @param curLocalStateArray * @param enabledArray */ public StateGraph[] search_dfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function search_dfs"); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; //Stack<State[]> stateStack = new Stack<State[]>(); HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); //HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // Set of PrjStates that have been seen before. Set class documentation // for how it behaves. Timing Change. StateSet prjStateSet = new StateSet(); PrjState initPrjState; // Create the appropriate type for the PrjState depending on whether timing is // being used or not. Timing Change. if(!Options.getTimingAnalysisFlag()){ // If not doing timing. initPrjState = new PrjState(initStateArray); } else{ // If timing is enabled. initPrjState = new TimedPrjState(initStateArray); // Set the initial values of the inequality variables. //((TimedPrjState) initPrjState).updateInequalityVariables(); } prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) { System.out.println("%%%%%%% stateStackTop %%%%%%%%"); printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) printDstLpnList(sgList); boolean init = true; LpnTranList initEnabled; if(!Options.getTimingAnalysisFlag()){ // Timing Change. initEnabled = sgList[0].getEnabled(initStateArray[0], init); } else { // When timing is enabled, it is the project state that will determine // what is enabled since it contains the zone. This indicates the zeroth zone // contained in the project and the zeroth LPN to get the transitions from. initEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, 0); } lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); init = false; if (Options.getDebugMode()) { System.out.println("call getEnabled on initStateArray at 0: "); System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransitionSet(initEnabled, ""); } boolean memExceedsLimit = false; main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) { if (curUsedMem > Options.getMemUpperBound()) { System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******"); System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******"); memExceedsLimit = true; } } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); if (failureTranIsEnabled(curEnabled)) { return null; } if (Options.getDebugMode()) { System.out.println(" printStateArray(curStateArray); System.out.println("+++++++ curEnabled trans ++++++++"); printTransLinkedList(curEnabled); } // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); if (Options.getDebugMode()) { System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); System.out.println(" printLpnTranStack(lpnTranStack); } curIndexStack.pop(); curIndex++; while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); if(!Options.getTimingAnalysisFlag()){ // Timing Change curEnabled = (sgList[curIndex].getEnabled(curStateArray[curIndex], init)).clone(); } else{ // Get the enabled transitions from the zone that are associated with // the current LPN. curEnabled = ((TimedPrjState) stateStackTop).getPossibleEvents(0, curIndex); } if (curEnabled.size() > 0) { if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransLinkedList(curEnabled); } lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); if (Options.getDebugMode()) printIntegerStack("curIndexStack after push 1", curIndexStack); break; } curIndex++; } } if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); printStateArray(stateStackTop.toStateArray()); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curEnabled.removeLast(); if (Options.getDebugMode()) { System.out.println(" System.out.println("Fired transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); System.out.println(" } State[] nextStateArray; PrjState nextPrjState; // Moved this definition up. Timing Change. // The next state depends on whether timing is in use or not. // Timing Change. if(!Options.getTimingAnalysisFlag()){ // Get the next states from the fire method and define the next project state. nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran, null, null); nextPrjState = new PrjState(nextStateArray); } else{ // Get the next timed state and extract the next un-timed states. nextPrjState = sgList[curIndex].fire(sgList, stateStackTop, (EventSet) firedTran); nextStateArray = nextPrjState.toStateArray(); } tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[numLpns]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[numLpns]; for (int i = 0; i < numLpns; i++) { StateGraph sg = sgList[i]; LinkedList<Transition> enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sg.getEnabled(curStateArray[i], init); } else{ // Get the enabled transitions from the Zone for the appropriate // LPN. //enabledList = ((TimedPrjState) stateStackTop).getEnabled(i); enabledList = ((TimedPrjState) stateStackTop).getPossibleEvents(0, i); } curEnabledArray[i] = enabledList; if(!Options.getTimingAnalysisFlag()){ // Timing Change. enabledList = sg.getEnabled(nextStateArray[i], init); } else{ //enabledList = ((TimedPrjState) nextPrjState).getEnabled(i); enabledList = ((TimedPrjState) nextPrjState).getPossibleEvents(0, i); } nextEnabledArray[i] = enabledList; if (Options.getReportDisablingError()) { Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } if (Analysis.deadLock(sgList, nextStateArray) == true) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } //PrjState nextPrjState = new PrjState(nextStateArray); // Moved earlier. Timing Change. Boolean existingState = prjStateSet.contains(nextPrjState); //|| stateStack.contains(nextPrjState); if (existingState == false) { prjStateSet.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray()); System.out.println("firedTran = " + firedTran.getName()); System.out.println("***nextStateMap for stateStackTop before firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState.equals(stateStackTop)) { prjState.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } } stateStackTop = nextPrjState; if (Options.getDebugMode()) { System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%"); printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); printTransitionSet((LpnTranList) nextEnabledArray[0], ""); } lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); if (Options.getDebugMode()) { System.out.println("******** lpnTranStack ***********"); printLpnTranStack(lpnTranStack); } curIndexStack.push(0); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); } for (PrjState prjState : prjStateSet) { if (prjState.equals(nextPrjState)) { nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone()); } } if (Options.getDebugMode()) { System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray()); System.out.println("firedTran = " + firedTran.getName()); System.out.println("nextStateMap for stateStackTop before firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } } } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt //+ ", # of prjStates found: " + totalStateCnt + ", " + prjStateSet.stateString() + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(false, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) drawGlobalStateGraph(sgList, prjStateSet.toHashSet(), true); return sgList; } private boolean failureTranIsEnabled(LinkedList<Transition> curEnabled) { boolean failureTranIsEnabled = false; for (Transition tran : curEnabled) { if (tran.isFail()) { JOptionPane.showMessageDialog(Gui.frame, "Failure transition " + tran.getName() + "is enabled.", "Error", JOptionPane.ERROR_MESSAGE); failureTranIsEnabled = true; break; } } return failureTranIsEnabled; } private void drawGlobalStateGraph(StateGraph[] sgList, HashSet<PrjState> prjStateSet, boolean fullSG) { try { String fileName = null; if (fullSG) { fileName = Options.getPrjSgPath() + "full_sg.dot"; } else { fileName = Options.getPrjSgPath() + Options.getPOR().toLowerCase() + "_" + Options.getCycleClosingMthd().toLowerCase() + "_" + Options.getCycleClosingAmpleMethd().toLowerCase() + "_sg.dot"; } BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (PrjState curGlobalState : prjStateSet) { // Build composite current global state. String curVarNames = ""; String curVarValues = ""; String curMarkings = ""; String curEnabledTrans = ""; String curGlobalStateIndex = ""; HashMap<String, Integer> vars = new HashMap<String, Integer>(); for (State curLocalState : curGlobalState.toStateArray()) { LhpnFile curLpn = curLocalState.getLpn(); for(int i = 0; i < curLpn.getVarIndexMap().size(); i++) { //System.out.println(curLpn.getVarIndexMap().getKey(i) + " = " + curLocalState.getVector()[i]); vars.put(curLpn.getVarIndexMap().getKey(i), curLocalState.getVector()[i]); } curMarkings = curMarkings + "," + intArrayToString("markings", curLocalState); if (!boolArrayToString("enabled trans", curLocalState).equals("")) curEnabledTrans = curEnabledTrans + "," + boolArrayToString("enabled trans", curLocalState); curGlobalStateIndex = curGlobalStateIndex + "_" + "S" + curLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); curVarValues = curVarValues + vValue + ", "; curVarNames = curVarNames + vName + ", "; } curVarNames = curVarNames.substring(0, curVarNames.lastIndexOf(",")); curVarValues = curVarValues.substring(0, curVarValues.lastIndexOf(",")); curMarkings = curMarkings.substring(curMarkings.indexOf(",")+1, curMarkings.length()); curEnabledTrans = curEnabledTrans.substring(curEnabledTrans.indexOf(",")+1, curEnabledTrans.length()); curGlobalStateIndex = curGlobalStateIndex.substring(curGlobalStateIndex.indexOf("_")+1, curGlobalStateIndex.length()); out.write("Inits[shape=plaintext, label=\"<" + curVarNames + ">\"]\n"); out.write(curGlobalStateIndex + "[shape=\"ellipse\",label=\"" + curGlobalStateIndex + "\\n<"+curVarValues+">" + "\\n<"+curEnabledTrans+">" + "\\n<"+curMarkings+">" + "\"]\n"); // // Build composite next global states. HashMap<Transition, PrjState> nextStateMap = curGlobalState.getNextStateMap(); for (Transition outTran : nextStateMap.keySet()) { PrjState nextGlobalState = nextStateMap.get(outTran); String nextVarNames = ""; String nextVarValues = ""; String nextMarkings = ""; String nextEnabledTrans = ""; String nextGlobalStateIndex = ""; for (State nextLocalState : nextGlobalState.toStateArray()) { LhpnFile nextLpn = nextLocalState.getLpn(); for(int i = 0; i < nextLpn.getVarIndexMap().size(); i++) { vars.put(nextLpn.getVarIndexMap().getKey(i), nextLocalState.getVector()[i]); } nextMarkings = nextMarkings + "," + intArrayToString("markings", nextLocalState); if (!boolArrayToString("enabled trans", nextLocalState).equals("")) nextEnabledTrans = nextEnabledTrans + "," + boolArrayToString("enabled trans", nextLocalState); nextGlobalStateIndex = nextGlobalStateIndex + "_" + "S" + nextLocalState.getIndex(); } for (String vName : vars.keySet()) { Integer vValue = vars.get(vName); nextVarValues = nextVarValues + vValue + ", "; nextVarNames = nextVarNames + vName + ", "; } nextVarNames = nextVarNames.substring(0, nextVarNames.lastIndexOf(",")); nextVarValues = nextVarValues.substring(0, nextVarValues.lastIndexOf(",")); nextMarkings = nextMarkings.substring(nextMarkings.indexOf(",")+1, nextMarkings.length()); nextEnabledTrans = nextEnabledTrans.substring(nextEnabledTrans.indexOf(",")+1, nextEnabledTrans.length()); nextGlobalStateIndex = nextGlobalStateIndex.substring(nextGlobalStateIndex.indexOf("_")+1, nextGlobalStateIndex.length()); out.write("Inits[shape=plaintext, label=\"<" + nextVarNames + ">\"]\n"); out.write(nextGlobalStateIndex + "[shape=\"ellipse\",label=\"" + nextGlobalStateIndex + "\\n<"+nextVarValues+">" + "\\n<"+nextEnabledTrans+">" + "\\n<"+nextMarkings+">" + "\"]\n"); String outTranName = outTran.getName(); if (outTran.isFail() && !outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=red]\n"); else if (!outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=blue]\n"); else if (outTran.isFail() && outTran.isPersistent()) out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\", fontcolor=purple]\n"); else out.write(curGlobalStateIndex + "->" + nextGlobalStateIndex + "[label=\"" + outTranName + "\"]\n"); } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } /* private void drawDependencyGraphsForNecessarySets(LhpnFile[] lpnList, HashMap<LpnTransitionPair, StaticSets> staticSetsMap) { String fileName = Options.getPrjSgPath() + "_necessarySet.dot"; BufferedWriter out; try { out = new BufferedWriter(new FileWriter(fileName)); out.write("digraph G {\n"); for (LpnTransitionPair seedTran : staticSetsMap.keySet()) { for (LpnTransitionPair canEnableTran : staticSetsMap.get(seedTran).getEnableSet()) { } } out.write("}"); out.close(); } catch (IOException e) { e.printStackTrace(); } } */ private String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVector().length; i++) { arrayStr = arrayStr + curState.getVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabled trans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ","; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private void printStateArray(State[] stateArray) { for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + "(" + stateArray[i].getLpn().getLabel() +") -> "); System.out.print("markings: " + intArrayToString("markings", stateArray[i]) + " / "); System.out.print("enabled trans: " + boolArrayToString("enabled trans", stateArray[i]) + " / "); System.out.print("var values: " + intArrayToString("vars", stateArray[i]) + " / "); System.out.print("\n"); } } private void printTransLinkedList(LinkedList<Transition> curPop) { for (int i=0; i< curPop.size(); i++) { System.out.print(curPop.get(i).getName() + " "); } System.out.println(""); } private void printIntegerStack(String stackName, Stack<Integer> curIndexStack) { System.out.println("+++++++++" + stackName + "+++++++++"); for (int i=0; i < curIndexStack.size(); i++) { System.out.println(stackName + "[" + i + "]" + curIndexStack.get(i)); } System.out.println(" } private void printDstLpnList(StateGraph[] lpnList) { System.out.println("++++++ dstLpnList ++++++"); for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); System.out.println("LPN: " + curLPN.getLabel()); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j< allTrans.length; j++) { System.out.print(allTrans[j].getName() + ": "); for (int k=0; k< allTrans[j].getDstLpnList().size(); k++) { System.out.print(allTrans[j].getDstLpnList().get(k).getLabel() + ","); } System.out.print("\n"); } System.out.println(" } System.out.println("++++++++++++++++++++"); } private void constructDstLpnList(StateGraph[] lpnList) { for (int i=0; i<lpnList.length; i++) { LhpnFile curLPN = lpnList[i].getLpn(); Transition[] allTrans = curLPN.getAllTransitions(); for (int j=0; j<allTrans.length; j++) { Transition curTran = allTrans[j]; for (int k=0; k<lpnList.length; k++) { curTran.setDstLpnList(lpnList[k].getLpn()); } } } } /** * This method performs first-depth search on an array of LPNs and applies partial order reduction technique with the traceback. * @param sgList * @param initStateArray * @param cycleClosingMthdIndex * @return */ @SuppressWarnings("unchecked") public StateGraph[] search_dfsPOR(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> calling function search_dfsPOR"); System.out.println("---> " + Options.getPOR()); System.out.println("---> " + Options.getCycleClosingMthd()); System.out.println("---> " + Options.getCycleClosingAmpleMethd()); double peakUsedMem = 0; double peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int numLpns = sgList.length; LhpnFile[] lpnList = new LhpnFile[numLpns]; for (int i=0; i<numLpns; i++) { lpnList[i] = sgList[i].getLpn(); } HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); prjStateSet.add(initPrjState); PrjState stateStackTop = initPrjState; if (Options.getDebugMode()) { System.out.println("%%%%%%% stateStackTop %%%%%%%%"); printStateArray(stateStackTop.toStateArray()); } stateStack.add(stateStackTop); constructDstLpnList(sgList); if (Options.getDebugMode()) { printDstLpnList(sgList); createPORDebugFile(); } // Find static pieces for POR. HashMap<Integer, Transition[]> allTransitions = new HashMap<Integer, Transition[]>(lpnList.length); HashMap<LpnTransitionPair, StaticSets> staticSetsMap = new HashMap<LpnTransitionPair, StaticSets>(); for (int i=0; i<lpnList.length; i++) allTransitions.put(i, lpnList[i].getAllTransitions()); HashMap<LpnTransitionPair, Integer> tranFiringFreq = new HashMap<LpnTransitionPair, Integer>(allTransitions.keySet().size()); for (int lpnIndex=0; lpnIndex<lpnList.length; lpnIndex++) { if (Options.getDebugMode()) System.out.println("LPN = " + lpnList[lpnIndex].getLabel()); for (Transition curTran: allTransitions.get(lpnIndex)) { StaticSets curStatic = new StaticSets(curTran, allTransitions); curStatic.buildCurTranDisableOtherTransSet(lpnIndex); if (Options.getPORdeadlockPreserve()) curStatic.buildOtherTransDisableCurTranSet(lpnIndex); curStatic.buildModifyAssignSet(); curStatic.buildEnableBySettingEnablingTrue(); // if (Options.getDebugMode()) // curStatic.buildEnableByBringingToken(); LpnTransitionPair lpnTranPair = new LpnTransitionPair(lpnIndex,curTran.getIndex()); staticSetsMap.put(lpnTranPair, curStatic); //if (!Options.getNecessaryUsingDependencyGraphs()) tranFiringFreq.put(lpnTranPair, 0); } } if (Options.getDebugMode()) { printStaticSetsMap(lpnList, staticSetsMap); writeStaticSetsMapToPORDebugFile(lpnList, staticSetsMap); // if (Options.getNecessaryUsingDependencyGraphs()) // drawDependencyGraphsForNecessarySets(lpnList, staticSetsMap); } boolean init = true; LpnTranList initAmpleTrans = new LpnTranList(); if (Options.getDebugMode()) System.out.println("call getAmple on curStateArray at 0: "); // if (Options.getNecessaryUsingDependencyGraphs()) // tranFiringFreq = null; initAmpleTrans = getAmple(initStateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop); lpnTranStack.push(initAmpleTrans); init = false; if (Options.getDebugMode()) { System.out.println("+++++++ Push trans onto lpnTranStack @ 1++++++++"); printTransitionSet(initAmpleTrans, ""); } HashSet<LpnTransitionPair> initAmple = new HashSet<LpnTransitionPair>(); for (Transition t: initAmpleTrans) { initAmple.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex())); } updateLocalAmpleTbl(initAmple, sgList, initStateArray); boolean memExceedsLimit = false; main_while_loop: while (failure == false && stateStack.size() != 0) { if (Options.getDebugMode()) { System.out.println("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); writeStringWithNewLineToPORDebugFile("~~~~~~~~~~~ loop begins ~~~~~~~~~~~"); } long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack_depth: " + stateStack.size() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } if (!memExceedsLimit && Options.getMemUpperBoundFlag() && iterations % 100 == 0) { if (curUsedMem > Options.getMemUpperBound()) { System.out.println("******* Used memory exceeds memory upper bound (" + (float)Options.getMemUpperBound()/1000000 + "MB) *******"); System.out.println("******* Used memory = " + (float)curUsedMem/1000000 + "MB *******"); memExceedsLimit = true; } } State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); if (failureTranIsEnabled(curAmpleTrans)) { return null; } if (curAmpleTrans.size() == 0) { lpnTranStack.pop(); prjStateSet.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); System.out.println(" printLpnTranStack(lpnTranStack); // System.out.println(" // printStateStack(stateStack); System.out.println(" printPrjStateSet(prjStateSet); System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); } stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); continue; } Transition firedTran = curAmpleTrans.removeLast(); if (Options.getDebugMode()) { System.out.println(" System.out.println("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); System.out.println(" writeStringWithNewLineToPORDebugFile(" writeStringWithNewLineToPORDebugFile("Fired Transition: " + firedTran.getLpn().getLabel() + "(" + firedTran.getName() + ")"); writeStringWithNewLineToPORDebugFile(" } LpnTransitionPair firedLpnTranPair = new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex()); // if (!Options.getNecessaryUsingDependencyGraphs()) { Integer freq = tranFiringFreq.get(firedLpnTranPair) + 1; tranFiringFreq.put(firedLpnTranPair, freq); if (Options.getDebugMode()) { System.out.println("~~~~~~tranFiringFreq~~~~~~~"); printHashMap(tranFiringFreq, sgList); } State[] nextStateArray = sgList[firedLpnTranPair.getLpnIndex()].fire(sgList, curStateArray, firedTran, null, null); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. if (Options.getReportDisablingError()) { for (int i=0; i<numLpns; i++) { Transition disabledTran = firedTran.disablingError(curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } } LpnTranList nextAmpleTrans = new LpnTranList(); // if (Options.getNecessaryUsingDependencyGraphs()) // nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, null, sgList, prjStateSet, stateStackTop); // else nextAmpleTrans = getAmple(curStateArray, nextStateArray, staticSetsMap, init, tranFiringFreq, sgList, prjStateSet, stateStackTop); // check for possible deadlock if (nextAmpleTrans.size() == 0) { System.out.println("*** Verification failed: deadlock."); failure = true; break main_while_loop; } HashSet<LpnTransitionPair> nextAmple = getLpnTransitionPair(nextAmpleTrans); PrjState nextPrjState = new PrjState(nextStateArray); Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); if (existingState == false) { if (Options.getDebugMode()) System.out.println("%%%%%%% existingSate == false %%%%%%%%"); if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray()); System.out.println("firedTran = " + firedTran.getName()); System.out.println("***nextStateMap for stateStackTop before firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState.equals(stateStackTop)) { prjState.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } } updateLocalAmpleTbl(nextAmple, sgList, nextStateArray); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("%%%%%%% Add global state to stateStack %%%%%%%%"); printStateArray(stateStackTop.toStateArray()); System.out.println("+++++++ Push trans onto lpnTranStack @ 2++++++++"); printTransitionSet((LpnTranList) nextAmpleTrans, ""); } lpnTranStack.push((LpnTranList) nextAmpleTrans.clone()); totalStates++; } else { if (Options.getOutputSgFlag()) { if (Options.getDebugMode()) { System.out.println("******* curStateArray *******"); printStateArray(curStateArray); System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); } for (PrjState prjState : prjStateSet) { if (prjState.equals(nextPrjState)) { nextPrjState.setNextStateMap((HashMap<Transition, PrjState>) prjState.getNextStateMap().clone()); } } if (Options.getDebugMode()) { System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray()); System.out.println("firedTran = " + firedTran.getName()); System.out.println("nextStateMap for stateStackTop before firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } stateStackTop.setTranOut(firedTran, nextPrjState); if (Options.getDebugMode()) { System.out.println("***nextStateMap for stateStackTop after firedTran being added: "); printNextStateMap(stateStackTop.getNextStateMap()); } for (PrjState prjState : prjStateSet) { if (prjState == stateStackTop) { prjState.setNextStateMap((HashMap<Transition, PrjState>) stateStackTop.getNextStateMap().clone()); if (Options.getDebugMode()) { System.out.println("***nextStateMap for prjState: "); printNextStateMap(prjState.getNextStateMap()); } } } } if (!Options.getCycleClosingMthd().toLowerCase().equals("no_cycleclosing")) { // Cycle closing check if (prjStateSet.contains(nextPrjState) && stateStack.contains(nextPrjState)) { if (Options.getDebugMode()) System.out.println("%%%%%%% Cycle Closing %%%%%%%%"); HashSet<LpnTransitionPair> nextAmpleSet = new HashSet<LpnTransitionPair>(); HashSet<LpnTransitionPair> curAmpleSet = new HashSet<LpnTransitionPair>(); for (Transition t : nextAmpleTrans) { nextAmpleSet.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex())); } for (Transition t: curAmpleTrans) { curAmpleSet.add(new LpnTransitionPair(t.getLpn().getLpnIndex(), t.getIndex())); } curAmpleSet.add(new LpnTransitionPair(firedTran.getLpn().getLpnIndex(), firedTran.getIndex())); HashSet<LpnTransitionPair> newNextAmple = new HashSet<LpnTransitionPair>(); // if (Options.getNecessaryUsingDependencyGraphs()) // newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap, // null, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack); // else newNextAmple = computeCycleClosingTrans(curStateArray, nextStateArray, staticSetsMap, tranFiringFreq, sgList, prjStateSet, nextPrjState, nextAmpleSet, curAmpleSet, stateStack); if (newNextAmple != null && !newNextAmple.isEmpty()) { LpnTranList newNextAmpleTrans = getLpnTranList(newNextAmple, sgList); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); if (Options.getDebugMode()) { System.out.println("nextPrjState: "); printStateArray(nextPrjState.toStateArray()); System.out.println("nextStateMap for nextPrjState: "); printNextStateMap(nextPrjState.getNextStateMap()); } stateStackTop = nextPrjState; stateStack.add(stateStackTop); if (Options.getDebugMode()) { System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); printStateArray(stateStackTop.toStateArray()); System.out.println("stateStackTop: "); printStateArray(stateStackTop.toStateArray()); System.out.println("nextStateMap for stateStackTop: "); printNextStateMap(nextPrjState.getNextStateMap()); } lpnTranStack.push(newNextAmpleTrans.clone()); if (Options.getDebugMode()) { System.out.println("+++++++ Push these trans onto lpnTranStack @ Cycle Closing ++++++++"); printTransitionSet((LpnTranList) newNextAmpleTrans, ""); System.out.println("******* lpnTranStack ***************"); printLpnTranStack(lpnTranStack); } } } } updateLocalAmpleTbl(nextAmple, sgList, nextStateArray); } } if (Options.getDebugMode()) { try { PORdebugBufferedWriter.close(); PORdebugFileStream.close(); } catch (IOException e) { e.printStackTrace(); } } double totalStateCnt = prjStateSet.size(); System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStateCnt + ", max_stack_depth: " + max_stack_depth + ", peak total memory: " + peakTotalMem / 1000000 + " MB" + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); if (Options.getOutputLogFlag()) writePerformanceResultsToLogFile(true, tranFiringCnt, totalStateCnt, peakTotalMem / 1000000, peakUsedMem / 1000000); if (Options.getOutputSgFlag()) { drawGlobalStateGraph(sgList, prjStateSet, false); } return sgList; } private void createPORDebugFile() { try { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; PORdebugFileStream = new FileWriter(PORdebugFileName); PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing the debugging file for partial order reduction."); } } private void writeStringWithNewLineToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writeStringToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); //PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writePerformanceResultsToLogFile(boolean isPOR, int tranFiringCnt, double totalStateCnt, double peakTotalMem, double peakUsedMem) { try { String fileName = null; if (isPOR) { if (Options.getNecessaryUsingDependencyGraphs()) fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; else fileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".log"; } else fileName = Options.getPrjSgPath() + Options.getLogName() + "_full" + ".log"; BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); out.write("tranFiringCnt" + "\t" + "prjStateCnt" + "\t" + "maxStackDepth" + "\t" + "peakTotalMem(MB)" + "\t" + "peakUsedMem(MB)\n"); out.write(tranFiringCnt + "\t" + totalStateCnt + "\t" + max_stack_depth + "\t" + peakTotalMem + "\t" + peakUsedMem + "\n"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private void printLpnTranStack(Stack<LinkedList<Transition>> lpnTranStack) { for (int i=0; i<lpnTranStack.size(); i++) { LinkedList<Transition> tranList = lpnTranStack.get(i); for (int j=0; j<tranList.size(); j++) { System.out.println(tranList.get(j).getName()); } System.out.println(" } } private void printNextStateMap(HashMap<Transition, PrjState> nextStateMap) { for (Transition t: nextStateMap.keySet()) { System.out.print(t.getName() + " -> "); State[] stateArray = nextStateMap.get(t).getStateArray(); for (int i=0; i<stateArray.length; i++) { System.out.print("S" + stateArray[i].getIndex() + ", "); } System.out.print("\n"); } } private HashSet<LpnTransitionPair> getLpnTransitionPair(LpnTranList ampleTrans) { HashSet<LpnTransitionPair> ample = new HashSet<LpnTransitionPair>(); for (Transition tran : ampleTrans) { ample.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex())); } return ample; } private LpnTranList getLpnTranList(HashSet<LpnTransitionPair> newNextAmple, StateGraph[] sgList) { LpnTranList newNextAmpleTrans = new LpnTranList(); for (LpnTransitionPair lpnTran : newNextAmple) { Transition tran = sgList[lpnTran.getLpnIndex()].getLpn().getTransition(lpnTran.getTranIndex()); newNextAmpleTrans.add(tran); } return newNextAmpleTrans; } private HashSet<LpnTransitionPair> computeCycleClosingTrans(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair, StaticSets> staticSetsMap, HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> prjStateSet, PrjState nextPrjState, HashSet<LpnTransitionPair> nextAmple, HashSet<LpnTransitionPair> curAmple, HashSet<PrjState> stateStack) { for (State s : nextStateArray) if (s == null) throw new NullPointerException(); String cycleClosingMthd = Options.getCycleClosingMthd(); HashSet<LpnTransitionPair> newNextAmple = new HashSet<LpnTransitionPair>(); HashSet<LpnTransitionPair> nextEnabled = new HashSet<LpnTransitionPair>(); HashSet<LpnTransitionPair> curEnabled = new HashSet<LpnTransitionPair>(); LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) lpnList[i] = sgList[i].getLpn(); for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { Transition tran = curLpn.getAllTransitions()[i]; if (nextStateArray[lpnIndex].getTranVector()[i]) nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), tran.getIndex())); if (curStateArray[lpnIndex].getTranVector()[i]) curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), tran.getIndex())); } } // Cycle closing on global state graph if (Options.getDebugMode()) System.out.println("~~~~~~~ existing global state ~~~~~~~~"); if (cycleClosingMthd.equals("strong")) { newNextAmple.addAll(getIntSetSubstraction(curEnabled, nextAmple)); updateLocalAmpleTbl(newNextAmple, sgList, nextStateArray); } else if (cycleClosingMthd.equals("behavioral")) { if (Options.getDebugMode()) System.out.println("****** behavioral: cycle closing check ********"); HashSet<LpnTransitionPair> curReduced = getIntSetSubstraction(curEnabled, curAmple); HashSet<LpnTransitionPair> oldNextAmple = new HashSet<LpnTransitionPair>(); DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // TODO: Is oldNextAmple correctly obtained below? if (Options.getDebugMode()) { System.out.println("******* nextStateArray *******"); printStateArray(nextStateArray); } for (int lpnIndex=0; lpnIndex < sgList.length; lpnIndex++) { if (sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]) != null) { LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextStateArray[lpnIndex]); if (Options.getDebugMode()) printTransitionSet(oldLocalNextAmpleTrans, "oldLocalNextAmpleTrans"); for (Transition oldLocalTran : oldLocalNextAmpleTrans) oldNextAmple.add(new LpnTransitionPair(lpnIndex, oldLocalTran.getIndex())); } } HashSet<LpnTransitionPair> ignored = getIntSetSubstraction(curReduced, oldNextAmple); boolean isCycleClosingAmpleComputation = true; for (LpnTransitionPair seed : ignored) { HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList, isCycleClosingAmpleComputation); if (Options.getDebugMode()) { printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); } // TODO: Is this still necessary? // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if ((newNextAmple.size() == 0 || dependent.size() < newNextAmple.size()) && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); DependentSet dependentSet = new DependentSet(dependent, seed, isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); dependentSetQueue.add(dependentSet); } cachedNecessarySets.clear(); if (!dependentSetQueue.isEmpty()) { // System.out.println("depdentSetQueue is NOT empty."); // newNextAmple = dependentSetQueue.poll().getDependent(); // TODO: Will newNextAmpleTmp - oldNextAmple be safe? HashSet<LpnTransitionPair> newNextAmpleTmp = dependentSetQueue.poll().getDependent(); newNextAmple = getIntSetSubstraction(newNextAmpleTmp, oldNextAmple); updateLocalAmpleTbl(newNextAmple, sgList, nextStateArray); } if (Options.getDebugMode()) { printIntegerSet(newNextAmple, sgList, "newNextAmple"); System.out.println("******** behavioral: end of cycle closing check *****"); } } else if (cycleClosingMthd.equals("state_search")) { // TODO: complete cycle closing check for state search. } return newNextAmple; } private void updateLocalAmpleTbl(HashSet<LpnTransitionPair> newNextAmple, StateGraph[] sgList, State[] nextStateArray) { // Ample set at each state is stored in the enabledSetTbl in each state graph. for (LpnTransitionPair lpnTran : newNextAmple) { State nextState = nextStateArray[lpnTran.getLpnIndex()]; Transition tran = sgList[lpnTran.getLpnIndex()].getLpn().getTransition(lpnTran.getTranIndex()); if (sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState) != null) { if (!sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState).contains(tran)) sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().get(nextState).add(tran); } else { LpnTranList newLpnTranList = new LpnTranList(); newLpnTranList.add(tran); sgList[lpnTran.getLpnIndex()].getEnabledSetTbl().put(nextStateArray[lpnTran.getLpnIndex()], newLpnTranList); if (Options.getDebugMode()) { System.out.println("@ updateLocalAmpleTbl: "); System.out.println("Add S" + nextStateArray[lpnTran.getLpnIndex()].getIndex() + " to the enabledSetTbl of " + sgList[lpnTran.getLpnIndex()].getLpn().getLabel() + "."); } } } if (Options.getDebugMode()) printEnabledSetTbl(sgList); } private void printPrjStateSet(HashSet<PrjState> prjStateSet) { for (PrjState curGlobal : prjStateSet) { State[] curStateArray = curGlobal.toStateArray(); printStateArray(curStateArray); System.out.println(" } } // /** // * This method performs first-depth search on multiple LPNs and applies partial order reduction technique with the trace-back. // * @param sgList // * @param initStateArray // * @param cycleClosingMthdIndex // * @return // */ // public StateGraph[] search_dfsPORrefinedCycleRule(final StateGraph[] sgList, final State[] initStateArray, int cycleClosingMthdIndex) { // if (cycleClosingMthdIndex == 1) // else if (cycleClosingMthdIndex == 2) // else if (cycleClosingMthdIndex == 4) // double peakUsedMem = 0; // double peakTotalMem = 0; // boolean failure = false; // int tranFiringCnt = 0; // int totalStates = 1; // int numLpns = sgList.length; // HashSet<PrjState> stateStack = new HashSet<PrjState>(); // Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); // Stack<Integer> curIndexStack = new Stack<Integer>(); // HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); // PrjState initPrjState = new PrjState(initStateArray); // prjStateSet.add(initPrjState); // PrjState stateStackTop = initPrjState; // System.out.println("%%%%%%% Add states to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.add(stateStackTop); // // Prepare static pieces for POR // HashMap<Integer, HashMap<Integer, StaticSets>> staticSetsMap = new HashMap<Integer, HashMap<Integer, StaticSets>>(); // Transition[] allTransitions = sgList[0].getLpn().getAllTransitions(); // HashMap<Integer, StaticSets> tmpMap = new HashMap<Integer, StaticSets>(); // HashMap<Integer, Integer> tranFiringFreq = new HashMap<Integer, Integer>(allTransitions.length); // for (Transition curTran: allTransitions) { // StaticSets curStatic = new StaticSets(sgList[0].getLpn(), curTran, allTransitions); // curStatic.buildDisableSet(); // curStatic.buildEnableSet(); // curStatic.buildModifyAssignSet(); // tmpMap.put(curTran.getIndex(), curStatic); // tranFiringFreq.put(curTran.getIndex(), 0); // staticSetsMap.put(sgList[0].getLpn().getLpnIndex(), tmpMap); // printStaticSetMap(staticSetsMap); // System.out.println("call getAmple on initStateArray at 0: "); // boolean init = true; // AmpleSet initAmple = new AmpleSet(); // initAmple = sgList[0].getAmple(initStateArray[0], staticSetsMap, init, tranFiringFreq); // HashMap<State, LpnTranList> initEnabledSetTbl = (HashMap<State, LpnTranList>) sgList[0].copyEnabledSetTbl(); // lpnTranStack.push(initAmple.getAmpleSet()); // curIndexStack.push(0); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) initAmple.getAmpleSet(), ""); // main_while_loop: while (failure == false && stateStack.size() != 0) { // System.out.println("$$$$$$$$$$$ loop begins $$$$$$$$$$"); // long curTotalMem = Runtime.getRuntime().totalMemory(); // long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); // if (curTotalMem > peakTotalMem) // peakTotalMem = curTotalMem; // if (curUsedMem > peakUsedMem) // peakUsedMem = curUsedMem; // if (stateStack.size() > max_stack_depth) // max_stack_depth = stateStack.size(); // iterations++; // if (iterations % 100000 == 0) { // System.out.println("---> #iteration " + iterations // + "> # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStates // + ", stack_depth: " + stateStack.size() // + " used memory: " + (float) curUsedMem / 1000000 // + " free memory: " // + (float) Runtime.getRuntime().freeMemory() / 1000000); // State[] curStateArray = stateStackTop.toStateArray(); //stateStack.peek(); // int curIndex = curIndexStack.peek(); //// System.out.println("curIndex = " + curIndex); // //AmpleSet curAmple = new AmpleSet(); // //LinkedList<Transition> curAmpleTrans = curAmple.getAmpleSet(); // LinkedList<Transition> curAmpleTrans = lpnTranStack.peek(); //// printStateArray(curStateArray); //// System.out.println("+++++++ curAmple trans ++++++++"); //// printTransLinkedList(curAmpleTrans); // // If all enabled transitions of the current LPN are considered, // // then consider the next LPN // // by increasing the curIndex. // // Otherwise, if all enabled transitions of all LPNs are considered, // // then pop the stacks. // if (curAmpleTrans.size() == 0) { // lpnTranStack.pop(); //// System.out.println("+++++++ Pop trans off lpnTranStack ++++++++"); // curIndexStack.pop(); //// System.out.println("+++++++ Pop index off curIndexStack ++++++++"); // curIndex++; //// System.out.println("curIndex = " + curIndex); // while (curIndex < numLpns) { // System.out.println("call getEnabled on curStateArray at 1: "); // LpnTranList tmpAmpleTrans = (LpnTranList) (sgList[curIndex].getAmple(curStateArray[curIndex], staticSetsMap, init, tranFiringFreq)).getAmpleSet(); // curAmpleTrans = tmpAmpleTrans.clone(); // //printTransitionSet(curEnabled, "curEnabled set"); // if (curAmpleTrans.size() > 0) { // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransLinkedList(curAmpleTrans); // lpnTranStack.push(curAmpleTrans); // curIndexStack.push(curIndex); // printIntegerStack("curIndexStack after push 1", curIndexStack); // break; // curIndex++; // if (curIndex == numLpns) { // prjStateSet.add(stateStackTop); // System.out.println("%%%%%%% Remove stateStackTop from stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // stateStack.remove(stateStackTop); // stateStackTop = stateStackTop.getFather(); // continue; // Transition firedTran = curAmpleTrans.removeLast(); // System.out.println(" // System.out.println("Fired transition: " + firedTran.getName()); // System.out.println(" // Integer freq = tranFiringFreq.get(firedTran.getIndex()) + 1; // tranFiringFreq.put(firedTran.getIndex(), freq); // System.out.println("~~~~~~tranFiringFreq~~~~~~~"); // printHashMap(tranFiringFreq, allTransitions); // State[] nextStateArray = sgList[curIndex].fire(sgList, curStateArray, firedTran); // tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. // @SuppressWarnings("unchecked") // LinkedList<Transition>[] curAmpleArray = new LinkedList[numLpns]; // @SuppressWarnings("unchecked") // LinkedList<Transition>[] nextAmpleArray = new LinkedList[numLpns]; // boolean updatedAmpleDueToCycleRule = false; // for (int i = 0; i < numLpns; i++) { // StateGraph sg_tmp = sgList[i]; // System.out.println("call getAmple on curStateArray at 2: i = " + i); // AmpleSet ampleList = new AmpleSet(); // if (init) { // ampleList = initAmple; // sg_tmp.setEnabledSetTbl(initEnabledSetTbl); // init = false; // else // ampleList = sg_tmp.getAmple(curStateArray[i], staticSetsMap, init, tranFiringFreq); // curAmpleArray[i] = ampleList.getAmpleSet(); // System.out.println("call getAmpleRefinedCycleRule on nextStateArray at 3: i = " + i); // ampleList = sg_tmp.getAmpleRefinedCycleRule(curStateArray[i], nextStateArray[i], staticSetsMap, stateStack, stateStackTop, init, cycleClosingMthdIndex, i, tranFiringFreq); // nextAmpleArray[i] = ampleList.getAmpleSet(); // if (!updatedAmpleDueToCycleRule && ampleList.getAmpleChanged()) { // updatedAmpleDueToCycleRule = true; // for (LinkedList<Transition> tranList : curAmpleArray) { // printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : curAmpleArray) { //// printTransLinkedList(tranList); //// for (LinkedList<Transition> tranList : nextAmpleArray) { //// printTransLinkedList(tranList); // Transition disabledTran = firedTran.disablingError( // curStateArray[i].getEnabledTransitions(), nextStateArray[i].getEnabledTransitions()); // if (disabledTran != null) { // System.err.println("Disabling Error: " // + disabledTran.getFullLabel() + " is disabled by " // + firedTran.getFullLabel()); // failure = true; // break main_while_loop; // if (Analysis.deadLock(sgList, nextStateArray, staticSetsMap, init, tranFiringFreq) == true) { // failure = true; // break main_while_loop; // PrjState nextPrjState = new PrjState(nextStateArray); // Boolean existingState = prjStateSet.contains(nextPrjState) || stateStack.contains(nextPrjState); // if (existingState == true && updatedAmpleDueToCycleRule) { // // cycle closing // System.out.println("%%%%%%% existingSate == true %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // if (existingState == false) { // System.out.println("%%%%%%% existingSate == false %%%%%%%%"); // stateStackTop.setChild(nextPrjState); // nextPrjState.setFather(stateStackTop); // stateStackTop = nextPrjState; // stateStack.add(stateStackTop); // System.out.println("%%%%%%% Add state to stateStack %%%%%%%%"); // printStateArray(stateStackTop.toStateArray()); // System.out.println("+++++++ Push trans onto lpnTranStack ++++++++"); // printTransitionSet((LpnTranList) nextAmpleArray[0], ""); // lpnTranStack.push((LpnTranList) nextAmpleArray[0].clone()); // curIndexStack.push(0); // totalStates++; // // end of main_while_loop // double totalStateCnt = prjStateSet.size(); // System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt // + ", # of prjStates found: " + totalStateCnt // + ", max_stack_depth: " + max_stack_depth // + ", peak total memory: " + peakTotalMem / 1000000 + " MB" // + ", peak used memory: " + peakUsedMem / 1000000 + " MB"); // // This currently works for a single LPN. // return sgList; // return null; private void printHashMap(HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList) { for (LpnTransitionPair curIndex : tranFiringFreq.keySet()) { LhpnFile curLpn = sgList[curIndex.getLpnIndex()].getLpn(); Transition curTran = curLpn.getTransition(curIndex.getTranIndex()); System.out.println(curLpn.getLabel() + "(" + curTran.getName() + ")" + " -> " + tranFiringFreq.get(curIndex)); } } private void printStaticSetsMap( LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) { System.out.println(" for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); printLpnTranPair(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet"); printLpnTranPair(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue"); } } private void writeStaticSetsMapToPORDebugFile( LhpnFile[] lpnList, HashMap<LpnTransitionPair,StaticSets> staticSetsMap) { try { PORdebugBufferedWriter.write(" PORdebugBufferedWriter.newLine(); for (LpnTransitionPair lpnTranPair : staticSetsMap.keySet()) { StaticSets statSets = staticSetsMap.get(lpnTranPair); writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getDisableSet(), "disableSet"); writeLpnTranPairToPORDebugFile(lpnList, statSets.getTran(), statSets.getEnableBySettingEnablingTrue(), "enableBySetingEnablingTrue"); } } catch (IOException e) { e.printStackTrace(); } } // private Transition[] assignStickyTransitions(LhpnFile lpn) { // // allProcessTrans is a hashmap from a transition to its process color (integer). // HashMap<Transition, Integer> allProcessTrans = new HashMap<Transition, Integer>(); // // create an Abstraction object to call the divideProcesses method. // Abstraction abs = new Abstraction(lpn); // abs.decomposeLpnIntoProcesses(); // allProcessTrans.putAll( // (HashMap<Transition, Integer>)abs.getTransWithProcIDs().clone()); // HashMap<Integer, LpnProcess> processMap = new HashMap<Integer, LpnProcess>(); // for (Iterator<Transition> tranIter = allProcessTrans.keySet().iterator(); tranIter.hasNext();) { // Transition curTran = tranIter.next(); // Integer procId = allProcessTrans.get(curTran); // if (!processMap.containsKey(procId)) { // LpnProcess newProcess = new LpnProcess(procId); // newProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // newProcess.addPlaceToProcess(p); // processMap.put(procId, newProcess); // else { // LpnProcess curProcess = processMap.get(procId); // curProcess.addTranToProcess(curTran); // if (curTran.getPreset() != null) { // Place[] preset = curTran.getPreset(); // for (Place p : preset) { // curProcess.addPlaceToProcess(p); // for(Iterator<Integer> processMapIter = processMap.keySet().iterator(); processMapIter.hasNext();) { // LpnProcess curProc = processMap.get(processMapIter.next()); // curProc.assignStickyTransitions(); // curProc.printProcWithStickyTrans(); // return lpn.getAllTransitions(); // private void printPlacesIndices(ArrayList<String> allPlaces) { // System.out.println("Indices of all places: "); // for (int i=0; i < allPlaces.size(); i++) { // System.out.println(allPlaces.get(i) + "\t" + i); // private void printTransIndices(Transition[] allTransitions) { // System.out.println("Indices of all transitions: "); // for (int i=0; i < allTransitions.length; i++) { // System.out.println(allTransitions[i].getName() + "\t" + allTransitions[i].getIndex()); private void printLpnTranPair(LhpnFile[] lpnList, Transition curTran, HashSet<LpnTransitionPair> curDisable, String setName) { System.out.print(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); if (curDisable.isEmpty()) { System.out.println("empty"); } else { for (LpnTransitionPair lpnTranPair: curDisable) { System.out.print("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); } System.out.print("\n"); } } private void writeLpnTranPairToPORDebugFile(LhpnFile[] lpnList, Transition curTran, HashSet<LpnTransitionPair> curDisable, String setName) { try { //PORdebugBufferedWriter.write(setName + " for " + curTran.getName() + "(" + curTran.getIndex() + ")" + " is: "); PORdebugBufferedWriter.write(setName + " for (" + curTran.getLpn().getLabel() + " , " + curTran.getName() + ") is: "); if (curDisable.isEmpty()) { PORdebugBufferedWriter.write("empty"); PORdebugBufferedWriter.newLine(); } else { for (LpnTransitionPair lpnTranPair: curDisable) { PORdebugBufferedWriter.append("(" + lpnList[lpnTranPair.getLpnIndex()].getLabel() + ", " + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ")," + "\t"); } PORdebugBufferedWriter.newLine(); } PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void printTransitionSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " is: "); if (transitionSet.isEmpty()) { System.out.println("empty"); } else { for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { Transition tranInDisable = curTranIter.next(); System.out.print(tranInDisable.getName() + " "); } System.out.print("\n"); } } // private void printTransitionSet(LinkedList<Transition> transitionSet, String setName) { // System.out.print(setName + " is: "); // if (transitionSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { // Transition tranInDisable = curTranIter.next(); // System.out.print(tranInDisable.getIndex() + " "); // System.out.print("\n"); /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. The enabledSetTbl (for each StateGraph obj) stores the AMPLE set for each state of each LPN. * @param stateArray * @param stateStack * @param enable * @param disableByStealingToken * @param disable * @param init * @param tranFiringFreq * @param sgList * @return */ public LpnTranList getAmple(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap, boolean init, HashMap<LpnTransitionPair, Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> stateStack, PrjState stateStackTop) { State[] stateArray = null; if (nextStateArray == null) stateArray = curStateArray; else stateArray = nextStateArray; for (State s : stateArray) if (s == null) throw new NullPointerException(); LpnTranList ample = new LpnTranList(); HashSet<LpnTransitionPair> curEnabled = new HashSet<LpnTransitionPair>(); for (int lpnIndex=0; lpnIndex<stateArray.length; lpnIndex++) { State state = stateArray[lpnIndex]; if (init) { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { Transition tran = curLpn.getAllTransitions()[i]; if (sgList[lpnIndex].isEnabled(tran,state)){ curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i)); } } } else { LhpnFile curLpn = sgList[lpnIndex].getLpn(); for (int i=0; i < curLpn.getAllTransitions().length; i++) { if (stateArray[lpnIndex].getTranVector()[i]) { curEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i)); } } } } HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>(); if (Options.getDebugMode()) { System.out.println("******** Partial Order Reduction ************"); printIntegerSet(curEnabled, sgList, "Enabled set"); System.out.println("******* Begin POR"); writeStringWithNewLineToPORDebugFile("******* Partial Order Reduction *******"); writeIntegerSetToPORDebugFile(curEnabled, sgList, "Enabled set"); writeStringWithNewLineToPORDebugFile("******* Begin POR *******"); } if (curEnabled.isEmpty()) { return ample; } // if (Options.getNecessaryUsingDependencyGraphs()) // ready = partialOrderReductionUsingDependencyGraphs(stateArray, curEnabled, staticSetsMap, sgList); // else ready = partialOrderReduction(stateArray, curEnabled, staticSetsMap, tranFiringFreq, sgList); if (Options.getDebugMode()) { System.out.println("******* End POR *******"); printIntegerSet(ready, sgList, "Ready set"); System.out.println("********************"); writeStringWithNewLineToPORDebugFile("******* End POR *******"); writeIntegerSetToPORDebugFile(ready, sgList, "Ready set"); writeStringWithNewLineToPORDebugFile("********************"); } //if (tranFiringFreq != null) { LinkedList<LpnTransitionPair> readyList = new LinkedList<LpnTransitionPair>(); for (LpnTransitionPair inReady : ready) { readyList.add(inReady); } mergeSort(readyList, tranFiringFreq); for (LpnTransitionPair inReady : readyList) { LhpnFile lpn = sgList[inReady.getLpnIndex()].getLpn(); Transition tran = lpn.getTransition(inReady.getTranIndex()); ample.addFirst(tran); } // else { // for (LpnTransitionPair inReady : ready) { // LhpnFile lpn = sgList[inReady.getLpnIndex()].getLpn(); // Transition tran = lpn.getTransition(inReady.getTranIndex()); // ample.add(tran); return ample; } private LinkedList<LpnTransitionPair> mergeSort(LinkedList<LpnTransitionPair> array, HashMap<LpnTransitionPair, Integer> tranFiringFreq) { if (array.size() == 1) return array; int middle = array.size() / 2; LinkedList<LpnTransitionPair> left = new LinkedList<LpnTransitionPair>(); LinkedList<LpnTransitionPair> right = new LinkedList<LpnTransitionPair>(); for (int i=0; i<middle; i++) { left.add(i, array.get(i)); } for (int i=middle; i<array.size();i++) { right.add(i-middle, array.get(i)); } left = mergeSort(left, tranFiringFreq); right = mergeSort(right, tranFiringFreq); return merge(left, right, tranFiringFreq); } private LinkedList<LpnTransitionPair> merge(LinkedList<LpnTransitionPair> left, LinkedList<LpnTransitionPair> right, HashMap<LpnTransitionPair, Integer> tranFiringFreq) { LinkedList<LpnTransitionPair> result = new LinkedList<LpnTransitionPair>(); while (left.size() > 0 || right.size() > 0) { if (left.size() > 0 && right.size() > 0) { if (tranFiringFreq.get(left.peek()) <= tranFiringFreq.get(right.peek())) { result.addLast(left.poll()); } else { result.addLast(right.poll()); } } else if (left.size()>0) { result.addLast(left.poll()); } else if (right.size()>0) { result.addLast(right.poll()); } } return result; } /** * Return the set of all LPN transitions that are enabled in 'state'. The "init" flag indicates whether a transition * needs to be evaluated. * @param nextState * @param stateStackTop * @param enable * @param disableByStealingToken * @param disable * @param init * @param cycleClosingMthdIndex * @param lpnIndex * @param isNextState * @return */ public LpnTranList getAmpleRefinedCycleRule(State[] curStateArray, State[] nextStateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap, boolean init, HashMap<LpnTransitionPair,Integer> tranFiringFreq, StateGraph[] sgList, HashSet<PrjState> stateStack, PrjState stateStackTop) { // AmpleSet nextAmple = new AmpleSet(); // if (nextState == null) { // throw new NullPointerException(); // if(ampleSetTbl.containsKey(nextState) == true && stateOnStack(nextState, stateStack)) { // System.out.println("~~~~~~~ existing state in enabledSetTbl and on stateStack: S" + nextState.getIndex() + "~~~~~~~~"); // printTransitionSet((LpnTranList)ampleSetTbl.get(nextState), "Old ample at this state: "); // // Cycle closing check // LpnTranList nextAmpleTransOld = (LpnTranList) nextAmple.getAmpleSet(); // nextAmpleTransOld = ampleSetTbl.get(nextState); // LpnTranList curAmpleTrans = ampleSetTbl.get(curState); // LpnTranList curReduced = new LpnTranList(); // LpnTranList curEnabled = curState.getEnabledTransitions(); // for (int i=0; i<curEnabled.size(); i++) { // if (!curAmpleTrans.contains(curEnabled.get(i))) { // curReduced.add(curEnabled.get(i)); // if (!nextAmpleTransOld.containsAll(curReduced)) { // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // printTransitionSet(curEnabled, "curEnabled:"); // printTransitionSet(curAmpleTrans, "curAmpleTrans:"); // printTransitionSet(curReduced, "curReduced:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextEnabled:"); // printTransitionSet(nextAmpleTransOld, "nextAmpleTransOld:"); // nextAmple.setAmpleChanged(); // HashSet<LpnTransitionPair> curEnabledIndicies = new HashSet<LpnTransitionPair>(); // for (int i=0; i<curEnabled.size(); i++) { // curEnabledIndicies.add(curEnabled.get(i).getIndex()); // // transToAdd = curReduced - nextAmpleOld // LpnTranList overlyReducedTrans = getSetSubtraction(curReduced, nextAmpleTransOld); // HashSet<Integer> transToAddIndices = new HashSet<Integer>(); // for (int i=0; i<overlyReducedTrans.size(); i++) { // transToAddIndices.add(overlyReducedTrans.get(i).getIndex()); // HashSet<Integer> nextAmpleNewIndices = (HashSet<Integer>) curEnabledIndicies.clone(); // for (Integer tranToAdd : transToAddIndices) { // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // //Transition enabledTransition = this.lpn.getAllTransitions()[tranToAdd]; // dependent = getDependentSet(curState,tranToAdd,dependent,curEnabledIndicies,staticMap); // // printIntegerSet(dependent, "dependent set for enabled transition " + this.lpn.getAllTransitions()[enabledTran]); // boolean dependentOnlyHasDummyTrans = true; // for (Integer curTranIndex : dependent) { // Transition curTran = this.lpn.getAllTransitions()[curTranIndex]; // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans && isDummyTran(curTran.getName()); // if (dependent.size() < nextAmpleNewIndices.size() && !dependentOnlyHasDummyTrans) // nextAmpleNewIndices = (HashSet<Integer>) dependent.clone(); // if (nextAmpleNewIndices.size() == 1) // break; // LpnTranList nextAmpleNew = new LpnTranList(); // for (Integer nextAmpleNewIndex : nextAmpleNewIndices) { // nextAmpleNew.add(this.getLpn().getTransition(nextAmpleNewIndex)); // LpnTranList transToAdd = getSetSubtraction(nextAmpleNew, nextAmpleTransOld); // boolean allTransToAddFired = false; // if (cycleClosingMthdIndex == 2) { // // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. // if (transToAdd != null) { // LpnTranList transToAddCopy = transToAdd.copy(); // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // allTransToAddFired = allTransToAddFired(transToAddCopy, // allTransToAddFired, stateVisited, stateStackTop, lpnIndex); // // Update the old ample of the next state // if (!allTransToAddFired || cycleClosingMthdIndex == 1) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(transToAdd); // ampleSetTbl.get(nextState).addAll(transToAdd); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // if (cycleClosingMthdIndex == 4) { // nextAmple.getAmpleSet().clear(); // nextAmple.getAmpleSet().addAll(overlyReducedTrans); // ampleSetTbl.get(nextState).addAll(overlyReducedTrans); // printTransitionSet(nextAmpleNew, "nextAmpleNew:"); // printTransitionSet(transToAdd, "transToAdd:"); // System.out.println("((((((((((((((((((((()))))))))))))))))))))"); // // enabledSetTble stores the ample set at curState. // // The fully enabled set at each state is stored in the tranVector in each state. // return (AmpleSet) nextAmple; // for (State s : nextStateArray) // if (s == null) // throw new NullPointerException(); // cachedNecessarySets.clear(); // String cycleClosingMthd = Options.getCycleClosingMthd(); // AmpleSet nextAmple = new AmpleSet(); // HashSet<LpnTransitionPair> nextEnabled = new HashSet<LpnTransitionPair>(); //// boolean allEnabledAreSticky = false; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State nextState = nextStateArray[lpnIndex]; // if (init) { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // //allEnabledAreSticky = true; // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (sgList[lpnIndex].isEnabled(tran,nextState)){ // nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // else { // LhpnFile curLpn = sgList[lpnIndex].getLpn(); // for (int i=0; i < curLpn.getAllTransitions().length; i++) { // Transition tran = curLpn.getAllTransitions()[i]; // if (nextStateArray[lpnIndex].getTranVector()[i]) { // nextEnabled.add(new LpnTransitionPair(curLpn.getLpnIndex(), i)); // //allEnabledAreSticky = allEnabledAreSticky && tran.isSticky(); // //sgList[lpnIndex].getEnabledSetTbl().put(nextStateArray[lpnIndex], new LpnTranList()); // DependentSetComparator depComp = new DependentSetComparator(tranFiringFreq); // PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(nextEnabled.size(), depComp); // LhpnFile[] lpnList = new LhpnFile[sgList.length]; // for (int i=0; i<sgList.length; i++) // lpnList[i] = sgList[i].getLpn(); // HashMap<LpnTransitionPair, LpnTranList> transToAddMap = new HashMap<LpnTransitionPair, LpnTranList>(); // Integer cycleClosingLpnIndex = -1; // for (int lpnIndex=0; lpnIndex<nextStateArray.length; lpnIndex++) { // State curState = curStateArray[lpnIndex]; // State nextState = nextStateArray[lpnIndex]; // if(sgList[lpnIndex].getEnabledSetTbl().containsKey(nextState) == true // && !sgList[lpnIndex].getEnabledSetTbl().get(nextState).isEmpty() // && stateOnStack(lpnIndex, nextState, stateStack) // && nextState.getIndex() != curState.getIndex()) { // cycleClosingLpnIndex = lpnIndex; // System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN " + sgList[lpnIndex].getLpn().getLabel() +": S" + nextState.getIndex() + "~~~~~~~~"); // printAmpleSet((LpnTranList)sgList[lpnIndex].getEnabledSetTbl().get(nextState), "Old ample at this state: "); // LpnTranList oldLocalNextAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(nextState); // LpnTranList curLocalAmpleTrans = sgList[lpnIndex].getEnabledSetTbl().get(curState); // LpnTranList reducedLocalTrans = new LpnTranList(); // LpnTranList curLocalEnabledTrans = curState.getEnabledTransitions(); // System.out.println("The firedTran is a cycle closing transition."); // if (cycleClosingMthd.toLowerCase().equals("behavioral") || cycleClosingMthd.toLowerCase().equals("state_search")) { // // firedTran is a cycle closing transition. // for (int i=0; i<curLocalEnabledTrans.size(); i++) { // if (!curLocalAmpleTrans.contains(curLocalEnabledTrans.get(i))) { // reducedLocalTrans.add(curLocalEnabledTrans.get(i)); // if (!oldLocalNextAmpleTrans.containsAll(reducedLocalTrans)) { // printTransitionSet(curLocalEnabledTrans, "curLocalEnabled:"); // printTransitionSet(curLocalAmpleTrans, "curAmpleTrans:"); // printTransitionSet(reducedLocalTrans, "reducedLocalTrans:"); // printTransitionSet(nextState.getEnabledTransitions(), "nextLocalEnabled:"); // printTransitionSet(oldLocalNextAmpleTrans, "nextAmpleTransOld:"); // // nextAmple.setAmpleChanged(); // // ignoredTrans should not be empty here. // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<LpnTransitionPair> ignored = new HashSet<LpnTransitionPair>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new LpnTransitionPair(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone(); // if (cycleClosingMthd.toLowerCase().equals("behavioral")) { // for (LpnTransitionPair seed : ignored) { // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for ignored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); //// if (nextAmpleNewIndices.size() == 1) //// break; // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (LpnTransitionPair tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else if (cycleClosingMthd.toLowerCase().equals("state_search")) { // // For every transition t in ignored, if t was fired in any state on stateStack, there is no need to put it to the new ample of nextState. // HashSet<Integer> stateVisited = new HashSet<Integer>(); // stateVisited.add(nextState.getIndex()); // LpnTranList trulyIgnoredTrans = ignoredTrans.copy(); // trulyIgnoredTrans = allIgnoredTransFired(trulyIgnoredTrans, stateVisited, stateStackTop, lpnIndex, sgList[lpnIndex]); // if (!trulyIgnoredTrans.isEmpty()) { // HashSet<LpnTransitionPair> trulyIgnored = new HashSet<LpnTransitionPair>(); // for (Transition tran : trulyIgnoredTrans) { // trulyIgnored.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (LpnTransitionPair seed : trulyIgnored) { // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for trulyIgnored transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // LpnTranList newLocalNextAmpleTrans = new LpnTranList(); // for (LpnTransitionPair tran : newNextAmple) { // if (tran.getLpnIndex() == lpnIndex) // newLocalNextAmpleTrans.add(sgList[lpnIndex].getLpn().getTransition(tran.getTranIndex())); // LpnTranList transToAdd = getSetSubtraction(newLocalNextAmpleTrans, oldLocalNextAmpleTrans); // transToAddMap.put(seed, transToAdd); // else { // All ignored transitions were fired before. It is safe to close the current cycle. // HashSet<LpnTransitionPair> oldLocalNextAmple = new HashSet<LpnTransitionPair>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (LpnTransitionPair seed : oldLocalNextAmple) { // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // // oldNextAmpleTrans.containsAll(curReducedTrans) == true (safe to close the current cycle) // HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone(); // HashSet<LpnTransitionPair> oldLocalNextAmple = new HashSet<LpnTransitionPair>(); // for (Transition tran : oldLocalNextAmpleTrans) // oldLocalNextAmple.add(new LpnTransitionPair(tran.getLpn().getLpnIndex(), tran.getIndex())); // for (LpnTransitionPair seed : oldLocalNextAmple) { // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in oldNextAmple is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // DependentSet dependentSet = new DependentSet(newNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else if (cycleClosingMthd.toLowerCase().equals("strong")) { // LpnTranList ignoredTrans = getSetSubtraction(reducedLocalTrans, oldLocalNextAmpleTrans); // HashSet<LpnTransitionPair> ignored = new HashSet<LpnTransitionPair>(); // for (int i=0; i<ignoredTrans.size(); i++) { // ignored.add(new LpnTransitionPair(lpnIndex, ignoredTrans.get(i).getIndex())); // HashSet<LpnTransitionPair> allNewNextAmple = new HashSet<LpnTransitionPair>(); // for (LpnTransitionPair seed : ignored) { // HashSet<LpnTransitionPair> newNextAmple = (HashSet<LpnTransitionPair>) nextEnabled.clone(); // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // dependent = computeDependent(nextStateArray,seed,dependent,nextEnabled,staticSetsMap, lpnList); // printIntegerSet(dependent, sgList, "dependent set for transition in curLocalEnabled is " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName() + ")"); // boolean dependentOnlyHasDummyTrans = true; // for (LpnTransitionPair dependentTran : dependent) { // dependentOnlyHasDummyTrans = dependentOnlyHasDummyTrans // && isDummyTran(sgList[dependentTran.getLpnIndex()].getLpn().getTransition(dependentTran.getTranIndex()).getName()); // if (dependent.size() < newNextAmple.size() && !dependentOnlyHasDummyTrans) // newNextAmple = (HashSet<LpnTransitionPair>) dependent.clone(); // allNewNextAmple.addAll(newNextAmple); // // The strong cycle condition requires all seeds in ignored to be included in the allNewNextAmple, as well as dependent set for each seed. // // So each seed should have the same new ample set. // for (LpnTransitionPair seed : ignored) { // DependentSet dependentSet = new DependentSet(allNewNextAmple, seed, // isDummyTran(sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()).getName())); // dependentSetQueue.add(dependentSet); // else { // firedTran is not a cycle closing transition. Compute next ample. //// if (nextEnabled.size() == 1) //// return nextEnabled; // System.out.println("The firedTran is NOT a cycle closing transition."); // HashSet<LpnTransitionPair> ready = null; // for (LpnTransitionPair seed : nextEnabled) { // System.out.println("@ partialOrderReduction, consider transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "("+ sgList[seed.getLpnIndex()].getLpn().getTransition(seed.getTranIndex()) + ")"); // HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); // Transition enabledTransition = sgList[seed.getLpnIndex()].getLpn().getAllTransitions()[seed.getTranIndex()]; // boolean enabledIsDummy = false; //// if (enabledTransition.isSticky()) { //// dependent = (HashSet<LpnTransitionPair>) nextEnabled.clone(); //// else { //// dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticMap, lpnList); // dependent = computeDependent(curStateArray,seed,dependent,nextEnabled,staticSetsMap,lpnList); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[seed.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // if (isDummyTran(enabledTransition.getName())) // enabledIsDummy = true; // for (LpnTransitionPair inDependent : dependent) { // if(inDependent.getLpnIndex() == cycleClosingLpnIndex) { // // check cycle closing condition // break; // DependentSet dependentSet = new DependentSet(dependent, seed, enabledIsDummy); // dependentSetQueue.add(dependentSet); // ready = dependentSetQueue.poll().getDependent(); //// // Update the old ample of the next state //// boolean allTransToAddFired = false; //// if (cycleClosingMthdIndex == 2) { //// // For every transition t in transToAdd, if t was fired in the any state on stateStack, there is no need to put it to the new ample of nextState. //// if (transToAdd != null) { //// LpnTranList transToAddCopy = transToAdd.copy(); //// HashSet<Integer> stateVisited = new HashSet<Integer>(); //// stateVisited.add(nextState.getIndex()); //// allTransToAddFired = allTransToAddFired(transToAddCopy, //// allTransToAddFired, stateVisited, stateStackTop, lpnIndex); //// // Update the old ample of the next state //// if (!allTransToAddFired || cycleClosingMthdIndex == 1) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(transToAdd); //// ampleSetTbl.get(nextState).addAll(transToAdd); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// if (cycleClosingMthdIndex == 4) { //// nextAmple.getAmpleSet().clear(); //// nextAmple.getAmpleSet().addAll(ignoredTrans); //// ampleSetTbl.get(nextState).addAll(ignoredTrans); //// printTransitionSet(nextAmpleNew, "nextAmpleNew:"); //// printTransitionSet(transToAdd, "transToAdd:"); //// System.out.println("((((((((((((((((((((()))))))))))))))))))))"); //// // enabledSetTble stores the ample set at curState. //// // The fully enabled set at each state is stored in the tranVector in each state. //// return (AmpleSet) nextAmple; return null; } private LpnTranList allIgnoredTransFired(LpnTranList ignoredTrans, HashSet<Integer> stateVisited, PrjState stateStackEntry, int lpnIndex, StateGraph sg) { State state = stateStackEntry.get(lpnIndex); System.out.println("state = " + state.getIndex()); State predecessor = stateStackEntry.getFather().get(lpnIndex); if (predecessor != null) System.out.println("predecessor = " + predecessor.getIndex()); if (predecessor == null || stateVisited.contains(predecessor.getIndex())) { return ignoredTrans; } else stateVisited.add(predecessor.getIndex()); LpnTranList predecessorOldAmple = sg.getEnabledSetTbl().get(predecessor);//enabledSetTbl.get(predecessor); for (Transition oldAmpleTran : predecessorOldAmple) { State tmpState = sg.getNextStateMap().get(predecessor).get(oldAmpleTran); if (tmpState.getIndex() == state.getIndex()) { ignoredTrans.remove(oldAmpleTran); break; } } if (ignoredTrans.size()==0) { return ignoredTrans; } else { ignoredTrans = allIgnoredTransFired(ignoredTrans, stateVisited, stateStackEntry.getFather(), lpnIndex, sg); } return ignoredTrans; } // for (Transition oldAmpleTran : oldAmple) { // State successor = nextStateMap.get(nextState).get(oldAmpleTran); // if (stateVisited.contains(successor.getIndex())) { // break; // else // stateVisited.add(successor.getIndex()); // LpnTranList successorOldAmple = enabledSetTbl.get(successor); // // Either successor or sucessorOldAmple should not be null for a nonterminal state graph. // HashSet<Transition> transToAddFired = new HashSet<Transition>(); // for (Transition tran : transToAddCopy) { // if (successorOldAmple.contains(tran)) // transToAddFired.add(tran); // transToAddCopy.removeAll(transToAddFired); // if (transToAddCopy.size() == 0) { // allTransFired = true; // break; // else { // allTransFired = allTransToAddFired(successorOldAmple, nextState, successor, // transToAddCopy, allTransFired, stateVisited, stateStackEntry, lpnIndex); // return allTransFired; /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ /** * An iterative implement of findsg_recursive(). * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_noDisabling_fireOrder(final StateGraph[] lpnList, final State[] initStateArray) { boolean firingOrder = false; long peakUsedMem = 0; long peakTotalMem = 0; boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length; HashSet<PrjLpnState> globalStateTbl = new HashSet<PrjLpnState>(); @SuppressWarnings("unchecked") IndexObjMap<LpnState>[] lpnStateCache = new IndexObjMap[arraySize]; //HashMap<LpnState, LpnState>[] lpnStateCache1 = new HashMap[arraySize]; Stack<LpnState[]> stateStack = new Stack<LpnState[]>(); Stack<LpnTranList[]> lpnTranStack = new Stack<LpnTranList[]>(); //get initial enable transition set LpnTranList initEnabled = new LpnTranList(); LpnTranList initFireFirst = new LpnTranList(); LpnState[] initLpnStateArray = new LpnState[arraySize]; for (int i = 0; i < arraySize; i++) { lpnStateCache[i] = new IndexObjMap<LpnState>(); LinkedList<Transition> enabledTrans = lpnList[i].getEnabled(initStateArray[i]); HashSet<Transition> enabledSet = new HashSet<Transition>(); if(!enabledTrans.isEmpty()) { for(Transition tran : enabledTrans) { enabledSet.add(tran); initEnabled.add(tran); } } LpnState curLpnState = new LpnState(lpnList[i].getLpn(), initStateArray[i], enabledSet); lpnStateCache[i].add(curLpnState); initLpnStateArray[i] = curLpnState; } LpnTranList[] initEnabledSet = new LpnTranList[2]; initEnabledSet[0] = initFireFirst; initEnabledSet[1] = initEnabled; lpnTranStack.push(initEnabledSet); stateStack.push(initLpnStateArray); globalStateTbl.add(new PrjLpnState(initLpnStateArray)); main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; //if(iterations>2)break; if (iterations % 100000 == 0) System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", current_stack_depth: " + stateStack.size() + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); LpnTranList[] curEnabled = lpnTranStack.peek(); LpnState[] curLpnStateArray = stateStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if(curEnabled[0].size()==0 && curEnabled[1].size()==0){ lpnTranStack.pop(); stateStack.pop(); continue; } Transition firedTran = null; if(curEnabled[0].size() != 0) firedTran = curEnabled[0].removeFirst(); else firedTran = curEnabled[1].removeFirst(); traceCex.addLast(firedTran); State[] curStateArray = new State[arraySize]; for( int i = 0; i < arraySize; i++) curStateArray[i] = curLpnStateArray[i].getState(); StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran, null, null); // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") HashSet<Transition>[] extendedNextEnabledArray = new HashSet[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> curEnabledSet = curLpnStateArray[i].getEnabled(); LpnTranList nextEnabledList = lpnList[i].getEnabled(nextStateArray[i]); HashSet<Transition> nextEnabledSet = new HashSet<Transition>(); for(Transition tran : nextEnabledList) { nextEnabledSet.add(tran); } extendedNextEnabledArray[i] = nextEnabledSet; //non_disabling for(Transition curTran : curEnabledSet) { if(curTran == firedTran) continue; if(nextEnabledSet.contains(curTran) == false) { int[] nextMarking = nextStateArray[i].getMarking(); // Not sure if the code below is correct. int[] preset = lpnList[i].getLpn().getPresetIndex(curTran.getName()); boolean included = true; if (preset != null && preset.length > 0) { for (int pp : preset) { boolean temp = false; for (int mi = 0; mi < nextMarking.length; mi++) { if (nextMarking[mi] == pp) { temp = true; break; } } if (temp == false) { included = false; break; } } } if(preset==null || preset.length==0 || included==true) { extendedNextEnabledArray[i].add(curTran); } } } } boolean deadlock=true; for(int i = 0; i < arraySize; i++) { if(extendedNextEnabledArray[i].size() != 0){ deadlock = false; break; } } if(deadlock==true) { failure = true; break main_while_loop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. LpnState[] nextLpnStateArray = new LpnState[arraySize]; for(int i = 0; i < arraySize; i++) { HashSet<Transition> lpnEnabledSet = new HashSet<Transition>(); for(Transition tran : extendedNextEnabledArray[i]) { lpnEnabledSet.add(tran); } LpnState tmp = new LpnState(lpnList[i].getLpn(), nextStateArray[i], lpnEnabledSet); LpnState tmpCached = (LpnState)(lpnStateCache[i].add(tmp)); nextLpnStateArray[i] = tmpCached; } boolean newState = globalStateTbl.add(new PrjLpnState(nextLpnStateArray)); if(newState == false) { traceCex.removeLast(); continue; } stateStack.push(nextLpnStateArray); LpnTranList[] nextEnabledSet = new LpnTranList[2]; LpnTranList fireFirstTrans = new LpnTranList(); LpnTranList otherTrans = new LpnTranList(); for(int i = 0; i < arraySize; i++) { for(Transition tran : nextLpnStateArray[i].getEnabled()) { if(firingOrder == true) if(curLpnStateArray[i].getEnabled().contains(tran)) otherTrans.add(tran); else fireFirstTrans.add(tran); else fireFirstTrans.add(tran); } } nextEnabledSet[0] = fireFirstTrans; nextEnabledSet[1] = otherTrans; lpnTranStack.push(nextEnabledSet); }// END while (stateStack.empty() == false) // graph.write(String.format("graph_%s_%s-tran_%s-state.gv",mode,tranFiringCnt, // prjStateSet.size())); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + globalStateTbl.size() + ", max_stack_depth: " + max_stack_depth); /* * by looking at stateStack, generate the trace showing the counter-example. */ if (failure == true) { System.out.println(" System.out.println("the deadlock trace:"); //update traceCex from stateStack // LpnState[] cur = null; // LpnState[] next = null; for(Transition tran : traceCex) System.out.println(tran.getFullLabel()); } System.out.println("Modules' local states: "); for (int i = 0; i < arraySize; i++) { System.out.println("module " + lpnList[i].getLpn().getLabel() + ": " + lpnList[i].reachSize()); } return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * When a state is considered during DFS, only one enabled transition is * selected to fire in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_1(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_1"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 500; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean compressed = false; boolean failure = false; int tranFiringCnt = 0; int totalStates = 1; int arraySize = lpnList.length; int newStateCnt = 0; Stack<State[]> stateStack = new Stack<State[]>(); Stack<LinkedList<Transition>> lpnTranStack = new Stack<LinkedList<Transition>>(); Stack<Integer> curIndexStack = new Stack<Integer>(); mddNode reachAll = null; mddNode reach = mddMgr.newNode(); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, initStateArray, true); mddMgr.add(reach, localIdxArray, compressed); stateStack.push(initStateArray); LpnTranList initEnabled = lpnList[0].getEnabled(initStateArray[0]); lpnTranStack.push(initEnabled.clone()); curIndexStack.push(0); int numMddCompression = 0; main_while_loop: while (failure == false && stateStack.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 100000 == 0) { long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", stack depth: " + stateStack.size() + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); numMddCompression++; if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); if(memUpBound < 1500) memUpBound *= numMddCompression; } } State[] curStateArray = stateStack.peek(); int curIndex = curIndexStack.peek(); LinkedList<Transition> curEnabled = lpnTranStack.peek(); // If all enabled transitions of the current LPN are considered, // then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, // then pop the stacks. if (curEnabled.size() == 0) { lpnTranStack.pop(); curIndexStack.pop(); curIndex++; while (curIndex < arraySize) { LpnTranList enabledCached = (lpnList[curIndex].getEnabled(curStateArray[curIndex])); if (enabledCached.size() > 0) { curEnabled = enabledCached.clone(); lpnTranStack.push(curEnabled); curIndexStack.push(curIndex); break; } else curIndex++; } } if (curIndex == arraySize) { stateStack.pop(); continue; } Transition firedTran = curEnabled.removeLast(); State[] nextStateArray = lpnList[curIndex].fire(lpnList, curStateArray,firedTran, null, null); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError( curEnabledArray[i], nextEnabledArray[i]); if (disabledTran != null) { System.err.println("Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. * if not, add it into reachable set, and push it onto stack. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, true); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; if (existingState == false) { mddMgr.add(reach, localIdxArray, compressed); newStateCnt++; stateStack.push(nextStateArray); lpnTranStack.push((LpnTranList) nextEnabledArray[0].clone()); curIndexStack.push(0); totalStates++; } } double totalStateCnt = mddMgr.numberOfStates(reach); System.out.println("---> run statistics: \n" + "# LPN transition firings: " + tranFiringCnt + "\n" + "# of prjStates found: " + totalStateCnt + "\n" + "max_stack_depth: " + max_stack_depth + "\n" + "peak MDD nodes: " + peakMddNodeCnt + "\n" + "peak used memory: " + peakUsedMem / 1000000 + " MB\n" + "peak total memory: " + peakTotalMem / 1000000 + " MB\n"); return null; } /** * findsg using iterative approach based on DFS search. The states found are * stored in MDD. * * It is similar to findsg_dfs_mdd_1 except that when a state is considered * during DFS, all enabled transition are fired, and all its successor * states are found in an iteration. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public Stack<State[]> search_dfs_mdd_2(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> calling function search_dfs_mdd_2"); int tranFiringCnt = 0; int totalStates = 0; int arraySize = lpnList.length; long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. boolean failure = false; MDT state2Explore = new MDT(arraySize); state2Explore.push(initStateArray); totalStates++; long peakState2Explore = 0; Stack<Integer> searchDepth = new Stack<Integer>(); searchDepth.push(1); boolean compressed = false; mddNode reachAll = null; mddNode reach = mddMgr.newNode(); main_while_loop: while (failure == false && state2Explore.empty() == false) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; iterations++; if (iterations % 100000 == 0) { int mddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > mddNodeCnt ? peakMddNodeCnt : mddNodeCnt; int state2ExploreSize = state2Explore.size(); peakState2Explore = peakState2Explore > state2ExploreSize ? peakState2Explore : state2ExploreSize; System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", # states to explore: " + state2ExploreSize + ", # MDT nodes: " + state2Explore.nodeCnt() + ", total MDD nodes: " + mddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachAll == null) reachAll = reach; else { mddNode newReachAll = mddMgr.union(reachAll, reach); if (newReachAll != reachAll) { mddMgr.remove(reachAll); reachAll = newReachAll; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } } State[] curStateArray = state2Explore.pop(); State[] nextStateArray = null; int states2ExploreCurLevel = searchDepth.pop(); if(states2ExploreCurLevel > 1) searchDepth.push(states2ExploreCurLevel-1); int[] localIdxArray = Analysis.getLocalStateIdxArray(lpnList, curStateArray, false); mddMgr.add(reach, localIdxArray, compressed); int nextStates2Explore = 0; for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; State curState = curStateArray[index]; LinkedList<Transition> curEnabledSet = curLpn.getEnabled(curState); LpnTranList curEnabled = (LpnTranList) curEnabledSet.clone(); while (curEnabled.size() > 0) { Transition firedTran = curEnabled.removeLast(); // TODO: (check) Not sure if curLpn.fire is correct. nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran, null, null); tranFiringCnt++; for (int i = 0; i < arraySize; i++) { StateGraph lpn_tmp = lpnList[i]; if (curStateArray[i] == nextStateArray[i]) continue; LinkedList<Transition> curEnabled_l = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabled = lpn_tmp.getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled_l, nextEnabled); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.err.println("Verification failed: deadlock."); failure = true; break main_while_loop; } /* * Check if the local indices of nextStateArray already exist. */ localIdxArray = Analysis.getLocalStateIdxArray(lpnList, nextStateArray, false); Boolean existingState = false; if (reachAll != null && mddMgr.contains(reachAll, localIdxArray) == true) existingState = true; else if (mddMgr.contains(reach, localIdxArray) == true) existingState = true; else if(state2Explore.contains(nextStateArray)==true) existingState = true; if (existingState == false) { totalStates++; //mddMgr.add(reach, localIdxArray, compressed); state2Explore.push(nextStateArray); nextStates2Explore++; } } } if(nextStates2Explore > 0) searchDepth.push(nextStates2Explore); } endoffunction: System.out.println(" + "---> run statistics: \n" + " # Depth of search (Length of Cex): " + searchDepth.size() + "\n" + " # LPN transition firings: " + (double)tranFiringCnt/1000000 + " M\n" + " # of prjStates found: " + (double)totalStates / 1000000 + " M\n" + " peak states to explore : " + (double) peakState2Explore / 1000000 + " M\n" + " peak MDD nodes: " + peakMddNodeCnt + "\n" + " peak used memory: " + peakUsedMem / 1000000 + " MB\n" + " peak total memory: " + peakTotalMem /1000000 + " MB\n" + "_____________________________________"); return null; } public LinkedList<Transition> search_bfs(final StateGraph[] sgList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; long peakMddNodeCnt = 0; int memUpBound = 1000; // Set an upper bound of memory in MB usage to // trigger MDD compression. int arraySize = sgList.length; for (int i = 0; i < arraySize; i++) sgList[i].addState(initStateArray[i]); mddNode reachSet = null; mddNode reach = mddMgr.newNode(); MDT frontier = new MDT(arraySize); MDT image = new MDT(arraySize); frontier.push(initStateArray); State[] curStateArray = null; int tranFiringCnt = 0; int totalStates = 0; int imageSize = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; long curMddNodeCnt = mddMgr.nodeCnt(); peakMddNodeCnt = peakMddNodeCnt > curMddNodeCnt ? peakMddNodeCnt : curMddNodeCnt; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + totalStates + ", total MDD nodes: " + curMddNodeCnt + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); if (curUsedMem >= memUpBound * 1000000) { mddMgr.compress(reach); if (reachSet == null) reachSet = reach; else { mddNode newReachSet = mddMgr.union(reachSet, reach); if (newReachSet != reachSet) { mddMgr.remove(reachSet); reachSet = newReachSet; } } mddMgr.remove(reach); reach = mddMgr.newNode(); } while(frontier.empty() == false) { boolean deadlock = true; // Stack<State[]> curStateArrayList = frontier.pop(); // while(curStateArrayList.empty() == false) { // curStateArray = curStateArrayList.pop(); { curStateArray = frontier.pop(); int[] localIdxArray = Analysis.getLocalStateIdxArray(sgList, curStateArray, false); mddMgr.add(reach, localIdxArray, false); totalStates++; for (int i = 0; i < arraySize; i++) { LinkedList<Transition> curEnabled = sgList[i].getEnabled(curStateArray[i]); if (curEnabled.size() > 0) deadlock = false; for (Transition firedTran : curEnabled) { // TODO: (check) Not sure if sgList[i].fire is correct. State[] nextStateArray = sgList[i].fire(sgList, curStateArray, firedTran, null, null); tranFiringCnt++; /* * Check if any transitions can be disabled by fireTran. */ LinkedList<Transition> nextEnabled = sgList[i].getEnabled(nextStateArray[i]); Transition disabledTran = firedTran.disablingError(curEnabled, nextEnabled); if (disabledTran != null) { System.err.println("*** Verification failed: disabling error: " + disabledTran.getFullLabel() + " disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } localIdxArray = Analysis.getLocalStateIdxArray(sgList, nextStateArray, false); if (mddMgr.contains(reachSet, localIdxArray) == false && mddMgr.contains(reach, localIdxArray) == false && frontier.contains(nextStateArray) == false) { if(image.contains(nextStateArray)==false) { image.push(nextStateArray); imageSize++; } } } } } /* * If curStateArray deadlocks (no enabled transitions), terminate. */ if (deadlock == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } } if(image.empty()==true) break; System.out.println("---> size of image: " + imageSize); frontier = image; image = new MDT(arraySize); imageSize = 0; } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt / 1000000 + "M\n" + "---> # of prjStates found: " + (double) totalStates / 1000000 + "M\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MDD nodes: " + peakMddNodeCnt); return null; } /** * BFS findsg using iterative approach. THe states found are stored in MDD. * * @param lpnList * @param curLocalStateArray * @param enabledArray * @return a linked list of a sequence of LPN transitions leading to the * failure if it is not empty. */ public LinkedList<Transition> search_bfs_mdd_localFirings(final StateGraph[] lpnList, final State[] initStateArray) { System.out.println("---> starting search_bfs"); long peakUsedMem = 0; long peakTotalMem = 0; int arraySize = lpnList.length; for (int i = 0; i < arraySize; i++) lpnList[i].addState(initStateArray[i]); // mddNode reachSet = mddMgr.newNode(); // mddMgr.add(reachSet, curLocalStateArray); mddNode reachSet = null; mddNode exploredSet = null; LinkedList<State>[] nextSetArray = (LinkedList<State>[]) (new LinkedList[arraySize]); for (int i = 0; i < arraySize; i++) nextSetArray[i] = new LinkedList<State>(); mddNode initMdd = mddMgr.doLocalFirings(lpnList, initStateArray, null); mddNode curMdd = initMdd; reachSet = curMdd; mddNode nextMdd = null; int[] curStateArray = null; int tranFiringCnt = 0; boolean verifyError = false; bfsWhileLoop: while (true) { if (verifyError == true) break; long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; curStateArray = mddMgr.next(curMdd, curStateArray); if (curStateArray == null) { // Break the loop if no new next states are found. // System.out.println("nextSet size " + nextSet.size()); if (nextMdd == null) break bfsWhileLoop; if (exploredSet == null) exploredSet = curMdd; else { mddNode newExplored = mddMgr.union(exploredSet, curMdd); if (newExplored != exploredSet) mddMgr.remove(exploredSet); exploredSet = newExplored; } mddMgr.remove(curMdd); curMdd = nextMdd; nextMdd = null; iterations++; System.out.println("iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of union calls: " + mddNode.numCalls + ", # of union cache nodes: " + mddNode.cacheNodes + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); System.out.println("---> # of prjStates found: " + mddMgr.numberOfStates(reachSet) + ", CurSet.Size = " + mddMgr.numberOfStates(curMdd)); continue; } if (exploredSet != null && mddMgr.contains(exploredSet, curStateArray) == true) continue; // If curStateArray deadlocks (no enabled transitions), terminate. if (Analysis.deadLock(lpnList, curStateArray) == true) { System.err.println("*** Verification failed: deadlock."); verifyError = true; break bfsWhileLoop; } // Do firings of non-local LPN transitions. for (int index = arraySize - 1; index >= 0; index StateGraph curLpn = lpnList[index]; LinkedList<Transition> curLocalEnabled = curLpn.getEnabled(curStateArray[index]); if (curLocalEnabled.size() == 0 || curLocalEnabled.getFirst().isLocal() == true) continue; for (Transition firedTran : curLocalEnabled) { if (firedTran.isLocal() == true) continue; // TODO: (check) Not sure if curLpn.fire is correct. State[] nextStateArray = curLpn.fire(lpnList, curStateArray, firedTran); tranFiringCnt++; @SuppressWarnings("unused") ArrayList<LinkedList<Transition>> nextEnabledArray = new ArrayList<LinkedList<Transition>>(1); for (int i = 0; i < arraySize; i++) { if (curStateArray[i] == nextStateArray[i].getIndex()) continue; StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> curEnabledList = lpn_tmp.getEnabled(curStateArray[i]); LinkedList<Transition> nextEnabledList = lpn_tmp.getEnabled(nextStateArray[i].getIndex()); Transition disabledTran = firedTran.disablingError(curEnabledList, nextEnabledList); if (disabledTran != null) { System.err.println("Verification failed: disabling error: " + disabledTran.getFullLabel() + ": is disabled by " + firedTran.getFullLabel() + "!!!"); verifyError = true; break bfsWhileLoop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { verifyError = true; break bfsWhileLoop; } // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the // next // enabled transition. int[] nextIdxArray = Analysis.getIdxArray(nextStateArray); if (reachSet != null && mddMgr.contains(reachSet, nextIdxArray) == true) continue; mddNode newNextMdd = mddMgr.doLocalFirings(lpnList, nextStateArray, reachSet); mddNode newReachSet = mddMgr.union(reachSet, newNextMdd); if (newReachSet != reachSet) mddMgr.remove(reachSet); reachSet = newReachSet; if (nextMdd == null) nextMdd = newNextMdd; else { mddNode tmpNextMdd = mddMgr.union(nextMdd, newNextMdd); if (tmpNextMdd != nextMdd) mddMgr.remove(nextMdd); nextMdd = tmpNextMdd; mddMgr.remove(newNextMdd); } } } } System.out.println("---> final numbers: # LPN transition firings: " + tranFiringCnt + "\n" + "---> # of prjStates found: " + (mddMgr.numberOfStates(reachSet)) + "\n" + "---> peak total memory: " + peakTotalMem / 1000000F + " MB\n" + "---> peak used memory: " + peakUsedMem / 1000000F + " MB\n" + "---> peak MMD nodes: " + mddMgr.peakNodeCnt()); return null; } /** * partial order reduction * * @param lpnList * @param curLocalStateArray * @param enabledArray */ public Stack<State[]> search_dfs_por(final StateGraph[] lpnList, final State[] initStateArray, LPNTranRelation lpnTranRelation, String approach) { System.out.println("---> Calling search_dfs with partial order reduction"); long peakUsedMem = 0; long peakTotalMem = 0; double stateCount = 1; int max_stack_depth = 0; int iterations = 0; boolean useMdd = true; mddNode reach = mddMgr.newNode(); //init por verification.platu.por1.AmpleSet ampleClass = new verification.platu.por1.AmpleSet(); //AmpleSubset ampleClass = new AmpleSubset(); HashMap<Transition,HashSet<Transition>> indepTranSet = new HashMap<Transition,HashSet<Transition>>(); if(approach == "state") indepTranSet = ampleClass.getIndepTranSet_FromState(lpnList, lpnTranRelation); else if (approach == "lpn") indepTranSet = ampleClass.getIndepTranSet_FromLPN(lpnList); System.out.println("finish get independent set!!!!"); boolean failure = false; int tranFiringCnt = 0; int arraySize = lpnList.length;; HashSet<PrjState> stateStack = new HashSet<PrjState>(); Stack<LpnTranList> lpnTranStack = new Stack<LpnTranList>(); Stack<HashSet<Transition>> firedTranStack = new Stack<HashSet<Transition>>(); //get initial enable transition set @SuppressWarnings("unchecked") LinkedList<Transition>[] initEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); initEnabledArray[i] = lpnList[i].getEnabled(initStateArray[i]); } //set initEnableSubset //LPNTranSet initEnableSubset = ampleClass.generateAmpleList(false, approach,initEnabledArray, indepTranSet); LpnTranList initEnableSubset = ampleClass.generateAmpleTranSet(initEnabledArray, indepTranSet); /* * Initialize the reach state set with the initial state. */ HashSet<PrjState> prjStateSet = new HashSet<PrjState>(); PrjState initPrjState = new PrjState(initStateArray); if (useMdd) { int[] initIdxArray = Analysis.getIdxArray(initStateArray); mddMgr.add(reach, initIdxArray, true); } else prjStateSet.add(initPrjState); stateStack.add(initPrjState); PrjState stateStackTop = initPrjState; lpnTranStack.push(initEnableSubset); firedTranStack.push(new HashSet<Transition>()); /* * Start the main search loop. */ main_while_loop: while(failure == false && stateStack.size() != 0) { long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); if (curTotalMem > peakTotalMem) peakTotalMem = curTotalMem; if (curUsedMem > peakUsedMem) peakUsedMem = curUsedMem; if (stateStack.size() > max_stack_depth) max_stack_depth = stateStack.size(); iterations++; if (iterations % 500000 == 0) { if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); System.out.println("---> #iteration " + iterations + "> # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", total MDD nodes: " + mddMgr.nodeCnt() + " used memory: " + (float) curUsedMem / 1000000 + " free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); } State[] curStateArray = stateStackTop.toStateArray(); LpnTranList curEnabled = lpnTranStack.peek(); // for (LPNTran tran : curEnabled) // for (int i = 0; i < arraySize; i++) // if (lpnList[i] == tran.getLpn()) // if (tran.isEnabled(curStateArray[i]) == false) { // System.out.println("transition " + tran.getFullLabel() + " not enabled in the current state"); // System.exit(0); // If all enabled transitions of the current LPN are considered, then consider the next LPN // by increasing the curIndex. // Otherwise, if all enabled transitions of all LPNs are considered, then pop the stacks. if(curEnabled.size() == 0) { lpnTranStack.pop(); firedTranStack.pop(); stateStack.remove(stateStackTop); stateStackTop = stateStackTop.getFather(); if (stateStack.size() > 0) traceCex.removeLast(); continue; } Transition firedTran = curEnabled.removeFirst(); firedTranStack.peek().add(firedTran); traceCex.addLast(firedTran); //System.out.println(tranFiringCnt + ": firedTran: "+ firedTran.getFullLabel()); // TODO: (??) Not sure if the state graph sg below is correct. StateGraph sg = null; for (int i=0; i<lpnList.length; i++) { if (lpnList[i].getLpn().equals(firedTran.getLpn())) { sg = lpnList[i]; } } State[] nextStateArray = sg.fire(lpnList, curStateArray, firedTran, null, null); tranFiringCnt++; // Check if the firedTran causes disabling error or deadlock. @SuppressWarnings("unchecked") LinkedList<Transition>[] curEnabledArray = new LinkedList[arraySize]; @SuppressWarnings("unchecked") LinkedList<Transition>[] nextEnabledArray = new LinkedList[arraySize]; for (int i = 0; i < arraySize; i++) { lpnList[i].getLpn().setLpnIndex(i); StateGraph lpn_tmp = lpnList[i]; LinkedList<Transition> enabledList = lpn_tmp.getEnabled(curStateArray[i]); curEnabledArray[i] = enabledList; enabledList = lpn_tmp.getEnabled(nextStateArray[i]); nextEnabledArray[i] = enabledList; Transition disabledTran = firedTran.disablingError(curEnabledArray[i], nextEnabledArray[i]); if(disabledTran != null) { System.out.println("---> Disabling Error: " + disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); System.out.println("Current state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(curStateArray[ii]); System.out.println("Enabled set: " + curEnabledArray[ii]); } System.out.println("======================\nNext state:"); for(int ii = 0; ii < arraySize; ii++) { System.out.println("module " + lpnList[ii].getLpn().getLabel()); System.out.println(nextStateArray[ii]); System.out.println("Enabled set: " + nextEnabledArray[ii]); } System.out.println(); failure = true; break main_while_loop; } } if (Analysis.deadLock(lpnList, nextStateArray) == true) { System.out.println("---> Deadlock."); // System.out.println("Deadlock state:"); // for(int ii = 0; ii < arraySize; ii++) { // System.out.println("module " + lpnList[ii].getLabel()); // System.out.println(nextStateArray[ii]); // System.out.println("Enabled set: " + nextEnabledArray[ii]); failure = true; break main_while_loop; } /* // Add nextPrjState into prjStateSet // If nextPrjState has been traversed before, skip to the next // enabled transition. //exist cycle */ PrjState nextPrjState = new PrjState(nextStateArray); boolean isExisting = false; int[] nextIdxArray = null; if(useMdd==true) nextIdxArray = Analysis.getIdxArray(nextStateArray); if (useMdd == true) isExisting = mddMgr.contains(reach, nextIdxArray); else isExisting = prjStateSet.contains(nextPrjState); if (isExisting == false) { if (useMdd == true) { mddMgr.add(reach, nextIdxArray, true); } else prjStateSet.add(nextPrjState); //get next enable transition set //LPNTranSet nextEnableSubset = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextEnableSubset = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // LPNTranSet nextEnableSubset = new LPNTranSet(); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // nextEnableSubset.addLast(tran); stateStack.add(nextPrjState); stateStackTop.setChild(nextPrjState); nextPrjState.setFather(stateStackTop); stateStackTop = nextPrjState; lpnTranStack.push(nextEnableSubset); firedTranStack.push(new HashSet<Transition>()); // for (int i = 0; i < arraySize; i++) // for (LPNTran tran : nextEnabledArray[i]) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for (LPNTran tran : nextEnableSubset) // System.out.print(tran.getFullLabel() + ", "); // HashSet<LPNTran> allEnabledSet = new HashSet<LPNTran>(); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : nextEnabledArray[i]) { // allEnabledSet.add(tran); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // if(nextEnableSubset.size() > 0) { // for (LPNTran tran : nextEnableSubset) { // if (allEnabledSet.contains(tran) == false) { // System.out.println("\n\n" + tran.getFullLabel() + " in reduced set but not enabled\n"); // System.exit(0); // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n continue; } /* * Remove firedTran from traceCex if its successor state already exists. */ traceCex.removeLast(); /* * When firedTran forms a cycle in the state graph, consider all enabled transitions except those * 1. already fired in the current state, * 2. in the ample set of the next state. */ if(stateStack.contains(nextPrjState)==true && curEnabled.size()==0) { //System.out.println("formed a cycle......"); LpnTranList original = new LpnTranList(); LpnTranList reduced = new LpnTranList(); //LPNTranSet nextStateAmpleSet = ampleClass.generateAmpleList(false, approach, nextEnabledArray, indepTranSet); LpnTranList nextStateAmpleSet = ampleClass.generateAmpleTranSet(nextEnabledArray, indepTranSet); // System.out.println("Back state's ample set:"); // for(LPNTran tran : nextStateAmpleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); int enabledTranCnt = 0; LpnTranList[] tmp = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) { tmp[i] = new LpnTranList(); for (Transition tran : curEnabledArray[i]) { original.addLast(tran); if (firedTranStack.peek().contains(tran)==false && nextStateAmpleSet.contains(tran)==false) { tmp[i].addLast(tran); reduced.addLast(tran); enabledTranCnt++; } } } LpnTranList ampleSet = new LpnTranList(); if(enabledTranCnt > 0) //ampleSet = ampleClass.generateAmpleList(false, approach, tmp, indepTranSet); ampleSet = ampleClass.generateAmpleTranSet(tmp, indepTranSet); LpnTranList sortedAmpleSet = ampleSet; /* * Sort transitions in ampleSet for better performance for MDD. * Not needed for hash table. */ if (useMdd == true) { LpnTranList[] newCurEnabledArray = new LpnTranList[arraySize]; for (int i = 0; i < arraySize; i++) newCurEnabledArray[i] = new LpnTranList(); for (Transition tran : ampleSet) newCurEnabledArray[tran.getLpn().getLpnIndex()].addLast(tran); sortedAmpleSet = new LpnTranList(); for (int i = 0; i < arraySize; i++) { LpnTranList localEnabledSet = newCurEnabledArray[i]; for (Transition tran : localEnabledSet) sortedAmpleSet.addLast(tran); } } // for(LPNTran tran : original) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : ampleSet) // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : firedTranStack.peek()) // allCurEnabled.remove(tran); lpnTranStack.pop(); lpnTranStack.push(sortedAmpleSet); // for (int i = 0; i < arraySize; i++) { // for (LPNTran tran : curEnabledArray[i]) { // System.out.print(tran.getFullLabel() + ", "); // System.out.println("\n"); // for(LPNTran tran : allCurEnabled) // System.out.print(tran.getFullLabel() + ", "); } //System.out.println("Backtrack........\n"); }//END while (stateStack.empty() == false) if (useMdd==true) stateCount = mddMgr.numberOfStates(reach); else stateCount = prjStateSet.size(); //long curTotalMem = Runtime.getRuntime().totalMemory(); long curUsedMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("SUMMARY: # LPN transition firings: " + tranFiringCnt + ", # of prjStates found: " + stateCount + ", max_stack_depth: " + max_stack_depth + ", used memory: " + (float) curUsedMem / 1000000 + ", free memory: " + (float) Runtime.getRuntime().freeMemory() / 1000000); return null; } // /** // * Check if this project deadlocks in the current state 'stateArray'. // * @param sgList // * @param stateArray // * @param staticSetsMap // * @param enableSet // * @param disableByStealingToken // * @param disableSet // * @param init // * @return // */ // // Called by search search_dfsPOR // public boolean deadLock(StateGraph[] sgList, State[] stateArray, HashMap<LpnTransitionPair,StaticSets> staticSetsMap, // boolean init, HashMap<LpnTransitionPair, Integer> tranFiringFreq, HashSet<PrjState> stateStack, PrjState stateStackTop, int cycleClosingMethdIndex) { // boolean deadlock = true; // System.out.println("@ deadlock:"); //// for (int i = 0; i < stateArray.length; i++) { //// LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); //// if (tmp.size() > 0) { //// deadlock = false; //// break; // LinkedList<Transition> tmp = getAmple(stateArray, null, staticSetsMap, init, tranFiringFreq, sgList, stateStack, stateStackTop, cycleClosingMethdIndex).getAmpleSet(); // if (tmp.size() > 0) { // deadlock = false; // System.out.println("@ end of deadlock"); // return deadlock; public static boolean deadLock(StateGraph[] lpnArray, State[] stateArray) { boolean deadlock = true; for (int i = 0; i < stateArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } public static boolean deadLock(StateGraph[] lpnArray, int[] stateIdxArray) { boolean deadlock = true; for (int i = 0; i < stateIdxArray.length; i++) { LinkedList<Transition> tmp = lpnArray[i].getEnabled(stateIdxArray[i]); if (tmp.size() > 0) { deadlock = false; break; } } return deadlock; } // /* // * Scan enabledArray, identify all sticky transitions other the firedTran, and return them. // * // * Arguments remain constant. // */ // public static LpnTranList[] getStickyTrans(LpnTranList[] enabledArray, Transition firedTran) { // int arraySize = enabledArray.length; // LpnTranList[] stickyTranArray = new LpnTranList[arraySize]; // for (int i = 0; i < arraySize; i++) { // stickyTranArray[i] = new LpnTranList(); // for (Transition tran : enabledArray[i]) { // if (tran != firedTran) // stickyTranArray[i].add(tran); // if(stickyTranArray[i].size()==0) // stickyTranArray[i] = null; // return stickyTranArray; /** * Identify if any sticky transitions in currentStickyTransArray can existing in the nextState. If so, add them to * nextStickyTransArray. * * Arguments: curStickyTransArray and nextState are constant, nextStickyTransArray may be added with sticky transitions * from curStickyTransArray. * * Return: sticky transitions from curStickyTransArray that are not marking disabled in nextState. */ public static LpnTranList[] checkStickyTrans( LpnTranList[] curStickyTransArray, LpnTranList[] nextEnabledArray, LpnTranList[] nextStickyTransArray, State nextState, LhpnFile LPN) { int arraySize = curStickyTransArray.length; LpnTranList[] stickyTransArray = new LpnTranList[arraySize]; boolean[] hasStickyTrans = new boolean[arraySize]; for (int i = 0; i < arraySize; i++) { HashSet<Transition> tmp = new HashSet<Transition>(); if(nextStickyTransArray[i] != null) for(Transition tran : nextStickyTransArray[i]) tmp.add(tran); stickyTransArray[i] = new LpnTranList(); hasStickyTrans[i] = false; for (Transition tran : curStickyTransArray[i]) { if (tran.isPersistent() == true && tmp.contains(tran)==false) { int[] nextMarking = nextState.getMarking(); int[] preset = LPN.getPresetIndex(tran.getName());//tran.getPreSet(); boolean included = false; if (preset != null && preset.length > 0) { for (int pp : preset) { for (int mi = 0; i < nextMarking.length; i++) { if (nextMarking[mi] == pp) { included = true; break; } } if (included == false) break; } } if(preset==null || preset.length==0 || included==true) { stickyTransArray[i].add(tran); hasStickyTrans[i] = true; } } } if(stickyTransArray[i].size()==0) stickyTransArray[i] = null; } return stickyTransArray; } /* * Return an array of indices for the given stateArray. */ private static int[] getIdxArray(State[] stateArray) { int[] idxArray = new int[stateArray.length]; for(int i = 0; i < stateArray.length; i++) { idxArray[i] = stateArray[i].getIndex(); } return idxArray; } private static int[] getLocalStateIdxArray(StateGraph[] sgList, State[] stateArray, boolean reverse) { int arraySize = sgList.length; int[] localIdxArray = new int[arraySize]; for(int i = 0; i < arraySize; i++) { if(reverse == false) localIdxArray[i] = sgList[i].getLocalState(stateArray[i]).getIndex(); else localIdxArray[arraySize - i - 1] = sgList[i].getLocalState(stateArray[i]).getIndex(); //System.out.print(localIdxArray[i] + " "); } //System.out.println(); return localIdxArray; } private void printEnabledSetTbl(StateGraph[] sgList) { for (int i=0; i<sgList.length; i++) { System.out.println("******* enabledSetTbl for " + sgList[i].getLpn().getLabel() + " **********"); for (State s : sgList[i].getEnabledSetTbl().keySet()) { System.out.print("S" + s.getIndex() + " -> "); printTransitionSet(sgList[i].getEnabledSetTbl().get(s), ""); } } } private HashSet<LpnTransitionPair> partialOrderReductionUsingDependencyGraphs(State[] curStateArray, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<LpnTransitionPair> ready = new HashSet<LpnTransitionPair>(); LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) { lpnList[i] = sgList[i].getLpn(); } // enabledTran is independent of other transitions for (LpnTransitionPair enabledTran : curEnabled) { if (staticMap.get(enabledTran).getDisableSet().isEmpty()) { ready.add(enabledTran); return ready; } } for (LpnTransitionPair enabledTran : curEnabled) { if (Options.getDebugMode()) { System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set."); writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + "). Compute its dependent set."); } HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); if (ready.isEmpty()) ready = (HashSet<LpnTransitionPair>) dependent.clone(); else if (dependent.size() < ready.size() && !ready.isEmpty()) ready = (HashSet<LpnTransitionPair>) dependent.clone(); if (ready.size() == 1) { cachedNecessarySets.clear(); return ready; } } cachedNecessarySets.clear(); return ready; } private HashSet<LpnTransitionPair> partialOrderReduction(State[] curStateArray, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, HashMap<LpnTransitionPair,Integer> tranFiringFreqMap, StateGraph[] sgList) { if (curEnabled.size() == 1) return curEnabled; HashSet<LpnTransitionPair> ready = null; LhpnFile[] lpnList = new LhpnFile[sgList.length]; for (int i=0; i<sgList.length; i++) { lpnList[i] = sgList[i].getLpn(); } DependentSetComparator depComp = new DependentSetComparator(tranFiringFreqMap); PriorityQueue<DependentSet> dependentSetQueue = new PriorityQueue<DependentSet>(curEnabled.size(), depComp); for (LpnTransitionPair enabledTran : curEnabled) { if (Options.getDebugMode()){ System.out.println("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("@ partialOrderReduction, consider transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() + "("+ sgList[enabledTran.getLpnIndex()].getLpn().getTransition(enabledTran.getTranIndex()) + ")"); } HashSet<LpnTransitionPair> dependent = new HashSet<LpnTransitionPair>(); Transition enabledTransition = sgList[enabledTran.getLpnIndex()].getLpn().getAllTransitions()[enabledTran.getTranIndex()]; boolean enabledIsDummy = false; boolean isCycleClosingAmpleComputation = false; dependent = computeDependent(curStateArray,enabledTran,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation); // printIntegerSet(dependent, sgList, "dependent set for enabled transition " + sgList[enabledTran.getLpnIndex()].getLpn().getLabel() // + "(" + enabledTransition.getName() + ")"); // TODO: temporarily dealing with dummy transitions (This requires the dummy transitions to have "_dummy" in their names.) if(isDummyTran(enabledTransition.getName())) enabledIsDummy = true; DependentSet dependentSet = new DependentSet(dependent, enabledTran, enabledIsDummy); dependentSetQueue.add(dependentSet); // if (ready.isEmpty()) // ready = (HashSet<LpnTransitionPair>) dependent.clone(); // else if (dependent.size() < ready.size() && !ready.isEmpty()) // ready = (HashSet<LpnTransitionPair>) dependent.clone(); // if (ready.size() == 1) { // cachedNecessarySets.clear(); // return ready; } cachedNecessarySets.clear(); ready = dependentSetQueue.poll().getDependent(); return ready; } private boolean isDummyTran(String tranName) { if (tranName.contains("_dummy")) return true; else return false; } private HashSet<LpnTransitionPair> computeDependent(State[] curStateArray, LpnTransitionPair seedTran, HashSet<LpnTransitionPair> dependent, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList, boolean isCycleClosingAmpleComputation) { // disableSet is the set of transitions that can be disabled by firing enabledLpnTran, or can disable enabledLpnTran. HashSet<LpnTransitionPair> disableSet = staticMap.get(seedTran).getDisableSet(); HashSet<LpnTransitionPair> otherTransDisableEnabledTran = staticMap.get(seedTran).getOtherTransDisableCurTranSet(); if (Options.getDebugMode()) { System.out.println("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName()); //printIntegerSet(canModifyAssign, lpnList, lpnList[enabledLpnTran.getLpnIndex()].getTransition(enabledLpnTran.getTranIndex()) + " can modify assignments"); printIntegerSet(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeStringWithNewLineToPORDebugFile("@ getDependentSet, consider transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName()); writeIntegerSetToPORDebugFile(disableSet, lpnList, "Disable set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } dependent.add(seedTran); // for (LpnTransitionPair lpnTranPair : canModifyAssign) { // if (curEnabled.contains(lpnTranPair)) // dependent.add(lpnTranPair); if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 0, dependent set for " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } // // dependent is equal to enabled. Terminate. // if (dependent.size() == curEnabled.size()) { // if (Options.getDebugMode()) // System.out.println("Check 0: dependent == curEnabled. Return dependent."); // return dependent; for (LpnTransitionPair tranInDisableSet : disableSet) { if (Options.getDebugMode()) { System.out.println("Consider transition in the disable set of " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() +"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("Consider transition in the disable set of " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "): " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() +"(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); } boolean tranInDisableSetIsPersistent = lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).isPersistent(); if (curEnabled.contains(tranInDisableSet) && !dependent.contains(tranInDisableSet) && (!tranInDisableSetIsPersistent || otherTransDisableEnabledTran.contains(tranInDisableSet))) { dependent.addAll(computeDependent(curStateArray,tranInDisableSet,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation)); if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 1 for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } } else if (!curEnabled.contains(tranInDisableSet)) { if(Options.getPOR().toLowerCase().equals("tboff") // no trace-back || (Options.getCycleClosingAmpleMethd().toLowerCase().equals("cctboff") && isCycleClosingAmpleComputation)) { dependent.addAll(curEnabled); break; } LpnTransitionPair origTran = new LpnTransitionPair(tranInDisableSet.getLpnIndex(), tranInDisableSet.getTranIndex()); HashSet<LpnTransitionPair> necessary = null; if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } if (cachedNecessarySets.containsKey(tranInDisableSet)) { if (Options.getDebugMode()) { System.out.println("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets."); writeStringWithNewLineToPORDebugFile("Found transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()).getName() + ") in the cached necessary sets."); } necessary = cachedNecessarySets.get(tranInDisableSet); } else { if (Options.getNecessaryUsingDependencyGraphs()) { if (Options.getDebugMode()) { System.out.println("==== Compute necessary using BFS ===="); writeStringWithNewLineToPORDebugFile("==== Compute necessary using BFS ===="); } necessary = computeNecessaryUsingDependencyGraphs(curStateArray,tranInDisableSet,curEnabled, staticMap, lpnList); } else { if (Options.getDebugMode()) { System.out.println("==== Compute necessary using DFS ===="); writeStringWithNewLineToPORDebugFile("==== Compute necessary using DFS ===="); } necessary = computeNecessary(curStateArray,tranInDisableSet,dependent,curEnabled, staticMap, lpnList, origTran); } } if (necessary != null && !necessary.isEmpty()) { cachedNecessarySets.put(tranInDisableSet, necessary); if (Options.getDebugMode()) { printIntegerSet(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); writeIntegerSetToPORDebugFile(necessary, lpnList, "necessary set for transition " + lpnList[tranInDisableSet.getLpnIndex()].getLabel() + "(" + lpnList[tranInDisableSet.getLpnIndex()].getTransition(tranInDisableSet.getTranIndex()) + ")"); } for (LpnTransitionPair tranNecessary : necessary) { if (!dependent.contains(tranNecessary)) { if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):"); System.out.println("It does not contain this transition found by computeNecessary: " + lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")" + ". Compute its dependent set."); writeIntegerSetToPORDebugFile(dependent, lpnList, "Dependent set for " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + "):"); writeStringWithNewLineToPORDebugFile("It does not contain this transition found by computeNecessary: " + lpnList[tranNecessary.getLpnIndex()].getLabel() + "(" + lpnList[tranNecessary.getLpnIndex()].getTransition(tranNecessary.getTranIndex()) + ")" + ". Compute its dependent set."); } dependent.addAll(computeDependent(curStateArray,tranNecessary,dependent,curEnabled,staticMap, lpnList, isCycleClosingAmpleComputation)); } } } else { if (Options.getDebugMode()) { System.out.println("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty."); writeStringWithNewLineToPORDebugFile("necessary set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()) + " is empty."); } dependent.addAll(curEnabled); } if (Options.getDebugMode()) { printIntegerSet(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); writeIntegerSetToPORDebugFile(dependent, lpnList, "@ getDependentSet at 2, dependent set for transition " + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex())); } } } return dependent; } @SuppressWarnings("unchecked") private HashSet<LpnTransitionPair> computeNecessary(State[] curStateArray, LpnTransitionPair tran, HashSet<LpnTransitionPair> dependent, HashSet<LpnTransitionPair> curEnabledIndices, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList, LpnTransitionPair origTran) { if (Options.getDebugMode()) { System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")"); } if (cachedNecessarySets.containsKey(tran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. "); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. "); } return cachedNecessarySets.get(tran); } // Search for transition(s) that can help to bring the marking(s). HashSet<LpnTransitionPair> nMarking = null; Transition transition = lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()); int[] presetPlaces = lpnList[tran.getLpnIndex()].getPresetIndex(transition.getName()); for (int i=0; i < presetPlaces.length; i++) { int place = presetPlaces[i]; if (curStateArray[tran.getLpnIndex()].getMarking()[place]==0) { if (Options.getDebugMode()) { System.out.println(" + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + " writeStringWithNewLineToPORDebugFile(" + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") " + " } HashSet<LpnTransitionPair> nMarkingTemp = new HashSet<LpnTransitionPair>(); String placeName = lpnList[tran.getLpnIndex()].getAllPlaces().get(place); if (Options.getDebugMode()) { System.out.println("preset place of " + transition.getName() + " is " + placeName); writeStringWithNewLineToPORDebugFile("preset place of " + transition.getName() + " is " + placeName); } int[] presetTrans = lpnList[tran.getLpnIndex()].getPresetIndex(placeName); for (int j=0; j < presetTrans.length; j++) { LpnTransitionPair presetTran = new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]); if (Options.getDebugMode()) { System.out.println("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("preset transition of " + placeName + " is " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ")"); } if (origTran.getVisitedTrans().contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); writeStringWithNewLineToPORDebugFile("Transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); } if (cachedNecessarySets.containsKey(presetTran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nMarkingTemp = cachedNecessarySets.get(presetTran); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[presetTran.getLpnIndex()].getLabel() + "(" + lpnList[presetTran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); } nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j]));; } continue; } else origTran.addVisitedTran(presetTran); if (Options.getDebugMode()) { System.out.println("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~"); writeStringWithNewLineToPORDebugFile("~~~~~~~~~ transVisited for transition " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")~~~~~~~~~"); for (LpnTransitionPair visitedTran : origTran.getVisitedTrans()) { System.out.println(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") "); writeStringWithNewLineToPORDebugFile(lpnList[visitedTran.getLpnIndex()].getLabel() + "(" + lpnList[visitedTran.getLpnIndex()].getTransition(visitedTran.getTranIndex()).getName() + ") "); } System.out.println("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ")."); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ")."); } if (curEnabledIndices.contains(presetTran)) { if (Options.getDebugMode()) { System.out.println("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); writeStringWithNewLineToPORDebugFile("@ nMarking: curEnabled contains transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTran.getTranIndex()).getName() + "). Add to nMarkingTmp."); } nMarkingTemp.add(new LpnTransitionPair(tran.getLpnIndex(), presetTrans[j])); } else { if (Options.getDebugMode()) { System.out.println("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set."); writeStringWithNewLineToPORDebugFile("@ nMarking: transition " + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + " is not enabled. Compute its necessary set."); } HashSet<LpnTransitionPair> tmp = null; tmp = computeNecessary(curStateArray, presetTran, dependent, curEnabledIndices, staticMap, lpnList, origTran); if (tmp != null) nMarkingTemp.addAll(tmp); else if (Options.getDebugMode()) { System.out.println("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null."); writeStringWithNewLineToPORDebugFile("@ nMarking: necessary set for transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(presetTrans[j]).getName() + ") is null."); } } } if (nMarkingTemp != null) if (nMarking == null || nMarkingTemp.size() < nMarking.size()) nMarking = (HashSet<LpnTransitionPair>) nMarkingTemp.clone(); } else if (Options.getDebugMode()) { System.out.println("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked."); writeStringWithNewLineToPORDebugFile("Place " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getAllPlaces().get(place) + ") is marked."); } } // Search for transition(s) that can help to enable the current transition. HashSet<LpnTransitionPair> nEnable = null; int[] varValueVector = curStateArray[tran.getLpnIndex()].getVector();//curState.getVector(); HashSet<LpnTransitionPair> canEnable = staticMap.get(tran).getEnableBySettingEnablingTrue(); if (Options.getDebugMode()) { System.out.println(" printIntegerSet(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") can be enabled by"); writeStringWithNewLineToPORDebugFile(" writeIntegerSetToPORDebugFile(canEnable, lpnList, lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()) + ") can be enabled by"); } if (transition.getEnablingTree() != null && transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0 && !canEnable.isEmpty()) { nEnable = new HashSet<LpnTransitionPair>(); for (LpnTransitionPair tranCanEnable : canEnable) { if (curEnabledIndices.contains(tranCanEnable)) { nEnable.add(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable."); writeStringWithNewLineToPORDebugFile("@ nEnable: curEnabled contains transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + "). Add to nEnable."); } } else { if (origTran.getVisitedTrans().contains(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); writeStringWithNewLineToPORDebugFile("Transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()) + ") is visted before by " + lpnList[origTran.getLpnIndex()].getLabel() + "(" + lpnList[origTran.getLpnIndex()].getTransition(origTran.getTranIndex()).getName() + ")."); } if (cachedNecessarySets.containsKey(tranCanEnable)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Add it to nMarkingTemp."); } nEnable.addAll(cachedNecessarySets.get(tranCanEnable)); } continue; } else origTran.addVisitedTran(tranCanEnable); if (Options.getDebugMode()) { System.out.println("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + " is not enabled. Compute its necessary set."); } HashSet<LpnTransitionPair> tmp = null; tmp = computeNecessary(curStateArray, tranCanEnable, dependent, curEnabledIndices, staticMap, lpnList, origTran); if (tmp != null) nEnable.addAll(tmp); else if (Options.getDebugMode()) { System.out.println("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null."); writeStringWithNewLineToPORDebugFile("@ nEnable: necessary set for transition " + lpnList[tranCanEnable.getLpnIndex()].getLabel() + "(" + lpnList[tranCanEnable.getLpnIndex()].getTransition(tranCanEnable.getTranIndex()).getName() + ") is null."); } } } } if (Options.getDebugMode()) { if (transition.getEnablingTree() == null) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ") has no enabling condition."); } else if (transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) !=0.0) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is true."); } else if (transition.getEnablingTree() != null && transition.getEnablingTree().evaluateExpr(lpnList[tran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0 && canEnable.isEmpty()) { System.out.println("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is false, but no other transitions that can help to enable it were found ."); writeStringWithNewLineToPORDebugFile("@ nEnable: transition " + lpnList[tran.getLpnIndex()].getLabel() + "(" + lpnList[tran.getLpnIndex()].getTransition(tran.getTranIndex()).getName() + ")'s enabling condition is false, but no other transitions that can help to enable it were found ."); } printIntegerSet(nMarking, lpnList, "nMarking for transition " + transition.getName()); printIntegerSet(nEnable, lpnList, "nEnable for transition " + transition.getName()); writeIntegerSetToPORDebugFile(nMarking, lpnList, "nMarking for transition " + transition.getName()); writeIntegerSetToPORDebugFile(nEnable, lpnList, "nEnable for transition " + transition.getName()); } if (nEnable == null && nMarking != null) { if (!nMarking.isEmpty()) cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } else if (nMarking == null && nEnable != null) { if (!nEnable.isEmpty()) cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } // else if (nMarking == null && nEnable == null) { // return null; else { if (!nMarking.isEmpty() && !nEnable.isEmpty()) { if (getIntSetSubstraction(nMarking, dependent).size() < getIntSetSubstraction(nEnable, dependent).size()) { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } else { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } } else if (nMarking.isEmpty() && !nEnable.isEmpty()) { cachedNecessarySets.put(tran, nEnable); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nEnable; } else { cachedNecessarySets.put(tran, nMarking); if (Options.getDebugMode()) { printCachedNecessarySets(lpnList); writeCachedNecessarySetsToPORDebugFile(lpnList); } return nMarking; } } } private HashSet<LpnTransitionPair> computeNecessaryUsingDependencyGraphs(State[] curStateArray, LpnTransitionPair seedTran, HashSet<LpnTransitionPair> curEnabled, HashMap<LpnTransitionPair, StaticSets> staticMap, LhpnFile[] lpnList) { if (Options.getDebugMode()) { System.out.println("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName() + ")"); writeStringWithNewLineToPORDebugFile("@ getNecessary, consider transition: " + lpnList[seedTran.getLpnIndex()].getLabel() + "(" + lpnList[seedTran.getLpnIndex()].getTransition(seedTran.getTranIndex()).getName() + ")"); } // Use breadth-first search to find the shorted path from the seed transition to an enabled transition. LinkedList<LpnTransitionPair> exploredTransQueue = new LinkedList<LpnTransitionPair>(); HashSet<LpnTransitionPair> allExploredTrans = new HashSet<LpnTransitionPair>(); exploredTransQueue.add(seedTran); //boolean foundEnabledTran = false; HashSet<LpnTransitionPair> canEnable = new HashSet<LpnTransitionPair>(); while(!exploredTransQueue.isEmpty()){ LpnTransitionPair curTran = exploredTransQueue.poll(); allExploredTrans.add(curTran); if (cachedNecessarySets.containsKey(curTran)) { if (Options.getDebugMode()) { System.out.println("Found transition" + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Terminate BFS."); writeStringWithNewLineToPORDebugFile("Found transition" + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()).getName() + ")" + "'s necessary set in the cached necessary sets. Terminate BFS."); } return cachedNecessarySets.get(curTran); } canEnable = buildCanBringTokenSet(curTran,lpnList, curStateArray); // Decide if canSetEnablingTrue set can help to enable curTran. Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); int[] varValueVector = curStateArray[curTran.getLpnIndex()].getVector(); if (curTransition.getEnablingTree() != null && curTransition.getEnablingTree().evaluateExpr(lpnList[curTran.getLpnIndex()].getAllVarsWithValuesAsString(varValueVector)) == 0.0) canEnable.addAll(staticMap.get(curTran).getEnableBySettingEnablingTrue()); if (Options.getDebugMode()) { printIntegerSet(canEnable, lpnList, "Neighbors that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); writeIntegerSetToPORDebugFile(canEnable, lpnList, "Neighbors that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + ") "); } for (LpnTransitionPair neighborTran : canEnable) { if (curEnabled.contains(neighborTran)) { HashSet<LpnTransitionPair> necessarySet = new HashSet<LpnTransitionPair>(); necessarySet.add(neighborTran); // TODO: Is it true that the necessary set for a disabled transition only contains a single element before the dependent set of the element is computed? cachedNecessarySets.put(seedTran, necessarySet); if (Options.getDebugMode()) { System.out.println("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")"); writeStringWithNewLineToPORDebugFile("Enabled neighbor that can help to enable trnasition " + lpnList[curTran.getLpnIndex()].getLabel() + "(" + lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()) + "): " + lpnList[neighborTran.getLpnIndex()].getLabel() + "(" + lpnList[neighborTran.getLpnIndex()].getTransition(neighborTran.getTranIndex()) + ")"); } return necessarySet; } if (!allExploredTrans.contains(neighborTran)) { allExploredTrans.add(neighborTran); exploredTransQueue.add(neighborTran); } } canEnable.clear(); } return null; } private HashSet<LpnTransitionPair> buildCanBringTokenSet( LpnTransitionPair curTran, LhpnFile[] lpnList, State[] curStateArray) { // Build transition(s) set that can help to bring the marking(s). Transition curTransition = lpnList[curTran.getLpnIndex()].getTransition(curTran.getTranIndex()); int[] presetPlaces = lpnList[curTran.getLpnIndex()].getPresetIndex(curTransition.getName()); HashSet<LpnTransitionPair> canBringToken = new HashSet<LpnTransitionPair>(); for (int i=0; i < presetPlaces.length; i++) { int place = presetPlaces[i]; if (curStateArray[curTran.getLpnIndex()].getMarking()[place]==0) { String placeName = lpnList[curTran.getLpnIndex()].getAllPlaces().get(place); int[] presetTrans = lpnList[curTran.getLpnIndex()].getPresetIndex(placeName); for (int j=0; j < presetTrans.length; j++) { LpnTransitionPair presetTran = new LpnTransitionPair(curTran.getLpnIndex(), presetTrans[j]); canBringToken.add(presetTran); } } } return canBringToken; } private void printCachedNecessarySets(LhpnFile[] lpnList) { System.out.println("================ cachedNecessarySets ================="); for (LpnTransitionPair key : cachedNecessarySets.keySet()) { System.out.print(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => "); HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key); for (LpnTransitionPair necessary : necessarySet) { System.out.print(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") "); } System.out.print("\n"); } } private void writeCachedNecessarySetsToPORDebugFile(LhpnFile[] lpnList) { writeStringWithNewLineToPORDebugFile("================ cachedNecessarySets ================="); for (LpnTransitionPair key : cachedNecessarySets.keySet()) { writeStringToPORDebugFile(lpnList[key.getLpnIndex()].getLabel() + "(" + lpnList[key.getLpnIndex()].getTransition(key.getTranIndex()).getName() + ") => "); HashSet<LpnTransitionPair> necessarySet = cachedNecessarySets.get(key); for (LpnTransitionPair necessary : necessarySet) { writeStringToPORDebugFile(lpnList[necessary.getLpnIndex()].getLabel() + "(" + lpnList[necessary.getLpnIndex()].getTransition(necessary.getTranIndex()).getName() + ") "); } writeStringWithNewLineToPORDebugFile(""); } } private HashSet<LpnTransitionPair> getIntSetSubstraction( HashSet<LpnTransitionPair> left, HashSet<LpnTransitionPair> right) { HashSet<LpnTransitionPair> sub = new HashSet<LpnTransitionPair>(); for (LpnTransitionPair lpnTranPair : left) { if (!right.contains(lpnTranPair)) sub.add(lpnTranPair); } return sub; } // private LpnTranList getSetSubtraction(LpnTranList left, LpnTranList right) { // LpnTranList sub = new LpnTranList(); // for (Transition lpnTran : left) { // if (!right.contains(lpnTran)) // sub.add(lpnTran); // return sub; public boolean stateOnStack(int lpnIndex, State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); if (stateArray[lpnIndex] == curState) { isStateOnStack = true; break; } } return isStateOnStack; } private void printIntegerSet(HashSet<LpnTransitionPair> indicies, StateGraph[] sgList, String setName) { if (!setName.isEmpty()) System.out.print(setName + ": "); if (indicies == null) { System.out.println("null"); } else if (indicies.isEmpty()) { System.out.println("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { System.out.print("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "(" + sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } System.out.print("\n"); } } private void writeIntegerSetToPORDebugFile(HashSet<LpnTransitionPair> indicies, StateGraph[] sgList, String setName) { if (!setName.isEmpty()) writeStringToPORDebugFile(setName + ": "); if (indicies == null) { writeStringWithNewLineToPORDebugFile("null"); } else if (indicies.isEmpty()) { writeStringWithNewLineToPORDebugFile("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { writeStringToPORDebugFile("\t" + sgList[lpnTranPair.getLpnIndex()].getLpn().getLabel() + "(" + sgList[lpnTranPair.getLpnIndex()].getLpn().getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } writeStringWithNewLineToPORDebugFile(""); } } private void printIntegerSet(HashSet<LpnTransitionPair> indicies, LhpnFile[] lpnList, String setName) { if (!setName.isEmpty()) System.out.print(setName + ": "); if (indicies == null) { System.out.println("null"); } else if (indicies.isEmpty()) { System.out.println("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { System.out.print(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "(" + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } System.out.print("\n"); } } private void writeIntegerSetToPORDebugFile(HashSet<LpnTransitionPair> indicies, LhpnFile[] lpnList, String setName) { if (!setName.isEmpty()) writeStringToPORDebugFile(setName + ": "); if (indicies == null) { writeStringWithNewLineToPORDebugFile("null"); } else if (indicies.isEmpty()) { writeStringWithNewLineToPORDebugFile("empty"); } else { for (LpnTransitionPair lpnTranPair : indicies) { writeStringToPORDebugFile(lpnList[lpnTranPair.getLpnIndex()].getLabel() + "(" + lpnList[lpnTranPair.getLpnIndex()].getAllTransitions()[lpnTranPair.getTranIndex()].getName() + ") \t"); } writeStringWithNewLineToPORDebugFile(""); } } }
package de.hebis.it.hds.gnd.in.subfields; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class PersonFields { private final static Logger LOG = LogManager.getLogger(PersonFields.class); /** * Personal name &lt;datafield tag="100"&gt;.<br> * Subfields will be stored in the form "$a $b &lt;$c&gt;. (schema:prefered)<br> * * @param dataField The content of the data field */ public static void personalName(DataField dataField) { if (LOG.isTraceEnabled()) LOG.trace(dataField.getRecordId() + ": in method"); StringBuilder fullName = buildFormatedName(dataField); if ((fullName != null) && (fullName.length() > 0)) { dataField.storeUnique("preferred", fullName.toString()); } } /** * Alternative names &lt;datafield tag="400"&gt;.<br> * Subfields will be stored in the form "$a $b &lt;$c&gt;. (schema:synonyms)<br> * * @param dataField The content of the data field */ public static void tracingPersonalName(DataField dataField) { if (LOG.isTraceEnabled()) LOG.trace(dataField.getRecordId() + ": in method"); StringBuilder fullName = buildFormatedName(dataField); if ((fullName != null) && (fullName.length() > 0)) { dataField.storeMultiValued("synonyms", fullName.toString()); } // is a 2nd pass required? if ("navi".equals(dataField.getSub9SubField('4'))) { if (LOG.isDebugEnabled()) LOG.debug(dataField.getRecordId() + ": Real name in synonyms found."); dataField.replaceUnique("look4me", "true"); } } /** * Related personal names &lt;datafield tag="500"&gt;.<br> * Subfield '$0' into (schema:relatedIds)<br> * Subfield '$a' into (schema:related)<br> * * @param dataField The content of the data field */ public static void relatedPersonalName(DataField dataField) { if (LOG.isTraceEnabled()) LOG.trace(dataField.getRecordId() + ": in method"); dataField.storeValues("0", "relatedIds", true, "https?://d-nb.info.*"); // dismiss redundant URI dataField.storeValues("a", "related", true, null); } /** * Alternative names in other systems &lt;datafield tag="700"&gt;.<br> * Subfield '$a' is taken as alias. (schema:synonyms)<br> * Optional trailing informations "ABC%DE3..." will be removed. Result: "ABC" * * @param dataField The content of the data field */ public static void linkingEntryPersonalName(DataField dataField) { if (LOG.isTraceEnabled()) LOG.trace(dataField.getRecordId() + ": in method"); String altName = dataField.getFirstValue("a"); dataField.storeMultiValued("synonyms", altName.replaceAll("%DE.*", "")); dataField.storeValues("0", "sameAs", true, "http.+"); // no URLs } private static StringBuilder buildFormatedName(DataField dataField) { // name String name = dataField.getFirstValue("a"); if (name == null) { LOG.warn(dataField.getRecordId() + ": Field 100 without $a."); return null; } StringBuilder fullName = new StringBuilder(); fullName.append(name); // nummeration String numeration = dataField.getFirstValue("b"); if (numeration != null) { fullName.append(' '); fullName.append(numeration); } // title(s) List<String> titles = dataField.get("c"); if (titles != null) { for (Object title : titles) { fullName.append(" <"); fullName.append((String) title); fullName.append('>'); } } return fullName; } }
package com.jme3.input; import com.jme3.app.Application; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.InputListener; import com.jme3.input.controls.JoyAxisTrigger; import com.jme3.input.controls.JoyButtonTrigger; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseAxisTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.input.controls.TouchListener; import com.jme3.input.controls.TouchTrigger; import com.jme3.input.controls.Trigger; import com.jme3.input.event.InputEvent; import com.jme3.input.event.JoyAxisEvent; import com.jme3.input.event.JoyButtonEvent; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.input.event.TouchEvent; import com.jme3.math.FastMath; import com.jme3.math.Vector2f; import com.jme3.util.IntMap; import com.jme3.util.IntMap.Entry; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * The <code>InputManager</code> is responsible for converting input events * received from the Key, Mouse and Joy Input implementations into an * abstract, input device independent representation that user code can use. * <p> * By default an <code>InputManager</code> is included with every Application instance for use * in user code to query input, unless the Application is created as headless * or with input explicitly disabled. * <p> * The input manager has two concepts, a {@link Trigger} and a mapping. * A trigger represents a specific input trigger, such as a key button, * or a mouse axis. A mapping represents a link onto one or several triggers, * when the appropriate trigger is activated (e.g. a key is pressed), the * mapping will be invoked. Any listeners registered to receive an event * from the mapping will have an event raised. * <p> * There are two types of events that {@link InputListener input listeners} * can receive, one is {@link ActionListener#onAction(java.lang.String, boolean, float) action} * events and another is {@link AnalogListener#onAnalog(java.lang.String, float, float) analog} * events. * <p> * <code>onAction</code> events are raised when the specific input * activates or deactivates. For a digital input such as key press, the <code>onAction()</code> * event will be raised with the <code>isPressed</code> argument equal to true, * when the key is released, <code>onAction</code> is called again but this time * with the <code>isPressed</code> argument set to false. * For analog inputs, the <code>onAction</code> method will be called any time * the input is non-zero, however an exception to this is for joystick axis inputs, * which are only called when the input is above the {@link InputManager#setAxisDeadZone(float) dead zone}. * <p> * <code>onAnalog</code> events are raised every frame while the input is activated. * For digital inputs, every frame that the input is active will cause the * <code>onAnalog</code> method to be called, the argument <code>value</code> * argument will equal to the frame's time per frame (TPF) value but only * for digital inputs. For analog inputs however, the <code>value</code> argument * will equal the actual analog value. */ public class InputManager implements RawInputListener { private static final Logger logger = Logger.getLogger(InputManager.class.getName()); private final KeyInput keys; private final MouseInput mouse; private final JoyInput joystick; private final TouchInput touch; private float frameTPF; private long lastLastUpdateTime = 0; private long lastUpdateTime = 0; private long frameDelta = 0; private long firstTime = 0; private boolean eventsPermitted = false; private boolean mouseVisible = true; private boolean safeMode = false; private float axisDeadZone = 0.05f; private Vector2f cursorPos = new Vector2f(); private Joystick[] joysticks; private final IntMap<ArrayList<Mapping>> bindings = new IntMap<ArrayList<Mapping>>(); private final HashMap<String, Mapping> mappings = new HashMap<String, Mapping>(); private final IntMap<Long> pressedButtons = new IntMap<Long>(); private final IntMap<Float> axisValues = new IntMap<Float>(); private ArrayList<RawInputListener> rawListeners = new ArrayList<RawInputListener>(); private RawInputListener[] rawListenerArray = null; private ArrayList<InputEvent> inputQueue = new ArrayList<InputEvent>(); private static class Mapping { private final String name; private final ArrayList<Integer> triggers = new ArrayList<Integer>(); private final ArrayList<InputListener> listeners = new ArrayList<InputListener>(); public Mapping(String name) { this.name = name; } } public InputManager(MouseInput mouse, KeyInput keys, JoyInput joystick, TouchInput touch) { if (keys == null || mouse == null) { throw new NullPointerException("Mouse or keyboard cannot be null"); } this.keys = keys; this.mouse = mouse; this.joystick = joystick; this.touch = touch; keys.setInputListener(this); mouse.setInputListener(this); if (joystick != null) { joystick.setInputListener(this); joysticks = joystick.loadJoysticks(this); } if (touch != null) { touch.setInputListener(this); } firstTime = keys.getInputTimeNanos(); } private void invokeActions(int hash, boolean pressed) { ArrayList<Mapping> maps = bindings.get(hash); if (maps == null) { return; } int size = maps.size(); for (int i = size - 1; i >= 0; i Mapping mapping = maps.get(i); ArrayList<InputListener> listeners = mapping.listeners; int listenerSize = listeners.size(); for (int j = listenerSize - 1; j >= 0; j InputListener listener = listeners.get(j); if (listener instanceof ActionListener) { ((ActionListener) listener).onAction(mapping.name, pressed, frameTPF); } } } } private float computeAnalogValue(long timeDelta) { if (safeMode || frameDelta == 0) { return 1f; } else { return FastMath.clamp((float) timeDelta / (float) frameDelta, 0, 1); } } private void invokeTimedActions(int hash, long time, boolean pressed) { if (!bindings.containsKey(hash)) { return; } if (pressed) { pressedButtons.put(hash, time); } else { Long pressTimeObj = pressedButtons.remove(hash); if (pressTimeObj == null) { return; // under certain circumstances it can be null, ignore } // the event then. long pressTime = pressTimeObj; long lastUpdate = lastLastUpdateTime; long releaseTime = time; long timeDelta = releaseTime - Math.max(pressTime, lastUpdate); if (timeDelta > 0) { invokeAnalogs(hash, computeAnalogValue(timeDelta), false); } } } private void invokeUpdateActions() { for (Entry<Long> pressedButton : pressedButtons) { int hash = pressedButton.getKey(); long pressTime = pressedButton.getValue(); long timeDelta = lastUpdateTime - Math.max(lastLastUpdateTime, pressTime); if (timeDelta > 0) { invokeAnalogs(hash, computeAnalogValue(timeDelta), false); } } for (Entry<Float> axisValue : axisValues) { int hash = axisValue.getKey(); float value = axisValue.getValue(); invokeAnalogs(hash, value * frameTPF, true); } } private void invokeAnalogs(int hash, float value, boolean isAxis) { ArrayList<Mapping> maps = bindings.get(hash); if (maps == null) { return; } if (!isAxis) { value *= frameTPF; } int size = maps.size(); for (int i = size - 1; i >= 0; i Mapping mapping = maps.get(i); ArrayList<InputListener> listeners = mapping.listeners; int listenerSize = listeners.size(); for (int j = listenerSize - 1; j >= 0; j InputListener listener = listeners.get(j); if (listener instanceof AnalogListener) { // NOTE: multiply by TPF for any button bindings ((AnalogListener) listener).onAnalog(mapping.name, value, frameTPF); } } } } private void invokeAnalogsAndActions(int hash, float value, boolean applyTpf) { if (value < axisDeadZone) { invokeAnalogs(hash, value, !applyTpf); return; } ArrayList<Mapping> maps = bindings.get(hash); if (maps == null) { return; } boolean valueChanged = !axisValues.containsKey(hash); if (applyTpf) { value *= frameTPF; } int size = maps.size(); for (int i = size - 1; i >= 0; i Mapping mapping = maps.get(i); ArrayList<InputListener> listeners = mapping.listeners; int listenerSize = listeners.size(); for (int j = listenerSize - 1; j >= 0; j InputListener listener = listeners.get(j); if (listener instanceof ActionListener && valueChanged) { ((ActionListener) listener).onAction(mapping.name, true, frameTPF); } if (listener instanceof AnalogListener) { ((AnalogListener) listener).onAnalog(mapping.name, value, frameTPF); } } } } /** * Callback from RawInputListener. Do not use. */ public void beginInput() { } /** * Callback from RawInputListener. Do not use. */ public void endInput() { } private void onJoyAxisEventQueued(JoyAxisEvent evt) { // for (int i = 0; i < rawListeners.size(); i++){ // rawListeners.get(i).onJoyAxisEvent(evt); int joyId = evt.getJoyIndex(); int axis = evt.getAxisIndex(); float value = evt.getValue(); if (value < axisDeadZone && value > -axisDeadZone) { int hash1 = JoyAxisTrigger.joyAxisHash(joyId, axis, true); int hash2 = JoyAxisTrigger.joyAxisHash(joyId, axis, false); Float val1 = axisValues.get(hash1); Float val2 = axisValues.get(hash2); if (val1 != null && val1.floatValue() > axisDeadZone) { invokeActions(hash1, false); } if (val2 != null && val2.floatValue() > axisDeadZone) { invokeActions(hash2, false); } axisValues.remove(hash1); axisValues.remove(hash2); } else if (value < 0) { int hash = JoyAxisTrigger.joyAxisHash(joyId, axis, true); int otherHash = JoyAxisTrigger.joyAxisHash(joyId, axis, false); invokeAnalogsAndActions(hash, -value, true); axisValues.put(hash, -value); axisValues.remove(otherHash); } else { int hash = JoyAxisTrigger.joyAxisHash(joyId, axis, false); int otherHash = JoyAxisTrigger.joyAxisHash(joyId, axis, true); invokeAnalogsAndActions(hash, value, true); axisValues.put(hash, value); axisValues.remove(otherHash); } } /** * Callback from RawInputListener. Do not use. */ public void onJoyAxisEvent(JoyAxisEvent evt) { if (!eventsPermitted) { throw new UnsupportedOperationException("JoyInput has raised an event at an illegal time."); } inputQueue.add(evt); } private void onJoyButtonEventQueued(JoyButtonEvent evt) { // for (int i = 0; i < rawListeners.size(); i++){ // rawListeners.get(i).onJoyButtonEvent(evt); int hash = JoyButtonTrigger.joyButtonHash(evt.getJoyIndex(), evt.getButtonIndex()); invokeActions(hash, evt.isPressed()); invokeTimedActions(hash, evt.getTime(), evt.isPressed()); } /** * Callback from RawInputListener. Do not use. */ public void onJoyButtonEvent(JoyButtonEvent evt) { if (!eventsPermitted) { throw new UnsupportedOperationException("JoyInput has raised an event at an illegal time."); } inputQueue.add(evt); } private void onMouseMotionEventQueued(MouseMotionEvent evt) { // for (int i = 0; i < rawListeners.size(); i++){ // rawListeners.get(i).onMouseMotionEvent(evt); if (evt.getDX() != 0) { float val = Math.abs(evt.getDX()) / 1024f; invokeAnalogsAndActions(MouseAxisTrigger.mouseAxisHash(MouseInput.AXIS_X, evt.getDX() < 0), val, false); } if (evt.getDY() != 0) { float val = Math.abs(evt.getDY()) / 1024f; invokeAnalogsAndActions(MouseAxisTrigger.mouseAxisHash(MouseInput.AXIS_Y, evt.getDY() < 0), val, false); } if (evt.getDeltaWheel() != 0) { float val = Math.abs(evt.getDeltaWheel()) / 100f; invokeAnalogsAndActions(MouseAxisTrigger.mouseAxisHash(MouseInput.AXIS_WHEEL, evt.getDeltaWheel() < 0), val, false); } } /** * Callback from RawInputListener. Do not use. */ public void onMouseMotionEvent(MouseMotionEvent evt) { if (!eventsPermitted) { throw new UnsupportedOperationException("MouseInput has raised an event at an illegal time."); } cursorPos.set(evt.getX(), evt.getY()); inputQueue.add(evt); } private void onMouseButtonEventQueued(MouseButtonEvent evt) { int hash = MouseButtonTrigger.mouseButtonHash(evt.getButtonIndex()); invokeActions(hash, evt.isPressed()); invokeTimedActions(hash, evt.getTime(), evt.isPressed()); } /** * Callback from RawInputListener. Do not use. */ public void onMouseButtonEvent(MouseButtonEvent evt) { if (!eventsPermitted) { throw new UnsupportedOperationException("MouseInput has raised an event at an illegal time."); } //updating cursor pos on click, so that non android touch events can properly update cursor position. cursorPos.set(evt.getX(), evt.getY()); inputQueue.add(evt); } private void onKeyEventQueued(KeyInputEvent evt) { if (evt.isRepeating()) { return; // repeat events not used for bindings } int hash = KeyTrigger.keyHash(evt.getKeyCode()); invokeActions(hash, evt.isPressed()); invokeTimedActions(hash, evt.getTime(), evt.isPressed()); } /** * Callback from RawInputListener. Do not use. */ public void onKeyEvent(KeyInputEvent evt) { if (!eventsPermitted) { throw new UnsupportedOperationException("KeyInput has raised an event at an illegal time."); } inputQueue.add(evt); } /** * Set the deadzone for joystick axes. * * <p>{@link ActionListener#onAction(java.lang.String, boolean, float) } * events will only be raised if the joystick axis value is greater than * the <code>deadZone</code>. * * @param deadZone the deadzone for joystick axes. */ public void setAxisDeadZone(float deadZone) { this.axisDeadZone = deadZone; } /** * Returns the deadzone for joystick axes. * * @return the deadzone for joystick axes. */ public float getAxisDeadZone() { return axisDeadZone; } /** * Adds a new listener to receive events on the given mappings. * * <p>The given InputListener will be registered to receive events * on the specified mapping names. When a mapping raises an event, the * listener will have its appropriate method invoked, either * {@link ActionListener#onAction(java.lang.String, boolean, float) } * or {@link AnalogListener#onAnalog(java.lang.String, float, float) } * depending on which interface the <code>listener</code> implements. * If the listener implements both interfaces, then it will receive the * appropriate event for each method. * * @param listener The listener to register to receive input events. * @param mappingNames The mapping names which the listener will receive * events from. * * @see InputManager#removeListener(com.jme3.input.controls.InputListener) */ public void addListener(InputListener listener, String... mappingNames) { for (String mappingName : mappingNames) { Mapping mapping = mappings.get(mappingName); if (mapping == null) { mapping = new Mapping(mappingName); mappings.put(mappingName, mapping); } if (!mapping.listeners.contains(listener)) { mapping.listeners.add(listener); } } } /** * Removes a listener from receiving events. * * <p>This will unregister the listener from any mappings that it * was previously registered with via * {@link InputManager#addListener(com.jme3.input.controls.InputListener, java.lang.String[]) }. * * @param listener The listener to unregister. * * @see InputManager#addListener(com.jme3.input.controls.InputListener, java.lang.String[]) */ public void removeListener(InputListener listener) { for (Mapping mapping : mappings.values()) { mapping.listeners.remove(listener); } } /** * Create a new mapping to the given triggers. * * <p> * The given mapping will be assigned to the given triggers, when * any of the triggers given raise an event, the listeners * registered to the mappings will receive appropriate events. * * @param mappingName The mapping name to assign. * @param triggers The triggers to which the mapping is to be registered. * * @see InputManager#deleteMapping(java.lang.String) */ public void addMapping(String mappingName, Trigger... triggers) { Mapping mapping = mappings.get(mappingName); if (mapping == null) { mapping = new Mapping(mappingName); mappings.put(mappingName, mapping); } for (Trigger trigger : triggers) { int hash = trigger.triggerHashCode(); ArrayList<Mapping> names = bindings.get(hash); if (names == null) { names = new ArrayList<Mapping>(); bindings.put(hash, names); } if (!names.contains(mapping)) { names.add(mapping); mapping.triggers.add(hash); } else { logger.log(Level.WARNING, "Attempted to add mapping \"{0}\" twice to trigger.", mappingName); } } } /** * Deletes a mapping from receiving trigger events. * * <p> * The given mapping will no longer be assigned to receive trigger * events. * * @param mappingName The mapping name to unregister. * * @see InputManager#addMapping(java.lang.String, com.jme3.input.controls.Trigger[]) */ public void deleteMapping(String mappingName) { Mapping mapping = mappings.remove(mappingName); if (mapping == null) { throw new IllegalArgumentException("Cannot find mapping: " + mappingName); } ArrayList<Integer> triggers = mapping.triggers; for (int i = triggers.size() - 1; i >= 0; i int hash = triggers.get(i); ArrayList<Mapping> maps = bindings.get(hash); maps.remove(mapping); } } /** * Deletes a specific trigger registered to a mapping. * * <p> * The given mapping will no longer receive events raised by the * trigger. * * @param mappingName The mapping name to cease receiving events from the * trigger. * @param trigger The trigger to no longer invoke events on the mapping. */ public void deleteTrigger(String mappingName, Trigger trigger) { Mapping mapping = mappings.get(mappingName); if (mapping == null) { throw new IllegalArgumentException("Cannot find mapping: " + mappingName); } ArrayList<Mapping> maps = bindings.get(trigger.triggerHashCode()); maps.remove(mapping); } /** * Clears all the input mappings from this InputManager. * Consequently, also clears all of the * InputListeners as well. */ public void clearMappings() { mappings.clear(); bindings.clear(); reset(); } /** * Do not use. * Called to reset pressed keys or buttons when focus is restored. */ public void reset() { pressedButtons.clear(); axisValues.clear(); } /** * Returns whether the mouse cursor is visible or not. * * <p>By default the cursor is visible. * * @param visible whether the mouse cursor is visible or not. * * @see InputManager#setCursorVisible(boolean) */ public boolean isCursorVisible() { return mouseVisible; } /** * Set whether the mouse cursor should be visible or not. * * @param visible whether the mouse cursor should be visible or not. */ public void setCursorVisible(boolean visible) { if (mouseVisible != visible) { mouseVisible = visible; mouse.setCursorVisible(mouseVisible); } } /** * Returns the current cursor position. The position is relative to the * bottom-left of the screen and is in pixels. * * @return the current cursor position */ public Vector2f getCursorPosition() { return cursorPos; } /** * Returns an array of all joysticks installed on the system. * * @return an array of all joysticks installed on the system. */ public Joystick[] getJoysticks() { return joysticks; } /** * Adds a {@link RawInputListener} to receive raw input events. * * <p> * Any raw input listeners registered to this <code>InputManager</code> * will receive raw input events first, before they get handled * by the <code>InputManager</code> itself. The listeners are * each processed in the order they were added, e.g. FIFO. * <p> * If a raw input listener has handled the event and does not wish * other listeners down the list to process the event, it may set the * {@link InputEvent#setConsumed() consumed flag} to indicate the * event was consumed and shouldn't be processed any further. * The listener may do this either at each of the event callbacks * or at the {@link RawInputListener#endInput() } method. * * @param listener A listener to receive raw input events. * * @see RawInputListener */ public void addRawInputListener(RawInputListener listener) { rawListeners.add(listener); rawListenerArray = null; } /** * Removes a {@link RawInputListener} so that it no longer * receives raw input events. * * @param listener The listener to cease receiving raw input events. * * @see InputManager#addRawInputListener(com.jme3.input.RawInputListener) */ public void removeRawInputListener(RawInputListener listener) { rawListeners.remove(listener); rawListenerArray = null; } /** * Clears all {@link RawInputListener}s. * * @see InputManager#addRawInputListener(com.jme3.input.RawInputListener) */ public void clearRawInputListeners() { rawListeners.clear(); rawListenerArray = null; } private RawInputListener[] getRawListenerArray() { if (rawListenerArray == null) rawListenerArray = rawListeners.toArray(new RawInputListener[rawListeners.size()]); return rawListenerArray; } /** * Enable simulation of mouse events. Used for touchscreen input only. * * @param value True to enable simulation of mouse events */ public void setSimulateMouse(boolean value) { if (touch != null) { touch.setSimulateMouse(value); } } /** * Enable simulation of keyboard events. Used for touchscreen input only. * * @param value True to enable simulation of keyboard events */ public void setSimulateKeyboard(boolean value) { if (touch != null) { touch.setSimulateKeyboard(value); } } private void processQueue() { int queueSize = inputQueue.size(); RawInputListener[] array = getRawListenerArray(); for (RawInputListener listener : array) { listener.beginInput(); for (int j = 0; j < queueSize; j++) { InputEvent event = inputQueue.get(j); if (event.isConsumed()) { continue; } if (event instanceof MouseMotionEvent) { listener.onMouseMotionEvent((MouseMotionEvent) event); } else if (event instanceof KeyInputEvent) { listener.onKeyEvent((KeyInputEvent) event); } else if (event instanceof MouseButtonEvent) { listener.onMouseButtonEvent((MouseButtonEvent) event); } else if (event instanceof JoyAxisEvent) { listener.onJoyAxisEvent((JoyAxisEvent) event); } else if (event instanceof JoyButtonEvent) { listener.onJoyButtonEvent((JoyButtonEvent) event); } else if (event instanceof TouchEvent) { listener.onTouchEvent((TouchEvent) event); } else { assert false; } } listener.endInput(); } for (int i = 0; i < queueSize; i++) { InputEvent event = inputQueue.get(i); if (event.isConsumed()) { continue; } if (event instanceof MouseMotionEvent) { onMouseMotionEventQueued((MouseMotionEvent) event); } else if (event instanceof KeyInputEvent) { onKeyEventQueued((KeyInputEvent) event); } else if (event instanceof MouseButtonEvent) { onMouseButtonEventQueued((MouseButtonEvent) event); } else if (event instanceof JoyAxisEvent) { onJoyAxisEventQueued((JoyAxisEvent) event); } else if (event instanceof JoyButtonEvent) { onJoyButtonEventQueued((JoyButtonEvent) event); } else if (event instanceof TouchEvent) { onTouchEventQueued((TouchEvent) event); } else { assert false; } // larynx, 2011.06.10 - flag event as reusable because // the android input uses a non-allocating ringbuffer which // needs to know when the event is not anymore in inputQueue // and therefor can be reused. event.setConsumed(); } inputQueue.clear(); } /** * Updates the <code>InputManager</code>. * This will query current input devices and send * appropriate events to registered listeners. * * @param tpf Time per frame value. */ public void update(float tpf) { frameTPF = tpf; // Activate safemode if the TPF value is so small // that rounding errors are inevitable safeMode = tpf < 0.015f; long currentTime = keys.getInputTimeNanos(); frameDelta = currentTime - lastUpdateTime; eventsPermitted = true; keys.update(); mouse.update(); if (joystick != null) { joystick.update(); } if (touch != null) { touch.update(); } eventsPermitted = false; processQueue(); invokeUpdateActions(); lastLastUpdateTime = lastUpdateTime; lastUpdateTime = currentTime; } /** * Dispatches touch events to touch listeners * @param evt The touch event to be dispatched to all onTouch listeners */ public void onTouchEventQueued(TouchEvent evt) { ArrayList<Mapping> maps = bindings.get(TouchTrigger.touchHash(evt.getKeyCode())); if (maps == null) { return; } int size = maps.size(); for (int i = size - 1; i >= 0; i Mapping mapping = maps.get(i); ArrayList<InputListener> listeners = mapping.listeners; int listenerSize = listeners.size(); for (int j = listenerSize - 1; j >= 0; j InputListener listener = listeners.get(j); if (listener instanceof TouchListener) { ((TouchListener) listener).onTouch(mapping.name, evt, frameTPF); } } } } /** * Callback from RawInputListener. Do not use. */ @Override public void onTouchEvent(TouchEvent evt) { if (!eventsPermitted) { throw new UnsupportedOperationException("TouchInput has raised an event at an illegal time."); } inputQueue.add(evt); } }
package org.voovan.tools; import org.voovan.Global; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.math.BigDecimal; import java.util.*; import java.util.concurrent.ThreadPoolExecutor; public class TPerformance { private static OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); public enum MEMTYPE{ NOHEAP_INIT, HEAP_INIT, NOHEAP_MAX, HEAP_MAX, NOHEAP_USAGE, HEAP_USAGE, NOHEAP_COMMIT, HEAP_COMMIT } /** * * @return */ public static double getSystemLoadAverage(){ return osmxb.getSystemLoadAverage(); } /** * CPU * @return CPU */ public static int getProcessorCount(){ return osmxb.getAvailableProcessors(); } /** * CPU * @return CPU */ public static double cpuPerCoreLoadAvg(){ double perCoreLoadAvg = osmxb.getSystemLoadAverage()/osmxb.getAvailableProcessors(); BigDecimal bg = new BigDecimal(perCoreLoadAvg); perCoreLoadAvg = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); return perCoreLoadAvg; } /** * JVM * @return * */ public static double getJvmMemoryUsage(){ //maxMemory()java, -Xmx //totalMemory()java //freeMemory() Runtime runtime = Runtime.getRuntime(); double memoryUsage = 1-((double)runtime.freeMemory()+(runtime.maxMemory()-runtime.totalMemory()))/(double)runtime.maxMemory(); BigDecimal bg = new BigDecimal(memoryUsage); memoryUsage = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); return memoryUsage; } /** * (,) * @param memType * @return */ public static long getJvmMemoryInfo(MEMTYPE memType){ if(memType==MEMTYPE.NOHEAP_INIT){ return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getInit(); } else if(memType==MEMTYPE.NOHEAP_MAX){ return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getMax(); } else if(memType==MEMTYPE.NOHEAP_USAGE){ return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed(); } else if(memType== MEMTYPE.NOHEAP_COMMIT){ return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getCommitted(); } else if(memType==MEMTYPE.HEAP_INIT){ return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getInit(); } else if(memType==MEMTYPE.HEAP_MAX){ return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax(); } else if(memType==MEMTYPE.HEAP_USAGE){ return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); } else if(memType==MEMTYPE.HEAP_COMMIT){ return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted(); }else{ throw new RuntimeException("getMemoryInfo function arg error!"); } } /** * * @return */ public static MemoryInfo getJvmMemoryInfo(){ MemoryInfo memoryInfo = new MemoryInfo(); memoryInfo.setHeapInit(getJvmMemoryInfo(MEMTYPE.HEAP_INIT)); memoryInfo.setHeapUsage(getJvmMemoryInfo(MEMTYPE.HEAP_USAGE)); memoryInfo.setHeapCommit(getJvmMemoryInfo(MEMTYPE.HEAP_COMMIT)); memoryInfo.setHeapMax(getJvmMemoryInfo(MEMTYPE.HEAP_MAX)); memoryInfo.setNoHeapInit(getJvmMemoryInfo(MEMTYPE.NOHEAP_INIT)); memoryInfo.setNoHeapUsage(getJvmMemoryInfo(MEMTYPE.NOHEAP_USAGE)); memoryInfo.setNoHeapCommit(getJvmMemoryInfo(MEMTYPE.NOHEAP_COMMIT)); memoryInfo.setNoHeapMax(getJvmMemoryInfo(MEMTYPE.NOHEAP_MAX)); memoryInfo.setFree(Runtime.getRuntime().freeMemory()); memoryInfo.setTotal(Runtime.getRuntime().totalMemory()); memoryInfo.setMax(Runtime.getRuntime().maxMemory()); return memoryInfo; } /** * * @param pid Id * @param regex * @return * @throws IOException IO */ public static Map<String,ObjectInfo> getJVMObjectInfo(long pid, String regex) throws IOException { Hashtable<String,ObjectInfo> result = new Hashtable<String,ObjectInfo>(); InputStream processInputStream = TEnv.createSysProcess("jmap -histo "+pid, null, (File)null).getInputStream(); String console = new String(TStream.readAll(processInputStream)); String[] consoleLines = console.split(System.lineSeparator()); for(int lineCount = 3;lineCount<consoleLines.length;lineCount++){ String lineContent = consoleLines[lineCount]; long count = Long.parseLong(lineContent.substring(5,19).trim()); long size = Long.parseLong(lineContent.substring(19,34).trim()); String name = lineContent.substring(34,lineContent.length()).trim(); if(name.isEmpty()){ continue; } if(TString.regexMatch(name,regex) > 0) { ObjectInfo objectInfo = new ObjectInfo(name, size, count); result.put(name,objectInfo); } } return result; } /** * JVM(,) * @param regex * @return Map */ public static Map<String,TPerformance.ObjectInfo> getJVMObjectInfo(String regex) { Map<String,TPerformance.ObjectInfo> result; try { result = TPerformance.getJVMObjectInfo(TEnv.getCurrentPID(),regex); } catch (IOException e) { result = new Hashtable<String,TPerformance.ObjectInfo>(); } return result; } /** * JVM * @return */ public static Map<String,Object> getThreadPoolInfo(){ Map<String,Object> threadPoolInfo = new HashMap<String,Object>(); ThreadPoolExecutor threadPoolInstance = Global.getThreadPool(); threadPoolInfo.put("ActiveCount",threadPoolInstance.getActiveCount()); threadPoolInfo.put("CorePoolSize",threadPoolInstance.getCorePoolSize()); threadPoolInfo.put("FinishedTaskCount",threadPoolInstance.getCompletedTaskCount()); threadPoolInfo.put("TaskCount",threadPoolInstance.getTaskCount()); threadPoolInfo.put("QueueSize",threadPoolInstance.getQueue().size()); return threadPoolInfo; } /** * JVM * @return */ public static List<Map<String,Object>> getThreadDetail(){ ArrayList<Map<String,Object>> threadDetailList = new ArrayList<Map<String,Object>>(); for(Thread thread : TEnv.getThreads()){ Map<String,Object> threadDetail = new Hashtable<String,Object>(); threadDetail.put("Name",thread.getName()); threadDetail.put("Id",thread.getId()); threadDetail.put("Priority",thread.getPriority()); threadDetail.put("ThreadGroup",thread.getThreadGroup().getName()); threadDetail.put("StackTrace",TEnv.getStackElementsMessage(thread.getStackTrace())); threadDetail.put("State",thread.getState().name()); threadDetailList.add(threadDetail); } return threadDetailList; } /** * * @return Map */ public static Map<String,Object> getProcessorInfo(){ Map<String,Object> processInfo = new Hashtable<String,Object>(); processInfo.put("ProcessorCount",TPerformance.getProcessorCount()); processInfo.put("SystemLoadAverage",TPerformance.getSystemLoadAverage()); return processInfo; } /** * JVM * @return JVM Map */ public static Map<String,Object> getJVMInfo(){ Map<String, Object> jvmInfo = new Hashtable<String, Object>(); for(Map.Entry<Object,Object> entry : System.getProperties().entrySet()){ jvmInfo.put(entry.getKey().toString(),entry.getValue().toString()); } return jvmInfo; } /** * * Linux * @return MB, 1: , 2: , 3: , 4: , 5: * @throws IOException IO * @throws InterruptedException */ public static Map<String, Integer> getSysMemInfo() throws IOException, InterruptedException { if(System.getProperty("os.name").toLowerCase().contains("linux")) { try(FileInputStream fileInputStream = new FileInputStream("/proc/meminfo")) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); Map<String, Integer> result = new HashMap<String, Integer>(); String lineStr = null; StringTokenizer token = null; while ((lineStr = bufferedReader.readLine()) != null) { token = new StringTokenizer(lineStr); if (!token.hasMoreTokens()) continue; String tokenStr = token.nextToken(); if (!token.hasMoreTokens()) continue; if (tokenStr.equalsIgnoreCase("MemTotal:")) { result.put("MemTotal", Integer.parseInt(token.nextToken()) / 1024); } else if (tokenStr.equalsIgnoreCase("MemFree:")) { result.put("MemFree", Integer.parseInt(token.nextToken()) / 1024); } else if (tokenStr.equalsIgnoreCase("MemAvailable:")) { result.put("MemAvailable", Integer.parseInt(token.nextToken()) / 1024); } else if (tokenStr.equalsIgnoreCase("SwapTotal:")) { result.put("SwapTotal", Integer.parseInt(token.nextToken()) / 1024); } else if (tokenStr.equalsIgnoreCase("SwapFree:")) { result.put("SwapFree", Integer.parseInt(token.nextToken()) / 1024); } } return result; } } else { return null; } } /** * CPU * Linux * @return float efficiency * @throws IOException * @throws InterruptedException */ public static Float getSysCpuUsage() throws IOException, InterruptedException { if(System.getProperty("os.name").toLowerCase().contains("linux")) { try(FileInputStream fileInputStream = new FileInputStream("/proc/stat")) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); StringTokenizer token = new StringTokenizer(bufferedReader.readLine()); token.nextToken(); int user1 = Integer.parseInt(token.nextToken()); int nice1 = Integer.parseInt(token.nextToken()); int sys1 = Integer.parseInt(token.nextToken()); int idle1 = Integer.parseInt(token.nextToken()); Thread.sleep(1000); bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));; token = new StringTokenizer(bufferedReader.readLine()); token.nextToken(); int user2 = Integer.parseInt(token.nextToken()); int nice2 = Integer.parseInt(token.nextToken()); int sys2 = Integer.parseInt(token.nextToken()); int idle2 = Integer.parseInt(token.nextToken()); return (float) ((user2 + sys2 + nice2) - (user1 + sys1 + nice1)) / (float) ((user2 + nice2 + sys2 + idle2) - (user1 + nice1 + sys1 + idle1)); } }else{ return null; } } /** * JVM */ public static class ObjectInfo{ private String name; private long size; private long count; public ObjectInfo(String name,long size,long count){ this.name = name; this.size = size; this.count = count; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } } public static class MemoryInfo{ private long heapInit; private long heapUsage; private long heapMax; private long heapCommit; private long noHeapInit; private long noHeapUsage; private long noHeapMax; private long noHeapCommit; private long free; private long max; private long total; public long getFree() { return free; } public void setFree(long free) { this.free = free; } public long getMax() { return max; } public void setMax(long max) { this.max = max; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public long getHeapInit() { return heapInit; } public void setHeapInit(long heapInit) { this.heapInit = heapInit; } public long getHeapUsage() { return heapUsage; } public void setHeapUsage(long heapUsage) { this.heapUsage = heapUsage; } public long getHeapMax() { return heapMax; } public void setHeapMax(long heapMax) { this.heapMax = heapMax; } public long getHeapCommit() { return heapCommit; } public void setHeapCommit(long heapCommit) { this.heapCommit = heapCommit; } public long getNoHeapInit() { return noHeapInit; } public void setNoHeapInit(long noHeapInit) { this.noHeapInit = noHeapInit; } public long getNoHeapUsage() { return noHeapUsage; } public void setNoHeapUsage(long noHeapUsage) { this.noHeapUsage = noHeapUsage; } public long getNoHeapMax() { return noHeapMax; } public void setNoHeapMax(long noHeapMax) { this.noHeapMax = noHeapMax; } public long getNoHeapCommit() { return noHeapCommit; } public void setNoHeapCommit(long noHeapCommit) { this.noHeapCommit = noHeapCommit; } } }
package de.mrapp.android.adapter.decorator; import android.util.SparseArray; import android.view.View; /** * A view holder, which provides references to previously referenced views in * order to reuse them. * * @author Michael Rapp * * @since 1.0.0 */ public class ViewHolder { /** * A sparse array, which maps the resource IDs of already referenced views * to the views themselves. */ private SparseArray<View> views; /** * Creates a new view holder. */ public ViewHolder() { this.views = new SparseArray<View>(); } /** * Returns the view, which belongs to a specific resource ID. If the view * has already been referenced, the reference, which is stored in the view * holder, will be reused. Otherwise the method * <code>findViewById(int):View</code> of the given parent view is used to * reference the view. * * @param parentView * The parent view, the view, which should be returned, belongs * to as an instance of the class {@link View}. The view may not * be null * @param viewId * The resource ID of the view, which should be returned, as an * {@link Integer} value. The ID must be a valid resource ID of a * view, which belongs to the given parent view * @return The view, which belongs to the given resource ID, as an instance * of the class {@link View}. The view may not be null */ public final View getView(final View parentView, final int viewId) { View view = views.get(viewId); if (view == null) { view = parentView.findViewById(viewId); views.put(viewId, view); } return view; } }
package bibifi; import junit.framework.TestCase; public class App1Test extends TestCase { public void testCtor() { App1 app = new App1(); App1 app2 = new App1(); } }
package org.voovan.tools.log; import org.voovan.Global; import org.voovan.tools.*; import org.voovan.tools.hashwheeltimer.HashWheelTask; import java.io.*; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; public class Formater { private String template; private volatile LoggerThread loggerThread; private List<String> logLevel; private String dateStamp; private int maxLineLength = -1; private String lineHead; private String lineTail; private static String DATE = TDateTime.now("yyyyMMdd"); static{ Global.getHashWheelTimer().addTask(new HashWheelTask() { @Override public void run() { DATE = TDateTime.now("yyyyMMdd"); } }, 1); } protected String getDateStamp() { return dateStamp; } protected void setDateStamp(String dateStamp) { this.dateStamp = dateStamp; } /** * * @param template */ public Formater(String template) { this.template = template; logLevel = new Vector<String>(); logLevel.addAll(TObject.asList(LoggerStatic.getLogConfig("LogLevel", LoggerStatic.LOG_LEVEL).split(","))); this.dateStamp = DATE; final Formater finalFormater = this; Global.getHashWheelTimer().addTask(new HashWheelTask() { @Override public void run() { if(Logger.isEnable()) { packLogFile(); if (!finalFormater.getDateStamp().equals(DATE)) { loggerThread.setOutputStreams(getOutputStreams()); finalFormater.setDateStamp(DATE); } } } }, 1); } /** * * @return */ public List<String> getLogLevel() { return logLevel; } /** * * @return */ public static StackTraceElement currentStackLine() { StackTraceElement[] stackTraceElements = TEnv.getStackElements(); return stackTraceElements[6]; } /** * * @return */ private static String currentThreadName() { Thread currentThread = Thread.currentThread(); return currentThread.getName(); } private int realLength(String str){ return str.replaceAll("\\{\\{n\\}\\}","").replaceAll("\\{\\{.*\\}\\}"," ").replaceAll("\033\\[\\d{2}m", "").length(); } /** * * @param message * @return */ private String lineFormat(Message message){ return TString.tokenReplace(template, message.getTokens()) + TFile.getLineSeparator(); } /** * Token * @param message */ public void fillTokens(Message message){ Map<String, String> tokens = new HashMap<String, String>(); message.setTokens(tokens); //Message tokens.put("t", "\t"); tokens.put("s", " "); tokens.put("n", TFile.getLineSeparator()); tokens.put("I", message.getMessage()); if(LoggerStatic.HAS_COLOR) { if (!TEnv.OS_NAME.toUpperCase().contains("WINDOWS")) { tokens.put("F0", "\033[30m"); tokens.put("F1", "\033[31m"); tokens.put("F2", "\033[32m"); tokens.put("F3", "\033[33m"); tokens.put("F4", "\033[34m"); tokens.put("F5", "\033[35m"); tokens.put("F6", "\033[36m"); tokens.put("F7", "\033[37m"); tokens.put("FD", "\033[39m"); tokens.put("B0", "\033[40m"); tokens.put("B1", "\033[41m"); tokens.put("B2", "\033[42m"); tokens.put("B3", "\033[43m"); tokens.put("B4", "\033[44m"); tokens.put("B5", "\033[45m"); tokens.put("B6", "\033[46m"); tokens.put("B7", "\033[47m"); tokens.put("BD", "\033[49m"); } else { tokens.put("F0", ""); tokens.put("F1", ""); tokens.put("F2", ""); tokens.put("F3", ""); tokens.put("F4", ""); tokens.put("F5", ""); tokens.put("F6", ""); tokens.put("F7", ""); tokens.put("FD", ""); tokens.put("B0", ""); tokens.put("B1", ""); tokens.put("B2", ""); tokens.put("B3", ""); tokens.put("B4", ""); tokens.put("B5", ""); tokens.put("B6", ""); tokens.put("B7", ""); tokens.put("BD", ""); } } if(LoggerStatic.HAS_LEVEL) { tokens.put("P", TObject.nullDefault(message.getLevel(), "INFO")); } if(LoggerStatic.HAS_THREAD) { tokens.put("T", currentThreadName()); } if(LoggerStatic.HAS_DATE) { tokens.put("D", TDateTime.now("yyyy-MM-dd HH:mm:ss:SS z")); } if(LoggerStatic.HAS_RUNTIME) { tokens.put("R", Long.toString(System.currentTimeMillis() - LoggerStatic.getStartTimeMillis())); } if(LoggerStatic.HAS_STACK) { StackTraceElement stackTraceElement = currentStackLine(); tokens.put("SI", stackTraceElement.toString()); tokens.put("L", Integer.toString((stackTraceElement.getLineNumber()))); tokens.put("M", stackTraceElement.getMethodName()); tokens.put("F", stackTraceElement.getFileName()); tokens.put("C", stackTraceElement.getClassName()); } } /** * * @param message * @return */ public String format(Message message) { fillTokens(message); return lineFormat(message); } /** * * @param message * @return */ public String simpleFormat(Message message){ fillTokens(message); return TString.tokenReplace(message.getMessage(), message.getTokens()); } /** * * @param message * @return */ public boolean messageWritable(Message message){ if(logLevel.contains("ALL")){ return true; } else if(logLevel.contains(message.getLevel())){ return true; }else{ return false; } } /** * , * @param message */ public void writeFormatedLog(Message message) { if(messageWritable(message)){ if("SIMPLE".equals(message.getLevel())){ writeLog(simpleFormat(message)+"\r\n"); }else{ writeLog(format(message)); } } } /** * * @param msg */ public synchronized void writeLog(String msg) { if(Logger.isEnable()){ if (loggerThread == null || loggerThread.isFinished()) { this.loggerThread = LoggerThread.start(getOutputStreams()); } loggerThread.addLogMessage(msg); } } private void packLogFile(){ long packSize = (long) (Double.valueOf(LoggerStatic.getLogConfig("PackSize", "1024")) * 1024L * 1024L); final String logFilePath = getFormatedLogFilePath(); final String tmpFilePath = TFile.getFileDirectory(logFilePath) + ".tmpPackLog"; File logFile = new File(logFilePath); File tmpLogFile = new File(tmpFilePath); if(packSize > 0 && logFile.length() > packSize){ try { if (loggerThread.pause()) { try { TFile.moveFile(logFile, tmpLogFile); Global.getThreadPool().execute(()->{ String logFileExtendName = TFile.getFileExtension(logFilePath); String innerLogFilePath = logFilePath.replace("." + logFileExtendName, ""); try { File packFile = new File(innerLogFilePath + "." + TDateTime.now("HHmmss") + "." + logFileExtendName + ".gz"); TZip.encodeGZip(tmpLogFile, packFile); TFile.deleteFile(tmpLogFile); } catch (Exception e) { System.out.println("[ERROR] Pack log file " + innerLogFilePath + "error: "); e.printStackTrace(); } }); } catch (IOException e) { e.printStackTrace(); } loggerThread.setOutputStreams(getOutputStreams()); } } finally { loggerThread.unpause(); } } } /** * * @return */ public static String getFormatedLogFilePath(){ String filePath = ""; String logFile = LoggerStatic.getLogConfig("LogFile", LoggerStatic.LOG_FILE); if(logFile!=null) { Map<String, String> tokens = new HashMap<String, String>(); tokens.put("D", DATE); tokens.put("WorkDir", TFile.getContextPath()); filePath = TString.tokenReplace(logFile, tokens); String fileDirectory = filePath.substring(0, filePath.lastIndexOf(File.separator)); File loggerFile = new File(fileDirectory); if (!loggerFile.exists()) { if(!loggerFile.mkdirs()){ System.out.println("Logger file directory error!"); } } }else{ filePath = null; } return filePath; } /** * * @return */ public static Formater newInstance() { return new Formater(LoggerStatic.LOG_TEMPLATE); } /** * * @return */ protected static OutputStream[] getOutputStreams(){ String[] LogTypes = LoggerStatic.getLogConfig("LogType", LoggerStatic.LOG_TYPE).split(","); String logFilePath = getFormatedLogFilePath(); OutputStream[] outputStreams = new OutputStream[LogTypes.length]; for (int i = 0; i < LogTypes.length; i++) { String logType = LogTypes[i].trim(); switch (logType) { case "STDOUT": outputStreams[i] = System.out; break; case "STDERR": outputStreams[i] = System.err; break; case "FILE": try { outputStreams[i] = new FileOutputStream(logFilePath,true); } catch (FileNotFoundException e) { System.out.println("log file: ["+logFilePath+"] is not found.\r\n"); } break; default: break; } } return outputStreams; } }
package com.google.refine.importing; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.apache.commons.io.FileCleaningTracker; import org.apache.tools.bzip2.CBZip2InputStream; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarInputStream; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibm.icu.text.NumberFormat; import com.google.refine.ProjectManager; import com.google.refine.ProjectMetadata; import com.google.refine.RefineServlet; import com.google.refine.importing.ImportingManager.Format; import com.google.refine.importing.UrlRewriter.Result; import com.google.refine.model.Project; import com.google.refine.util.JSONUtilities; public class ImportingUtilities { final static protected Logger logger = LoggerFactory.getLogger("importing-utilities"); static public interface Progress { public void setProgress(String message, int percent); public boolean isCanceled(); } static public void loadDataAndPrepareJob( HttpServletRequest request, HttpServletResponse response, Properties parameters, final ImportingJob job, JSONObject config) throws IOException, ServletException { JSONObject retrievalRecord = new JSONObject(); JSONUtilities.safePut(config, "retrievalRecord", retrievalRecord); JSONUtilities.safePut(config, "state", "loading-raw-data"); final JSONObject progress = new JSONObject(); JSONUtilities.safePut(config, "progress", progress); try { ImportingUtilities.retrieveContentFromPostRequest( request, parameters, job.getRawDataDir(), retrievalRecord, new Progress() { @Override public void setProgress(String message, int percent) { if (message != null) { JSONUtilities.safePut(progress, "message", message); } JSONUtilities.safePut(progress, "percent", percent); } @Override public boolean isCanceled() { return job.canceled; } } ); } catch (Exception e) { JSONUtilities.safePut(config, "state", "error"); JSONUtilities.safePut(config, "error", "Error uploading data"); JSONUtilities.safePut(config, "errorDetails", e.getLocalizedMessage()); return; } JSONArray fileSelectionIndexes = new JSONArray(); JSONUtilities.safePut(config, "fileSelection", fileSelectionIndexes); String bestFormat = ImportingUtilities.autoSelectFiles(job, retrievalRecord, fileSelectionIndexes); bestFormat = ImportingUtilities.guessBetterFormat(job, bestFormat); JSONArray rankedFormats = new JSONArray(); JSONUtilities.safePut(config, "rankedFormats", rankedFormats); ImportingUtilities.rankFormats(job, bestFormat, rankedFormats); JSONUtilities.safePut(config, "state", "ready"); JSONUtilities.safePut(config, "hasData", true); config.remove("progress"); } static public void updateJobWithNewFileSelection(ImportingJob job, JSONArray fileSelectionArray) { JSONUtilities.safePut(job.config, "fileSelection", fileSelectionArray); String bestFormat = ImportingUtilities.getCommonFormatForSelectedFiles(job, fileSelectionArray); bestFormat = ImportingUtilities.guessBetterFormat(job, bestFormat); JSONArray rankedFormats = new JSONArray(); JSONUtilities.safePut(job.config, "rankedFormats", rankedFormats); ImportingUtilities.rankFormats(job, bestFormat, rankedFormats); } static public void retrieveContentFromPostRequest( HttpServletRequest request, Properties parameters, File rawDataDir, JSONObject retrievalRecord, final Progress progress ) throws Exception { JSONArray fileRecords = new JSONArray(); JSONUtilities.safePut(retrievalRecord, "files", fileRecords); int clipboardCount = 0; int uploadCount = 0; int downloadCount = 0; int archiveCount = 0; // This tracks the total progress, which involves uploading data from the client // as well as downloading data from URLs. final SavingUpdate update = new SavingUpdate() { @Override public void savedMore() { progress.setProgress(null, calculateProgressPercent(totalExpectedSize, totalRetrievedSize)); } @Override public boolean isCanceled() { return progress.isCanceled(); } }; DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setFileCleaningTracker(new FileCleaningTracker()); ServletFileUpload upload = new ServletFileUpload(fileItemFactory); upload.setProgressListener(new ProgressListener() { boolean setContentLength = false; long lastBytesRead = 0; @Override public void update(long bytesRead, long contentLength, int itemCount) { if (!setContentLength) { // Only try to set the content length if we really know it. if (contentLength >= 0) { update.totalExpectedSize += contentLength; setContentLength = true; } } if (setContentLength) { update.totalRetrievedSize += (bytesRead - lastBytesRead); lastBytesRead = bytesRead; update.savedMore(); } } }); progress.setProgress("Uploading data ...", -1); parts: for (Object obj : upload.parseRequest(request)) { if (progress.isCanceled()) { break; } FileItem fileItem = (FileItem) obj; InputStream stream = fileItem.getInputStream(); String name = fileItem.getFieldName().toLowerCase(); if (fileItem.isFormField()) { if (name.equals("clipboard")) { String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } File file = allocateFile(rawDataDir, "clipboard.txt"); JSONObject fileRecord = new JSONObject(); JSONUtilities.safePut(fileRecord, "origin", "clipboard"); JSONUtilities.safePut(fileRecord, "declaredEncoding", encoding); JSONUtilities.safePut(fileRecord, "declaredMimeType", (String) null); JSONUtilities.safePut(fileRecord, "format", "text"); JSONUtilities.safePut(fileRecord, "fileName", "(clipboard)"); JSONUtilities.safePut(fileRecord, "location", getRelativePath(file, rawDataDir)); progress.setProgress("Uploading pasted clipboard text", calculateProgressPercent(update.totalExpectedSize, update.totalRetrievedSize)); JSONUtilities.safePut(fileRecord, "size", saveStreamToFile(stream, file, null)); clipboardCount++; JSONUtilities.append(fileRecords, fileRecord); } else if (name.equals("download")) { String urlString = Streams.asString(stream); URL url = new URL(urlString); JSONObject fileRecord = new JSONObject(); JSONUtilities.safePut(fileRecord, "origin", "download"); JSONUtilities.safePut(fileRecord, "url", urlString); for (UrlRewriter rewriter : ImportingManager.urlRewriters) { Result result = rewriter.rewrite(urlString); if (result != null) { urlString = result.rewrittenUrl; url = new URL(urlString); JSONUtilities.safePut(fileRecord, "url", urlString); JSONUtilities.safePut(fileRecord, "format", result.format); if (!result.download) { downloadCount++; JSONUtilities.append(fileRecords, fileRecord); continue parts; } } } URLConnection urlConnection = url.openConnection(); urlConnection.setConnectTimeout(5000); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; RefineServlet.setUserAgent(httpConnection); } urlConnection.connect(); InputStream stream2 = urlConnection.getInputStream(); try { File file = allocateFile(rawDataDir, url.getFile()); int contentLength = urlConnection.getContentLength(); if (contentLength > 0) { update.totalExpectedSize += contentLength; } JSONUtilities.safePut(fileRecord, "declaredEncoding", urlConnection.getContentEncoding()); JSONUtilities.safePut(fileRecord, "declaredMimeType", urlConnection.getContentType()); JSONUtilities.safePut(fileRecord, "fileName", file.getName()); JSONUtilities.safePut(fileRecord, "location", getRelativePath(file, rawDataDir)); progress.setProgress("Downloading " + urlString, calculateProgressPercent(update.totalExpectedSize, update.totalRetrievedSize)); long actualLength = saveStreamToFile(stream2, file, update); JSONUtilities.safePut(fileRecord, "size", actualLength); if (actualLength == 0) { throw new Exception("No content found in " + urlString); } else if (contentLength >= 0) { update.totalExpectedSize += (actualLength - contentLength); } else { update.totalExpectedSize += actualLength; } progress.setProgress("Saving " + urlString + " locally", calculateProgressPercent(update.totalExpectedSize, update.totalRetrievedSize)); if (postProcessRetrievedFile(file, fileRecord, fileRecords, progress)) { archiveCount++; } downloadCount++; } finally { stream2.close(); } } else { String value = Streams.asString(stream); parameters.put(name, value); // TODO: We really want to store this on the request so it's available for everyone // request.getParameterMap().put(name, value); } } else { // is file content String fileName = fileItem.getName(); if (fileName.length() > 0) { long fileSize = fileItem.getSize(); File file = allocateFile(rawDataDir, fileName); JSONObject fileRecord = new JSONObject(); JSONUtilities.safePut(fileRecord, "origin", "upload"); JSONUtilities.safePut(fileRecord, "declaredEncoding", request.getCharacterEncoding()); JSONUtilities.safePut(fileRecord, "declaredMimeType", fileItem.getContentType()); JSONUtilities.safePut(fileRecord, "fileName", fileName); JSONUtilities.safePut(fileRecord, "location", getRelativePath(file, rawDataDir)); progress.setProgress( "Saving file " + fileName + " locally (" + formatBytes(fileSize) + " bytes)", calculateProgressPercent(update.totalExpectedSize, update.totalRetrievedSize)); JSONUtilities.safePut(fileRecord, "size", saveStreamToFile(stream, file, null)); if (postProcessRetrievedFile(file, fileRecord, fileRecords, progress)) { archiveCount++; } uploadCount++; } } } JSONUtilities.safePut(retrievalRecord, "uploadCount", uploadCount); JSONUtilities.safePut(retrievalRecord, "downloadCount", downloadCount); JSONUtilities.safePut(retrievalRecord, "clipboardCount", clipboardCount); JSONUtilities.safePut(retrievalRecord, "archiveCount", archiveCount); } static public String getRelativePath(File file, File dir) { String location = file.getAbsolutePath().substring(dir.getAbsolutePath().length()); return (location.startsWith(File.separator)) ? location.substring(1) : location; } static public File allocateFile(File dir, String name) { int q = name.indexOf('?'); if (q > 0) { name = name.substring(0, q); } File file = new File(dir, name); int dot = name.indexOf('.'); String prefix = dot < 0 ? name : name.substring(0, dot); String suffix = dot < 0 ? "" : name.substring(dot); int index = 2; while (file.exists()) { file = new File(dir, prefix + "-" + index++ + suffix); } file.getParentFile().mkdirs(); return file; } static public Reader getFileReader(ImportingJob job, JSONObject fileRecord, String commonEncoding) throws FileNotFoundException { return getFileReader(getFile(job, JSONUtilities.getString(fileRecord, "location", "")), fileRecord, commonEncoding); } static public Reader getFileReader(File file, JSONObject fileRecord, String commonEncoding) throws FileNotFoundException { return getReaderFromStream(new FileInputStream(file), fileRecord, commonEncoding); } static public Reader getReaderFromStream(InputStream inputStream, JSONObject fileRecord, String commonEncoding) { String encoding = getEncoding(fileRecord); if (encoding == null) { encoding = commonEncoding; } if (encoding != null) { try { return new InputStreamReader(inputStream, encoding); } catch (UnsupportedEncodingException e) { // Ignore and fall through } } return new InputStreamReader(inputStream); } static public File getFile(ImportingJob job, JSONObject fileRecord) { return getFile(job, JSONUtilities.getString(fileRecord, "location", "")); } static public File getFile(ImportingJob job, String location) { return new File(job.getRawDataDir(), location); } static public String getFileSource(JSONObject fileRecord) { return JSONUtilities.getString( fileRecord, "url", JSONUtilities.getString(fileRecord, "fileName", "unknown") ); } static private abstract class SavingUpdate { public long totalExpectedSize = 0; public long totalRetrievedSize = 0; abstract public void savedMore(); abstract public boolean isCanceled(); } static public long saveStreamToFile(InputStream stream, File file, SavingUpdate update) throws IOException { long length = 0; FileOutputStream fos = new FileOutputStream(file); try { byte[] bytes = new byte[4096]; int c; while ((update == null || !update.isCanceled()) && (c = stream.read(bytes)) > 0) { fos.write(bytes, 0, c); length += c; if (update != null) { update.totalRetrievedSize += c; update.savedMore(); } } return length; } finally { fos.close(); } } static public boolean postProcessRetrievedFile( File file, JSONObject fileRecord, JSONArray fileRecords, final Progress progress) { String mimeType = JSONUtilities.getString(fileRecord, "declaredMimeType", null); String contentEncoding = JSONUtilities.getString(fileRecord, "declaredEncoding", null); File rawDataDir = file.getParentFile(); InputStream archiveIS = tryOpenAsArchive(file, mimeType, contentEncoding); if (archiveIS != null) { try { if (explodeArchive(rawDataDir, archiveIS, fileRecord, fileRecords, progress)) { file.delete(); return true; } } finally { try { archiveIS.close(); } catch (IOException e) { // TODO: what to do? } } } InputStream uncompressedIS = tryOpenAsCompressedFile(file, mimeType, contentEncoding); if (uncompressedIS != null) { try { File file2 = uncompressFile(rawDataDir, uncompressedIS, fileRecord, progress); file.delete(); file = file2; } catch (IOException e) { // TODO: what to do? e.printStackTrace(); } finally { try { uncompressedIS.close(); } catch (IOException e) { // TODO: what to do? } } } postProcessSingleRetrievedFile(file, fileRecord); JSONUtilities.append(fileRecords, fileRecord); return false; } static public void postProcessSingleRetrievedFile(File file, JSONObject fileRecord) { if (!fileRecord.has("format")) { JSONUtilities.safePut(fileRecord, "format", ImportingManager.getFormat( file.getName(), JSONUtilities.getString(fileRecord, "declaredMimeType", null))); } } static public InputStream tryOpenAsArchive(File file, String mimeType) { return tryOpenAsArchive(file, mimeType, null); } static public InputStream tryOpenAsArchive(File file, String mimeType, String contentType) { String fileName = file.getName(); try { if (fileName.endsWith(".tar.gz") || fileName.endsWith(".tgz")) { return new TarInputStream(new GZIPInputStream(new FileInputStream(file))); } else if (fileName.endsWith(".tar.bz2")) { return new TarInputStream(new CBZip2InputStream(new FileInputStream(file))); } else if (fileName.endsWith(".tar") || "application/x-tar".equals(contentType)) { return new TarInputStream(new FileInputStream(file)); } else if (fileName.endsWith(".zip") || "application/x-zip-compressed".equals(contentType) || "application/zip".equals(contentType) || "application/x-compressed".equals(contentType) || "multipar/x-zip".equals(contentType)) { return new ZipInputStream(new FileInputStream(file)); } else if (fileName.endsWith(".kmz")) { return new ZipInputStream(new FileInputStream(file)); } } catch (IOException e) { } return null; } static public boolean explodeArchive( File rawDataDir, InputStream archiveIS, JSONObject archiveFileRecord, JSONArray fileRecords, final Progress progress ) { if (archiveIS instanceof TarInputStream) { TarInputStream tis = (TarInputStream) archiveIS; try { TarEntry te; while (!progress.isCanceled() && (te = tis.getNextEntry()) != null) { if (!te.isDirectory()) { String fileName2 = te.getName(); File file2 = allocateFile(rawDataDir, fileName2); progress.setProgress("Extracting " + fileName2, -1); JSONObject fileRecord2 = new JSONObject(); JSONUtilities.safePut(fileRecord2, "origin", JSONUtilities.getString(archiveFileRecord, "origin", null)); JSONUtilities.safePut(fileRecord2, "declaredEncoding", (String) null); JSONUtilities.safePut(fileRecord2, "declaredMimeType", (String) null); JSONUtilities.safePut(fileRecord2, "fileName", fileName2); JSONUtilities.safePut(fileRecord2, "archiveFileName", JSONUtilities.getString(archiveFileRecord, "fileName", null)); JSONUtilities.safePut(fileRecord2, "location", getRelativePath(file2, rawDataDir)); JSONUtilities.safePut(fileRecord2, "size", saveStreamToFile(tis, file2, null)); postProcessSingleRetrievedFile(file2, fileRecord2); JSONUtilities.append(fileRecords, fileRecord2); } } } catch (IOException e) { // TODO: what to do? e.printStackTrace(); } return true; } else if (archiveIS instanceof ZipInputStream) { ZipInputStream zis = (ZipInputStream) archiveIS; try { ZipEntry ze; while (!progress.isCanceled() && (ze = zis.getNextEntry()) != null) { if (!ze.isDirectory()) { String fileName2 = ze.getName(); File file2 = allocateFile(rawDataDir, fileName2); progress.setProgress("Extracting " + fileName2, -1); JSONObject fileRecord2 = new JSONObject(); JSONUtilities.safePut(fileRecord2, "origin", JSONUtilities.getString(archiveFileRecord, "origin", null)); JSONUtilities.safePut(fileRecord2, "declaredEncoding", (String) null); JSONUtilities.safePut(fileRecord2, "declaredMimeType", (String) null); JSONUtilities.safePut(fileRecord2, "fileName", fileName2); JSONUtilities.safePut(fileRecord2, "archiveFileName", JSONUtilities.getString(archiveFileRecord, "fileName", null)); JSONUtilities.safePut(fileRecord2, "location", getRelativePath(file2, rawDataDir)); JSONUtilities.safePut(fileRecord2, "size", saveStreamToFile(zis, file2, null)); postProcessSingleRetrievedFile(file2, fileRecord2); JSONUtilities.append(fileRecords, fileRecord2); } } } catch (IOException e) { // TODO: what to do? e.printStackTrace(); } return true; } return false; } static public InputStream tryOpenAsCompressedFile(File file, String mimeType) { return tryOpenAsCompressedFile(file, mimeType, null); } static public InputStream tryOpenAsCompressedFile(File file, String mimeType, String contentEncoding) { String fileName = file.getName(); try { /* * TODO: Do we need to support MIME types as well as content encodings? * application/x-bzip2 * application/x-gzip * multipart/x-gzip */ if (fileName.endsWith(".gz") || "gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { return new GZIPInputStream(new FileInputStream(file)); } else if (fileName.endsWith(".bz2")) { return new CBZip2InputStream(new FileInputStream(file)); } } catch (IOException e) { } return null; } static public File uncompressFile( File rawDataDir, InputStream uncompressedIS, JSONObject fileRecord, final Progress progress ) throws IOException { String fileName = JSONUtilities.getString(fileRecord, "fileName", "unknown"); File file2 = allocateFile(rawDataDir, fileName); progress.setProgress("Uncompressing " + fileName, -1); saveStreamToFile(uncompressedIS, file2, null); JSONUtilities.safePut(fileRecord, "declaredEncoding", (String) null); // TODO: Why is MIME type cleared here? JSONUtilities.safePut(fileRecord, "declaredMimeType", (String) null); String location = JSONUtilities.getString(fileRecord, "location", ""); location = location.substring(0,location.lastIndexOf('/')) + "/" + file2; JSONUtilities.safePut(fileRecord, "location", location); return file2; } static private int calculateProgressPercent(long totalExpectedSize, long totalRetrievedSize) { return totalExpectedSize == 0 ? -1 : (int) (totalRetrievedSize * 100 / totalExpectedSize); } static private String formatBytes(long bytes) { return NumberFormat.getIntegerInstance().format(bytes); } static public String getEncoding(JSONObject fileRecord) { String encoding = JSONUtilities.getString(fileRecord, "encoding", null); if (encoding == null || encoding.isEmpty()) { encoding = JSONUtilities.getString(fileRecord, "declaredEncoding", null); } return encoding; } static public String autoSelectFiles(ImportingJob job, JSONObject retrievalRecord, JSONArray fileSelectionIndexes) { final Map<String, Integer> formatToCount = new HashMap<String, Integer>(); List<String> formats = new ArrayList<String>(); JSONArray fileRecords = JSONUtilities.getArray(retrievalRecord, "files"); int count = fileRecords.length(); for (int i = 0; i < count; i++) { JSONObject fileRecord = JSONUtilities.getObjectElement(fileRecords, i); String format = JSONUtilities.getString(fileRecord, "format", null); if (format != null) { if (formatToCount.containsKey(format)) { formatToCount.put(format, formatToCount.get(format) + 1); } else { formatToCount.put(format, 1); formats.add(format); } } } Collections.sort(formats, new Comparator<String>() { @Override public int compare(String o1, String o2) { return formatToCount.get(o2) - formatToCount.get(o1); } }); // Default to text/line-based to to avoid parsing as binary/excel. String bestFormat = formats.size() > 0 ? formats.get(0) : "text/line-based"; if (JSONUtilities.getInt(retrievalRecord, "archiveCount", 0) == 0) { // If there's no archive, then select everything for (int i = 0; i < count; i++) { JSONUtilities.append(fileSelectionIndexes, i); } } else { // Otherwise, select files matching the best format for (int i = 0; i < count; i++) { JSONObject fileRecord = JSONUtilities.getObjectElement(fileRecords, i); String format = JSONUtilities.getString(fileRecord, "format", null); if (format != null && format.equals(bestFormat)) { JSONUtilities.append(fileSelectionIndexes, i); } } // If nothing matches the best format but we have some files, // then select them all if (fileSelectionIndexes.length() == 0 && count > 0) { for (int i = 0; i < count; i++) { JSONUtilities.append(fileSelectionIndexes, i); } } } return bestFormat; } static public String getCommonFormatForSelectedFiles(ImportingJob job, JSONArray fileSelectionIndexes) { JSONObject retrievalRecord = JSONUtilities.getObject(job.config, "retrievalRecord"); final Map<String, Integer> formatToCount = new HashMap<String, Integer>(); List<String> formats = new ArrayList<String>(); JSONArray fileRecords = JSONUtilities.getArray(retrievalRecord, "files"); int count = fileSelectionIndexes.length(); for (int i = 0; i < count; i++) { int index = JSONUtilities.getIntElement(fileSelectionIndexes, i, -1); if (index >= 0 && index < fileRecords.length()) { JSONObject fileRecord = JSONUtilities.getObjectElement(fileRecords, index); String format = JSONUtilities.getString(fileRecord, "format", null); if (format != null) { if (formatToCount.containsKey(format)) { formatToCount.put(format, formatToCount.get(format) + 1); } else { formatToCount.put(format, 1); formats.add(format); } } } } Collections.sort(formats, new Comparator<String>() { @Override public int compare(String o1, String o2) { return formatToCount.get(o2) - formatToCount.get(o1); } }); return formats.size() > 0 ? formats.get(0) : null; } static String guessBetterFormat(ImportingJob job, String bestFormat) { JSONObject retrievalRecord = JSONUtilities.getObject(job.config, "retrievalRecord"); return retrievalRecord != null ? guessBetterFormat(job, retrievalRecord, bestFormat) : bestFormat; } static String guessBetterFormat(ImportingJob job, JSONObject retrievalRecord, String bestFormat) { JSONArray fileRecords = JSONUtilities.getArray(retrievalRecord, "files"); return fileRecords != null ? guessBetterFormat(job, fileRecords, bestFormat) : bestFormat; } static String guessBetterFormat(ImportingJob job, JSONArray fileRecords, String bestFormat) { if (bestFormat != null && fileRecords != null && fileRecords.length() > 0) { JSONObject firstFileRecord = JSONUtilities.getObjectElement(fileRecords, 0); String encoding = getEncoding(firstFileRecord); String location = JSONUtilities.getString(firstFileRecord, "location", null); if (location != null) { File file = new File(job.getRawDataDir(), location); while (true) { String betterFormat = null; List<FormatGuesser> guessers = ImportingManager.formatToGuessers.get(bestFormat); if (guessers != null) { for (FormatGuesser guesser : guessers) { betterFormat = guesser.guess(file, encoding, bestFormat); if (betterFormat != null) { break; } } } if (betterFormat != null && !betterFormat.equals(bestFormat)) { bestFormat = betterFormat; } else { break; } } } } return bestFormat; } static void rankFormats(ImportingJob job, final String bestFormat, JSONArray rankedFormats) { final Map<String, String[]> formatToSegments = new HashMap<String, String[]>(); boolean download = bestFormat == null ? true : ImportingManager.formatToRecord.get(bestFormat).download; List<String> formats = new ArrayList<String>(ImportingManager.formatToRecord.keySet().size()); for (String format : ImportingManager.formatToRecord.keySet()) { Format record = ImportingManager.formatToRecord.get(format); if (record.uiClass != null && record.parser != null && record.download == download) { formats.add(format); formatToSegments.put(format, format.split("/")); } } if (bestFormat == null) { Collections.sort(formats); } else { Collections.sort(formats, new Comparator<String>() { @Override public int compare(String format1, String format2) { if (format1.equals(bestFormat)) { return -1; } else if (format2.equals(bestFormat)) { return 1; } else { return compareBySegments(format1, format2); } } int compareBySegments(String format1, String format2) { int c = commonSegments(format2) - commonSegments(format1); return c != 0 ? c : format1.compareTo(format2); } int commonSegments(String format) { String[] bestSegments = formatToSegments.get(bestFormat); String[] segments = formatToSegments.get(format); if (bestSegments == null || segments == null) { return 0; } else { int i; for (i = 0; i < bestSegments.length && i < segments.length; i++) { if (!bestSegments[i].equals(segments[i])) { break; } } return i; } } }); } for (String format : formats) { JSONUtilities.append(rankedFormats, format); } } static public List<JSONObject> getSelectedFileRecords(ImportingJob job) { List<JSONObject> results = new ArrayList<JSONObject>(); JSONObject retrievalRecord = JSONUtilities.getObject(job.config, "retrievalRecord"); if (retrievalRecord != null) { JSONArray fileRecordArray = JSONUtilities.getArray(retrievalRecord, "files"); if (fileRecordArray != null) { JSONArray fileSelectionArray = JSONUtilities.getArray(job.config, "fileSelection"); if (fileSelectionArray != null) { for (int i = 0; i < fileSelectionArray.length(); i++) { int index = JSONUtilities.getIntElement(fileSelectionArray, i, -1); if (index >= 0 && index < fileRecordArray.length()) { results.add(JSONUtilities.getObjectElement(fileRecordArray, index)); } } } } } return results; } static public void previewParse(ImportingJob job, String format, JSONObject optionObj, List<Exception> exceptions) { Format record = ImportingManager.formatToRecord.get(format); if (record == null || record.parser == null) { // TODO: what to do? return; } job.prepareNewProject(); record.parser.parse( job.project, job.metadata, job, getSelectedFileRecords(job), format, 100, optionObj, exceptions ); job.project.update(); // update all internal models, indexes, caches, etc. } static public long createProject( final ImportingJob job, final String format, final JSONObject optionObj, final List<Exception> exceptions, boolean synchronous) { final Format record = ImportingManager.formatToRecord.get(format); if (record == null || record.parser == null) { // TODO: what to do? return -1; } JSONUtilities.safePut(job.config, "state", "creating-project"); final Project project = new Project(); if (synchronous) { createProjectSynchronously( job, format, optionObj, exceptions, record, project); } else { new Thread() { @Override public void run() { createProjectSynchronously( job, format, optionObj, exceptions, record, project); } }.start(); } return project.id; } static private void createProjectSynchronously( final ImportingJob job, final String format, final JSONObject optionObj, final List<Exception> exceptions, final Format record, final Project project ) { ProjectMetadata pm = new ProjectMetadata(); pm.setName(JSONUtilities.getString(optionObj, "projectName", "Untitled")); String encoding = JSONUtilities.getString(optionObj, "encoding", "UTF-8"); if ("".equals(encoding)) { // encoding can be present, but empty, which won't trigger JSONUtilities default processing encoding = "UTF-8"; } pm.setEncoding(encoding); record.parser.parse( project, pm, job, getSelectedFileRecords(job), format, -1, optionObj, exceptions ); if (!job.canceled) { if (exceptions.size() == 0) { project.update(); // update all internal models, indexes, caches, etc. ProjectManager.singleton.registerProject(project, pm); JSONUtilities.safePut(job.config, "projectID", project.id); JSONUtilities.safePut(job.config, "state", "created-project"); } else { JSONUtilities.safePut(job.config, "state", "error"); JSONUtilities.safePut(job.config, "errors", DefaultImportingController.convertErrorsToJsonArray(exceptions)); } job.touch(); job.updating = false; } } static public void setCreatingProjectProgress(ImportingJob job, String message, int percent) { JSONObject progress = JSONUtilities.getObject(job.config, "progress"); if (progress == null) { progress = new JSONObject(); JSONUtilities.safePut(job.config, "progress", progress); } JSONUtilities.safePut(progress, "message", message); JSONUtilities.safePut(progress, "percent", percent); JSONUtilities.safePut(progress, "memory", Runtime.getRuntime().totalMemory() / 1000000); JSONUtilities.safePut(progress, "maxmemory", Runtime.getRuntime().maxMemory() / 1000000); } }
package de.sebhn.algorithm.excersise5; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Class DLXNode represents a matrix element of the cover matrix with value 1 links go to up down * left right neigbors, and column header can also be used as column header or root of column * headers matrix is sparsely coded try to do all operations very efficiently. */ class DLXNode { // represents 1 element or header DLXNode C; // reference to column-header DLXNode L, R, U, D; // left, right, up, down references DLXNode() { C = L = R = U = D = this; } // supports circular lists } public class PentominoZIPDLX { static DLXNode h, kopfTeil[]; static long cnt; static int n; /** * Zahl wird von der Konsole eingelesen. Mit dieser Zahl wird dann das Programm gestartet. */ public PentominoZIPDLX() { cnt = 0; try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.print("Gib dein n ein: "); n = Integer.parseInt(br.readLine()); } catch (IOException e) { e.printStackTrace(); } if (n > 0) { matrixKonfigurieren(); System.out.println("\n\nn=" + n + "\t\ta(" + n + ")=" + cnt); } else if (n < 0) { System.out.println("Bitte nur positive Werte eingeben!"); } else { System.out.println("\n\nn=" + n + "\t\ta(" + n + ")= 1"); } } /** * @param i Ist der aktuelle Index aus der For-Schleife von der Methode "kopfteilVerschieben". * @param mod Kann je nach Pentomino den Fall 1 oder 2 Annehmen. * @return boolean */ public static boolean ueberpruefeModulo(int i, int mod) { return i % 6 + mod < 6 ? true : false; } /** * @param t Parameter ist ein int-Array und beinhaltet die notwendigen Zahlen, um den Pentomino zu * beschreiben. * @param mod mod==1 bedeutet, dass in der Modulo Funktion, der Modulo von 5+1 genommen wird. * mod==2 bedeutet, dass in der Modulo Funktion, der Modulo von 5+2 genommen wird. * @param plus4 Wenn plus4 true ist, dann wird der Index der For-Schleife um 5 anstatt um 1 * erhht. */ public static void kopfteilVerschieben(int[] t, int mod, boolean plus4) { boolean moduloErgebnis = true; for (int i = 0; i + t[5] <= 6 * n - 1; i++) { DLXNode[] dlxArray = {new DLXNode(), new DLXNode(), new DLXNode(), new DLXNode(), new DLXNode(), new DLXNode()}; if (mod >= 1) { moduloErgebnis = ueberpruefeModulo(i, mod); } if (moduloErgebnis) { for (int m = 0; m < dlxArray.length; m++) { dlxArray[m].U = kopfTeil[i + t[m]].U; dlxArray[m].D = kopfTeil[i + t[m]]; kopfTeil[i + t[m]].U.D = dlxArray[m]; kopfTeil[i + t[m]].U = dlxArray[m]; dlxArray[m].C = kopfTeil[i + t[m]]; dlxArray[m].R = dlxArray[m + 1 > 4 ? 0 : m + 1]; dlxArray[m].L = dlxArray[m - 1 < 0 ? 4 : m - 1]; } } if (plus4) { i += 4; } } } /** * Der Matrix werden initiale Einstellungen mitgegeben und der Kopfteil wird erstellt und * zugewiesen. */ public static void matrixKonfigurieren() { h = new DLXNode(); kopfTeil = new DLXNode[6 * n]; kopfTeil[0] = new DLXNode(); for (int i = 1; i < 6 * n; i++) { kopfTeil[i] = new DLXNode(); kopfTeil[i].L = kopfTeil[i - 1]; kopfTeil[i].R = kopfTeil[0]; kopfTeil[i - 1].R = kopfTeil[i]; kopfTeil[0].L = kopfTeil[i]; } h.R = kopfTeil[0]; h.L = kopfTeil[kopfTeil.length - 1]; kopfTeil[0].L = h; kopfTeil[kopfTeil.length - 1].R = h; // I1-Pentomino kopfteilVerschieben(new int[] {0, 5, 10, 15, 20}, 0, false); // I2-Pentomino kopfteilVerschieben(new int[] {0, 1, 2, 3, 4}, 0, true); // P1-Pentomino kopfteilVerschieben(new int[] {0, 1, 5, 6, 10}, 1, false); // P2-Pentomino kopfteilVerschieben(new int[] {0, 1, 5, 6, 11}, 1, false); // P3-Pentomino kopfteilVerschieben(new int[] {0, 5, 6, 10, 11}, 1, false); // P4-Pentomino kopfteilVerschieben(new int[] {1, 5, 6, 10, 11}, 1, false); // P5-Pentomino kopfteilVerschieben(new int[] {0, 1, 2, 6, 7}, 2, false); // P6-Pentomino kopfteilVerschieben(new int[] {1, 2, 5, 6, 7}, 2, false); // P7-Pentomino kopfteilVerschieben(new int[] {0, 1, 5, 6, 7}, 2, false); // P8-Pentomino kopfteilVerschieben(new int[] {0, 1, 2, 5, 6}, 2, false); // Z1-Pentomino kopfteilVerschieben(new int[] {0, 5, 6, 7, 12}, 2, false); // Z2-Pentomino kopfteilVerschieben(new int[] {2, 5, 6, 7, 10}, 2, false); // Z3-Pentomino kopfteilVerschieben(new int[] {0, 1, 6, 11, 12}, 2, false); // Z4-Pentomino kopfteilVerschieben(new int[] {1, 2, 6, 10, 11}, 2, false); sucheUndZaehle(0); } /** * search tries to find and count all complete coverings of the DLX matrix. Is a recursive, * depth-first, backtracking algorithm that finds all solutions to the exact cover problem encoded * in the DLX matrix. each time all columns are covered, static long cnt is increased * * @param int k: number of level */ public static void sucheUndZaehle(int k) { // finds & counts solutions if (h.R == h) { cnt++; return; } // if empty: count & done DLXNode c = h.R; // choose next column c cover(c); // remove c from columns for (DLXNode r = c.D; r != c; r = r.D) { // forall rows with 1 in c for (DLXNode j = r.R; j != r; j = j.R) // forall 1-elements in row cover(j.C); sucheUndZaehle(k + 1); for (DLXNode j = r.L; j != r; j = j.L) // forall 1-elements in row uncover(j.C); // backtrack: un-remove } uncover(c); // un-remove c to columns } /** * cover "covers" a column c of the DLX matrix column c will no longer be found in the column list * rows i with 1 element in column c will no longer be found in other column lists than c so * column c and rows i are invisible after execution of cover * * @param DLXNode c: kopfTeil element of column that has to be covered * */ public static void cover(DLXNode c) { // remove column c c.R.L = c.L; // remove header c.L.R = c.R; // .. from row list for (DLXNode i = c.D; i != c; i = i.D) // forall rows with 1 for (DLXNode j = i.R; i != j; j = j.R) { // forall elem in row j.D.U = j.U; // remove row element j.U.D = j.D; // .. from column list } } /** * uncover "uncovers" a column c of the DLX matrix all operations of cover are undone so column c * and rows i are visible again after execution of uncover * * @param DLXNode c: kopfTeil element of column that has to be uncovered */ public static void uncover(DLXNode c) {// undo remove col c for (DLXNode i = c.U; i != c; i = i.U) // forall rows with 1 for (DLXNode j = i.L; i != j; j = j.L) { // forall elem in row j.D.U = j; // un-remove row elem j.U.D = j; // .. to column list } c.R.L = c; // un-remove header c.L.R = c; // .. to row list } public static void main(String[] args) { new PentominoZIPDLX(); } }
package de.st_ddt.crazylogin; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class CrazyLoginPlayerListener implements Listener { private final CrazyLogin plugin; private final HashMap<String, Location> movementBlocker = new HashMap<String, Location>(); private final HashMap<String, Location> savelogin = new HashMap<String, Location>(); public CrazyLoginPlayerListener(final CrazyLogin plugin) { super(); this.plugin = plugin; } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void PlayerLogin(final PlayerLoginEvent event) { final Player player = event.getPlayer(); if (!plugin.checkNameLength(event.getPlayer().getName())) { event.setResult(Result.KICK_OTHER); event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "NAME.INVALIDLENGTH", plugin.getMinNameLength(), plugin.getMaxNameLength())); return; } if (plugin.isTempBanned(event.getAddress().getHostAddress())) { event.setResult(Result.KICK_OTHER); event.setKickMessage(ChatColor.RED + "Banned until : " + ChatColor.YELLOW + plugin.getTempBannedString(event.getAddress().getHostAddress())); return; } if (plugin.isForceSingleSessionEnabled()) if (player.isOnline()) { if (plugin.isForceSingleSessionSameIPBypassEnabled()) if (player.getAddress() != null) if (event.getAddress().getHostAddress().equals(player.getAddress().getAddress().getHostAddress())) if (event.getAddress().getHostName().equals(player.getAddress().getAddress().getHostName())) return; event.setResult(Result.KICK_OTHER); event.setKickMessage(plugin.getLocale().getLocaleMessage(player, "SESSION.DUPLICATE")); plugin.broadcastLocaleMessage(true, "crazylogin.warnsession", "SESSION.DUPLICATEWARN", event.getAddress().getHostAddress(), player.getName()); plugin.sendLocaleMessage("SESSION.DUPLICATEWARN", player, event.getAddress().getHostAddress(), player.getName()); } } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void PlayerJoin(final PlayerJoinEvent event) { final Player player = event.getPlayer(); if (movementBlocker.get(player.getName().toLowerCase()) != null) player.teleport(movementBlocker.get(player.getName().toLowerCase()), TeleportCause.PLUGIN); if (!plugin.hasAccount(player)) { if (plugin.isResettingGuestLocationsEnabled()) if (movementBlocker.get(player.getName().toLowerCase()) == null) movementBlocker.put(player.getName().toLowerCase(), player.getLocation()); if (plugin.isAlwaysNeedPassword()) plugin.sendLocaleMessage("REGISTER.HEADER", player); else plugin.sendLocaleMessage("REGISTER.HEADER2", player); plugin.sendLocaleMessage("REGISTER.MESSAGE", player); final int autoKick = plugin.getAutoKickUnregistered(); if (autoKick != -1) plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("REGISTER.REQUEST"), true), autoKick * 20); return; } final LoginPlayerData playerdata = plugin.getPlayerData(player); if (!playerdata.hasIP(player.getAddress().getAddress().getHostAddress())) playerdata.logout(); playerdata.checkTimeOut(plugin); if (plugin.isLoggedIn(player)) return; Location location = player.getLocation(); if (plugin.isForceSaveLoginEnabled()) { triggerSaveLogin(player); location = player.getWorld().getSpawnLocation(); } if (movementBlocker.get(player.getName().toLowerCase()) == null) movementBlocker.put(player.getName().toLowerCase(), location); plugin.sendLocaleMessage("LOGIN.REQUEST", player); final int autoKick = plugin.getAutoKick(); if (autoKick >= 10) plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new ScheduledKickTask(player, plugin.getLocale().getLanguageEntry("LOGIN.REQUEST"), plugin.getAutoTempBan()), autoKick * 20); } @EventHandler public void PlayerQuit(final PlayerQuitEvent event) { final Player player = event.getPlayer(); final LoginData playerdata = plugin.getPlayerData(player); disableSaveLogin(player); if (playerdata != null) { if (!plugin.isLoggedIn(player)) return; playerdata.notifyAction(); if (plugin.isInstantAutoLogoutEnabled()) playerdata.logout(); } } @EventHandler public void PlayerInventoryOpen(final InventoryOpenEvent event) { if (!(event.getPlayer() instanceof Player)) return; final Player player = (Player) event.getPlayer(); if (plugin.isLoggedIn(player)) return; event.setCancelled(true); plugin.requestLogin(player); } @EventHandler public void PlayerPickupItem(final PlayerPickupItemEvent event) { if (plugin.isLoggedIn(event.getPlayer())) return; event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } @EventHandler public void PlayerDropItem(final PlayerDropItemEvent event) { if (plugin.isLoggedIn(event.getPlayer())) return; event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } @EventHandler public void PlayerInteract(final PlayerInteractEvent event) { if (plugin.isLoggedIn(event.getPlayer())) return; event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } @EventHandler public void PlayerInteractEntity(final PlayerInteractEntityEvent event) { if (plugin.isLoggedIn(event.getPlayer())) return; event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } @EventHandler public void PlayerMove(final PlayerMoveEvent event) { final Player player = event.getPlayer(); if (plugin.isLoggedIn(player)) return; final Location current = movementBlocker.get(player.getName().toLowerCase()); if (current == null) return; if (current.getWorld() == event.getTo().getWorld()) if (current.distance(event.getTo()) < plugin.getMoveRange()) return; event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } @EventHandler public void PlayerTeleport(final PlayerTeleportEvent event) { final Player player = event.getPlayer(); if (plugin.isLoggedIn(player)) return; if (movementBlocker.get(player.getName().toLowerCase()) == null) return; if (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.UNKNOWN) { movementBlocker.put(player.getName().toLowerCase(), event.getTo()); return; } event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } @EventHandler public void PlayerDamage(final EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; final Player player = (Player) event.getEntity(); if (plugin.isLoggedIn(player)) return; event.setCancelled(true); } @EventHandler public void PlayerDamage(final EntityDamageByBlockEvent event) { if (!(event.getEntity() instanceof Player)) return; final Player player = (Player) event.getEntity(); if (plugin.isLoggedIn(player)) return; triggerSaveLogin(player); event.setCancelled(true); } @EventHandler public void PlayerDamage(final EntityDamageByEntityEvent event) { if (!(event.getEntity() instanceof Player)) return; final Player player = (Player) event.getEntity(); if (plugin.isLoggedIn(player)) return; triggerSaveLogin(player); event.setCancelled(true); } @EventHandler public void PlayerPreCommand(final PlayerCommandPreprocessEvent event) { final Player player = event.getPlayer(); if (!plugin.isBlockingGuestCommandsEnabled() || plugin.hasAccount(player)) if (plugin.isLoggedIn(player)) return; final String message = event.getMessage().toLowerCase(); if (message.startsWith("/")) { if (message.startsWith("/login") || message.startsWith("/crazylogin password") || message.startsWith("/crazylanguage") || message.startsWith("/language") || message.startsWith("/register")) return; for (final String command : plugin.getCommandWhiteList()) if (message.startsWith(command)) return; event.setCancelled(true); plugin.broadcastLocaleMessage(true, "crazylogin.warncommandexploits", "COMMAND.EXPLOITWARN", player.getName(), player.getAddress().getAddress().getHostAddress(), message); if (plugin.isAutoKickCommandUsers()) { player.kickPlayer(plugin.getLocale().getLocaleMessage(player, "LOGIN.REQUEST")); return; } plugin.requestLogin(event.getPlayer()); return; } } @EventHandler public void PlayerCommand(final PlayerChatEvent event) { final Player player = event.getPlayer(); if (plugin.isLoggedIn(player)) return; event.setCancelled(true); plugin.requestLogin(event.getPlayer()); } public void addToMovementBlocker(final Player player) { addToMovementBlocker(player.getName(), player.getLocation()); } public void addToMovementBlocker(final String player, final Location location) { movementBlocker.put(player.toLowerCase(), location); } public boolean removeFromMovementBlocker(final OfflinePlayer player) { return removeFromMovementBlocker(player.getName()); } public boolean removeFromMovementBlocker(final String player) { return movementBlocker.remove(player.toLowerCase()) != null; } public void clearMovementBlocker(final boolean guestsOnly) { if (guestsOnly) { for (final String name : movementBlocker.keySet()) if (!plugin.hasAccount(name)) movementBlocker.remove(name); } else movementBlocker.clear(); } public void triggerSaveLogin(Player player) { if (savelogin.get(player.getName().toLowerCase()) == null) savelogin.put(player.getName().toLowerCase(), player.getLocation()); player.teleport(player.getWorld().getSpawnLocation(), TeleportCause.PLUGIN); } public void disableSaveLogin(final Player player) { final Location location = savelogin.remove(player.getName().toLowerCase()); if (location == null) return; player.teleport(location, TeleportCause.PLUGIN); } public boolean dropSaveLogin(final String player) { return savelogin.remove(player.toLowerCase()) != null; } }
package whelk.export.marc; import org.apache.commons.lang3.StringUtils; import se.kb.libris.export.ExportProfile; import se.kb.libris.util.marc.MarcRecord; import se.kb.libris.util.marc.io.Iso2709MarcRecordWriter; import se.kb.libris.util.marc.io.MarcRecordWriter; import se.kb.libris.util.marc.io.MarcXmlRecordWriter; import whelk.Document; import whelk.Whelk; import whelk.converter.marc.JsonLD2MarcXMLConverter; import whelk.util.MarcExport; import whelk.util.ThreadPool; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Vector; public class TotalExport { private final int BATCH_SIZE = 200; private JsonLD2MarcXMLConverter m_toMarcXmlConverter; private Whelk m_whelk; final static Logger log = LogManager.getLogger(TotalExport.class); public TotalExport(Whelk whelk) { m_whelk = whelk; m_toMarcXmlConverter = new JsonLD2MarcXMLConverter(whelk.createMarcFrameConverter()); } class Batch { public Batch(ExportProfile profile, MarcRecordWriter output) { bibUrisToConvert = new ArrayList<>(BATCH_SIZE); this.profile = profile; this.output = output; } List<String> bibUrisToConvert; ExportProfile profile; MarcRecordWriter output; } public static void main(String[] args) throws IOException, SQLException, InterruptedException { if (args.length != 3) printUsageAndExit(); ExportProfile profile = new ExportProfile(new File(args[0])); long size = Long.parseLong(args[1]); long segment = Long.parseLong(args[2]); String encoding = profile.getProperty("characterencoding"); if (encoding.equals("Latin1Strip")) { encoding = "ISO-8859-1"; } MarcRecordWriter output = null; if (profile.getProperty("format", "ISO2709").equalsIgnoreCase("MARCXML")) output = new MarcXmlRecordWriter(System.out, encoding); else output = new Iso2709MarcRecordWriter(System.out, encoding); new TotalExport(Whelk.createLoadedCoreWhelk()).dump(profile, size, segment, output); output.close(); } private static void printUsageAndExit() { System.out.println("Usage: java -Dxl.secret.properties=SECRETPROPSFILE -jar marc_export.jar PROFILE-FILE SEGMENT-SIZE SEGMENT"); System.out.println(""); System.out.println(" PROFILE-FILE should be a Java-properties file with the export-profile settings."); System.out.println(" SEGMENT-SIZE is the number of records to dump in each segment."); System.out.println(" SEGMENT is the number of the segment to be dumped."); System.out.println(""); System.out.println("For example:"); System.out.println(" java -jar marc_export.jar export.properties 1000 1"); System.out.println("Would generate the second segment (each consisting of 1000 records) of all records held by whatever"); System.out.println("is in location=[] in export.properties."); System.out.println(""); System.out.println("To not use segmentation, both SEGMENT and SEGMENT-SIZE should be '0'."); System.exit(1); } private void dump(ExportProfile profile, long size, long segment, MarcRecordWriter output) throws SQLException, InterruptedException { ThreadPool threadPool = new ThreadPool(4 * Runtime.getRuntime().availableProcessors()); Batch batch = new Batch(profile, output); try (Connection connection = getConnection(); PreparedStatement statement = getAllHeldURIsStatement(profile, size, size*segment, connection); ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { String bibMainEntityUri = resultSet.getString(1); batch.bibUrisToConvert.add(bibMainEntityUri); if (batch.bibUrisToConvert.size() >= BATCH_SIZE) { threadPool.executeOnThread(batch, this::executeBatch); batch = new Batch(profile, output); } } if (!batch.bibUrisToConvert.isEmpty()) threadPool.executeOnThread(batch, this::executeBatch); } threadPool.joinAll(); } private void executeBatch(Batch batch, int threadIndex) { try (Connection connection = m_whelk.getStorage().getConnection()) { for (String bibUri : batch.bibUrisToConvert) { String systemID = m_whelk.getStorage().getSystemIdByIri(bibUri, connection); if (systemID == null) { log.warn("BibURI " + bibUri + " not found in system, skipping..."); continue; } Document document = m_whelk.getStorage().loadEmbellished(systemID, m_whelk.getJsonld()); Vector<MarcRecord> result = MarcExport.compileVirtualMarcRecord(batch.profile, document, m_whelk, m_toMarcXmlConverter); if (result == null) // A conversion error will already have been logged. continue; for (MarcRecord mr : result) { try { synchronized (this) { batch.output.writeRecord(mr); } } catch (Exception e) { throw new RuntimeException(e); } } } } catch (SQLException e) { throw new RuntimeException(e); } } private Connection getConnection() throws SQLException { Connection connection = m_whelk.getStorage().getConnection(); connection.setAutoCommit(false); return connection; } private PreparedStatement getAllHeldURIsStatement(ExportProfile profile, long limit, long offset, Connection connection) throws SQLException { String locations = profile.getProperty("locations", ""); if (isObviouslyBadSql(locations)) // Not watertight, but this is not user-input. It's admin-input. throw new RuntimeException("SQL INJECTION SUSPECTED."); List<String> libraryUriList = Arrays.asList(locations.split(" ")); String stringList = "'https: String sql = "SELECT data sql = sql.replace("£", stringList); PreparedStatement preparedStatement = connection.prepareStatement(sql); if (limit != 0) { sql += " ORDER BY created LIMIT ? OFFSET ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setLong(1, limit); preparedStatement.setLong(2, offset); } preparedStatement.setFetchSize(100); return preparedStatement; } private boolean isObviouslyBadSql(String sql) { String[] badWords = { "DROP", "TRUNCATE", "MODIFY", "ALTER", "UPDATE", }; for (String word : badWords) if (StringUtils.containsIgnoreCase(sql, word)) return true; return false; } }
package nars.gui; import java.io.File; import java.io.IOException; import javax.swing.JFrame; import nars.core.NAR; import nars.core.build.DefaultNARBuilder.CommandLineNARBuilder; import nars.gui.input.InputPanel; import nars.gui.output.LogPanel; import nars.gui.output.SwingLogPanel; import nars.io.TextInput; /** * The main Swing GUI class of the open-nars project. * Creates default Swing GUI windows to operate a NAR. */ public class NARSwing { /** * The information about the version and date of the project. */ public static final String INFO = "Open-NARS v1.6.1"; /** * The project web sites. */ public static final String WEBSITE = " Open-NARS website: http://code.google.com/p/open-nars/ \n" + " NARS website: http://sites.google.com/site/narswang/"; public final NAR nar; public NARSwing(NAR nar) { super(); this.nar = nar; NARControls narControls = new NARControls(nar); Window mainWindow = new Window(INFO, narControls); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setBounds(10, 10, 270, 600); mainWindow.setVisible(true); mainWindow.setVisible(true); LogPanel outputLog = new SwingLogPanel(narControls); //new HTMLLogPanel(narControls); Window outputWindow = new Window("Log", outputLog); outputWindow.setLocation(mainWindow.getLocation().x + mainWindow.getWidth(), mainWindow.getLocation().y); outputWindow.setSize(800, 400); outputWindow.setVisible(true); InputPanel inputPanel = new InputPanel(nar); Window inputWindow = new Window("Text Input", inputPanel); inputWindow.setLocation(outputWindow.getLocation().x, outputWindow.getLocation().y+outputWindow.getHeight()); inputWindow.setSize(800, 200); inputWindow.setVisible(true); } /** * The entry point of the standalone application. * <p> * Create an instance of the class * * @param args optional argument used : one addInput file, possibly followed by --silence <integer> */ public static void main(String args[]) { NAR nar = new CommandLineNARBuilder(args).build(); //temporary: //NAR nar = new ContinuousBagNARBuilder(false).build(); //NAR nar = new RealTimeNARBuilder(false).build(); NARSwing swing = new NARSwing(nar); if (args.length > 0 && CommandLineNARBuilder.isReallyFile(args[0])) { try { nar.addInput(new TextInput(new File(args[0]))); } catch (IOException ex) { ex.printStackTrace(); } } if (args.length > 1) swing.nar.start(0); } /* static { try { //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //UIManager.setLookAndFeel(new GTKLookAndFeel()); for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { System.out.println(info + " " + info.getName()); if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { // If Nimbus is not available, you can set the GUI to another look and feel. } } */ }
package monads; import static org.junit.Assert.assertEquals; import static monads.Stack.*; import static monads.Pair.*; import org.junit.Test; public class StackTest { private static final Object A = new Object(); private static final Object B = new Object(); private Pair pair = pair(empty()); @Test public void starts_empty() { assertEquals(empty(), pair.stack); } @Test(expected = Exception.class) public void forbids_pop_when_empty() { Stack.pop(pair.stack); } private static interface StackFunction { Pair eval(Stack stack); } private static class StackPush implements StackFunction { private Object value; public StackPush(Object value) { this.value = value; } public Pair eval(Stack stack) { return Stack.push(stack, value); } } private StackPush push(Object value) { return new StackPush(value); } private static class StackPop implements StackFunction { public Pair eval(Stack stack) { return Stack.pop(stack); } } private StackPop pop() { return new StackPop(); } @Test public void pushes_and_pops_an_objects() { pair = push(A).eval(pair.stack); pair = pop().eval(pair.stack); assertEquals(A, pair.value); assertEquals(empty(), pair.stack); } @Test public void pops_objects_in_reverse_push_order() { pair = push(A).eval(pair.stack); pair = push(B).eval(pair.stack); pair = pop().eval(pair.stack); assertEquals(B, pair.value); pair = pop().eval(pair.stack); assertEquals(A, pair.value); assertEquals(empty(), pair.stack); } }
package dr.inference.operators; import dr.inference.loggers.LogColumn; import dr.inference.loggers.Loggable; import dr.inference.loggers.NumberColumn; import dr.math.MathUtils; import dr.xml.*; import java.util.List; import java.util.Vector; import java.util.logging.Logger; /** * This class implements a simple operator schedule. * * @author Alexei Drummond * @version $Id: SimpleOperatorSchedule.java,v 1.5 2005/06/14 10:40:34 rambaut Exp $ */ public class SimpleOperatorSchedule implements OperatorSchedule, Loggable { public static final String OPERATOR_SCHEDULE = "operators"; public static final String SEQUENTIAL = "sequential"; public static final String OPTIMIZATION_SCHEDULE = "optimizationSchedule"; List<MCMCOperator> operators = null; double totalWeight = 0; int current = 0; boolean sequential = false; int optimizationSchedule = OperatorSchedule.DEFAULT_SCHEDULE; public SimpleOperatorSchedule() { operators = new Vector<MCMCOperator>(); } public void addOperators(List<MCMCOperator> operators) { for (MCMCOperator operator : operators) { operators.add(operator); totalWeight += operator.getWeight(); } } public void operatorsHasBeenUpdated() { totalWeight = 0.0; for (MCMCOperator operator : operators) { totalWeight += operator.getWeight(); } } public void addOperator(MCMCOperator op) { operators.add(op); totalWeight += op.getWeight(); } public double getWeight(int index) { return operators.get(index).getWeight(); } public int getNextOperatorIndex() { if (sequential) { int index = getWeightedOperatorIndex(current); current += 1; if (current >= totalWeight) { current = 0; } return index; } return getWeightedOperatorIndex(MathUtils.nextDouble() * totalWeight); } public void setSequential(boolean seq) { sequential = seq; } private int getWeightedOperatorIndex(double q) { int index = 0; double weight = getWeight(index); while (weight <= q) { index += 1; weight += getWeight(index); } return index; } public MCMCOperator getOperator(int index) { return operators.get(index); } public int getOperatorCount() { return operators.size(); } public double getOptimizationTransform(double d) { if (optimizationSchedule == OperatorSchedule.LOG_SCHEDULE) return Math.log(d); if (optimizationSchedule == OperatorSchedule.SQRT_SCHEDULE) return Math.sqrt(d); return d; } public void setOptimizationSchedule(int schedule) { optimizationSchedule = schedule; } // Loggable IMPLEMENTATION /** * @return the log columns. */ public LogColumn[] getColumns() { LogColumn[] columns = new LogColumn[getOperatorCount()]; for (int i = 0; i < getOperatorCount(); i++) { MCMCOperator op = getOperator(i); columns[i] = new OperatorColumn(op.getOperatorName(), op); } return columns; } private class OperatorColumn extends NumberColumn { private MCMCOperator op; public OperatorColumn(String label, MCMCOperator op) { super(label); this.op = op; } public double getDoubleValue() { return MCMCOperator.Utils.getAcceptanceProbability(op); } } public static dr.xml.XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return OPERATOR_SCHEDULE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { SimpleOperatorSchedule schedule = new SimpleOperatorSchedule(); if (xo.hasAttribute(SEQUENTIAL)) { schedule.setSequential(xo.getBooleanAttribute(SEQUENTIAL)); } if (xo.hasAttribute(OPTIMIZATION_SCHEDULE)) { String type = xo.getStringAttribute(OPTIMIZATION_SCHEDULE); Logger.getLogger("dr.inference").info("Optimization Scheduule: " + type); if (type.equals(OperatorSchedule.LOG_STRING)) schedule.setOptimizationSchedule(OperatorSchedule.LOG_SCHEDULE); else if (type.equals(OperatorSchedule.SQRT_STRING)) schedule.setOptimizationSchedule(SQRT_SCHEDULE); else if (!type.equals(OperatorSchedule.DEFAULT_STRING)) throw new RuntimeException("Unsupported optimization schedule"); } for (int i = 0; i < xo.getChildCount(); i++) { Object child = xo.getChild(i); if (child instanceof MCMCOperator) { schedule.addOperator((MCMCOperator) child); } } return schedule; }
package cn.jiguang.cordova.im; import android.text.TextUtils; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import cn.jpush.im.android.api.JMessageClient; import cn.jpush.im.android.api.content.CustomContent; import cn.jpush.im.android.api.content.EventNotificationContent; import cn.jpush.im.android.api.content.FileContent; import cn.jpush.im.android.api.content.ImageContent; import cn.jpush.im.android.api.content.LocationContent; import cn.jpush.im.android.api.content.MessageContent; import cn.jpush.im.android.api.content.TextContent; import cn.jpush.im.android.api.content.VoiceContent; import cn.jpush.im.android.api.enums.ConversationType; import cn.jpush.im.android.api.enums.MessageDirect; import cn.jpush.im.android.api.model.Conversation; import cn.jpush.im.android.api.model.GroupInfo; import cn.jpush.im.android.api.model.Message; import cn.jpush.im.android.api.model.UserInfo; class JsonUtils { static Map<String, String> fromJson(JSONObject jsonObject) throws JSONException { Map<String, String> map = new HashMap<String, String>(); Iterator<String> keysItr = jsonObject.keys(); while (keysItr.hasNext()) { String key = keysItr.next(); String value = jsonObject.getString(key); map.put(key, value); } return map; } static JSONObject toJson(Map<String, String> map) { Iterator<String> iterator = map.keySet().iterator(); JSONObject jsonObject = new JSONObject(); while (iterator.hasNext()) { String key = iterator.next(); try { jsonObject.put(key, map.get(key)); } catch (JSONException e) { Log.wtf("RequestManager", "Failed to put value for " + key + " into JSONObject.", e); } } return jsonObject; } static JSONObject toJson(final UserInfo userInfo) { if (userInfo == null) { return null; } final JSONObject result = new JSONObject(); try { result.put("type", "user"); result.put("gender", userInfo.getGender()); result.put("username", userInfo.getUserName()); result.put("appKey", userInfo.getAppKey()); result.put("nickname", userInfo.getNickname()); if (userInfo.getAvatarFile() != null) { result.put("avatarThumbPath", userInfo.getAvatarFile().getAbsolutePath()); } else { result.put("avatarThumbPath", ""); } result.put("birthday", userInfo.getBirthday()); result.put("region", userInfo.getRegion()); result.put("signature", userInfo.getSignature()); result.put("address", userInfo.getAddress()); result.put("noteName", userInfo.getNotename()); result.put("noteText", userInfo.getNoteText()); result.put("isNoDisturb", userInfo.getNoDisturb() == 1); result.put("isInBlackList", userInfo.getNoDisturb() == 1); result.put("isFriend", userInfo.isFriend()); Map<String, String> extras = userInfo.getExtras(); JSONObject extrasJson = toJson(extras); result.put("extras", extrasJson.toString()); } catch (JSONException e) { e.printStackTrace(); } return result; } static JSONObject toJson(GroupInfo groupInfo) { JSONObject result = new JSONObject(); try { result.put("type", "group"); result.put("id", String.valueOf(groupInfo.getGroupID())); result.put("name", groupInfo.getGroupName()); result.put("desc", groupInfo.getGroupDescription()); result.put("level", groupInfo.getGroupLevel()); result.put("owner", groupInfo.getGroupOwner()); result.put("ownerAppKey", groupInfo.getOwnerAppkey()); result.put("maxMemberCount", groupInfo.getMaxMemberCount()); result.put("isNoDisturb", groupInfo.getNoDisturb() == 1); result.put("isBlocked", groupInfo.isGroupBlocked() == 1); } catch (JSONException e) { e.printStackTrace(); } return result; } static JSONObject toJson(Message msg) { JSONObject result = new JSONObject(); try { result.put("id", String.valueOf(msg.getId())); result.put("serverMessageId", String.valueOf(msg.getServerMessageId())); result.put("from", toJson(msg.getFromUser())); if (msg.getDirect() == MessageDirect.send) { if (msg.getTargetType() == ConversationType.single) { result.put("target", toJson((UserInfo) msg.getTargetInfo())); } else if (msg.getTargetType() == ConversationType.group) { result.put("target", toJson((GroupInfo) msg.getTargetInfo())); } } else if (msg.getDirect() == MessageDirect.receive) { if (msg.getTargetType() == ConversationType.single) { result.put("target", toJson(JMessageClient.getMyInfo())); } else if (msg.getTargetType() == ConversationType.group) { result.put("target", toJson((GroupInfo) msg.getTargetInfo())); } } MessageContent content = msg.getContent(); if (content.getStringExtras() != null) { result.put("extras", toJson(content.getStringExtras())); } else { result.put("extras", new JSONObject()); } result.put("createTime", msg.getCreateTime()); switch (msg.getContentType()) { case text: result.put("type", "text"); result.put("text", ((TextContent) content).getText()); break; case image: result.put("type", "image"); result.put("thumbPath", ((ImageContent) content).getLocalThumbnailPath()); break; case voice: result.put("type", "voice"); result.put("path", ((VoiceContent) content).getLocalPath()); result.put("duration", ((VoiceContent) content).getDuration()); break; case file: result.put("type", "file"); result.put("fileName", ((FileContent) content).getFileName()); break; case custom: result.put("type", "custom"); Map<String, String> customObject = ((CustomContent) content).getAllStringValues(); result.put("customObject", toJson(customObject)); break; case location: result.put("type", "location"); result.put("latitude", ((LocationContent) content).getLatitude()); result.put("longitude", ((LocationContent) content).getLongitude()); result.put("address", ((LocationContent) content).getAddress()); result.put("scale", ((LocationContent) content).getScale()); break; case eventNotification: result.put("type", "event"); List usernameList = ((EventNotificationContent) content).getUserNames(); result.put("usernames", toJson(usernameList)); switch (((EventNotificationContent) content).getEventNotificationType()) { case group_member_added: result.put("eventType", "group_member_added"); break; case group_member_removed: result.put("eventType", "group_member_removed"); break; case group_member_exit: result.put("eventType", "group_member_exit"); break; } } } catch (JSONException e) { e.printStackTrace(); } return result; } static JSONObject toJson(Conversation conversation) { JSONObject json = new JSONObject(); try { json.put("title", conversation.getTitle()); json.put("conversationType", conversation.getType()); json.put("unreadCount", conversation.getUnReadMsgCnt()); if (conversation.getLatestMessage() != null) { json.put("latestMessage", toJson(conversation.getLatestMessage())); } if (conversation.getType() == ConversationType.single) { UserInfo targetInfo = (UserInfo) conversation.getTargetInfo(); json.put("target", toJson(targetInfo)); } else if (conversation.getType() == ConversationType.group) { GroupInfo targetInfo = (GroupInfo) conversation.getTargetInfo(); json.put("target", toJson(targetInfo)); } String extraStr = conversation.getExtra(); JSONObject extra = TextUtils.isEmpty(extraStr) ? new JSONObject() : new JSONObject(extraStr); json.put("extra", extra); } catch (JSONException e) { e.printStackTrace(); } return json; } static JSONArray toJson(List list) { JSONArray jsonArray = new JSONArray(); for (Object object : list) { if (object instanceof UserInfo) { jsonArray.put(toJson((UserInfo) object)); } else if (object instanceof GroupInfo) { jsonArray.put(toJson((GroupInfo) object)); } else if (object instanceof Message) { jsonArray.put(toJson((Message) object)); } else { jsonArray.put(object); } } return jsonArray; } static JSONObject toJson(String eventName, JSONObject value) { JSONObject result = new JSONObject(); try { result.put("eventName", eventName); result.put("value", value); } catch (JSONException e) { e.printStackTrace(); } return result; } }
package com.github.nsnjson; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import org.junit.*; import static com.github.nsnjson.format.Format.*; public class DriverTest extends AbstractFormatTest { @Test public void testNull() { shouldBeConsistencyWhenGivenNull(getNull(), getNullPresentation()); } @Test public void testNumberInt() { NumericNode value = getNumberInt(); shouldBeConsistencyWhenGivenNumberIsInt(value, getNumberIntPresentation(value)); } @Test public void testNumberLong() { NumericNode value = getNumberLong(); shouldBeConsistencyWhenGivenNumberIsLong(value, getNumberLongPresentation(value)); } @Test public void testNumberDouble() { NumericNode value = getNumberDouble(); shouldBeConsistencyWhenGivenNumberIsDouble(value, getNumberDoublePresentation(value)); } @Test public void testEmptyString() { TextNode value = getEmptyString(); shouldBeConsistencyWhenGivenStringIsEmpty(value, getStringPresentation(value)); } @Test public void testString() { TextNode value = getString(); shouldBeConsistencyWhenGivenString(value, getStringPresentation(value)); } @Test public void testBooleanTrue() { BooleanNode value = getBooleanTrue(); shouldBeConsistencyWhenGivenBooleanIsTrue(value, getBooleanPresentation(value)); } @Test public void testBooleanFalse() { BooleanNode value = getBooleanFalse(); shouldBeConsistencyWhenGivenBooleanIsFalse(value, getBooleanPresentation(value)); } @Test public void testEmptyArray() { shouldBeConsistencyWhenGivenArrayIsEmpty(getEmptyArray(), getEmptyArrayPresentation()); } @Test public void shouldBeConsistencyWhenGivenArray() { ObjectMapper objectMapper = new ObjectMapper(); JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ArrayNode array = objectMapper.createArrayNode(); array.add(getNull()); array.add(numberInt); array.add(numberLong); array.add(numberDouble); array.add(string); array.add(booleanTrue); array.add(booleanFalse); ObjectNode presentationOfNull = objectMapper.createObjectNode(); presentationOfNull.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberInt = objectMapper.createObjectNode(); presentationOfNumberInt.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberInt.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLong = objectMapper.createObjectNode(); presentationOfNumberLong.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLong.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDouble = objectMapper.createObjectNode(); presentationOfNumberDouble.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDouble.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfString = objectMapper.createObjectNode(); presentationOfString.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfString.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrue = objectMapper.createObjectNode(); presentationOfBooleanTrue.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrue.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalse = objectMapper.createObjectNode(); presentationOfBooleanFalse.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalse.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNull); presentationOfArrayItems.add(presentationOfNumberInt); presentationOfArrayItems.add(presentationOfNumberLong); presentationOfArrayItems.add(presentationOfNumberDouble); presentationOfArrayItems.add(presentationOfString); presentationOfArrayItems.add(presentationOfBooleanTrue); presentationOfArrayItems.add(presentationOfBooleanFalse); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_ARRAY); presentation.set(FIELD_VALUE, presentationOfArrayItems); assertConsistency(array, presentation); } @Test public void shouldBeConsistencyWhenGivenObjectIsEmpty() { assertConsistency(getEmptyObject(), getEmptyObjectPresentation()); } @Test public void shouldBeConsistencyWhenGivenObject() { ObjectMapper objectMapper = new ObjectMapper(); String nullField = "null_field"; String numberIntField = "int_field"; String numberLongField = "long_field"; String numberDoubleField = "double_field"; String stringField = "string_field"; String booleanTrueField = "true_field"; String booleanFalseField = "false_field"; JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ObjectNode object = objectMapper.createObjectNode(); object.set(nullField, getNull()); object.set(numberIntField, numberInt); object.set(numberLongField, numberLong); object.set(numberDoubleField, numberDouble); object.set(stringField, string); object.set(booleanTrueField, booleanTrue); object.set(booleanFalseField, booleanFalse); ObjectNode presentationOfNullField = objectMapper.createObjectNode(); presentationOfNullField.put(FIELD_NAME, nullField); presentationOfNullField.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberIntField = objectMapper.createObjectNode(); presentationOfNumberIntField.put(FIELD_NAME, numberIntField); presentationOfNumberIntField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberIntField.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLongField = objectMapper.createObjectNode(); presentationOfNumberLongField.put(FIELD_NAME, numberLongField); presentationOfNumberLongField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLongField.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDoubleField = objectMapper.createObjectNode(); presentationOfNumberDoubleField.put(FIELD_NAME, numberDoubleField); presentationOfNumberDoubleField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDoubleField.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfStringField = objectMapper.createObjectNode(); presentationOfStringField.put(FIELD_NAME, stringField); presentationOfStringField.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfStringField.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrueField = objectMapper.createObjectNode(); presentationOfBooleanTrueField.put(FIELD_NAME, booleanTrueField); presentationOfBooleanTrueField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrueField.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalseField = objectMapper.createObjectNode(); presentationOfBooleanFalseField.put(FIELD_NAME, booleanFalseField); presentationOfBooleanFalseField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalseField.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNullField); presentationOfArrayItems.add(presentationOfNumberIntField); presentationOfArrayItems.add(presentationOfNumberLongField); presentationOfArrayItems.add(presentationOfNumberDoubleField); presentationOfArrayItems.add(presentationOfStringField); presentationOfArrayItems.add(presentationOfBooleanTrueField); presentationOfArrayItems.add(presentationOfBooleanFalseField); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_OBJECT); presentation.set(FIELD_VALUE, presentationOfArrayItems); assertConsistency(object, presentation); } private void shouldBeConsistencyWhenGivenNull(NullNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenNumberIsInt(NumericNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenNumber(value, presentation); } private void shouldBeConsistencyWhenGivenNumberIsLong(NumericNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenNumber(value, presentation); } private void shouldBeConsistencyWhenGivenNumberIsDouble(NumericNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenNumber(value, presentation); } private void shouldBeConsistencyWhenGivenNumber(NumericNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenStringIsEmpty(TextNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenString(value, presentation); } private void shouldBeConsistencyWhenGivenString(TextNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenBooleanIsTrue(BooleanNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenBoolean(value, presentation); } private void shouldBeConsistencyWhenGivenBooleanIsFalse(BooleanNode value, ObjectNode presentation) { shouldBeConsistencyWhenGivenBoolean(value, presentation); } private void shouldBeConsistencyWhenGivenBoolean(BooleanNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenArrayIsEmpty(ArrayNode array, ObjectNode presentation) { assertConsistency(array, presentation); } private static void assertConsistency(JsonNode value, ObjectNode presentation) { Assert.assertEquals(value, Driver.decode(Driver.encode(value))); Assert.assertEquals(presentation, Driver.encode(Driver.decode(presentation))); } }
package com.precious.calccedo.handlers; import com.precious.calccedo.Calccedo; import com.precious.calccedo.configuration.Configuration; import java.util.ArrayList; /** * * @author Ibrahim Abdsaid Hanna * ibrahim.seniore@gmail.com */ public class CalccedoHandler extends Calccedo implements Handler { private ArrayList<Character> list; private ArrayList<Character> list2; public CalccedoHandler(){ list=new ArrayList<>(); list.add('S'); list.add('C'); list.add('T'); list.add('L'); list.add('<'); list.add('('); list2=new ArrayList<>(); list2.add('/'); list2.add('%'); list2.add('+'); list2.add('-'); list2.add('*'); list2.add('^'); list2.add('n'); list2.add('s'); list2.add('g'); list2.add('<'); list2.add('('); init(); } private Quote parsePartethis(String formula) { int offsetA=0; int offsetZ=0; for(int i=formula.length()-1;i>=0;i if(formula.charAt(i)=='('){ offsetA=i; for(int j=i;j<formula.length();j++){ if(formula.charAt(j)==')'){ offsetZ=j; i=-1; break; } } } } if(offsetA==0){ return new Quote(formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else{ try{ if(formula.substring(offsetA-3, offsetA).equals("Sin")){ return new Quote("Sin", formula.substring(offsetA, offsetZ+1),offsetA, offsetZ+1); } else if(formula.substring(offsetA-3, offsetA).equals("Cos")){ return new Quote("Cos", formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else if(formula.substring(offsetA-3, offsetA).equals("Tan")){ return new Quote("Tan", formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else if(formula.substring(offsetA-3, offsetA).equals("Log")){ return new Quote("Log", formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } else{ return new Quote(formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } } catch(Exception ex){ return new Quote(formula.substring(offsetA, offsetZ+1), offsetA, offsetZ+1); } } } private String obtainQuoteOperand(String digits){ if(digits.equals("Sin")){ return "Sin"; } else if(digits.equals("Cos")){ return "Cos"; } if(digits.equals("Tan")){ return "Tan"; } if(digits.equals("Log")){ return "Log"; } else{ return ""; } } @Override public boolean isNumber(char c){ if(c=='.'){ return true; } try{ Integer.parseInt(""+c); return true; } catch(Exception ex){ return false; } } @Override public String optimizeFormula(String formula) { String newformula=""; for(int i=0;i<formula.length();i++){ if(list.contains(formula.charAt(i)) && i>0){ if(list2.contains(formula.charAt(i-1)) && i>0){ newformula=newformula+formula.charAt(i); } else{ newformula=newformula+"*"+formula.charAt(i); } } else if(isNumber(formula.charAt(i))){ if(i>0&&(formula.charAt(i-1)==')'||formula.charAt(i-1)=='>')){ newformula=newformula+"*"+formula.charAt(i); } else{ newformula=newformula+formula.charAt(i); } } else{ newformula=newformula+formula.charAt(i); } } if(Configuration.deepTracing) System.out.println("optinmization is >>>>>>>>>>>"+newformula); return newformula; } @Override public boolean initValidation(String formula) { if(!formula.contains("(")&&!formula.contains("<")&&!formula.contains(">")&&!formula.contains(")")){ return true; } int openedPartethis=0; int openedRoot=0; for(int i=0;i<formula.length();i++){ if(formula.charAt(i)=='('){ openedPartethis++; } if(formula.charAt(i)==')'){ openedPartethis } if(openedPartethis<0){ return false; } if(formula.charAt(i)=='<'){ openedRoot++; } if(formula.charAt(i)=='>'){ openedRoot } if(openedRoot<0){ return false; } } return openedPartethis==0 && openedRoot==0 ; } @Override public String calculate(String formula) { // validate formula if(!initValidation(formula)) return "Error"; // optimize formula formula=optimizeFormula(formula); // calculate inside partethis String firstProcess= calculatePartethis(formula); if(firstProcess.equals("error")){ return "Error"; } // include final formula inside partetehis to process it // second peocess is the final process in calccedo, just because conatins only +,- String secondProcess= calculatePartethis("("+firstProcess+")"); if(secondProcess.equals("error")){ return "Error"; } // detect final result contain fractions, if not return result as Integer value if(secondProcess.endsWith(".0")){ secondProcess=secondProcess.substring(0,secondProcess.lastIndexOf(".0")); } return secondProcess; } private String calculatePartethis(String formula){ Quote quote; SubFormula subFormula; QuoteResult quoteResult; while(formula.contains("(")){ quote=parsePartethis(formula); subFormula=new SubFormula(quote); quoteResult=subFormula.getQuoteResult(); if(quoteResult==null){ return "error"; } else{ formula=formula.substring(0,quoteResult.offsetA)+quoteResult.result+formula.substring(quoteResult.offsetZ,formula.length()); } } if(Configuration.deepTracing) System.out.println("formula after parsing partethis"+formula); return formula; } @Override public boolean isNumber(String quote) { try{ Double.parseDouble(quote); return true; } catch(Exception ex){ if(Configuration.deepTracing){ // System.err.println(ex+"\n just dummy exception do in behind while validating Numbers\n"); System.out.println("\nCalccedo Info: this is just info to help developers how Calccedo Library work"); System.out.println("Info quote "+quote+", cannot wrapped to Double, so it will complete loop until finishing operations \n"); } return false; } } }
package edu.teco.dnd.eclipse.deployView; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; 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.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import edu.teco.dnd.blocks.FunctionBlock; import edu.teco.dnd.blocks.InvalidFunctionBlockException; import edu.teco.dnd.deploy.Constraint; import edu.teco.dnd.deploy.Distribution; import edu.teco.dnd.deploy.Distribution.BlockTarget; import edu.teco.dnd.deploy.Deploy; import edu.teco.dnd.deploy.DeployListener; import edu.teco.dnd.deploy.DistributionGenerator; import edu.teco.dnd.deploy.MinimalModuleCountEvaluator; import edu.teco.dnd.deploy.UserConstraints; import edu.teco.dnd.eclipse.Activator; import edu.teco.dnd.eclipse.EclipseUtil; import edu.teco.dnd.eclipse.ModuleManager; import edu.teco.dnd.eclipse.ModuleManagerListener; import edu.teco.dnd.graphiti.model.FunctionBlockModel; import edu.teco.dnd.module.Module; import edu.teco.dnd.util.Dependencies; import edu.teco.dnd.util.FutureListener; import edu.teco.dnd.util.FutureNotifier; import edu.teco.dnd.util.StringUtil; /** * This class gives the user access to all functionality needed to deploy an * application. The user can load an existing data flow graph, rename its * function blocks and constrain them to specific modules and / or places. The * user can also create a distribution and deploy the function blocks on the * modules. * */ public class DeployView extends EditorPart implements ModuleManagerListener { /** * The logger for this class. */ private static final Logger LOGGER = LogManager.getLogger(DeployView.class); private Display display; private Activator activator; private ModuleManager manager; private ArrayList<UUID> idList = new ArrayList<UUID>(); private Collection<FunctionBlockModel> functionBlockModels; private Map<TableItem, FunctionBlockModel> mapItemToBlockModel; private Map<FunctionBlock, BlockTarget> mapBlockToTarget; private DeployViewGraphics graphicsManager; private boolean newConstraints; private Button serverButton; private Button updateModulesButton; // Button to update moduleCombo private Button updateBlocksButton; private Button createButton; // Button to create deployment private Button deployButton; // Button to deploy deployment private Button constraintsButton; private Label appName; private Text blockModelName; // Name of BlockModel private Combo moduleCombo; private Text places; private Table deployment; // Table to show blockModels and current // deployment private int selectedIndex; // Index of selected field of moduleCombo // = index in idList + 1 private UUID selectedID; private TableItem selectedItem; private FunctionBlockModel selectedBlockModel; private Map<FunctionBlockModel, UUID> moduleConstraints = new HashMap<FunctionBlockModel, UUID>(); private Map<FunctionBlockModel, String> placeConstraints = new HashMap<FunctionBlockModel, String>(); private URL[] classPath = new URL[0]; @Override public void setFocus() { } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { LOGGER.entry(site, input); setSite(site); setInput(input); activator = Activator.getDefault(); display = Display.getCurrent(); manager = activator.getModuleManager(); if (display == null) { display = Display.getDefault(); LOGGER.trace( "Display.getCurrent() returned null, using Display.getDefault(): {}", display); } manager.addModuleManagerListener(this); LOGGER.exit(); mapBlockToTarget = new HashMap<FunctionBlock, BlockTarget>(); } @Override public void createPartControl(Composite parent) { functionBlockModels = new ArrayList<FunctionBlockModel>(); mapItemToBlockModel = new HashMap<TableItem, FunctionBlockModel>(); graphicsManager = new DeployViewGraphics(parent, activator); graphicsManager.initializeParent(); appName = graphicsManager.createAppNameLabel(); serverButton = graphicsManager.createServerButton(); graphicsManager.createBlockModelSpecsLabel(); deployment = graphicsManager.createDeploymentTable(); updateModulesButton = graphicsManager.createUpdateModulesButton(); graphicsManager.createBlockModelLabel(); blockModelName = graphicsManager.createBlockModelName(); updateBlocksButton = graphicsManager.createUpdateBlocksButton(); graphicsManager.createModuleLabel(); moduleCombo = graphicsManager.createModuleCombo(); createButton = graphicsManager.createCreateButton(); graphicsManager.createPlaceLabel(); places = graphicsManager.createPlacesText(); deployButton = graphicsManager.createDeployButton(); constraintsButton = graphicsManager.createConstraintsButton(); createSelectionListeners(); loadBlockModels(getEditorInput()); } /** * Invoked whenever the UpdateModules Button is pressed. */ private void updateModules() { if (Activator.getDefault().isRunning()) { warn("Not implemented yet. \n Later: Will update information on moduleCombo"); } else { warn("Server not running"); } } /** * Invoked whenever the UpdateBlocks Button is pressed. */ private void updateBlocks() { Collection<FunctionBlockModel> newBlockModels = new ArrayList<FunctionBlockModel>(); Map<UUID, FunctionBlockModel> newIDs = new HashMap<UUID, FunctionBlockModel>(); Map<UUID, FunctionBlockModel> oldIDs = new HashMap<UUID, FunctionBlockModel>(); if (getEditorInput() instanceof FileEditorInput) { try { newBlockModels = loadInput((FileEditorInput) getEditorInput()); } catch (IOException e) { LOGGER.catching(e); } } else { LOGGER.error("Input is not a FileEditorInput {}", getEditorInput()); } for (FunctionBlockModel model : newBlockModels) { newIDs.put(model.getID(), model); } for (FunctionBlockModel model : functionBlockModels) { oldIDs.put(model.getID(), model); } resetDeployment(); if (selectedBlockModel != null) { if (!newIDs.keySet().contains(selectedBlockModel.getID())) { resetSelectedBlock(); } else { selectedBlockModel = newIDs.get(selectedBlockModel.getID()); if (selectedBlockModel.getPosition() != null) { places.setText(selectedBlockModel.getPosition()); } if (selectedBlockModel.getBlockName() != null) { blockModelName.setText(selectedBlockModel.getBlockName()); } } } for (FunctionBlockModel oldModel : functionBlockModels) { if (newIDs.containsKey(oldModel.getID())) { FunctionBlockModel newModel = newIDs.get(oldModel.getID()); replaceBlock(oldModel, newModel); } else { removeBlock(oldModel); } } for (FunctionBlockModel newModel : newBlockModels) { if (!oldIDs.containsKey(newModel.getID())) { addBlock(newModel); } } functionBlockModels = newBlockModels; } /** * Adds representation of a functionBlockModel that has just been added to * the functionBlockModels list. * * @param model * FunctionBlockModel to add. */ private void addBlock(FunctionBlockModel model) { TableItem item = new TableItem(deployment, SWT.NONE); String name = model.getBlockName(); if (name != null) { item.setText(0, name); } String position = model.getPosition(); if (position != null && !position.isEmpty()) { item.setText(2, position); placeConstraints.put(model, position); } mapItemToBlockModel.put(item, model); } /** * Replaces a FunctionBlockModel another FunctionBlockModel. This method * does NOT add the newBlock to the functionBlockModels list but takes care * of everything else - representation and constraints. * * @param oldBlock * old Block * @param newBlock * new Block. */ private void replaceBlock(FunctionBlockModel oldBlock, FunctionBlockModel newBlock) { TableItem item = getItem(oldBlock); UUID module = moduleConstraints.get(oldBlock); moduleConstraints.remove(oldBlock); placeConstraints.remove(oldBlock); mapItemToBlockModel.put(item, newBlock); if (newBlock.getBlockName() != null) { item.setText(0, newBlock.getBlockName()); } if (module != null) { moduleConstraints.put(newBlock, module); } String newPosition = newBlock.getPosition(); if (newPosition != null) { item.setText(2, newPosition); if (!newPosition.isEmpty()) { placeConstraints.put(newBlock, newPosition); } } else { item.setText(2, ""); } } private void removeBlock(FunctionBlockModel model) { TableItem item = getItem(model); moduleConstraints.remove(model); placeConstraints.remove(model); mapItemToBlockModel.remove(item); item.dispose(); } /** * Invoked whenever the Create Button is pressed. */ private void create() { Collection<Module> moduleCollection = getModuleCollection(); if (functionBlockModels.isEmpty()) { warn("No blockModels to distribute"); return; } if (moduleCollection.isEmpty()) { warn("No modules to deploy on"); return; } final ClassLoader classLoader = new URLClassLoader(classPath, DeployView.class.getClassLoader()); Map<FunctionBlock, FunctionBlockModel> blocksToModels = new HashMap<FunctionBlock, FunctionBlockModel>(); for (FunctionBlockModel model : functionBlockModels) { try { blocksToModels.put(model.createBlock(classLoader), model); } catch (InvalidFunctionBlockException e) { e.printStackTrace(); } } Collection<Constraint> constraints = new ArrayList<Constraint>(); constraints .add(new UserConstraints(moduleConstraints, placeConstraints)); DistributionGenerator generator = new DistributionGenerator( new MinimalModuleCountEvaluator(), constraints); Distribution dist = generator.getDistribution(blocksToModels.keySet(), moduleCollection); if (dist == null) { warn("No valid deployment exists"); } else { mapBlockToTarget = dist.getMapping(); for (FunctionBlock block : mapBlockToTarget.keySet()) { FunctionBlockModel blockModel = blocksToModels.get(block); TableItem item = getItem(blockModel); final String name = mapBlockToTarget.get(block).getModule() .getName(); item.setText(3, name == null ? "" : name); final String location = mapBlockToTarget.get(block).getModule() .getLocation(); item.setText(4, location == null ? "" : location); deployButton.setEnabled(true); newConstraints = false; } } } /** * Invoked whenever the Deploy Button is pressed. */ private void deploy() { if (mapBlockToTarget.isEmpty()) { warn(DeployViewTexts.NO_DEPLOYMENT_YET); return; } if (newConstraints) { int cancel = warn(DeployViewTexts.NEWCONSTRAINTS); if (cancel == -4) { return; } } final Dependencies dependencies = new Dependencies( StringUtil.joinArray(classPath, ":"), Arrays.asList( Pattern.compile("java\\..*"), Pattern.compile("edu\\.teco\\.dnd\\..*"), Pattern.compile("com\\.google\\.gson\\..*"), Pattern.compile("org\\.apache\\.bcel\\..*"), Pattern.compile("io\\.netty\\..*"), Pattern.compile("org\\.apache\\.logging\\.log4j") ) ); final Deploy deploy = new Deploy(Activator.getDefault().getConnectionManager(), mapBlockToTarget, appName.getText(), dependencies); // TODO: I don't know if this will be needed by DeployView. It can be used to wait until the deployment finishes or to run code at that point deploy.getDeployFutureNotifier().addListener(new FutureListener<FutureNotifier<? super Void>>() { @Override public void operationComplete(FutureNotifier<? super Void> future) { if (LOGGER.isInfoEnabled()) { LOGGER.info("deploy: {}", future.isSuccess()); } } }); deploy.addListener(new DeployListener() { // TODO: actually show the progress. Probably using Eclipse Jobs @Override public void moduleJoined(UUID appId, UUID moduleUUID) { LOGGER.debug("Module {} joined Application {}", moduleUUID, appId); } @Override public void moduleLoadedClasses(UUID appId, UUID moduleUUID) { LOGGER.debug("Module {} loaded all classes for Application {}", moduleUUID, appId); } @Override public void moduleLoadedBlocks(UUID appId, UUID moduleUUID) { LOGGER.debug( "Module {} loaded all FunctionBlocks for Application {}", moduleUUID, appId); } @Override public void moduleStarted(final UUID appId, final UUID moduleUUID) { LOGGER.debug("Module {} started the Application {}", moduleUUID, appId); } @Override public void deployFailed(UUID appId, Throwable cause) { LOGGER.debug("deploying Application {} failed: {}", appId, cause); } }); deploy.deploy(); resetDeployment(); } /** * Invoked whenever a Function BlockModel from the deploymentTable is * selected. */ protected void blockModelSelected() { moduleCombo.setEnabled(true); places.setEnabled(true); constraintsButton.setEnabled(true); blockModelName.setEnabled(true); TableItem[] items = deployment.getSelection(); if (items.length == 1) { selectedItem = items[0]; selectedBlockModel = mapItemToBlockModel.get(items[0]); blockModelName.setText(selectedBlockModel.getBlockName()); if (placeConstraints.containsKey(selectedBlockModel)) { places.setText(placeConstraints.get(selectedBlockModel)); } else { places.setText(""); } selectedIndex = idList.indexOf(moduleConstraints .get(selectedBlockModel)) + 1; moduleCombo.select(selectedIndex); } } /** * Invoked whenever a Module from moduleCombo is selected. */ private void moduleSelected() { selectedIndex = moduleCombo.getSelectionIndex(); } private void saveConstraints() { String text = places.getText(); if (selectedIndex > 0) { selectedID = idList.get(selectedIndex - 1); } else { selectedID = null; } if (!text.isEmpty() && selectedID != null) { int cancel = warn(DeployViewTexts.WARN_CONSTRAINTS); if (cancel == -4) { return; } } if (text.isEmpty()) { placeConstraints.remove(selectedBlockModel); } else { placeConstraints.put(selectedBlockModel, text); } selectedBlockModel.setPosition(text); selectedItem.setText(2, text); if (selectedID != null) { moduleConstraints.put(selectedBlockModel, selectedID); String module = moduleCombo.getItem(selectedIndex); selectedItem.setText(1, module); } else { selectedItem.setText(1, ""); moduleConstraints.remove(selectedBlockModel); } selectedBlockModel.setBlockName(this.blockModelName.getText()); selectedItem.setText(0, blockModelName.getText()); newConstraints = true; } /** * Adds a Module ID. * * @param id * the ID to add */ private synchronized void addID(final UUID id) { LOGGER.entry(id); if (!idList.contains(id)) { LOGGER.trace("id {} is new, adding", id); moduleCombo.add(id.toString()); idList.add(id); } else { LOGGER.debug("trying to add existing id {}", id); } LOGGER.exit(); } /** * Removes a Module ID including all dependent information on this module. * * @param id * the ID to remove */ private synchronized void removeID(final UUID id) { LOGGER.entry(id); int idIndex = idList.indexOf(id); if (idIndex >= 0) { moduleCombo.remove(idIndex + 1); idList.remove(idIndex); resetDeployment(); for (FunctionBlockModel model : moduleConstraints.keySet()) { if (moduleConstraints.get(model).equals(id)) { moduleConstraints.remove(model); getItem(model).setText(1, ""); } } LOGGER.trace("found combo entry for id {}", id); } else { LOGGER.debug("trying to remove nonexistant id {}", id); } LOGGER.exit(); } /** * Loads the FunctinoBlockModels of a data flow graph and displays them in * the deployment table. * * @param input * the input of the editor */ private void loadBlockModels(IEditorInput input) { // set to empty Collection to prevent NPE in case loading fails functionBlockModels = new ArrayList<FunctionBlockModel>(); if (input instanceof FileEditorInput) { final IProject project = EclipseUtil.getWorkspaceProject(((FileEditorInput) input).getPath()); if (project != null) { classPath = getClassPath(project); } else { classPath = new URL[0]; } try { functionBlockModels = loadInput((FileEditorInput) input); } catch (IOException e) { LOGGER.catching(e); } } else { LOGGER.error("Input is not a FileEditorInput {}", input); } mapItemToBlockModel.clear(); for (FunctionBlockModel blockModel : functionBlockModels) { addBlock(blockModel); } } private URL[] getClassPath(final IProject project) { final Set<IPath> paths = EclipseUtil.getAbsoluteBinPaths(project); final ArrayList<URL> classPath = new ArrayList<URL>(paths.size()); for (final IPath path : paths) { try { classPath.add(path.toFile().toURI().toURL()); } catch (final MalformedURLException e) { if (LOGGER.isDebugEnabled()) { LOGGER.catching(Level.DEBUG, e); LOGGER.debug("Not adding path {} to class path", path); } } } return classPath.toArray(new URL[0]); } /** * Loads the given data flow graph. The file given in the editor input must * be a valid graph. Its function block models are loaded into a list and * returned. * * @param input * the input of the editor * @return a collection of FunctionBlockModels that were defined in the * model * @throws IOException * if reading fails */ private Collection<FunctionBlockModel> loadInput(final FileEditorInput input) throws IOException { LOGGER.entry(input); Collection<FunctionBlockModel> blockModelList = new ArrayList<FunctionBlockModel>(); appName.setText(input.getFile().getName().replaceAll("\\.diagram", "")); URI uri = URI.createURI(input.getURI().toASCIIString()); Resource resource = new XMIResourceImpl(uri); resource.load(null); for (EObject object : resource.getContents()) { if (object instanceof FunctionBlockModel) { LOGGER.trace("found FunctionBlockModel {}", object); blockModelList.add(((FunctionBlockModel) object)); } } return blockModelList; } /** * Opens a warning window with the given message. * * @param message * Warning message */ private int warn(String message) { Display display = Display.getCurrent(); Shell shell = new Shell(display); MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); dialog.setText("Warning"); dialog.setMessage(message); return dialog.open(); } /** * Returns a Collection of currently running modules that are already * resolved. Does not contain modules that haven't been resolved from their * UUID yet. * * @return collection of currently running modules to deploy on. */ private Collection<Module> getModuleCollection() { Collection<Module> collection = new ArrayList<Module>(); Map<UUID, Module> map = manager.getMap(); for (UUID id : map.keySet()) { Module m = map.get(id); if (m != null) { collection.add(m); } } return collection; } /** * Returns table item representing a given function blockModel. * * @param blockModel * The blockModel to find in the table * @return item holding the blockModel */ private TableItem getItem(FunctionBlockModel blockModel) { UUID id = blockModel.getID(); for (TableItem i : mapItemToBlockModel.keySet()) { if (mapItemToBlockModel.get(i).getID() == id) { return i; } } return null; } /** * Invoked whenever a possibly created deployment gets invalid. */ private void resetDeployment() { mapBlockToTarget = new HashMap<FunctionBlock, BlockTarget>(); deployButton.setEnabled(false); for (TableItem item : deployment.getItems()) { item.setText(3, ""); item.setText(4, ""); } } /** * Invoked whenever the selected Block gets dirty. */ private void resetSelectedBlock() { places.setText(""); selectedItem = null; selectedBlockModel = null; blockModelName.setText("<select block on the left>"); blockModelName.setEnabled(false); moduleCombo.setEnabled(false); places.setEnabled(false); constraintsButton.setEnabled(false); } @Override public void doSave(IProgressMonitor monitor) { // TODO Auto-generated method stub } @Override public void doSaveAs() { // TODO Auto-generated method stub } @Override public boolean isDirty() { // TODO Auto-generated method stub return false; } @Override public boolean isSaveAsAllowed() { // TODO Auto-generated method stub return false; } @Override public void dispose() { manager.removeModuleManagerListener(this); } @Override public void moduleOnline(final UUID id) { LOGGER.entry(id); display.asyncExec(new Runnable() { @Override public void run() { addID(id); } }); LOGGER.exit(); } @Override public void moduleOffline(final UUID id) { LOGGER.entry(id); display.asyncExec(new Runnable() { @Override public void run() { removeID(id); } }); LOGGER.exit(); } @Override public void moduleResolved(final UUID id, final Module module) { display.asyncExec(new Runnable() { @Override public void run() { if (!idList.contains(id)) { LOGGER.entry(id); LOGGER.trace("id {} is new, adding", id); idList.add(id); LOGGER.exit(); } int comboIndex = idList.indexOf(id) + 1; String text = ""; if (module.getName() != null) { text = module.getName(); } text = text.concat(" : "); text = text.concat(id.toString()); moduleCombo.setItem(comboIndex, text); if (moduleConstraints.containsValue(id)) { for (FunctionBlockModel blockModel : moduleConstraints .keySet()) { getItem(blockModel).setText(1, text); } } } }); } @Override public void serverOnline(final Map<UUID, Module> modules) { display.asyncExec(new Runnable() { @Override public void run() { if (serverButton != null) { serverButton.setText("Stop Server"); } updateModulesButton.setEnabled(true); createButton.setEnabled(true); moduleCombo.setToolTipText(""); synchronized (DeployView.this) { while (!idList.isEmpty()) { removeID(idList.get(0)); // hoffentlich? } for (UUID moduleID : modules.keySet()) { addID(moduleID); } } } }); } @Override public void serverOffline() { display.asyncExec(new Runnable() { @Override public void run() { if (serverButton != null) { serverButton.setText("Start Server"); } updateModulesButton.setEnabled(false); createButton.setEnabled(false); resetDeployment(); moduleCombo .setToolTipText(DeployViewTexts.SELECTMODULEOFFLINE_TOOLTIP); synchronized (DeployView.this) { while (!idList.isEmpty()) { removeID(idList.get(0)); // hoffentlich? } } } }); } private void createSelectionListeners() { serverButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new Thread() { @Override public void run() { if (DeployView.this.activator.isRunning()) { DeployView.this.activator.shutdownServer(); } else { DeployView.this.activator.startServer(); } } }.run(); } }); deployment.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.blockModelSelected(); } }); updateModulesButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.updateModules(); } }); updateBlocksButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.updateBlocks(); } }); moduleCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.moduleSelected(); } }); createButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.create(); } }); deployButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.deploy(); } }); constraintsButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.saveConstraints(); } }); } }
package com.goinstant.auth; import java.util.LinkedList; import java.util.Map; import java.util.List; import java.util.TreeMap; import java.util.TreeSet; import java.lang.System; import java.text.ParseException; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.junit.Test; import com.goinstant.auth.Group; import com.goinstant.auth.PlainGroup; import com.goinstant.auth.PlainUser; import com.goinstant.auth.Signer; import com.goinstant.auth.User; import com.nimbusds.jose.crypto.MACVerifier; import com.nimbusds.jose.*; import com.nimbusds.jwt.*; import net.minidev.json.JSONObject; import net.minidev.json.JSONArray; /** * Unit tests for Goinstant-auth's Signer class. */ public class SignerTest{ static final String sharedKey = "HKYdFdnezle2yrI2_Ph3cHz144bISk-cvuAbeAAA999"; static int countNonNullKeys(Map<String,Object> map) { int count = 0; for (Map.Entry<String,Object> entry : map.entrySet()) { if (entry.getValue() != null) { count++; } } return count; } private JWTClaimsSet verifyJWT(JWSObject parsed) throws Exception { MACVerifier verifier = new MACVerifier(Signer.parseKey(sharedKey)); try { boolean valid = parsed.verify(verifier); assertTrue(parsed.verify(verifier)); } catch (JOSEException e) { assertTrue(false); } ReadOnlyJWSHeader header = parsed.getHeader(); assertEquals(2, header.getIncludedParameters().size()); assertTrue(header.getAlgorithm() == JWSAlgorithm.HS256); assertEquals("JWT", header.getType().toString()); Payload payload = parsed.getPayload(); JWTClaimsSet claims = JWTClaimsSet.parse(payload.toString()); return claims; } /** * Does a signature check for a user not belonging to any groups. */ @Test public void testHappyPath() throws Exception { Signer signer = new Signer(sharedKey); PlainUser user = new PlainUser("bar", "example.com", "bob"); String token = signer.sign(user); JWSObject parsed = JWSObject.parse(token); JWTClaimsSet claims = verifyJWT(parsed); // assert no extra claims than the four below: assertEquals(4, countNonNullKeys(claims.getAllClaims())); assertEquals("bar", claims.getSubject()); assertEquals("example.com", claims.getIssuer()); assertEquals("bob", claims.getCustomClaim("dn")); List<String> aud = claims.getAudience(); assertEquals(1, aud.size()); assertEquals("goinstant.net", aud.get(0)); // re-sign String token2 = signer.sign(user); assertEquals(token, token2); } /** * Does a signature check for a user belonging to a group */ @Test public void testHappyPathWithGroups() throws Exception { Signer signer = new Signer(sharedKey); TreeSet<Group> groups = new TreeSet<Group>(); // deterministic ordering groups.add(new PlainGroup("42", "Meaning Group")); groups.add(new PlainGroup("1234", "Group 1234")); PlainUser user = new PlainUser("bar", "example.com", "bob", groups); String token = signer.sign(user); JWSObject parsed = JWSObject.parse(token); JWTClaimsSet claims = verifyJWT(parsed); // assert no extra claims than the five below: assertEquals(5, countNonNullKeys(claims.getAllClaims())); assertEquals("bar", claims.getSubject()); assertEquals("example.com", claims.getIssuer()); assertEquals("bob", claims.getCustomClaim("dn")); List<String> aud = claims.getAudience(); assertThat(aud.size(), is(1)); assertThat(aud, hasItem("goinstant.net")); Object o = claims.getCustomClaim("g"); assertThat(o, instanceOf(JSONArray.class)); @SuppressWarnings("unchecked") // instanceOf above checks JSONArray g = (JSONArray)o; assertThat(g.size(), is(2)); assertThat(g, everyItem(instanceOf(JSONObject.class))); @SuppressWarnings("unchecked") // everyItem(instanceOf) above checks JSONObject g0 = (JSONObject) g.get(0); assertThat(g0.get("id").toString(), is("1234")); assertThat(g0.get("dn").toString(), is("Group 1234")); @SuppressWarnings("unchecked") // everyItem(instanceOf) above checks JSONObject g1 = (JSONObject) g.get(1); assertThat(g1.get("id").toString(), is("42")); assertThat(g1.get("dn").toString(), is("Meaning Group")); // re-sign String token2 = signer.sign(user); assertEquals(token, token2); } @Test(expected=IllegalArgumentException.class) public void testUserWithoutID() { Signer signer = new Signer(sharedKey); PlainUser user = new PlainUser(null, "example.com", "bob"); signer.sign(user); } @Test(expected=IllegalArgumentException.class) public void testUserWithEmptyId() { Signer signer = new Signer(sharedKey); PlainUser user = new PlainUser("", "example.com", "bob"); signer.sign(user); } @Test(expected=IllegalArgumentException.class) public void testUserWithoutDomain() { Signer signer = new Signer(sharedKey); PlainUser user = new PlainUser("bar", null, "bob"); signer.sign(user); } @Test(expected=IllegalArgumentException.class) public void testUserWithEmptyDomain() { Signer signer = new Signer(sharedKey); PlainUser user = new PlainUser("bar", "", "bob"); signer.sign(user); } }
package edu.washington.escience.myria.parallel; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.slf4j.LoggerFactory; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.ListenableFuture; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.MyriaConstants; import edu.washington.escience.myria.MyriaConstants.FTMODE; import edu.washington.escience.myria.MyriaSystemConfigKeys; import edu.washington.escience.myria.RelationKey; import edu.washington.escience.myria.Schema; import edu.washington.escience.myria.TupleWriter; import edu.washington.escience.myria.Type; import edu.washington.escience.myria.accessmethod.AccessMethod.IndexRef; import edu.washington.escience.myria.api.encoding.DatasetStatus; import edu.washington.escience.myria.api.encoding.QueryConstruct; import edu.washington.escience.myria.api.encoding.QueryConstruct.ConstructArgs; import edu.washington.escience.myria.api.encoding.QueryEncoding; import edu.washington.escience.myria.api.encoding.QueryStatusEncoding; import edu.washington.escience.myria.coordinator.catalog.CatalogException; import edu.washington.escience.myria.coordinator.catalog.CatalogMaker; import edu.washington.escience.myria.coordinator.catalog.MasterCatalog; import edu.washington.escience.myria.expression.Expression; import edu.washington.escience.myria.expression.VariableExpression; import edu.washington.escience.myria.expression.WorkerIdExpression; import edu.washington.escience.myria.operator.Apply; import edu.washington.escience.myria.operator.DataOutput; import edu.washington.escience.myria.operator.DbInsert; import edu.washington.escience.myria.operator.DbQueryScan; import edu.washington.escience.myria.operator.DuplicateTBGenerator; import edu.washington.escience.myria.operator.EOSSource; import edu.washington.escience.myria.operator.Operator; import edu.washington.escience.myria.operator.RootOperator; import edu.washington.escience.myria.operator.SinkRoot; import edu.washington.escience.myria.operator.agg.Aggregate; import edu.washington.escience.myria.operator.agg.Aggregator; import edu.washington.escience.myria.operator.agg.MultiGroupByAggregate; import edu.washington.escience.myria.operator.agg.SingleGroupByAggregate; import edu.washington.escience.myria.operator.network.CollectConsumer; import edu.washington.escience.myria.operator.network.CollectProducer; import edu.washington.escience.myria.operator.network.GenericShuffleConsumer; import edu.washington.escience.myria.operator.network.GenericShuffleProducer; import edu.washington.escience.myria.operator.network.partition.RoundRobinPartitionFunction; import edu.washington.escience.myria.parallel.ipc.IPCConnectionPool; import edu.washington.escience.myria.parallel.ipc.IPCMessage; import edu.washington.escience.myria.parallel.ipc.InJVMLoopbackChannelSink; import edu.washington.escience.myria.parallel.ipc.QueueBasedShortMessageProcessor; import edu.washington.escience.myria.proto.ControlProto.ControlMessage; import edu.washington.escience.myria.proto.QueryProto.QueryMessage; import edu.washington.escience.myria.proto.QueryProto.QueryReport; import edu.washington.escience.myria.proto.TransportProto.TransportMessage; import edu.washington.escience.myria.storage.TupleBatch; import edu.washington.escience.myria.storage.TupleBatchBuffer; import edu.washington.escience.myria.tool.MyriaConfigurationReader; import edu.washington.escience.myria.util.DateTimeUtils; import edu.washington.escience.myria.util.DeploymentUtils; import edu.washington.escience.myria.util.IPCUtils; import edu.washington.escience.myria.util.MyriaUtils; import edu.washington.escience.myria.util.concurrent.ErrorLoggingTimerTask; import edu.washington.escience.myria.util.concurrent.RenamingThreadFactory; /** * The master entrance. */ public final class Server { /** * Master message processor. */ private final class MessageProcessor implements Runnable { /** Constructor, set the thread name. */ public MessageProcessor() { super(); } @Override public void run() { TERMINATE_MESSAGE_PROCESSING : while (true) { IPCMessage.Data<TransportMessage> mw = null; try { mw = messageQueue.take(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); break TERMINATE_MESSAGE_PROCESSING; } final TransportMessage m = mw.getPayload(); final int senderID = mw.getRemoteID(); switch (m.getType()) { case CONTROL: final ControlMessage controlM = m.getControlMessage(); switch (controlM.getType()) { case WORKER_HEARTBEAT: LOGGER.trace("getting heartbeat from worker {}", senderID); updateHeartbeat(senderID); break; case REMOVE_WORKER_ACK: int workerID = controlM.getWorkerId(); removeWorkerAckReceived.get(workerID).add(senderID); break; case ADD_WORKER_ACK: workerID = controlM.getWorkerId(); addWorkerAckReceived.get(workerID).add(senderID); for (MasterSubQuery mqp : executingSubQueries.values()) { if (mqp.getFTMode().equals(FTMODE.rejoin) && mqp.getMissingWorkers().contains(workerID) && addWorkerAckReceived.get(workerID).containsAll(mqp.getWorkerAssigned())) { /* so a following ADD_WORKER_ACK won't cause queryMessage to be sent again */ mqp.getMissingWorkers().remove(workerID); try { connectionPool.sendShortMessage(workerID, IPCUtils.queryMessage(mqp.getSubQueryId(), mqp .getWorkerPlans().get(workerID))); } catch (final IOException e) { throw new RuntimeException(e); } } } break; default: LOGGER.error("Unexpected control message received at master: {}", controlM); } break; case QUERY: final QueryMessage qm = m.getQueryMessage(); final SubQueryId subQueryId = new SubQueryId(qm.getQueryId(), qm.getSubqueryId()); MasterSubQuery mqp = executingSubQueries.get(subQueryId); switch (qm.getType()) { case QUERY_READY_TO_EXECUTE: mqp.queryReceivedByWorker(senderID); break; case QUERY_COMPLETE: QueryReport qr = qm.getQueryReport(); if (qr.getSuccess()) { mqp.workerComplete(senderID); } else { ObjectInputStream osis = null; Throwable cause = null; try { osis = new ObjectInputStream(new ByteArrayInputStream(qr.getCause().toByteArray())); cause = (Throwable) (osis.readObject()); } catch (IOException | ClassNotFoundException e) { LOGGER.error("Error decoding failure cause", e); } mqp.workerFail(senderID, cause); LOGGER.error("Worker #{} failed in executing query #{}.", senderID, subQueryId, cause); } break; default: LOGGER.error("Unexpected query message received at master: {}", qm); break; } break; default: LOGGER.error("Unknown short message received at master: {}", m.getType()); break; } } } } /** The usage message for this server. */ static final String USAGE = "Usage: Server catalogFile [-explain] [-f queryFile]"; /** The logger for this class. */ private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Server.class); /** * Initial worker list. */ private final ConcurrentHashMap<Integer, SocketInfo> workers; /** * Queries currently active (queued, executing, being killed, etc.). */ private final ConcurrentHashMap<Long, Query> activeQueries; /** * Subqueries currently in execution. */ private final ConcurrentHashMap<SubQueryId, MasterSubQuery> executingSubQueries; /** * Current alive worker set. */ private final ConcurrentHashMap<Integer, Long> aliveWorkers; /** * Scheduled new workers, when a scheduled worker sends the first heartbeat, it'll be removed from this set. */ private final ConcurrentHashMap<Integer, SocketInfo> scheduledWorkers; /** * The time when new workers were scheduled. */ private final ConcurrentHashMap<Integer, Long> scheduledWorkersTime; /** * Execution environment variables for operators. */ private final ConcurrentHashMap<String, Object> execEnvVars; /** * All message queue. * * @TODO remove this queue as in {@link Worker}s. */ private final LinkedBlockingQueue<IPCMessage.Data<TransportMessage>> messageQueue; /** * The IPC Connection Pool. */ private final IPCConnectionPool connectionPool; /** * {@link ExecutorService} for message processing. */ private volatile ExecutorService messageProcessingExecutor; /** The Catalog stores the metadata about the Myria instance. */ private final MasterCatalog catalog; /** * The {@link OrderedMemoryAwareThreadPoolExecutor} who gets messages from {@link workerExecutor} and further process * them using application specific message handlers, e.g. {@link MasterShortMessageProcessor}. */ private volatile OrderedMemoryAwareThreadPoolExecutor ipcPipelineExecutor; /** * The {@link ExecutorService} who executes the master-side subqueries. */ private volatile ExecutorService serverQueryExecutor; /** * @return the query executor used in this worker. */ ExecutorService getQueryExecutor() { return serverQueryExecutor; } /** * max number of seconds for elegant cleanup. */ public static final int NUM_SECONDS_FOR_ELEGANT_CLEANUP = 10; /** for each worker id, record the set of workers which REMOVE_WORKER_ACK have been received. */ private final Map<Integer, Set<Integer>> removeWorkerAckReceived; /** for each worker id, record the set of workers which ADD_WORKER_ACK have been received. */ private final Map<Integer, Set<Integer>> addWorkerAckReceived; /** * Entry point for the Master. * * @param args the command line arguments. * @throws IOException if there's any error in reading catalog file. */ public static void main(final String[] args) throws IOException { try { Logger.getLogger("com.almworks.sqlite4java").setLevel(Level.SEVERE); Logger.getLogger("com.almworks.sqlite4java.Internal").setLevel(Level.SEVERE); if (args.length < 1) { LOGGER.error(USAGE); System.exit(-1); } final String catalogName = args[0]; final Server server = new Server(catalogName); if (LOGGER.isInfoEnabled()) { LOGGER.info("Workers are: "); for (final Entry<Integer, SocketInfo> w : server.workers.entrySet()) { LOGGER.info(w.getKey() + ": " + w.getValue().getHost() + ":" + w.getValue().getPort()); } } Runtime.getRuntime().addShutdownHook(new Thread("Master shutdown hook cleaner") { @Override public void run() { final Thread cleaner = new Thread("Shutdown hook cleaner") { @Override public void run() { server.cleanup(); } }; final Thread countDown = new Thread("Shutdown hook countdown") { @Override public void run() { LOGGER.info("Wait for {} seconds for graceful cleaning-up.", Server.NUM_SECONDS_FOR_ELEGANT_CLEANUP); int i; for (i = Server.NUM_SECONDS_FOR_ELEGANT_CLEANUP; i > 0; i try { if (LOGGER.isInfoEnabled()) { LOGGER.info(i + ""); } Thread.sleep(MyriaConstants.WAITING_INTERVAL_1_SECOND_IN_MS); if (!cleaner.isAlive()) { break; } } catch (InterruptedException e) { break; } } if (i <= 0) { LOGGER.info("Graceful cleaning-up timeout. Going to shutdown abruptly."); for (Thread t : Thread.getAllStackTraces().keySet()) { if (t != Thread.currentThread()) { t.interrupt(); } } } } }; cleaner.start(); countDown.start(); try { countDown.join(); } catch (InterruptedException e) { // should not happen return; } } }); server.start(); } catch (Exception e) { LOGGER.error("Unknown error occurs at Master. Quit directly.", e); } } /** * @return my connection pool for IPC. */ IPCConnectionPool getIPCConnectionPool() { return connectionPool; } /** * @return my pipeline executor. */ OrderedMemoryAwareThreadPoolExecutor getPipelineExecutor() { return ipcPipelineExecutor; } /** The socket info for the master. */ private final SocketInfo masterSocketInfo; /** * @return my execution environment variables for init of operators. */ ConcurrentHashMap<String, Object> getExecEnvVars() { return execEnvVars; } /** * @return execution mode. */ QueryExecutionMode getExecutionMode() { return QueryExecutionMode.NON_BLOCKING; } /** * Construct a server object, with configuration stored in the specified catalog file. * * @param catalogFileName the name of the file containing the catalog. * @throws FileNotFoundException the specified file not found. * @throws CatalogException if there is an error reading from the Catalog. */ public Server(final String catalogFileName) throws FileNotFoundException, CatalogException { catalog = MasterCatalog.open(catalogFileName); /* Get the master socket info */ List<SocketInfo> masters = catalog.getMasters(); if (masters.size() != 1) { throw new RuntimeException("Unexpected number of masters: expected 1, got " + masters.size()); } masterSocketInfo = masters.get(MyriaConstants.MASTER_ID); workers = new ConcurrentHashMap<>(catalog.getWorkers()); final ImmutableMap<String, String> allConfigurations = catalog.getAllConfigurations(); int inputBufferCapacity = Integer.valueOf(catalog.getConfigurationValue(MyriaSystemConfigKeys.OPERATOR_INPUT_BUFFER_CAPACITY)); int inputBufferRecoverTrigger = Integer.valueOf(catalog.getConfigurationValue(MyriaSystemConfigKeys.OPERATOR_INPUT_BUFFER_RECOVER_TRIGGER)); execEnvVars = new ConcurrentHashMap<>(); for (Entry<String, String> cE : allConfigurations.entrySet()) { execEnvVars.put(cE.getKey(), cE.getValue()); } execEnvVars.put(MyriaConstants.EXEC_ENV_VAR_NODE_ID, MyriaConstants.MASTER_ID); execEnvVars.put(MyriaConstants.EXEC_ENV_VAR_EXECUTION_MODE, getExecutionMode()); aliveWorkers = new ConcurrentHashMap<>(); scheduledWorkers = new ConcurrentHashMap<>(); scheduledWorkersTime = new ConcurrentHashMap<>(); removeWorkerAckReceived = new ConcurrentHashMap<>(); addWorkerAckReceived = new ConcurrentHashMap<>(); activeQueries = new ConcurrentHashMap<>(); executingSubQueries = new ConcurrentHashMap<>(); messageQueue = new LinkedBlockingQueue<>(); final Map<Integer, SocketInfo> computingUnits = new HashMap<>(workers); computingUnits.put(MyriaConstants.MASTER_ID, masterSocketInfo); connectionPool = new IPCConnectionPool(MyriaConstants.MASTER_ID, computingUnits, IPCConfigurations .createMasterIPCServerBootstrap(this), IPCConfigurations.createMasterIPCClientBootstrap(this), new TransportMessageSerializer(), new QueueBasedShortMessageProcessor<TransportMessage>(messageQueue), inputBufferCapacity, inputBufferRecoverTrigger); scheduledTaskExecutor = Executors.newSingleThreadScheduledExecutor(new RenamingThreadFactory("Master global timer")); final String databaseSystem = catalog.getConfigurationValue(MyriaSystemConfigKeys.WORKER_STORAGE_DATABASE_SYSTEM); execEnvVars.put(MyriaConstants.EXEC_ENV_VAR_DATABASE_SYSTEM, databaseSystem); } /** * timer task executor. */ private final ScheduledExecutorService scheduledTaskExecutor; /** * This class presents only for the purpose of debugging. No other usage. */ private class DebugHelper extends ErrorLoggingTimerTask { /** * Interval of execution. */ public static final int INTERVAL = MyriaConstants.WAITING_INTERVAL_1_SECOND_IN_MS; @Override public final synchronized void runInner() { System.currentTimeMillis(); } } /** * The thread to check received REMOVE_WORKER_ACK and send ADD_WORKER to each worker. It's a temporary solution to * guarantee message synchronization. Once we have a generalized design in the IPC layer in the future, it can be * removed. */ private Thread sendAddWorker = null; /** * The thread to check received REMOVE_WORKER_ACK and send ADD_WORKER to each worker. */ private class SendAddWorker implements Runnable { /** the worker id that was removed. */ private final int workerID; /** the expected number of REMOVE_WORKER_ACK messages to receive. */ private int numOfAck; /** the socket info of the new worker. */ private final SocketInfo socketInfo; /** * constructor. * * @param workerID the removed worker id. * @param socketInfo the new worker's socket info. * @param numOfAck the number of REMOVE_WORKER_ACK to receive. */ SendAddWorker(final int workerID, final SocketInfo socketInfo, final int numOfAck) { this.workerID = workerID; this.socketInfo = socketInfo; this.numOfAck = numOfAck; } @Override public void run() { while (numOfAck > 0) { for (int aliveWorkerId : aliveWorkers.keySet()) { if (removeWorkerAckReceived.get(workerID).remove(aliveWorkerId)) { numOfAck connectionPool.sendShortMessage(aliveWorkerId, IPCUtils.addWorkerTM(workerID, socketInfo)); } } try { Thread.sleep(MyriaConstants.SHORT_WAITING_INTERVAL_100_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } /** * @param workerID the worker to get updated */ private void updateHeartbeat(final int workerID) { if (scheduledWorkers.containsKey(workerID)) { SocketInfo newWorker = scheduledWorkers.remove(workerID); scheduledWorkersTime.remove(workerID); if (newWorker != null) { sendAddWorker.start(); } } aliveWorkers.put(workerID, System.currentTimeMillis()); } /** * Check worker livenesses periodically. If a worker is detected as dead, its queries will be notified, it will be * removed from connection pools, and a new worker will be scheduled. */ private class WorkerLivenessChecker extends ErrorLoggingTimerTask { @Override public final synchronized void runInner() { for (Integer workerId : aliveWorkers.keySet()) { long currentTime = System.currentTimeMillis(); if (currentTime - aliveWorkers.get(workerId) >= MyriaConstants.WORKER_IS_DEAD_INTERVAL) { /* scheduleAtFixedRate() is not accurate at all, use isRemoteAlive() to make sure the connection is lost. */ if (connectionPool.isRemoteAlive(workerId)) { updateHeartbeat(workerId); continue; } LOGGER.info("worker {} doesn't have heartbeats, treat it as dead.", workerId); aliveWorkers.remove(workerId); for (MasterSubQuery mqp : executingSubQueries.values()) { /* for each alive query that the failed worker is assigned to, tell the query that the worker failed. */ if (mqp.getWorkerAssigned().contains(workerId)) { mqp.workerFail(workerId, new LostHeartbeatException()); } if (mqp.getFTMode().equals(FTMODE.abandon)) { mqp.getMissingWorkers().add(workerId); mqp.updateProducerChannels(workerId, false); mqp.triggerFragmentEosEoiChecks(); } else if (mqp.getFTMode().equals(FTMODE.rejoin)) { mqp.getMissingWorkers().add(workerId); mqp.updateProducerChannels(workerId, false); } } removeWorkerAckReceived.put(workerId, Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>())); addWorkerAckReceived.put(workerId, Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>())); /* for using containsAll() later */ addWorkerAckReceived.get(workerId).add(workerId); try { /* remove the failed worker from the connectionPool. */ connectionPool.removeRemote(workerId).await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } /* tell other workers to remove it too. */ for (int aliveWorkerId : aliveWorkers.keySet()) { connectionPool.sendShortMessage(aliveWorkerId, IPCUtils.removeWorkerTM(workerId)); } /* Temporary solution: using exactly the same hostname:port. One good thing is the data is still there. */ /* Temporary solution: using exactly the same worker id. */ String newAddress = workers.get(workerId).getHost(); int newPort = workers.get(workerId).getPort(); int newWorkerId = workerId; /* a new worker will be launched, put its information in scheduledWorkers. */ scheduledWorkers.put(newWorkerId, new SocketInfo(newAddress, newPort)); scheduledWorkersTime.put(newWorkerId, currentTime); sendAddWorker = new Thread(new SendAddWorker(newWorkerId, new SocketInfo(newAddress, newPort), aliveWorkers.size())); connectionPool.putRemote(newWorkerId, new SocketInfo(newAddress, newPort)); /* start a thread to launch the new worker. */ new Thread(new NewWorkerScheduler(newWorkerId, newAddress, newPort)).start(); } } for (Integer workerId : scheduledWorkers.keySet()) { long currentTime = System.currentTimeMillis(); long time = scheduledWorkersTime.get(workerId); /* Had several trials and may need to change hostname:port of the scheduled new worker. */ if (currentTime - time >= MyriaConstants.SCHEDULED_WORKER_UNABLE_TO_START) { SocketInfo si = scheduledWorkers.remove(workerId); scheduledWorkersTime.remove(workerId); connectionPool.removeRemote(workerId); LOGGER.error("Worker #{} ({}) failed to start. Give up.", workerId, si); continue; // Temporary solution: simply giving up launching this new worker // TODO: find a new set of hostname:port for this scheduled worker } else /* Haven't heard heartbeats from the scheduled worker, try to launch it again. */ if (currentTime - time >= MyriaConstants.SCHEDULED_WORKER_FAILED_TO_START) { SocketInfo info = scheduledWorkers.get(workerId); new Thread(new NewWorkerScheduler(workerId, info.getHost(), info.getPort())).start(); } } } } /** The reader. */ private static final MyriaConfigurationReader READER = new MyriaConfigurationReader(); /** * The class to launch a new worker during recovery. */ private class NewWorkerScheduler implements Runnable { /** the new worker's worker id. */ private final int workerId; /** the new worker's port number id. */ private final int port; /** the new worker's hostname. */ private final String address; /** * constructor. * * @param workerId worker id. * @param address hostname. * @param port port number. */ NewWorkerScheduler(final int workerId, final String address, final int port) { this.workerId = workerId; this.address = address; this.port = port; } @Override public void run() { try { final String temp = Files.createTempDirectory(null).toAbsolutePath().toString(); Map<String, String> tmpMap = Collections.emptyMap(); String configFileName = catalog.getConfigurationValue(MyriaSystemConfigKeys.DEPLOYMENT_FILE); Map<String, Map<String, String>> config = READER.load(configFileName); CatalogMaker.makeOneWorkerCatalog(workerId + "", temp, config, tmpMap, true); final String workingDir = config.get("paths").get(workerId + ""); final String description = catalog.getConfigurationValue(MyriaSystemConfigKeys.DESCRIPTION); String remotePath = workingDir; if (description != null) { remotePath += "/" + description + "-files" + "/" + description; } DeploymentUtils.mkdir(address, remotePath); String localPath = temp + "/" + "worker_" + workerId; DeploymentUtils.rsyncFileToRemote(localPath, address, remotePath); final String maxHeapSize = config.get("deployment").get("max_heap_size"); LOGGER.info("starting new worker at {}:{}", address, port); boolean debug = config.get("deployment").get("debug_mode").equals("true"); DeploymentUtils.startWorker(address, workingDir, description, maxHeapSize, workerId + "", port, debug); } catch (CatalogException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } } /** * Master cleanup. */ private void cleanup() { LOGGER.info("{} is going to shutdown", MyriaConstants.SYSTEM_NAME); if (scheduledWorkers.size() > 0) { LOGGER.info("Waiting for scheduled recovery workers, please wait"); while (scheduledWorkers.size() > 0) { try { Thread.sleep(MyriaConstants.WAITING_INTERVAL_1_SECOND_IN_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } for (MasterSubQuery p : executingSubQueries.values()) { p.kill(); } if (messageProcessingExecutor != null && !messageProcessingExecutor.isShutdown()) { messageProcessingExecutor.shutdownNow(); } if (scheduledTaskExecutor != null && !scheduledTaskExecutor.isShutdown()) { scheduledTaskExecutor.shutdownNow(); } /* * Close the catalog before shutting down the IPC because there may be Catalog jobs pending that were triggered by * IPC events. */ catalog.close(); while (aliveWorkers.size() > 0) { // TODO add process kill LOGGER.info("Send shutdown requests to the workers, please wait"); for (final Integer workerId : aliveWorkers.keySet()) { SocketInfo workerAddr = workers.get(workerId); LOGGER.info("Shutting down #{} : {}", workerId, workerAddr); connectionPool.sendShortMessage(workerId, IPCUtils.CONTROL_SHUTDOWN); } for (final int workerId : aliveWorkers.keySet()) { if (!connectionPool.isRemoteAlive(workerId)) { aliveWorkers.remove(workerId); } } if (aliveWorkers.size() > 0) { try { Thread.sleep(MyriaConstants.WAITING_INTERVAL_1_SECOND_IN_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } connectionPool.shutdown(); connectionPool.releaseExternalResources(); if (ipcPipelineExecutor != null && !ipcPipelineExecutor.isShutdown()) { ipcPipelineExecutor.shutdown(); } LOGGER.info("Master connection pool shutdown complete."); LOGGER.info("Master finishes cleanup."); } /** * @param mqp the master query * @return the query dispatch {@link LocalSubQueryFuture}. * @throws DbException if any error occurs. */ private LocalSubQueryFuture dispatchWorkerQueryPlans(final MasterSubQuery mqp) throws DbException { // directly set the master part as already received. mqp.queryReceivedByWorker(MyriaConstants.MASTER_ID); for (final Map.Entry<Integer, SubQueryPlan> e : mqp.getWorkerPlans().entrySet()) { final Integer workerID = e.getKey(); while (!aliveWorkers.containsKey(workerID)) { try { Thread.sleep(MyriaConstants.SHORT_WAITING_INTERVAL_MS); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } try { connectionPool.sendShortMessage(workerID, IPCUtils.queryMessage(mqp.getSubQueryId(), e.getValue())); } catch (final IOException ee) { throw new DbException(ee); } } return mqp.getWorkerReceiveFuture(); } /** * @return if a query is running. * @param queryId queryID. */ public boolean queryCompleted(final long queryId) { return !activeQueries.containsKey(queryId); } /** * @return if no query is running. */ public boolean allQueriesCompleted() { return activeQueries.isEmpty(); } /** * Shutdown the master. */ public void shutdown() { cleanup(); } /** * Start all the threads that do work for the server. * * @throws Exception if any error occurs. */ public void start() throws Exception { LOGGER.info("Server starting on {}", masterSocketInfo); scheduledTaskExecutor.scheduleAtFixedRate(new DebugHelper(), DebugHelper.INTERVAL, DebugHelper.INTERVAL, TimeUnit.MILLISECONDS); scheduledTaskExecutor.scheduleAtFixedRate(new WorkerLivenessChecker(), MyriaConstants.WORKER_LIVENESS_CHECKER_INTERVAL, MyriaConstants.WORKER_LIVENESS_CHECKER_INTERVAL, TimeUnit.MILLISECONDS); messageProcessingExecutor = Executors.newCachedThreadPool(new RenamingThreadFactory("Master message processor")); serverQueryExecutor = Executors.newCachedThreadPool(new RenamingThreadFactory("Master query executor")); /** * The {@link Executor} who deals with IPC connection setup/cleanup. */ ExecutorService ipcBossExecutor = Executors.newCachedThreadPool(new RenamingThreadFactory("Master IPC boss")); /** * The {@link Executor} who deals with IPC message delivering and transformation. */ ExecutorService ipcWorkerExecutor = Executors.newCachedThreadPool(new RenamingThreadFactory("Master IPC worker")); ipcPipelineExecutor = new OrderedMemoryAwareThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2 + 1, 5 * MyriaConstants.MB, 0, MyriaConstants.THREAD_POOL_KEEP_ALIVE_TIME_IN_MS, TimeUnit.MILLISECONDS, new RenamingThreadFactory("Master Pipeline executor")); /** * The {@link ChannelFactory} for creating client side connections. */ ChannelFactory clientChannelFactory = new NioClientSocketChannelFactory(ipcBossExecutor, ipcWorkerExecutor, Runtime.getRuntime() .availableProcessors() * 2 + 1); /** * The {@link ChannelFactory} for creating server side accepted connections. */ ChannelFactory serverChannelFactory = new NioServerSocketChannelFactory(ipcBossExecutor, ipcWorkerExecutor, Runtime.getRuntime() .availableProcessors() * 2 + 1); // Start server with Nb of active threads = 2*NB CPU + 1 as maximum. ChannelPipelineFactory serverPipelineFactory = new IPCPipelineFactories.MasterServerPipelineFactory(connectionPool, getPipelineExecutor()); ChannelPipelineFactory clientPipelineFactory = new IPCPipelineFactories.MasterClientPipelineFactory(connectionPool, getPipelineExecutor()); ChannelPipelineFactory masterInJVMPipelineFactory = new IPCPipelineFactories.MasterInJVMPipelineFactory(connectionPool); connectionPool.start(serverChannelFactory, serverPipelineFactory, clientChannelFactory, clientPipelineFactory, masterInJVMPipelineFactory, new InJVMLoopbackChannelSink()); messageProcessingExecutor.submit(new MessageProcessor()); LOGGER.info("Server started on {}", masterSocketInfo); if (getSchema(MyriaConstants.PROFILING_RELATION) == null && getDBMS().equals(MyriaConstants.STORAGE_SYSTEM_POSTGRESQL)) { final Set<Integer> workerIds = workers.keySet(); importDataset(MyriaConstants.PROFILING_RELATION, MyriaConstants.PROFILING_SCHEMA, workerIds); importDataset(MyriaConstants.SENT_RELATION, MyriaConstants.SENT_SCHEMA, workerIds); } } /** * @return the dbms from {@link #execEnvVars}. */ public String getDBMS() { return (String) execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_DATABASE_SYSTEM); } /** * Kill a query with queryID. * * @param queryID the queryID. */ public void killQuery(final long queryID) { getQuery(queryID).kill(); } /** * Kill a subquery. * * @param subQueryId the ID of the subquery to be killed */ protected void killSubQuery(final SubQueryId subQueryId) { Preconditions.checkNotNull(subQueryId, "subQueryId"); MasterSubQuery subQuery = executingSubQueries.get(subQueryId); if (subQuery != null) { subQuery.kill(); } else { LOGGER.warn("tried to kill subquery {} but it is not executing.", subQueryId); } } /** * * Can be only used in test. * * @return true if the query plan is accepted and scheduled for execution. * @param masterRoot the root operator of the master plan * @param workerRoots the roots of the worker part of the plan, {workerID -> RootOperator[]} * @throws DbException if any error occurs. * @throws CatalogException catalog errors. */ public QueryFuture submitQueryPlan(final RootOperator masterRoot, final Map<Integer, RootOperator[]> workerRoots) throws DbException, CatalogException { String catalogInfoPlaceHolder = "MasterPlan: " + masterRoot + "; WorkerPlan: " + workerRoots; Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(); for (Entry<Integer, RootOperator[]> entry : workerRoots.entrySet()) { workerPlans.put(entry.getKey(), new SubQueryPlan(entry.getValue())); } return submitQuery(catalogInfoPlaceHolder, catalogInfoPlaceHolder, catalogInfoPlaceHolder, new SubQueryPlan( masterRoot), workerPlans, false); } /** * Submit a query for execution. The workerPlans may be removed in the future if the query compiler and schedulers are * ready. Returns null if there are too many active queries. * * @param rawQuery the raw user-defined query. E.g., the source Datalog program. * @param logicalRa the logical relational algebra of the compiled plan. * @param physicalPlan the Myria physical plan for the query. * @param workerPlans the physical parallel plan fragments for each worker. * @param masterPlan the physical parallel plan fragment for the master. * @param profilingMode is the profiling mode of the query on. * @throws DbException if any error in non-catalog data processing * @throws CatalogException if any error in processing catalog * @return the query future from which the query status can be looked up. */ public QueryFuture submitQuery(final String rawQuery, final String logicalRa, final String physicalPlan, final SubQueryPlan masterPlan, final Map<Integer, SubQueryPlan> workerPlans, @Nullable final Boolean profilingMode) throws DbException, CatalogException { QueryEncoding query = new QueryEncoding(); query.rawQuery = rawQuery; query.logicalRa = rawQuery; query.fragments = ImmutableList.of(); query.profilingMode = Objects.firstNonNull(profilingMode, false); return submitQuery(query, new SubQuery(masterPlan, workerPlans)); } /** * Submit a query for execution. The workerPlans may be removed in the future if the query compiler and schedulers are * ready. Returns null if there are too many active queries. * * @param query the query encoding. * @param plan the query to be executed * @throws DbException if any error in non-catalog data processing * @throws CatalogException if any error in processing catalog * @return the query future from which the query status can be looked up. */ public QueryFuture submitQuery(final QueryEncoding query, final QueryPlan plan) throws DbException, CatalogException { if (!canSubmitQuery()) { throw new DbException("Cannot submit query"); } if (query.profilingMode) { if (!(plan instanceof SubQuery || plan instanceof JsonSubQuery)) { throw new DbException("Profiling mode is not supported for plans (" + plan.getClass().getSimpleName() + ") that may contain multiple subqueries."); } if (!getDBMS().equals(MyriaConstants.STORAGE_SYSTEM_POSTGRESQL)) { throw new DbException("Profiling mode is only supported when using Postgres as the storage system."); } } if (plan instanceof JsonSubQuery) { /* Hack to instantiate a single-fragment query for the visualization. */ QueryConstruct.instantiate(((JsonSubQuery) plan).getFragments(), new ConstructArgs(this, -1)); } final long queryID = catalog.newQuery(query); return submitQuery(queryID, query, plan); } /** * Submit a query for execution. The workerPlans may be removed in the future if the query compiler and schedulers are * ready. Returns null if there are too many active queries. * * @param queryId the catalog's assigned ID for this query. * @param query contains the query options (profiling, fault tolerance) * @param plan the query to be executed * @throws DbException if any error in non-catalog data processing * @throws CatalogException if any error in processing catalog * @return the query future from which the query status can be looked up. */ private QueryFuture submitQuery(final long queryId, final QueryEncoding query, final QueryPlan plan) throws DbException, CatalogException { final Query queryState = new Query(queryId, query, plan, this); activeQueries.put(queryId, queryState); advanceQuery(queryState); return queryState.getFuture(); } /** * Advance the given query to the next {@link SubQuery}. If there is no next {@link SubQuery}, mark the entire query * as having succeeded. * * @param queryState the specified query * @return the future of the next {@Link SubQuery}, or <code>null</code> if this query has succeeded. * @throws DbException if there is an error */ private LocalSubQueryFuture advanceQuery(final Query queryState) throws DbException { Verify.verify(queryState.getCurrentSubQuery() == null, "expected queryState current task is null"); SubQuery task; try { task = queryState.nextSubQuery(); } catch (QueryKilledException qke) { queryState.markKilled(); finishQuery(queryState); return null; } catch (RuntimeException | DbException e) { queryState.markFailed(e); finishQuery(queryState); return null; } if (task == null) { queryState.markSuccess(); finishQuery(queryState); return null; } return submitSubQuery(queryState); } /** * Finish the specified query by updating its status in the Catalog and then removing it from the active queries. * * @param queryState the query to be finished * @throws DbException if there is an error updating the Catalog */ private void finishQuery(final Query queryState) throws DbException { try { catalog.queryFinished(queryState); } catch (CatalogException e) { throw new DbException("Error finishing query " + queryState.getQueryId(), e); } finally { activeQueries.remove(queryState.getQueryId()); } } /** * Submit the next subquery in the query for execution, and return its future. * * @param queryState the query containing the subquery to be executed * @return the future of the subquery * @throws DbException if there is an error submitting the subquery for execution */ private LocalSubQueryFuture submitSubQuery(final Query queryState) throws DbException { final SubQuery subQuery = Verify.verifyNotNull(queryState.getCurrentSubQuery(), "query state should have a current subquery"); final SubQueryId subQueryId = subQuery.getSubQueryId(); try { final MasterSubQuery mqp = new MasterSubQuery(subQuery, this); executingSubQueries.put(subQueryId, mqp); final LocalSubQueryFuture queryExecutionFuture = mqp.getExecutionFuture(); /* Add the future to update the metadata about created relations, if there are any. */ queryState.addDatasetMetadataUpdater(catalog, queryExecutionFuture); queryExecutionFuture.addListener(new LocalSubQueryFutureListener() { @Override public void operationComplete(final LocalSubQueryFuture future) throws Exception { finishSubQuery(subQueryId); final Long elapsedNanos = mqp.getExecutionStatistics().getQueryExecutionElapse(); if (future.isSuccess()) { LOGGER.info("Subquery #{} succeeded. Time elapsed: {}.", subQueryId, DateTimeUtils .nanoElapseToHumanReadable(elapsedNanos)); // TODO success management. advanceQuery(queryState); } else { Throwable cause = future.getCause(); LOGGER.info("Subquery #{} failed. Time elapsed: {}. Failure cause is {}.", subQueryId, DateTimeUtils .nanoElapseToHumanReadable(elapsedNanos), cause); if (cause instanceof QueryKilledException) { queryState.markKilled(); } else { queryState.markFailed(cause); } finishQuery(queryState); } } }); dispatchWorkerQueryPlans(mqp).addListener(new LocalSubQueryFutureListener() { @Override public void operationComplete(final LocalSubQueryFuture future) throws Exception { mqp.init(); if (subQueryId.getSubqueryId() == 0) { getQuery(subQueryId.getQueryId()).markStart(); } mqp.startExecution(); Server.this.startWorkerQuery(future.getLocalSubQuery().getSubQueryId()); } }); return mqp.getExecutionFuture(); } catch (DbException | RuntimeException e) { finishSubQuery(subQueryId); queryState.markFailed(e); finishQuery(queryState); throw e; } } /** * Finish the subquery by removing it from the data structures. * * @param subQueryId the id of the subquery to finish. */ private void finishSubQuery(final SubQueryId subQueryId) { long queryId = subQueryId.getQueryId(); executingSubQueries.remove(subQueryId); getQuery(queryId).finishSubQuery(); } /** * Tells all the workers to begin executing the specified {@link SubQuery}. * * @param subQueryId the id of the subquery to be started. */ private void startWorkerQuery(final SubQueryId subQueryId) { final MasterSubQuery mqp = executingSubQueries.get(subQueryId); for (final Integer workerID : mqp.getWorkerAssigned()) { connectionPool.sendShortMessage(workerID, IPCUtils.startQueryTM(subQueryId)); } } /** * @return the set of workers that are currently alive. */ public Set<Integer> getAliveWorkers() { return ImmutableSet.copyOf(aliveWorkers.keySet()); } /** * Return a random subset of workers. * * @param number the number of alive workers returned * @return a subset of workers that are currently alive. */ public Set<Integer> getRandomWorkers(final int number) { Preconditions.checkArgument(number <= getAliveWorkers().size(), "The number of workers requested cannot exceed the number of alive workers."); if (number == getAliveWorkers().size()) { return getAliveWorkers(); } List<Integer> workerList = new ArrayList<>(aliveWorkers.keySet()); Collections.shuffle(workerList); return ImmutableSet.copyOf(workerList.subList(0, number)); } /** * @return the set of known workers in this Master. */ public Map<Integer, SocketInfo> getWorkers() { return ImmutableMap.copyOf(workers); } /** * Ingest the given dataset. * * @param relationKey the name of the dataset. * @param workersToIngest restrict the workers to ingest data (null for all) * @param indexes the indexes created. * @param source the source of tuples to be ingested. * @return the status of the ingested dataset. * @throws InterruptedException interrupted * @throws DbException if there is an error */ public DatasetStatus ingestDataset(final RelationKey relationKey, final Set<Integer> workersToIngest, final List<List<IndexRef>> indexes, final Operator source) throws InterruptedException, DbException { /* Figure out the workers we will use. If workersToIngest is null, use all active workers. */ Set<Integer> actualWorkers = workersToIngest; if (workersToIngest == null) { actualWorkers = getAliveWorkers(); } Preconditions.checkArgument(actualWorkers.size() > 0, "Must use > 0 workers"); int[] workersArray = MyriaUtils.integerCollectionToIntArray(actualWorkers); /* The master plan: send the tuples out. */ ExchangePairID scatterId = ExchangePairID.newID(); GenericShuffleProducer scatter = new GenericShuffleProducer(source, scatterId, workersArray, new RoundRobinPartitionFunction(workersArray.length)); /* The workers' plan */ GenericShuffleConsumer gather = new GenericShuffleConsumer(source.getSchema(), scatterId, new int[] { MyriaConstants.MASTER_ID }); DbInsert insert = new DbInsert(gather, relationKey, true, indexes); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(); for (Integer workerId : workersArray) { workerPlans.put(workerId, new SubQueryPlan(insert)); } ListenableFuture<Query> qf; try { qf = submitQuery("ingest " + relationKey.toString(), "ingest " + relationKey.toString(), "ingest " + relationKey.toString(getDBMS()), new SubQueryPlan(scatter), workerPlans, false); } catch (CatalogException e) { throw new DbException("Error submitting query", e); } try { qf.get(); } catch (ExecutionException e) { throw new DbException("Error executing query", e.getCause()); } return getDatasetStatus(relationKey); } /** * @return whether this master can handle more queries or not. */ public boolean canSubmitQuery() { return (activeQueries.size() < MyriaConstants.MAX_ACTIVE_QUERIES); } /** * @param relationKey the relationalKey of the dataset to import * @param schema the schema of the dataset to import * @param workersToImportFrom the set of workers * @throws DbException if there is an error * @throws InterruptedException interrupted */ public void importDataset(final RelationKey relationKey, final Schema schema, final Set<Integer> workersToImportFrom) throws DbException, InterruptedException { /* Figure out the workers we will use. If workersToImportFrom is null, use all active workers. */ Set<Integer> actualWorkers = workersToImportFrom; if (workersToImportFrom == null) { actualWorkers = getWorkers().keySet(); } try { Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(); for (Integer workerId : actualWorkers) { workerPlans.put(workerId, new SubQueryPlan(new SinkRoot(new EOSSource()))); } ListenableFuture<Query> qf = submitQuery("import " + relationKey.toString(), "import " + relationKey.toString(), "import " + relationKey.toString(getDBMS()), new SubQueryPlan(new SinkRoot(new EOSSource())), workerPlans, false); Query queryState; try { queryState = qf.get(); } catch (ExecutionException e) { throw new DbException("Error executing query", e.getCause()); } /* TODO(dhalperi) -- figure out how to populate the numTuples column. */ catalog.addRelationMetadata(relationKey, schema, -1, queryState.getQueryId()); /* Add the round robin-partitioned shard. */ catalog.addStoredRelation(relationKey, actualWorkers, "RoundRobin"); } catch (CatalogException e) { throw new DbException(e); } } /** * @param relationKey the key of the desired relation. * @return the schema of the specified relation, or null if not found. * @throws CatalogException if there is an error getting the Schema out of the catalog. */ public Schema getSchema(final RelationKey relationKey) throws CatalogException { return catalog.getSchema(relationKey); } /** * @param relationKey the key of the desired relation. * @param storedRelationId indicates which copy of the desired relation we want to scan. * @return the list of workers that store the specified relation. * @throws CatalogException if there is an error accessing the catalog. */ public Set<Integer> getWorkersForRelation(final RelationKey relationKey, final Integer storedRelationId) throws CatalogException { return catalog.getWorkersForRelation(relationKey, storedRelationId); } /** * @param queryId the query that owns the desired temp relation. * @param relationKey the key of the desired temp relation. * @return the list of workers that store the specified relation. */ public Set<Integer> getWorkersForTempRelation(@Nonnull final Long queryId, @Nonnull final RelationKey relationKey) { return getQuery(queryId).getWorkersForTempRelation(relationKey); } /** * @param configKey config key. * @return master configuration. */ public String getConfiguration(final String configKey) { try { return catalog.getConfigurationValue(configKey); } catch (CatalogException e) { LOGGER.warn("Configuration retrieval error", e); return null; } } /** * @return the socket info for the master. */ protected SocketInfo getSocketInfo() { return masterSocketInfo; } /** * Computes and returns the status of the requested query, or null if the query does not exist. * * @param queryId the identifier of the query. * @throws CatalogException if there is an error in the catalog. * @return the status of this query. */ public QueryStatusEncoding getQueryStatus(final long queryId) throws CatalogException { /* Get the stored data for this query, e.g., the submitted program. */ QueryStatusEncoding queryStatus = catalog.getQuery(queryId); if (queryStatus == null) { return null; } Query state = activeQueries.get(queryId); if (state == null) { /* Not active, so the information from the Catalog is authoritative. */ return queryStatus; } /* Currently active, so fill in the latest information about the query. */ queryStatus.startTime = state.getStartTime(); queryStatus.finishTime = state.getEndTime(); queryStatus.elapsedNanos = state.getElapsedTime(); queryStatus.status = state.getStatus(); return queryStatus; } /** * Computes and returns the status of queries that have been submitted to Myria. * * @param limit the maximum number of results to return. Any value <= 0 is interpreted as all results. * @param maxId the largest query ID returned. If null or <= 0, all queries will be returned. * @throws CatalogException if there is an error in the catalog. * @return a list of the status of every query that has been submitted to Myria. */ public List<QueryStatusEncoding> getQueries(final long limit, final long maxId) throws CatalogException { List<QueryStatusEncoding> ret = new LinkedList<>(); /* Begin by adding the status for all the active queries. */ TreeSet<Long> activeQueryIds = new TreeSet<>(activeQueries.keySet()); final Iterator<Long> iter = activeQueryIds.descendingIterator(); while (iter.hasNext()) { long queryId = iter.next(); final QueryStatusEncoding status = getQueryStatus(queryId); if (status == null) { LOGGER.warn("Weird: query status for active query {} is null.", queryId); continue; } ret.add(status); } /* Now add in the status for all the inactive (finished, killed, etc.) queries. */ for (QueryStatusEncoding q : catalog.getQueries(limit, maxId)) { if (!activeQueryIds.contains(q.queryId)) { ret.add(q); } } return ret; } /** * @return A list of datasets in the system. * @throws DbException if there is an error accessing the desired Schema. */ public List<DatasetStatus> getDatasets() throws DbException { try { return catalog.getDatasets(); } catch (CatalogException e) { throw new DbException(e); } } /** * Get the metadata about a relation. * * @param relationKey specified which relation to get the metadata about. * @return the metadata of the specified relation. * @throws DbException if there is an error getting the status. */ public DatasetStatus getDatasetStatus(final RelationKey relationKey) throws DbException { try { return catalog.getDatasetStatus(relationKey); } catch (CatalogException e) { throw new DbException(e); } } /** * @param searchTerm the search term * @return the relations that match the search term * @throws DbException if there is an error getting the relation keys. */ public List<RelationKey> getMatchingRelationKeys(final String searchTerm) throws DbException { try { return catalog.getMatchingRelationKeys(searchTerm); } catch (CatalogException e) { throw new DbException(e); } } /** * @param userName the user whose datasets we want to access. * @return a list of datasets belonging to the specified user. * @throws DbException if there is an error accessing the Catalog. */ public List<DatasetStatus> getDatasetsForUser(final String userName) throws DbException { try { return catalog.getDatasetsForUser(userName); } catch (CatalogException e) { throw new DbException(e); } } /** * @param userName the user whose datasets we want to access. * @param programName the program by that user whose datasets we want to access. * @return a list of datasets belonging to the specified program. * @throws DbException if there is an error accessing the Catalog. */ public List<DatasetStatus> getDatasetsForProgram(final String userName, final String programName) throws DbException { try { return catalog.getDatasetsForProgram(userName, programName); } catch (CatalogException e) { throw new DbException(e); } } /** * @param queryId the id of the query. * @return a list of datasets belonging to the specified program. * @throws DbException if there is an error accessing the Catalog. */ public List<DatasetStatus> getDatasetsForQuery(final int queryId) throws DbException { try { return catalog.getDatasetsForQuery(queryId); } catch (CatalogException e) { throw new DbException(e); } } /** * @return number of queries. * @throws CatalogException if an error occurs */ public int getNumQueries() throws CatalogException { return catalog.getNumQueries(); } /** * Start a query that streams tuples from the specified relation to the specified {@link TupleWriter}. * * @param relationKey the relation to be downloaded. * @param writer the {@link TupleWriter} which will serialize the tuples. * @return the query future from which the query status can be looked up. * @throws DbException if there is an error in the system. */ public ListenableFuture<Query> startDataStream(final RelationKey relationKey, final TupleWriter writer) throws DbException { /* Get the relation's schema, to make sure it exists. */ final Schema schema; try { schema = catalog.getSchema(relationKey); } catch (CatalogException e) { throw new DbException(e); } Preconditions.checkArgument(schema != null, "relation %s was not found", relationKey); /* Get the workers that store it. */ Set<Integer> scanWorkers; try { scanWorkers = getWorkersForRelation(relationKey, null); } catch (CatalogException e) { throw new DbException(e); } /* Construct the operators that go elsewhere. */ DbQueryScan scan = new DbQueryScan(relationKey, schema); final ExchangePairID operatorId = ExchangePairID.newID(); CollectProducer producer = new CollectProducer(scan, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(scanWorkers.size()); for (Integer worker : scanWorkers) { workerPlans.put(worker, workerPlan); } /* Construct the master plan. */ final CollectConsumer consumer = new CollectConsumer(schema, operatorId, ImmutableSet.copyOf(scanWorkers)); DataOutput output = new DataOutput(consumer, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = "download " + relationKey.toString(); try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * Start a query that streams tuples from the specified relation to the specified {@link TupleWriter}. * * @param numTB the number of {@link TupleBatch}es to download from each worker. * @param writer the {@link TupleWriter} which will serialize the tuples. * @return the query future from which the query status can be looked up. * @throws DbException if there is an error in the system. */ public ListenableFuture<Query> startTestDataStream(final int numTB, final TupleWriter writer) throws DbException { final Schema schema = new Schema(ImmutableList.of(Type.LONG_TYPE, Type.STRING_TYPE), ImmutableList.of("id", "name")); Random r = new Random(); final TupleBatchBuffer tbb = new TupleBatchBuffer(schema); for (int i = 0; i < TupleBatch.BATCH_SIZE; i++) { tbb.putLong(0, r.nextLong()); tbb.putString(1, new java.util.Date().toString()); } TupleBatch tb = tbb.popAny(); final DuplicateTBGenerator scanTable = new DuplicateTBGenerator(tb, numTB); /* Get the workers that store it. */ Set<Integer> scanWorkers = getAliveWorkers(); /* Construct the operators that go elsewhere. */ final ExchangePairID operatorId = ExchangePairID.newID(); CollectProducer producer = new CollectProducer(scanTable, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(scanWorkers.size()); for (Integer worker : scanWorkers) { workerPlans.put(worker, workerPlan); } /* Construct the master plan. */ final CollectConsumer consumer = new CollectConsumer(schema, operatorId, ImmutableSet.copyOf(scanWorkers)); DataOutput output = new DataOutput(consumer, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = "download test"; try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * @param queryId query id. * @param fragmentId the fragment id to return data for. All fragments, if < 0. * @param writer writer to get data. * @return profiling logs for the query. * @throws DbException if there is an error when accessing profiling logs. */ public ListenableFuture<Query> startSentLogDataStream(final long queryId, final long fragmentId, final TupleWriter writer) throws DbException { final QueryStatusEncoding queryStatus = checkAndReturnQueryStatus(queryId); Set<Integer> actualWorkers = queryStatus.plan.getWorkers(); String fragmentWhere = ""; if (fragmentId >= 0) { fragmentWhere = "AND fragmentid = " + fragmentId; } final Schema schema = Schema.ofFields("fragmentid", Type.INT_TYPE, "destworker", Type.INT_TYPE, "numTuples", Type.LONG_TYPE); String sentQueryString = Joiner.on(' ').join("SELECT fragmentid, destworkerid, sum(numtuples) as numtuples FROM", MyriaConstants.SENT_RELATION.toString(getDBMS()) + "WHERE queryid =", queryId, fragmentWhere, "GROUP BY queryid, fragmentid, destworkerid"); DbQueryScan scan = new DbQueryScan(sentQueryString, schema); final ExchangePairID operatorId = ExchangePairID.newID(); ImmutableList.Builder<Expression> emitExpressions = ImmutableList.builder(); emitExpressions.add(new Expression("workerId", new WorkerIdExpression())); for (int column = 0; column < schema.numColumns(); column++) { VariableExpression copy = new VariableExpression(column); emitExpressions.add(new Expression(schema.getColumnName(column), copy)); } Apply addWorkerId = new Apply(scan, emitExpressions.build()); CollectProducer producer = new CollectProducer(addWorkerId, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(actualWorkers.size()); for (Integer worker : actualWorkers) { workerPlans.put(worker, workerPlan); } final CollectConsumer consumer = new CollectConsumer(addWorkerId.getSchema(), operatorId, ImmutableSet.copyOf(actualWorkers)); final MultiGroupByAggregate aggregate = new MultiGroupByAggregate(consumer, new int[] { 0, 1, 2 }, new int[] { 3 }, new int[] { Aggregator.AGG_OP_SUM }); // rename columns ImmutableList.Builder<Expression> renameExpressions = ImmutableList.builder(); renameExpressions.add(new Expression("src", new VariableExpression(0))); renameExpressions.add(new Expression("fragmentId", new VariableExpression(1))); renameExpressions.add(new Expression("dest", new VariableExpression(2))); renameExpressions.add(new Expression("numTuples", new VariableExpression(3))); final Apply rename = new Apply(aggregate, renameExpressions.build()); DataOutput output = new DataOutput(rename, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = Joiner.on("").join("download profiling log data for (query=", queryId, ", fragment=", fragmentId, ")"); try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * @param queryId query id. * @param fragmentId the fragment id to return data for. All fragments, if < 0. * @param start the earliest time where we need data * @param end the latest time * @param minSpanLength minimum length of a span to be returned * @param onlyRootOperator only return data for root operator * @param writer writer to get data. * @return profiling logs for the query. * * @throws DbException if there is an error when accessing profiling logs. */ public QueryFuture startLogDataStream(final long queryId, final long fragmentId, final long start, final long end, final long minSpanLength, final boolean onlyRootOperator, final TupleWriter writer) throws DbException { final QueryStatusEncoding queryStatus = checkAndReturnQueryStatus(queryId); Preconditions.checkArgument(start < end, "range cannot be negative"); final Schema schema = Schema.ofFields("opId", Type.INT_TYPE, "startTime", Type.LONG_TYPE, "endTime", Type.LONG_TYPE, "numTuples", Type.LONG_TYPE); Set<Integer> actualWorkers = queryStatus.plan.getWorkers(); String opCondition = ""; if (onlyRootOperator) { opCondition = Joiner.on(' ').join("AND opid = (SELECT opid FROM", MyriaConstants.PROFILING_RELATION.toString(getDBMS()), "WHERE", fragmentId, "=fragmentId AND", queryId, "=queryId ORDER BY starttime ASC limit 1)");; } String spanCondition = ""; if (minSpanLength > 0) { spanCondition = Joiner.on(' ').join("AND endtime - starttime >", minSpanLength); } String queryString = Joiner.on(' ').join("SELECT opid, starttime, endtime, numtuples FROM", MyriaConstants.PROFILING_RELATION.toString(getDBMS()), "WHERE fragmentId =", fragmentId, "AND queryid =", queryId, "AND endtime >", start, "AND starttime <", end, opCondition, spanCondition, "ORDER BY starttime ASC"); DbQueryScan scan = new DbQueryScan(queryString, schema); ImmutableList.Builder<Expression> emitExpressions = ImmutableList.builder(); emitExpressions.add(new Expression("workerId", new WorkerIdExpression())); for (int column = 0; column < schema.numColumns(); column++) { VariableExpression copy = new VariableExpression(column); emitExpressions.add(new Expression(schema.getColumnName(column), copy)); } Apply addWorkerId = new Apply(scan, emitExpressions.build()); final ExchangePairID operatorId = ExchangePairID.newID(); CollectProducer producer = new CollectProducer(addWorkerId, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(actualWorkers.size()); for (Integer worker : actualWorkers) { workerPlans.put(worker, workerPlan); } final CollectConsumer consumer = new CollectConsumer(addWorkerId.getSchema(), operatorId, ImmutableSet.copyOf(actualWorkers)); DataOutput output = new DataOutput(consumer, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = Joiner.on('\0').join("download profiling data (query=", queryId, ", fragment=", fragmentId, ", range=[", Joiner.on(", ").join(start, end), "]", ")"); try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * @param queryId query id. * @param fragmentId the fragment id to return data for. All fragments, if < 0. * @param start start of the histogram * @param end the end of the histogram * @param step the step size between min and max * @param onlyRootOp return histogram only for root operator * @param writer writer to get data. * @return profiling logs for the query. * * @throws DbException if there is an error when accessing profiling logs. */ public QueryFuture startHistogramDataStream(final long queryId, final long fragmentId, final long start, final long end, final long step, final boolean onlyRootOp, final TupleWriter writer) throws DbException { final QueryStatusEncoding queryStatus = checkAndReturnQueryStatus(queryId); Preconditions.checkArgument(start < end, "range cannot be negative"); Preconditions.checkArgument(step > 0, "step has to be greater than 0"); final Schema schema = Schema.ofFields("opId", Type.INT_TYPE, "nanoTime", Type.LONG_TYPE); final RelationKey relationKey = MyriaConstants.PROFILING_RELATION; Set<Integer> actualWorkers = queryStatus.plan.getWorkers(); String filterOpnameQueryString = ""; if (onlyRootOp) { filterOpnameQueryString = Joiner.on(' ').join("AND p.opid=(SELECT opid FROM", relationKey.toString(getDBMS()), "WHERE fragmentid=", fragmentId, " AND queryid=", queryId, "ORDER BY starttime ASC limit 1)"); } String histogramWorkerQueryString = Joiner.on(' ').join("SELECT p.opid, s.t AS nanotime FROM generate_series(", start, ", ", end, ", ", step, ") AS s(t), ", relationKey.toString(getDBMS()), " AS p WHERE p.queryid=", queryId, "AND p.fragmentid=", fragmentId, filterOpnameQueryString, "AND s.t BETWEEN p.starttime AND p.endtime"); DbQueryScan scan = new DbQueryScan(histogramWorkerQueryString, schema); final ExchangePairID operatorId = ExchangePairID.newID(); CollectProducer producer = new CollectProducer(scan, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(actualWorkers.size()); for (Integer worker : actualWorkers) { workerPlans.put(worker, workerPlan); } /* Aggregate histogram on master */ final CollectConsumer consumer = new CollectConsumer(scan.getSchema(), operatorId, ImmutableSet.copyOf(actualWorkers)); // sum up the number of workers working final MultiGroupByAggregate sumAggregate = new MultiGroupByAggregate(consumer, new int[] { 0, 1 }, new int[] { 1 }, new int[] { Aggregator.AGG_OP_COUNT }); // rename columns ImmutableList.Builder<Expression> renameExpressions = ImmutableList.builder(); renameExpressions.add(new Expression("opId", new VariableExpression(0))); renameExpressions.add(new Expression("nanoTime", new VariableExpression(1))); renameExpressions.add(new Expression("numWorkers", new VariableExpression(2))); final Apply rename = new Apply(sumAggregate, renameExpressions.build()); DataOutput output = new DataOutput(rename, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = Joiner.on('\0').join("download profiling histogram (query=", queryId, ", fragment=", fragmentId, ", range=[", Joiner.on(", ").join(start, end, step), "]", ")"); try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * @param queryId the query id * @param fragmentId the fragment id * @param writer writer to get data * @return profiling logs for the query. * @throws DbException if there is an error when accessing profiling logs. */ public QueryFuture startRangeDataStream(final Long queryId, final Long fragmentId, final TupleWriter writer) throws DbException { final QueryStatusEncoding queryStatus = checkAndReturnQueryStatus(queryId); final Schema schema = Schema.ofFields("startTime", Type.LONG_TYPE, "endTime", Type.LONG_TYPE); final RelationKey relationKey = MyriaConstants.PROFILING_RELATION; Set<Integer> actualWorkers = queryStatus.plan.getWorkers(); String opnameQueryString = Joiner.on(' ').join("SELECT min(starttime), max(endtime) FROM", relationKey.toString(getDBMS()), "WHERE queryid=", queryId, "AND fragmentid=", fragmentId); DbQueryScan scan = new DbQueryScan(opnameQueryString, schema); final ExchangePairID operatorId = ExchangePairID.newID(); CollectProducer producer = new CollectProducer(scan, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(actualWorkers.size()); for (Integer worker : actualWorkers) { workerPlans.put(worker, workerPlan); } /* Construct the master plan. */ final CollectConsumer consumer = new CollectConsumer(scan.getSchema(), operatorId, ImmutableSet.copyOf(actualWorkers)); // Aggregate range on master final Aggregate sumAggregate = new Aggregate(consumer, new int[] { 0, 1 }, new int[] { Aggregator.AGG_OP_MIN, Aggregator.AGG_OP_MAX }); DataOutput output = new DataOutput(sumAggregate, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = Joiner.on('\0').join("download time range (query=", queryId, ", fragment=", fragmentId, ")"); try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * @param queryId query id. * @param fragmentId the fragment id to return data for. All fragments, if < 0. * @param writer writer to get data. * @return contributions for operator. * * @throws DbException if there is an error when accessing profiling logs. */ public QueryFuture startContributionsStream(final long queryId, final long fragmentId, final TupleWriter writer) throws DbException { final QueryStatusEncoding queryStatus = checkAndReturnQueryStatus(queryId); final Schema schema = Schema.ofFields("opId", Type.INT_TYPE, "nanoTime", Type.LONG_TYPE); final RelationKey relationKey = MyriaConstants.PROFILING_RELATION; Set<Integer> actualWorkers = queryStatus.plan.getWorkers(); String fragIdCondition = ""; if (fragmentId >= 0) { fragIdCondition = "AND fragmentid=" + fragmentId; } String opContributionsQueryString = Joiner.on(' ').join("SELECT opid, sum(endtime - starttime) FROM ", relationKey.toString(getDBMS()), "WHERE queryid=", queryId, fragIdCondition, "GROUP BY opid"); DbQueryScan scan = new DbQueryScan(opContributionsQueryString, schema); final ExchangePairID operatorId = ExchangePairID.newID(); CollectProducer producer = new CollectProducer(scan, operatorId, MyriaConstants.MASTER_ID); SubQueryPlan workerPlan = new SubQueryPlan(producer); Map<Integer, SubQueryPlan> workerPlans = new HashMap<>(actualWorkers.size()); for (Integer worker : actualWorkers) { workerPlans.put(worker, workerPlan); } /* Aggregate on master */ final CollectConsumer consumer = new CollectConsumer(scan.getSchema(), operatorId, ImmutableSet.copyOf(actualWorkers)); // sum up contributions final SingleGroupByAggregate sumAggregate = new SingleGroupByAggregate(consumer, new int[] { 1 }, 0, new int[] { Aggregator.AGG_OP_SUM }); // rename columns ImmutableList.Builder<Expression> renameExpressions = ImmutableList.builder(); renameExpressions.add(new Expression("opId", new VariableExpression(0))); renameExpressions.add(new Expression("nanoTime", new VariableExpression(1))); final Apply rename = new Apply(sumAggregate, renameExpressions.build()); DataOutput output = new DataOutput(rename, writer); final SubQueryPlan masterPlan = new SubQueryPlan(output); /* Submit the plan for the download. */ String planString = Joiner.on('\0').join("download operator contributions (query=", queryId, ", fragment=", fragmentId, ")"); try { return submitQuery(planString, planString, planString, masterPlan, workerPlans, false); } catch (CatalogException e) { throw new DbException(e); } } /** * Get the query status and check whether the query ran successfully with profiling enabled. * * @param queryId the query id * @return the query status * @throws DbException if the query cannot be retrieved */ private QueryStatusEncoding checkAndReturnQueryStatus(final long queryId) throws DbException { /* Get the relation's schema, to make sure it exists. */ final QueryStatusEncoding queryStatus; try { queryStatus = catalog.getQuery(queryId); } catch (CatalogException e) { throw new DbException(e); } Preconditions.checkArgument(queryStatus != null, "query %s not found", queryId); Preconditions.checkArgument(queryStatus.status == QueryStatusEncoding.Status.SUCCESS, "query %s did not succeed (%s)", queryId, queryStatus.status); Preconditions.checkArgument(queryStatus.profilingMode, "query %s was not run with profiling enabled", queryId); return queryStatus; } /** * Update the {@link MasterCatalog} so that the specified relation has the specified tuple count. * * @param relation the relation to update * @param count the number of tuples in that relation * @throws DbException if there is an error in the catalog */ public void updateRelationTupleCount(final RelationKey relation, final long count) throws DbException { try { catalog.updateRelationTupleCount(relation, count); } catch (CatalogException e) { throw new DbException("updating the number of tuples in the catalog", e); } } /** * Set the global variable owned by the specified query and named by the specified key to the specified value. * * @param queryId the query to whom the variable belongs. * @param key the name of the variable * @param value the new value for the variable */ public void setQueryGlobal(final long queryId, @Nonnull final String key, @Nonnull final Object value) { Preconditions.checkNotNull(key, "key"); Preconditions.checkNotNull(value, "value"); getQuery(queryId).setGlobal(key, value); } /** * Get the value of global variable owned by the specified query and named by the specified key. * * @param queryId the query to whom the variable belongs. * @param key the name of the variable * @return the value of the variable */ @Nullable public Object getQueryGlobal(final long queryId, @Nonnull final String key) { Preconditions.checkNotNull(key, "key"); return getQuery(queryId).getGlobal(key); } /** * Return the schema of the specified temp relation in the specified query. * * @param queryId the query that owns the temp relation * @param name the name of the temporary relation * @return the schema of the specified temp relation in the specified query */ public Schema getTempSchema(@Nonnull final Long queryId, @Nonnull final String name) { return getQuery(queryId).getTempSchema(RelationKey.ofTemp(queryId, name)); } @Nonnull private Query getQuery(@Nonnull final Long queryId) { Query query = activeQueries.get(Preconditions.checkNotNull(queryId, "queryId")); Preconditions.checkArgument(query != null, "Query #%s is not active", queryId); return query; } }
package com.cradle.iitc_mobile.share; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import com.cradle.iitc_mobile.Log; import com.cradle.iitc_mobile.R; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class IntentGenerator { private static final String EXTRA_FLAG_IS_DEFAULT = "IITCM_IS_DEFAULT"; private static final String EXTRA_FLAG_TITLE = "IITCM_TITLE"; private static final HashSet<ComponentName> KNOWN_COPY_HANDLERS = new HashSet<ComponentName>(); static { if (KNOWN_COPY_HANDLERS.isEmpty()) { KNOWN_COPY_HANDLERS.add(new ComponentName( "com.google.android.apps.docs", "com.google.android.apps.docs.app.SendTextToClipboardActivity")); KNOWN_COPY_HANDLERS.add(new ComponentName( "com.aokp.romcontrol", "com.aokp.romcontrol.ShareToClipboard")); } } public static String getTitle(final Intent intent) throws IllegalArgumentException { if (intent.hasExtra(EXTRA_FLAG_TITLE)) return intent.getStringExtra(EXTRA_FLAG_TITLE); throw new IllegalArgumentException("Got an intent not generated by IntentGenerator!\n" + "Intent:\n" + intent.toString() + "\n" + "Extras:\n" + intent.getExtras().toString()); } public static boolean isDefault(final Intent intent) { return intent.hasExtra(EXTRA_FLAG_IS_DEFAULT) && intent.getBooleanExtra(EXTRA_FLAG_IS_DEFAULT, false); } private final Context mContext; private final PackageManager mPackageManager; public IntentGenerator(final Context context) { mContext = context; mPackageManager = mContext.getPackageManager(); } private boolean containsCopyIntent(final List<Intent> targets) { for (final Intent intent : targets) { for (final ComponentName handler : KNOWN_COPY_HANDLERS) { if (handler.equals(intent.getComponent())) return true; } } return false; } private ArrayList<Intent> resolveTargets(final Intent intent) { final String packageName = mContext.getPackageName(); final List<ResolveInfo> activityList = mPackageManager.queryIntentActivities(intent, 0); final ResolveInfo defaultTarget = mPackageManager.resolveActivity(intent, 0); final ArrayList<Intent> list = new ArrayList<Intent>(activityList.size()); for (final ResolveInfo resolveInfo : activityList) { final ActivityInfo activity = resolveInfo.activityInfo; final ComponentName component = new ComponentName(activity.packageName, activity.name); // remove IITCm from list (we only want other apps) if (activity.packageName.equals(packageName)) continue; // bug in package manager. not exported activities shouldn't even appear here // (usually you would have to compare the package name as well, but since we ignore our own activities, // this isn't necessary) if (!activity.exported) continue; final Intent targetIntent = new Intent(intent) .setComponent(component) .putExtra(EXTRA_FLAG_TITLE, activity.loadLabel(mPackageManager)); if (resolveInfo.activityInfo.name.equals(defaultTarget.activityInfo.name) && resolveInfo.activityInfo.packageName.equals(defaultTarget.activityInfo.packageName)) { targetIntent.putExtra(EXTRA_FLAG_IS_DEFAULT, true); } list.add(targetIntent); } return list; } public void cleanup(final Intent intent) { intent.removeExtra(EXTRA_FLAG_IS_DEFAULT); intent.removeExtra(EXTRA_FLAG_TITLE); } public ArrayList<Intent> getBrowserIntents(final String title, final String url) { final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); return resolveTargets(intent); } public ArrayList<Intent> getGeoIntents(final String title, final String mLl, final int mZoom) { final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(String.format("geo:%s?z=%d", mLl, mZoom))) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); final ArrayList<Intent> targets = resolveTargets(intent); // Unfortunately, only Google Maps supports this, most other apps fail for (final Intent target : targets) { final ComponentName cn = target.getComponent(); if ("com.google.android.apps.maps".equals(cn.getPackageName())) { try { final String encodedTitle = URLEncoder.encode(title, "UTF-8"); target.setData(Uri.parse(String.format("geo:0,0?q=%s%%20(%s)&z=%d", mLl, encodedTitle, mZoom))); } catch (final UnsupportedEncodingException e) { Log.w(e); } break; } } return targets; } public ArrayList<Intent> getShareIntents(final String title, final String text) { final Intent intent = new Intent(Intent.ACTION_SEND) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) .setType("text/plain") .putExtra(Intent.EXTRA_TEXT, text) .putExtra(Intent.EXTRA_SUBJECT, title); final ArrayList<Intent> targets = resolveTargets(intent); if (!containsCopyIntent(targets)) { // add SendToClipboard intent in case Drive is not installed targets.add(new Intent(intent) .setComponent(new ComponentName(mContext, SendToClipboard.class)) .putExtra(EXTRA_FLAG_TITLE, mContext.getString(R.string.activity_share_to_clipboard))); } return targets; } }
package hudson.plugins.git; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import hudson.EnvVars; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.model.*; import hudson.plugins.git.GitSCM.BuildChooserContextImpl; import hudson.plugins.git.GitSCM.DescriptorImpl; import hudson.plugins.git.browser.GitRepositoryBrowser; import hudson.plugins.git.browser.GithubWeb; import hudson.plugins.git.extensions.GitSCMExtension; import hudson.plugins.git.extensions.GitSCMExtensionDescriptor; import hudson.plugins.git.extensions.impl.*; import hudson.plugins.git.util.BuildChooserContext; import hudson.plugins.git.util.BuildChooserContext.ContextCallable; import hudson.plugins.git.util.BuildData; import hudson.plugins.git.util.DefaultBuildChooser; import hudson.plugins.git.util.GitUtils; import hudson.plugins.parameterizedtrigger.BuildTrigger; import hudson.plugins.parameterizedtrigger.ResultCondition; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.scm.PollingResult; import hudson.slaves.DumbSlave; import hudson.slaves.EnvironmentVariablesNodeProperty.Entry; import hudson.tools.ToolProperty; import hudson.triggers.SCMTrigger; import hudson.util.StreamTaskListener; import java.io.ByteArrayOutputStream; import jenkins.security.MasterToSlaveCallable; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.jenkinsci.plugins.gitclient.*; import org.jenkinsci.remoting.RoleChecker; import org.junit.Test; import org.jvnet.hudson.test.TestExtension; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.net.URL; import java.util.*; import org.eclipse.jgit.transport.RemoteConfig; import static org.hamcrest.CoreMatchers.instanceOf; import org.jvnet.hudson.test.Issue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.mockito.Mockito; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests for {@link GitSCM}. * @author ishaaq */ public class GitSCMTest extends AbstractGitTestCase { /** * Basic test - create a GitSCM based project, check it out and build for the first time. * Next test that polling works correctly, make another commit, check that polling finds it, * then build it and finally test the build culprits as well as the contents of the workspace. * @throws Exception if an exception gets thrown. */ @Test public void testBasic() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicRemotePoll() throws Exception { // FreeStyleProject project = setupProject("master", true, false); FreeStyleProject project = setupProject("master", false, null, null, null, true, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); // ... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBranchSpecWithRemotesMaster() throws Exception { FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecWithRemotesHierarchical() throws Exception { FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null); FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null); // create initial commit final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // create hierarchical branch, delete master branch, and build git.branch("rel-1/xy"); git.checkout("rel-1/xy"); git.deleteBranch("master"); build(projectMasterBranch, Result.FAILURE); build(projectHierarchicalBranch, Result.SUCCESS, commitFile1); } @Test public void testBranchSpecUsingTagWithSlash() throws Exception { FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null); // create initial commit and build final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag"); testRepo.git.tag("path/tag", "tag with a slash in the tag name"); build(projectMasterBranch, Result.SUCCESS, commitFile1); } @Test public void testBasicIncludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testIncludedRegionWithDeeperCommits() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, null, ".*3"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicExcludedRegion() throws Exception { FreeStyleProject project = setupProject("master", false, null, ".*2", null, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testCleanBeforeCheckout() throws Exception { FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null); ((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout()); final String commitFile1 = "commitFile1"; final String commitFile2 = "commitFile2"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1); final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<BranchSpec>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); git.branch(branch1); git.checkout(branch1); p.poll(listener).hasChanges(); assertTrue(firstBuild.getLog().contains("Cleaning")); assertTrue(firstBuild.getLog().indexOf("Cleaning") > firstBuild.getLog().indexOf("Cloning")); //clean should be after clone assertTrue(firstBuild.getLog().indexOf("Cleaning") < firstBuild.getLog().indexOf("Checking out")); //clean before checkout assertTrue(firstBuild.getWorkspace().child(commitFile1).exists()); git.checkout(branch1); final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2); p.poll(listener).hasChanges(); assertTrue(secondBuild.getLog().contains("Cleaning")); assertTrue(secondBuild.getLog().indexOf("Cleaning") < secondBuild.getLog().indexOf("Fetching upstream changes")); assertTrue(secondBuild.getWorkspace().child(commitFile2).exists()); } @Issue("JENKINS-8342") @Test public void testExcludedRegionMultiCommit() throws Exception { // Got 2 projects, each one should only build if changes in its own file FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null); FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null); String initialCommitFile = "initialFile"; commit(initialCommitFile, johnDoe, "initial commit"); build(clientProject, Result.SUCCESS, initialCommitFile); build(serverProject, Result.SUCCESS, initialCommitFile); assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges()); assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges()); // Got commits on serverFile, so only server project should build. commit("myserverFile", johnDoe, "commit first server file"); assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); // Got commits on both client and serverFile, so both projects should build. commit("myNewserverFile", johnDoe, "commit new server file"); commit("myclientFile", johnDoe, "commit first clientfile"); assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges()); assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges()); } /** * With multiple branches specified in the project and having commits from a user * excluded should not build the excluded revisions when another branch changes. */ /* @Issue("JENKINS-8342") @Test public void testMultipleBranchWithExcludedUser() throws Exception { final String branch1 = "Branch1"; final String branch2 = "Branch2"; List<BranchSpec> branches = new ArrayList<BranchSpec>(); branches.add(new BranchSpec("master")); branches.add(new BranchSpec(branch1)); branches.add(new BranchSpec(branch2)); final FreeStyleProject project = setupProject(branches, false, null, null, janeDoe.getName(), null, false, null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // create branches here so we can get back to them later... git.branch(branch1); git.branch(branch2); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // Add excluded commit final String commitFile4 = "commitFile4"; commit(commitFile4, janeDoe, "Commit number 4"); assertFalse("scm polling detected change in 'master', which should have been excluded", project.poll(listener).hasChanges()); // now jump back... git.checkout(branch1); final String branch1File1 = "branch1File1"; commit(branch1File1, janeDoe, "Branch1 commit number 1"); assertFalse("scm polling detected change in 'Branch1', which should have been excluded", project.poll(listener).hasChanges()); // and the other branch... git.checkout(branch2); final String branch2File1 = "branch2File1"; commit(branch2File1, janeDoe, "Branch2 commit number 1"); assertFalse("scm polling detected change in 'Branch2', which should have been excluded", project.poll(listener).hasChanges()); final String branch2File2 = "branch2File2"; commit(branch2File2, johnDoe, "Branch2 commit number 2"); assertTrue("scm polling should detect changes in 'Branch2' branch", project.poll(listener).hasChanges()); //... and build it... build(project, Result.SUCCESS, branch2File1, branch2File2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // now jump back again... git.checkout(branch1); // Commit excluded after non-excluded commit, should trigger build. final String branch1File2 = "branch1File2"; commit(branch1File2, johnDoe, "Branch1 commit number 2"); final String branch1File3 = "branch1File3"; commit(branch1File3, janeDoe, "Branch1 commit number 3"); assertTrue("scm polling should detect changes in 'Branch1' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, branch1File1, branch1File2, branch1File3); } */ @Test public void testBasicExcludedUser() throws Exception { FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges()); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have two culprit", 2, culprits.size()); PersonIdent[] expected = {johnDoe, janeDoe}; assertCulprits("jane doe and john doe should be the culprits", culprits, expected); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertTrue(build2.getWorkspace().child(commitFile3).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicInSubdir() throws Exception { FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir")); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, "subdir", Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertEquals("The workspace should have a 'subdir' subdirectory, but does not.", true, build2.getWorkspace().child("subdir").exists()); assertEquals("The 'subdir' subdirectory should contain commitFile2, but does not.", true, build2.getWorkspace().child("subdir").child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testBasicWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("HUDSON-7547") @Test public void testBasicWithSlaveNoExecutorsOnMaster() throws Exception { FreeStyleProject project = setupSimpleProject("master"); rule.jenkins.setNumExecutors(0); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testAuthorOrCommitterFalse() throws Exception { // Test with authorOrCommitter set to false and make sure we get the committer. FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the committer as the change author with authorOrCommiter==false", janeDoe.getName(), secondCulprits.iterator().next().getFullName()); } @Test public void testAuthorOrCommitterTrue() throws Exception { // Next, test with authorOrCommitter set to true and make sure we get the author. FreeStyleProject project = setupSimpleProject("master"); ((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog()); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, janeDoe, "Commit number 1"); final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final Set<User> secondCulprits = secondBuild.getCulprits(); assertEquals("The build should have only one culprit", 1, secondCulprits.size()); assertEquals("Did not get the author as the change author with authorOrCommiter==true", johnDoe.getName(), secondCulprits.iterator().next().getFullName()); } /** * Method name is self-explanatory. */ @Test public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); //now create and checkout a new branch: git.checkout(Constants.HEAD, "untracked"); //.. and commit to it: final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges()); } private String checkoutString(FreeStyleProject project, String envVar) { return "checkout -f " + getEnvVars(project).get(envVar); } @Test public void testEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); rule.assertLogContains(getEnvVars(project).get(GitSCM.GIT_BRANCH), build1); rule.assertLogContains(checkoutString(project, GitSCM.GIT_COMMIT), build1); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build2); rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build1); rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build2); rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build1); } @Issue("HUDSON-7411") @Test public void testNodeEnvVarsAvailable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); Node s = rule.createSlave(); setVariables(s, new Entry("TESTKEY", "slaveValue")); project.setAssignedLabel(s.getSelfLabel()); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertEquals("slaveValue", getEnvVars(project).get("TESTKEY")); } /** * A previous version of GitSCM would only build against branches, not tags. This test checks that that * regression has been fixed. */ @Test public void testGitSCMCanBuildAgainstTags() throws Exception { final String mytag = "mytag"; FreeStyleProject project = setupSimpleProject(mytag); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); // Try again. The first build will leave the repository in a bad state because we // cloned something without even a HEAD - which will mean it will want to re-clone once there is some // actual data. build(project, Result.FAILURE); // fail, because there's nothing to be checked out here //now create and checkout a new branch: final String tmpBranch = "tmp"; git.branch(tmpBranch); git.checkout(tmpBranch); // commit to it final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); build(project, Result.FAILURE); // fail, because there's nothing to be checked out here // tag it, then delete the tmp branch git.tag(mytag, "mytag initial"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, tag "mytag" exists but is // not part of "master" assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now, create tmp branch again against mytag: git.checkout(mytag); git.branch(tmpBranch); // another commit: final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges()); // now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up: git.tag(mytag, "mytag moved"); git.checkout("master"); git.deleteBranch(tmpBranch); // at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit: assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile3); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } /** * Not specifying a branch string in the project implies that we should be polling for changes in * all branches. */ @Test public void testMultipleBranchBuild() throws Exception { // empty string will result in a project that tracks against changes in all branches: final FreeStyleProject project = setupSimpleProject(""); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); // create a branch here so we can get back to this point later... final String fork = "fork"; git.branch(fork); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final String commitFile3 = "commitFile3"; commit(commitFile3, johnDoe, "Commit number 3"); assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1, commitFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); // now jump back... git.checkout(fork); // add some commits to the fork branch... final String forkFile1 = "forkFile1"; commit(forkFile1, johnDoe, "Fork commit number 1"); final String forkFile2 = "forkFile2"; commit(forkFile2, johnDoe, "Fork commit number 2"); assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, forkFile1, forkFile2); assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges()); } @Issue("JENKINS-19037") @SuppressWarnings("ResultOfObjectAllocationIgnored") @Test public void testBlankRepositoryName() throws Exception { new GitSCM(null); } @Issue("JENKINS-10060") @Test public void testSubmoduleFixup() throws Exception { File repo = tempFolder.newFolder(); FilePath moduleWs = new FilePath(repo); org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient(); {// first we create a Git repository with submodule moduleRepo.init(); moduleWs.child("a").touch(0); moduleRepo.add("a"); moduleRepo.commit("creating a module"); git.addSubmodule(repo.getAbsolutePath(), "module1"); git.commit("creating a super project"); } // configure two uproject 'u' -> 'd' that's chained together. FreeStyleProject u = createFreeStyleProject(); FreeStyleProject d = createFreeStyleProject(); u.setScm(new GitSCM(workDir.getPath())); u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS, new GitRevisionBuildParameters()))); d.setScm(new GitSCM(workDir.getPath())); rule.jenkins.rebuildDependencyGraph(); FreeStyleBuild ub = rule.assertBuildStatusSuccess(u.scheduleBuild2(0)); System.out.println(ub.getLog()); for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop Thread.sleep(100); FreeStyleBuild db = d.getLastBuild(); assertNotNull("downstream build didn't happen",db); rule.assertBuildStatusSuccess(db); } @Test public void testBuildChooserContext() throws Exception { final FreeStyleProject p = createFreeStyleProject(); final FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); BuildChooserContextImpl c = new BuildChooserContextImpl(p, b, null); c.actOnBuild(new ContextCallable<Run<?,?>, Object>() { public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,b); return null; } }); c.actOnProject(new ContextCallable<Job<?,?>, Object>() { public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException { assertSame(param,p); return null; } }); DumbSlave s = rule.createOnlineSlave(); assertEquals(p.toString(), s.getChannel().call(new BuildChooserContextTestCallable(c))); } private static class BuildChooserContextTestCallable extends MasterToSlaveCallable<String,IOException> { private final BuildChooserContext c; public BuildChooserContextTestCallable(BuildChooserContext c) { this.c = c; } public String call() throws IOException { try { return c.actOnProject(new ContextCallable<Job<?,?>, String>() { public String invoke(Job<?,?> param, VirtualChannel channel) throws IOException, InterruptedException { assertTrue(channel instanceof Channel); assertTrue(Hudson.getInstance()!=null); return param.toString(); } }); } catch (InterruptedException e) { throw new IOException(e); } } } // eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe]) static public void assertCulprits(String assertMsg, Set<User> actual, PersonIdent[] expected) { Collection<String> fullNames = Collections2.transform(actual, new Function<User,String>() { public String apply(User u) { return u.getFullName(); } }); for(PersonIdent p : expected) { assertTrue(assertMsg, fullNames.contains(p.getName())); } } @Test public void testEmailCommitter() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // setup global config final DescriptorImpl descriptor = (DescriptorImpl) project.getScm().getDescriptor(); descriptor.setCreateAccountBasedOnEmail(true); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "jeff@doe.com"); commit(commitFile2, jeffDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); final Set<User> culprits = build2.getCulprits(); assertEquals("The build should have only one culprit", 1, culprits.size()); User culprit = culprits.iterator().next(); assertEquals("", jeffDoe.getEmailAddress(), culprit.getId()); assertEquals("", jeffDoe.getName(), culprit.getFullName()); rule.assertBuildStatusSuccess(build); } @Test public void testFetchFromMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("second", tempFolder.newFolder(), listener); List<UserRemoteConfig> remotes = new ArrayList<UserRemoteConfig>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); project.setScm(new GitSCM( remotes, Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList())); // create initial commit and then run the build against it: final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); build(project, Result.SUCCESS, commitFile1); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); final String commitFile2 = "commitFile2"; secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); //... and build it... final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-25639") @Test public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception { FreeStyleProject project = setupSimpleProject("master"); TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", tempFolder.newFolder(), listener); List<UserRemoteConfig> remotes = new ArrayList<UserRemoteConfig>(); remotes.addAll(testRepo.remoteConfigs()); remotes.addAll(secondTestRepo.remoteConfigs()); GitSCM gitSCM = new GitSCM( remotes, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(gitSCM); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1"); commit("commitFile2", johnDoe, "Commit number 2"); git = Git.with(listener, new EnvVars()).in(build.getWorkspace()).getClient(); for (RemoteConfig remoteConfig : gitSCM.getRepositories()) { git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs()); } Collection<Revision> candidateRevisions = ((DefaultBuildChooser) (gitSCM).getBuildChooser()).getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null); assertEquals(1, candidateRevisions.size()); } @Test public void testMerge() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-20392") @Test public void testMergeChangelog() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF))); project.setScm(scm); // create initial commit and then run the build against it: // Here the changelog is by default empty (because changelog for first commit is always empty commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); // Create second commit and run build // Here the changelog should contain exactly this one new commit testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; String commitMessage = "Commit number 2"; commit(commitFile2, johnDoe, commitMessage); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); ChangeLogSet<? extends ChangeLogSet.Entry> changeLog = build2.getChangeSet(); assertEquals("Changelog should contain one item", 1, changeLog.getItems().length); GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0]; assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim()); } @Test public void testMergeWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF))); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Issue("JENKINS-25191") @Test public void testMultipleMergeFailed() throws Exception { FreeStyleProject project = setupSimpleProject("master"); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("master")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF))); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF))); commit("dummyFile", johnDoe, "Initial Commit"); testRepo.git.branch("integration1"); testRepo.git.branch("integration2"); build(project, Result.SUCCESS); final String commitFile = "commitFile"; testRepo.git.checkoutBranch("integration1","master"); commit(commitFile,"abc", johnDoe, "merge conflict with integration2"); testRepo.git.checkoutBranch("integration2","master"); commit(commitFile,"cde", johnDoe, "merge conflict with integration1"); final FreeStyleBuild build = build(project, Result.FAILURE); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeFailedWithSlave() throws Exception { FreeStyleProject project = setupSimpleProject("master"); project.setAssignedLabel(rule.createSlave().getSelfLabel()); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); commit(commitFile1, "other content", johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertBuildStatus(Result.FAILURE, build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testMergeWithMatrixBuild() throws Exception { //Create a matrix project and a couple of axes MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz"); project.setAxes(new AxisList(new Axis("VAR","a","b"))); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("*")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null))); project.setScm(scm); // create initial commit and then run the build against it: commit("commitFileBase", johnDoe, "Initial Commit"); testRepo.git.branch("integration"); build(project, Result.SUCCESS, "commitFileBase"); testRepo.git.checkout(null, "topic1"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); // do what the GitPublisher would do testRepo.git.deleteBranch("integration"); testRepo.git.checkout("topic1", "integration"); testRepo.git.checkout("master", "topic2"); final String commitFile2 = "commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges()); final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2); assertTrue(build2.getWorkspace().child(commitFile2).exists()); rule.assertBuildStatusSuccess(build2); assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); } @Test public void testEnvironmentVariableExpansion() throws Exception { FreeStyleProject project = createFreeStyleProject(); project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath())); // create initial commit and then run the build against it: commit("a.txt", johnDoe, "Initial Commit"); build(project, Result.SUCCESS, "a.txt"); PollingResult r = project.poll(StreamTaskListener.fromStdout()); assertFalse(r.hasChanges()); commit("b.txt", johnDoe, "Another commit"); r = project.poll(StreamTaskListener.fromStdout()); assertTrue(r.hasChanges()); build(project, Result.SUCCESS, "b.txt"); } @TestExtension("testEnvironmentVariableExpansion") public static class SupplySomeEnvVars extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException { envs.put("CAT",""); } } private List<UserRemoteConfig> createRepoList(String url) { List<UserRemoteConfig> repoList = new ArrayList<UserRemoteConfig>(); repoList.add(new UserRemoteConfig(url, null, null, null)); return repoList; } /** * Makes sure that git browser URL is preserved across config round trip. */ @Issue("JENKINS-22604") @Test public void testConfigRoundtripURLPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "https://github.com/jenkinsci/jenkins"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); assertEquals("Wrong key", "git " + url, scm.getKey()); } /** * Makes sure that git extensions are preserved across config round trip. */ @Issue("JENKINS-33695") @Test public void testConfigRoundtripExtensionsPreserved() throws Exception { FreeStyleProject p = createFreeStyleProject(); final String url = "git://github.com/jenkinsci/git-plugin.git"; GitRepositoryBrowser browser = new GithubWeb(url); GitSCM scm = new GitSCM(createRepoList(url), Collections.singletonList(new BranchSpec("*/master")), false, Collections.<SubmoduleConfig>emptyList(), browser, null, null); p.setScm(scm); /* Assert that no extensions are loaded initially */ assertEquals(Collections.emptyList(), scm.getExtensions().toList()); /* Add LocalBranch extension */ LocalBranch localBranchExtension = new LocalBranch("**"); scm.getExtensions().add(localBranchExtension); assertTrue(scm.getExtensions().toList().contains(localBranchExtension)); /* Save the configuration */ rule.configRoundtrip(p); List<GitSCMExtension> extensions = scm.getExtensions().toList();; assertTrue(extensions.contains(localBranchExtension)); assertEquals("Wrong extension count before reload", 1, extensions.size()); /* Reload configuration from disc */ p.doReload(); GitSCM reloadedGit = (GitSCM) p.getScm(); List<GitSCMExtension> reloadedExtensions = reloadedGit.getExtensions().toList(); assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size()); LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0); assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch()); } /** * Makes sure that the configuration form works. */ @Test public void testConfigRoundtrip() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins"); p.setScm(scm); rule.configRoundtrip(p); rule.assertEqualDataBoundBeans(scm,p.getScm()); } /** * Sample configuration that should result in no extensions at all */ @Test public void testDataCompatibility1() throws Exception { FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml")); GitSCM oldGit = (GitSCM) p.getScm(); assertEquals(Collections.emptyList(), oldGit.getExtensions().toList()); assertEquals(0, oldGit.getSubmoduleCfg().size()); assertEquals("git git://github.com/jenkinsci/model-ant-project.git", oldGit.getKey()); assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class)); GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser(); assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/"); } @Test public void testPleaseDontContinueAnyway() throws Exception { // create an empty repository with some commits testRepo.commit("a","foo",johnDoe, "added"); FreeStyleProject p = createFreeStyleProject(); p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath())); rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); // this should fail as it fails to fetch p.setScm(new GitSCM("http://localhost:4321/no/such/repository.git")); rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); } @Issue("JENKINS-19108") @Test public void testCheckoutToSpecificBranch() throws Exception { FreeStyleProject p = createFreeStyleProject(); GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/"); setupJGit(oldGit); oldGit.getExtensions().add(new LocalBranch("master")); p.setScm(oldGit); FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0)); GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient(); gc.withRepository(new RepositoryCallback<Void>() { public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException { Ref head = repo.getRef("HEAD"); assertTrue("Detached HEAD",head.isSymbolic()); Ref t = head.getTarget(); assertEquals(t.getName(),"refs/heads/master"); return null; } }); } /** * Verifies that if project specifies LocalBranch with value of "**" * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <br/> * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception */ @Test public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("**")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that if project specifies LocalBranch with null value (empty string) * that the checkout to a local branch using remote branch name sans 'origin'. * This feature is necessary to support Maven release builds that push updated * pom.xml to remote branch as * <br/> * <pre> * git push origin localbranch:localbranch * </pre> * @throws Exception */ @Test public void testCheckoutToDefaultLocalBranch_NULL() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); GitSCM git = (GitSCM)project.getScm(); git.getExtensions().add(new LocalBranch("")); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } /** * Verifies that GIT_LOCAL_BRANCH is not set if LocalBranch extension * is not configured. * @throws Exception */ @Test public void testCheckoutSansLocalBranchExtension() throws Exception { FreeStyleProject project = setupSimpleProject("master"); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH)); assertEquals("GIT_LOCAL_BRANCH", null, getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH)); } @Test public void testCheckoutFailureIsRetryable() throws Exception { FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1); final String commitFile2 = "commitFile2"; commit(commitFile2, janeDoe, "Commit number 2"); // create lock file to simulate lock collision File lock = new File(build1.getWorkspace().toString(), ".git/index.lock"); try { FileUtils.touch(lock); final FreeStyleBuild build2 = build(project, Result.FAILURE); rule.assertLogContains("java.io.IOException: Could not checkout", build2); } finally { lock.delete(); } } @Test public void testInitSparseCheckout() throws Exception { if (!gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("toto"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); assertFalse(build1.getWorkspace().child("titi").exists()); assertFalse(build1.getWorkspace().child(commitFile2).exists()); } @Test public void testInitSparseCheckoutBis() throws Exception { if (!gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testSparseCheckoutAfterNormalCheckout() throws Exception { if (!gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupSimpleProject("master"); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Lists.newArrayList(new SparseCheckoutPath("titi")))); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); } @Test public void testNormalCheckoutAfterSparseCheckout() throws Exception { if (!gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build2 = build(project, Result.SUCCESS); assertTrue(build2.getWorkspace().child("titi").exists()); assertTrue(build2.getWorkspace().child(commitFile2).exists()); assertFalse(build2.getWorkspace().child("toto").exists()); assertFalse(build2.getWorkspace().child(commitFile1).exists()); ((GitSCM) project.getScm()).getExtensions().remove(SparseCheckoutPaths.class); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertTrue(build1.getWorkspace().child("toto").exists()); assertTrue(build1.getWorkspace().child(commitFile1).exists()); } @Test public void testInitSparseCheckoutOverSlave() throws Exception { if (!gitVersionAtLeast(1, 7, 10)) { /* Older git versions have unexpected behaviors with sparse checkout */ return; } FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi"))); project.setAssignedLabel(rule.createSlave().getSelfLabel()); // run build first to create workspace final String commitFile1 = "toto/commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); final String commitFile2 = "titi/commitFile2"; commit(commitFile2, johnDoe, "Commit number 2"); final FreeStyleBuild build1 = build(project, Result.SUCCESS); assertTrue(build1.getWorkspace().child("titi").exists()); assertTrue(build1.getWorkspace().child(commitFile2).exists()); assertFalse(build1.getWorkspace().child("toto").exists()); assertFalse(build1.getWorkspace().child(commitFile1).exists()); } /** * Test for JENKINS-22009. * * @throws Exception */ @Test public void testPolling_environmentValueInBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master"))); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); // build the project build(project, Result.SUCCESS); assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") public void baseTestPolling_parentHead(List<GitSCMExtension> extensions) throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("**")), false, Collections.<SubmoduleConfig>emptyList(), null, null, extensions); project.setScm(scm); // commit something in order to create an initial base version in git commit("toto/commitFile1", johnDoe, "Commit number 1"); git.branch("someBranch"); commit("toto/commitFile2", johnDoe, "Commit number 2"); assertTrue("polling should detect changes",project.poll(listener).hasChanges()); // build the project build(project, Result.SUCCESS); /* Expects 1 build because the build of someBranch incorporates all * the changes from the master branch as well as the changes from someBranch. */ assertEquals("Wrong number of builds", 1, project.getBuilds().size()); assertFalse("polling should not detect changes",project.poll(listener).hasChanges()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>emptyList()); } @Issue("JENKINS-29066") @Test public void testPolling_parentHead_DisableRemotePoll() throws Exception { baseTestPolling_parentHead(Collections.<GitSCMExtension>singletonList(new DisableRemotePoll())); } @Test public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch"))); // Initial commit to master commit("file1", johnDoe, "Initial Commit"); // Create the branches git.branch("trackedbranch"); git.branch("manualbranch"); final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch"); final Action[] actions = {new ParametersAction(branchParam)}; FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, build); assertFalse("No changes to git since last build", project.poll(listener).hasChanges()); git.checkout("manualbranch"); commit("file2", johnDoe, "Commit to manually build branch"); assertFalse("No changes to tracked branch", project.poll(listener).hasChanges()); git.checkout("trackedbranch"); commit("file3", johnDoe, "Commit to tracked branch"); assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges()); } private final class FakeParametersAction implements EnvironmentContributingAction, Serializable { // Test class for testPolling_environmentValueAsEnvironmentContributingAction test case final ParametersAction m_forwardingAction; public FakeParametersAction(StringParameterValue params) { this.m_forwardingAction = new ParametersAction(params); } public void buildEnvVars(AbstractBuild<?, ?> ab, EnvVars ev) { this.m_forwardingAction.buildEnvVars(ab, ev); } public String getIconFileName() { return this.m_forwardingAction.getIconFileName(); } public String getDisplayName() { return this.m_forwardingAction.getDisplayName(); } public String getUrlName() { return this.m_forwardingAction.getUrlName(); } public List<ParameterValue> getParameters() { return this.m_forwardingAction.getParameters(); } private void writeObject(java.io.ObjectOutputStream out) throws IOException { } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { } private void readObjectNoData() throws ObjectStreamException { } } private boolean gitVersionAtLeast(int neededMajor, int neededMinor) throws IOException, InterruptedException { return gitVersionAtLeast(neededMajor, neededMinor, 0); } private boolean gitVersionAtLeast(int neededMajor, int neededMinor, int neededPatch) throws IOException, InterruptedException { final TaskListener procListener = StreamTaskListener.fromStderr(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final int returnCode = new Launcher.LocalLauncher(procListener).launch().cmds("git", "--version").stdout(out).join(); assertEquals("git --version non-zero return code", 0, returnCode); assertFalse("Process listener logged an error", procListener.getLogger().checkError()); final String versionOutput = out.toString().trim(); final String[] fields = versionOutput.split(" ")[2].replaceAll("msysgit.", "").split("\\."); final int gitMajor = Integer.parseInt(fields[0]); final int gitMinor = Integer.parseInt(fields[1]); final int gitPatch = Integer.parseInt(fields[2]); return gitMajor >= neededMajor && gitMinor >= neededMinor && gitPatch >= neededPatch; } @Test public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception { FreeStyleProject project = createFreeStyleProject(); List<UserRemoteConfig> remoteConfigs = new ArrayList<UserRemoteConfig>(); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null)); remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null)); GitSCM scm = new GitSCM(remoteConfigs, Collections.singletonList(new BranchSpec("origin/master")), false, Collections.<SubmoduleConfig> emptyList(), null, null, Collections.<GitSCMExtension> emptyList()); project.setScm(scm); commit("commitFile1", johnDoe, "Commit number 1"); FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause()).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); first_build.getWorkspace().deleteContents(); PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null); assertFalse(pollingResult.hasChanges()); } /** * Test for JENKINS-24467. * * @throws Exception */ @Test public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception { // create parameterized project with environment value in branch specification FreeStyleProject project = createFreeStyleProject(); GitSCM scm = new GitSCM( createRemoteRepositories(), Collections.singletonList(new BranchSpec("${MY_BRANCH}")), false, Collections.<SubmoduleConfig>emptyList(), null, null, Collections.<GitSCMExtension>emptyList()); project.setScm(scm); // Inital commit and build commit("toto/commitFile1", johnDoe, "Commit number 1"); String brokenPath = "\\broken/path\\of/doom"; if (!gitVersionAtLeast(1, 8)) { /* Git 1.7.10.4 fails the first build unless the git-upload-pack * program is available in its PATH. * Later versions of git don't have that problem. */ final String systemPath = System.getenv("PATH"); brokenPath = systemPath + File.pathSeparator + brokenPath; } final StringParameterValue real_param = new StringParameterValue("MY_BRANCH", "master"); final StringParameterValue fake_param = new StringParameterValue("PATH", brokenPath); final Action[] actions = {new ParametersAction(real_param), new FakeParametersAction(fake_param)}; FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get(); rule.assertBuildStatus(Result.SUCCESS, first_build); Launcher launcher = workspace.createLauncher(listener); final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener); assertEquals(environment.get("MY_BRANCH"), "master"); assertNotSame("Enviroment path should not be broken path", environment.get("PATH"), brokenPath); } /** * Tests that builds have the correctly specified Custom SCM names, associated with * each build. * @throws Exception on various exceptions */ @Test public void testCustomSCMName() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; final String scmNameString1 = ""; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should not detect any more changes after build", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); // Check unset build SCM Name carries final int buildNumber1 = notifyAndCheckScmName( project, commit1, scmNameString1, 1, git); final String scmNameString2 = "ScmName2"; git.getExtensions().replace(new ScmName(scmNameString2)); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); // Check second set SCM Name final int buildNumber2 = notifyAndCheckScmName( project, commit2, scmNameString2, 2, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); final String scmNameString3 = "ScmName3"; git.getExtensions().replace(new ScmName(scmNameString3)); commit("commitFile3", johnDoe, "Commit number 3"); assertTrue("scm polling should detect commit 3", project.poll(listener).hasChanges()); final ObjectId commit3 = testRepo.git.revListAll().get(0); // Check third set SCM Name final int buildNumber3 = notifyAndCheckScmName( project, commit3, scmNameString3, 3, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); commit("commitFile4", johnDoe, "Commit number 4"); assertTrue("scm polling should detect commit 4", project.poll(listener).hasChanges()); final ObjectId commit4 = testRepo.git.revListAll().get(0); // Check third set SCM Name still set final int buildNumber4 = notifyAndCheckScmName( project, commit4, scmNameString3, 4, git); checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git); checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git); checkNumberedBuildScmName(project, buildNumber3, scmNameString3, git); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for custom SCM name build data consistency. * @param project project to build * @param commit commit to build * @param expectedScmName Expected SCM name for commit. * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on various exceptions occur */ private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit, String expectedScmName, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final Build build = project.getLastBuild(); final BuildData buildData = git.getBuildData(build); assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal, commit, buildData .getLastBuiltRevision().getSha1()); assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal, commit, buildData.getLastBuild(commit).getSHA1()); assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit)); assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName()); return build.getNumber(); } private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber, String expectedScmName, GitSCM git) throws Exception { final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber)); assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName()); } /** * Tests that builds have the correctly specified branches, associated with * the commit id, passed with "notifyCommit" URL. * @throws Exception on various exceptions */ @Issue("JENKINS-24133") @Test public void testSha1NotificationBranches() throws Exception { final String branchName = "master"; final FreeStyleProject project = setupProject(branchName, false); project.addTrigger(new SCMTrigger("")); final GitSCM git = (GitSCM) project.getScm(); setupJGit(git); final String commitFile1 = "commitFile1"; commit(commitFile1, johnDoe, "Commit number 1"); assertTrue("scm polling should detect commit 1", project.poll(listener).hasChanges()); build(project, Result.SUCCESS, commitFile1); final ObjectId commit1 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit1, branchName, 1, git); commit("commitFile2", johnDoe, "Commit number 2"); assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges()); final ObjectId commit2 = testRepo.git.revListAll().get(0); notifyAndCheckBranch(project, commit2, branchName, 2, git); notifyAndCheckBranch(project, commit1, branchName, 1, git); } /* A null pointer exception was detected because the plugin failed to * write a branch name to the build data, so there was a SHA1 recorded * in the build data, but no branch name. */ @Test public void testNoNullPointerExceptionWithNullBranch() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch(null, sha1); List<Branch> branchList = new ArrayList<Branch>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<BuildData>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.buildEnvVars(build, new EnvVars()); // NPE here before fix applied /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchStarStar() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<Branch>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<BuildData>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("**")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchNull() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<Branch>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<BuildData>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); scm.getExtensions().add(new LocalBranch("")); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } @Test public void testBuildEnvVarsLocalBranchNotSet() throws Exception { ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d"); /* This is the null that causes NPE */ Branch branch = new Branch("origin/master", sha1); List<Branch> branchList = new ArrayList<Branch>(); branchList.add(branch); Revision revision = new Revision(sha1, branchList); /* BuildData mock that will use the Revision with null branch name */ BuildData buildData = Mockito.mock(BuildData.class); Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision); Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true); /* List of build data that will be returned by the mocked BuildData */ List<BuildData> buildDataList = new ArrayList<BuildData>(); buildDataList.add(buildData); /* AbstractBuild mock which returns the buildDataList that contains a null branch name */ AbstractBuild build = Mockito.mock(AbstractBuild.class); Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList); final FreeStyleProject project = setupProject("*/*", false); GitSCM scm = (GitSCM) project.getScm(); EnvVars env = new EnvVars(); scm.buildEnvVars(build, env); // NPE here before fix applied assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH")); assertEquals("GIT_LOCAL_BRANCH", null, env.get("GIT_LOCAL_BRANCH")); /* Verify mocks were called as expected */ verify(buildData, times(1)).getLastBuiltRevision(); verify(buildData, times(1)).hasBeenReferenced(anyString()); verify(build, times(1)).getActions(BuildData.class); } /** * Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1 * and tests for build data consistency. * @param project project to build * @param commit commit to build * @param expectedBranch branch, that is expected to be built * @param ordinal number of commit to log into errors, if any * @param git git SCM * @throws Exception on various exceptions occur */ private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit, String expectedBranch, int ordinal, GitSCM git) throws Exception { assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit)); final BuildData buildData = git.getBuildData(project.getLastBuild()); final Collection<Branch> builtBranches = buildData.lastBuild.getRevision().getBranches(); assertEquals("Commit " + ordinal + " should be built", commit, buildData .getLastBuiltRevision().getSha1()); final String expectedBranchString = "origin/" + expectedBranch; assertFalse("Branches should be detected for the build", builtBranches.isEmpty()); assertEquals(expectedBranch + " branch should be detected", expectedBranchString, builtBranches.iterator().next().getName()); assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH)); } /** * Method performs commit notification for the last committed SHA1 using * notifyCommit URL. * @param project project to trigger * @return whether the new build has been triggered (<code>true</code>) or * not (<code>false</code>). * @throws Exception on various exceptions */ private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws Exception { final int initialBuildNumber = project.getLastBuild().getNumber(); final String commit1 = ObjectId.toString(commitId); final String notificationPath = rule.getURL().toExternalForm() + "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1; final URL notifyUrl = new URL(notificationPath); final InputStream is = notifyUrl.openStream(); IOUtils.toString(is); IOUtils.closeQuietly(is); if ((project.getLastBuild().getNumber() == initialBuildNumber) && (rule.jenkins.getQueue().isEmpty())) { return false; } else { while (!rule.jenkins.getQueue().isEmpty()) { Thread.sleep(100); } final FreeStyleBuild build = project.getLastBuild(); while (build.isBuilding()) { Thread.sleep(100); } return true; } } private void setupJGit(GitSCM git) { git.gitTool="jgit"; rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.<ToolProperty<?>>emptyList())); } /** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */ @TestExtension public static class CleanEnvironment extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) { envs.remove(GitSCM.GIT_BRANCH); envs.remove(GitSCM.GIT_LOCAL_BRANCH); envs.remove(GitSCM.GIT_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_COMMIT); envs.remove(GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT); } } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.Joystick.*; public class RobotTemplate extends IterativeRobot { public double stickPut; public Joystick controller; public SpeedController motor1, motor2, motor3, motor4; double distance = 0; public void robotInit() { controller = new Joystick(1); motor1 = new Talon(1); motor2 = new Talon(2); motor3 = new Talon(3); motor4 = new Talon(4); stickPut = 0; } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /** * This function is called periodically during operator control */ public void teleopPeriodic() { stickPut = controller.getAxis(AxisType.kX); distance++; if(distance <= 0){ motor1.set(0.2);//back and forth between speeds, -1.0 to 1.0 }else{ motor1.set(0); } } /** * This function is called periodically during test mode */ public void testPeriodic() { } public void turn(double maxRate, double turn, SpeedController motorOne, SpeedController motorTwo) { if (turn >= 0) { boolean right = true; } else { boolean right = false; } } }
package no.cantara.jau; import com.fasterxml.jackson.databind.ObjectMapper; import jdk.nashorn.internal.ir.annotations.Ignore; import no.cantara.jau.serviceconfig.client.ConfigServiceClient; import no.cantara.jau.serviceconfig.client.ConfigurationStoreUtil; import no.cantara.jau.serviceconfig.client.DownloadUtil; import no.cantara.jau.serviceconfig.dto.ServiceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; import java.io.File; import java.util.Properties; import java.util.Scanner; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class JAUProcessTest { private static final ObjectMapper mapper = new ObjectMapper(); private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); ScheduledFuture<?> restarterHandle; private ApplicationProcess processHolder; private static final Logger log = LoggerFactory.getLogger(JAUProcessTest.class); @BeforeClass public void startServer() throws InterruptedException { processHolder = new ApplicationProcess(); } @AfterClass public void stop() { if (processHolder != null) { processHolder.stopProcess(); } restarterHandle.cancel(true); } @Ignore @Test public void testProcessDownloadStartupAndRunning() throws Exception { String jsonResponse = new Scanner( new File("config1.serviceconfig") ).useDelimiter("\\A").next(); // let us type a configuration the quick way.. ServiceConfig serviceConfig = mapper.readValue(jsonResponse, ServiceConfig.class); // Process stuff ApplicationProcess processHolder= new ApplicationProcess(); processHolder.setWorkingDirectory(new File("./")); String workingDirectory = processHolder.getWorkingDirectory().getAbsolutePath(); // Download stuff DownloadUtil.downloadAllFiles(serviceConfig.getDownloadItems(), workingDirectory); ConfigurationStoreUtil.toFiles(serviceConfig.getConfigurationStores(), workingDirectory); // Lets try to start String initialCommand = serviceConfig.getStartServiceScript(); int updateInterval=100; System.out.println("Initial command: "+initialCommand); processHolder.setWorkingDirectory(new File(workingDirectory)); processHolder.setCommand(initialCommand.split("\\s+")); processHolder.startProcess(); restarterHandle = scheduler.scheduleAtFixedRate( () -> { try { // Restart, whatever the reason the process is not running. if (!processHolder.processIsrunning()) { log.debug("Process is not running - restarting... clientId={}, lastChanged={}, command={}", processHolder.getClientId(), processHolder.getLastChangedTimestamp(), processHolder.getCommand()); processHolder.startProcess(); } } catch (Exception e) { log.debug("Error thrown from scheduled lambda.", e); } }, 1, updateInterval, MILLISECONDS ); Thread.sleep(4000); assertTrue(processHolder.processIsrunning(), "First check"); Thread.sleep(1000); assertTrue(processHolder.processIsrunning(), "Second check"); processHolder.stopProcess(); assertFalse(processHolder.processIsrunning(), "Seventh check"); Thread.sleep(4000); assertTrue(processHolder.processIsrunning(), "Eigth check"); } private static String getStringProperty(final Properties properties, String propertyKey, String defaultValue) { String property = properties.getProperty(propertyKey, defaultValue); if (property == null) { //-Dconfigservice.url= property = System.getProperty(propertyKey); } return property; } }
package seedu.tache.testutil; import java.util.Optional; import seedu.tache.model.tag.UniqueTagList; import seedu.tache.model.task.DateTime; import seedu.tache.model.task.Name; import seedu.tache.model.task.ReadOnlyTask; import seedu.tache.model.task.Task.RecurInterval; /** * A mutable task object. For testing only. */ public class TestTask implements ReadOnlyTask { private Name name; private Optional<DateTime> startDateTime; private Optional<DateTime> endDateTime; private UniqueTagList tags; private boolean isTimed; private boolean isActive; private boolean isRecurring; private RecurInterval interval; public TestTask() { tags = new UniqueTagList(); this.startDateTime = Optional.empty(); this.endDateTime = Optional.empty(); this.interval = RecurInterval.NONE; this.isTimed = false; this.isActive = true; this.isRecurring = false; } /** * Creates a copy of {@code taskToCopy}. */ public TestTask(TestTask taskToCopy) { this.name = taskToCopy.getName(); this.tags = taskToCopy.getTags(); this.startDateTime = taskToCopy.getStartDateTime(); this.endDateTime = taskToCopy.getEndDateTime(); this.interval = taskToCopy.getRecurInterval(); } public void setName(Name name) { this.name = name; } public void setTags(UniqueTagList tags) { this.tags = tags; } @Override public Name getName() { return name; } @Override public Optional<DateTime> getStartDateTime() { // TODO Auto-generated method stub return startDateTime; } @Override public Optional<DateTime> getEndDateTime() { // TODO Auto-generated method stub return endDateTime; } @Override public UniqueTagList getTags() { return tags; } @Override public String toString() { return getAsText(); } public String getAddCommand() { StringBuilder sb = new StringBuilder(); sb.append("add " + this.getName().fullName + " "); this.getTags().asObservableList().stream().forEach(s -> sb.append(";" + s.tagName + " ")); return sb.toString(); } @Override public boolean getTimedStatus() { return isTimed; } @Override public boolean getActiveStatus() { return isActive; } @Override public boolean getRecurringStatus() { return isRecurring; } @Override public RecurInterval getRecurInterval() { return interval; } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; public class RobotTemplate extends IterativeRobot { //Practise robot or competition robot static final boolean PRACTISE_ROBOT = false; //Encoder rate at max speed in slow gear static final double SLOW_MAX_ENCODER_RATE = 750.0; //Encoder rate at max speed in fast gear static final double FAST_MAX_ENCODER_RATE = 1700.0; //Speed to set the elevator motor to static final double ELEVATOR_SPEED = 0.8; //Max drive motor speed static final double MAX_DRIVE_SPEED = 1.0; //Encoder counts per metre travelled static final double COUNTS_PER_METRE = 500; //Starting encoder counts static final double ELEVATOR_BASE = 0; //Number of elevator encoder counts static final int MAX_ELEVATOR_COUNTS = 2400; //Number of seconds to wait in teleoperated mode before the minibot is allowed to be deployed static final double MINIBOT_RELEASE_TIME = 110.0; //Number of seconds after the minibot drops before we send it out horizontal static final double MINIBOT_HORIZONTAL_DELAY = 2.0; //Tolerance for the gyro pid static final double GYRO_TOLERANCE = 1; //Driver joystick class Driver { //Buttons static final int TRANS_TOGGLE = 8; static final int ARCADE_TOGGLE = 2; //Axis static final int X_AXIS_LEFT = 1; static final int Y_AXIS_LEFT = 2; static final int X_AXIS_RIGHT = 3; static final int Y_AXIS_RIGHT = 4; } //Operator joystick class Operator { //Buttons static final int ELEVATOR_STATE_GROUND = 1; static final int ELEVATOR_STATE_ONE = 11; static final int ELEVATOR_STATE_TWO = 12; static final int ELEVATOR_STATE_THREE = 9; static final int ELEVATOR_STATE_FOUR = 10; static final int ELEVATOR_STATE_FIVE = 7; static final int ELEVATOR_STATE_SIX = 8; static final int ELEVATOR_STATE_FEED = 2; static final int ELEVATOR_MANUAL_TOGGLE = 5; static final int GRIPPER_TOGGLE = 3; static final int ELBOW_UP = 6; static final int ELBOW_DOWN = 4; static final int MINIBOT_RELEASE_ONE = 5; static final int MINIBOT_RELEASE_TWO = 6; } //Driver station DriverStation ds = DriverStation.getInstance(); //Joysticks Joystick stickDriver = new Joystick(1); Joystick stickOperator = new Joystick(2); //Compressor, switch is DI 10, spike is relay 1 Compressor compressor = new Compressor(10, 1); //Relays Solenoid transShiftSingle; DoubleSolenoid transShiftDouble; Relay gripper = new Relay(3); Relay elbowOne = new Relay(4); Relay elbowTwo = new Relay(5); Relay minibotVertical = new Relay(6); Relay minibotHorizontal = new Relay(7); //A storage class to hold the output of a PIDController class PIDOutputStorage implements PIDOutput { //pidWrite override public void pidWrite(double output) { value = output; } //Get the value public double get() { return value; } //The output of the PID double value = 0; }; //A storage class to hold the output of a PIDController class OutputStorage { public void disable() { } public void set(double val) { value = val; } public void set(double val, byte i) { value = val; } public void pidWrite() { } //Get the value public double get() { return value; } //The output of the PID double value = 0; }; //Gyro Gyro gyro = new Gyro(1); PIDOutputStorage gyroOutput = new PIDOutputStorage(); PIDController pidGyro = new PIDController(0.0, 0.0005, 0.0, gyro, gyroOutput, 0.005); //Jaguars Jaguar jagLeft = new Jaguar(1); Jaguar jagRight = new Jaguar(2); //Stores output from robotDrive OutputStorage storageLeft = new OutputStorage(); OutputStorage storageRight = new OutputStorage(); //DI 3 doesn't work //Victors Victor vicElevator = new Victor(4); //Encoders PIDEncoder encLeft = new PIDEncoder(true, 3, 4, true); Encoder encNull = new Encoder(7, 8); PIDEncoder encElevator = new PIDEncoder(false, 5, 6); PIDEncoder encRight = new PIDEncoder(true, 1, 2, true); //Provides drive functions (arcade and tank drive) RobotDrive robotDrive = new RobotDrive(jagLeft, jagRight); //PIDs PIDController pidLeft = new PIDController(0.0, 0.0005, 0.0, encLeft, jagLeft, 0.005); PIDController pidRight = new PIDController(0.0, 0.0005, 0.0, encRight, jagRight, 0.005); //Toggle for manual or automated elevator control //Default -- automated Toggle manualElevatorToggle = new Toggle(false); //Toggle for the transmission shifter button //Default -- low gear Toggle transToggle = new Toggle(false); //Toggle for the gripper button //Default -- gripper is closed Toggle gripperToggle = new Toggle(false); //Toggle for arcade/tank drive //Default is tank drive Toggle arcadeToggle = new Toggle(false); //Enumeration of setpoints for different heights of the elevator class ElevatorSetpoint { static final double ground = ELEVATOR_BASE; static final double posOne = ELEVATOR_BASE + MAX_ELEVATOR_COUNTS * 1.0 / 6.0; static final double posTwo = ELEVATOR_BASE + MAX_ELEVATOR_COUNTS * 2.0 / 6.0; static final double posThree = ELEVATOR_BASE + MAX_ELEVATOR_COUNTS * 3.0 / 6.0; static final double posFour = ELEVATOR_BASE + MAX_ELEVATOR_COUNTS * 4.0 / 6.0; static final double posFive = ELEVATOR_BASE + MAX_ELEVATOR_COUNTS * 5.0 / 6.0; static final double posSix = ELEVATOR_BASE + MAX_ELEVATOR_COUNTS; static final double feed = ELEVATOR_BASE; } //The elevator setpoint, determined by which button on the operator joystick is pressed double elevatorSetpoint = ElevatorSetpoint.ground; //Runs when the robot is turned public void robotInit() { //Start our encoders encRight.start(); encLeft.start(); encElevator.start(); //Start our elevator encoder at 0 encElevator.reset(); //Input/output range for left encoder/motors pidLeft.setInputRange(-SLOW_MAX_ENCODER_RATE, SLOW_MAX_ENCODER_RATE); pidLeft.setOutputRange(-MAX_DRIVE_SPEED, MAX_DRIVE_SPEED); //Input/output range for right encoder/motors pidRight.setInputRange(-SLOW_MAX_ENCODER_RATE, SLOW_MAX_ENCODER_RATE); pidRight.setOutputRange(-MAX_DRIVE_SPEED, MAX_DRIVE_SPEED); //Input/output range for the gyro PID pidGyro.setInputRange(-360.0, 360.0); pidGyro.setOutputRange(-0.5, 0.5); //Start the compressor compressor.start(); //Initialize our transmissions based on if we are using the practise robot or the real robot if(!PRACTISE_ROBOT) transShiftSingle = new Solenoid(1); else transShiftDouble = new DoubleSolenoid(1, 2); } //Used in teleopPeriodic to print only once a second double lastPrintTime = 0; //Print function for our variables public void print(String mode) { //Current time final double curPrintTime = Timer.getFPGATimestamp(); //If it has been more than half a second if(curPrintTime - lastPrintTime > 0.5) { //Print statements System.out.println("[" + mode + "]"); System.out.println("DS DI 1: " + ds.getDigitalIn(1) + " DS AI 1: " + ds.getAnalogIn(1)); System.out.println("renc: " + encRight.encoder.get() + " lenc: " + encLeft.encoder.get() + " elevator: " + encElevator.pidGet()); System.out.println("rSet: " + pidRight.getSetpoint() + " lSet: " + pidLeft.getSetpoint() + " eSet: " + elevatorSetpoint); System.out.println("rPID: " + pidRight.get() + " lPID: " + pidLeft.get()); System.out.println("manualElevator: " + manualElevatorToggle.get()); System.out.println("elevAxis: " + stickOperator.getAxis(Joystick.AxisType.kY) + " leftAxis: " + stickDriver.getRawAxis(Driver.Y_AXIS_LEFT) + " rightAxis: " + stickDriver.getRawAxis(Driver.Y_AXIS_RIGHT)); System.out.println("Gyro PIDget: " + gyro.pidGet() + " gyro output storage: " + gyroOutput.get()); System.out.println(); //Update the last print time lastPrintTime = curPrintTime; } } //Returns whether or not the setpoint has been reached public boolean elevatorPID() { //Difference between setpoint and our position final double error = elevatorSetpoint - encElevator.pidGet(); //We can be off by 5% final double toleranceWhileGoingUp = MAX_ELEVATOR_COUNTS * 0.05; final double toleranceWhileGoingDown = -MAX_ELEVATOR_COUNTS * 0.05; //Different speeds going up/down final double speedWhileGoingUp = 1.0; final double speedWhileGoingDown = -0.7; //Go up when below setpoint, down when above setpoint if(error > 0 && error > toleranceWhileGoingUp) vicElevator.set(speedWhileGoingUp); else if(error < 0 && error < toleranceWhileGoingDown) vicElevator.set(speedWhileGoingDown); else { vicElevator.set(0.0); return true; } return false; } //Runs at the beginning of disabled period public void disabledInit() { //Disable PIDs pidLeft.disable(); pidRight.disable(); pidGyro.disable(); } //Runs periodically during disabled period public void disabledPeriodic() { //Call our print function with the current mode print("Disabled"); } //Runs continuously during disabled period public void disabledContinuous() { } //Enumeration of autonomous modes class AutonomousState { static final int Driving = 0; static final int Turning = 1; static final int Hanging = 2; static final int Release = 3; static final int Done = 4; static final int Sleep = 5; } //Class that defines the current step in autonomous mode class Step { //Constructors for Step public Step(int Type) { type = Type; } public Step(int Type, double Val) { type = Type; value = Val; } //The type of step public int type = AutonomousState.Done; //Get the value public double get() { return value; } //The amount we want to move by in the step (units depend on the type of step) double value = 0.0; } //Array to hold steps -- changed depending on which autonomous mode we want Step stepList[] = null; //Iterates through each step int stepIndex; //Number of times our setpoint has been reached int gyroCounter; boolean doNothing = ds.getDigitalIn(1); boolean heightOne = ds.getDigitalIn(2); boolean heightTwo = ds.getDigitalIn(3); boolean heightThree = ds.getDigitalIn(4); boolean releaseTube = ds.getDigitalIn(5); boolean hangLeft = ds.getDigitalIn(6); boolean hangMiddle = ds.getDigitalIn(7); boolean hangRIght = ds.getDigitalIn(8); //Runs at the beginning of autonomous period public void autonomousInit() { //Minibot defaults to up minibotVertical.set(Relay.Value.kReverse); minibotHorizontal.set(Relay.Value.kReverse); //Default to slow driving mode if(!PRACTISE_ROBOT) transShiftSingle.set(false); else transShiftDouble.set(DoubleSolenoid.Value.kReverse); //Reset gyro and enable PID on gyro pidGyro.enable(); gyro.reset(); //Enable PID on wheels pidLeft.enable(); pidRight.enable(); //Reset encoders encLeft.reset(); encRight.reset(); //Current step stepIndex = 0; //We havent reached our setpoint gyroCounter = 0; Step posOne[] = { new Step(AutonomousState.Driving, 0.5), new Step(AutonomousState.Hanging), new Step(AutonomousState.Release), new Step(AutonomousState.Done, 0), }; Step posTwo[] = { new Step(AutonomousState.Driving, 0.5), new Step(AutonomousState.Hanging), new Step(AutonomousState.Release), new Step(AutonomousState.Done, 0), }; Step posThree[] = { new Step(AutonomousState.Driving, 0.5), new Step(AutonomousState.Hanging), new Step(AutonomousState.Release), new Step(AutonomousState.Done, 0), }; Step posFour[] = { new Step(AutonomousState.Driving, 0.5), new Step(AutonomousState.Hanging), new Step(AutonomousState.Release), new Step(AutonomousState.Done, 0), }; Step posFive[] = { new Step(AutonomousState.Driving, 0.5), new Step(AutonomousState.Hanging), new Step(AutonomousState.Release), new Step(AutonomousState.Done, 0), }; Step posSix[] = { new Step(AutonomousState.Driving, 0.5), new Step(AutonomousState.Hanging), new Step(AutonomousState.Release), new Step(AutonomousState.Done, 0), }; //Round the analog input int position = 0; double input = ds.getAnalogIn(1); if(input - Math.floor(input) < 0.5) position = (int)Math.floor(input); if(input - Math.floor(input) >= 0.5) position = (int)Math.ceil(input); switch(position) { default: case 0: stepList = posOne; break; case 1: stepList = posTwo; break; case 2: stepList = posThree; break; case 3: stepList = posFour; break; case 4: stepList = posFive; break; case 5: stepList = posSix; break; } if(doNothing) { stepList = new Step[] { new Step(AutonomousState.Done, 0), }; } //Determine the setpoint of the elevator elevatorSetpoint = ElevatorSetpoint.posOne; elevatorSetpoint = heightOne && position != 1 && position != 4 ? ElevatorSetpoint.posOne : elevatorSetpoint; elevatorSetpoint = heightOne && (position == 1 || position == 4) ? ElevatorSetpoint.posTwo : elevatorSetpoint; elevatorSetpoint = heightTwo && position != 1 && position != 4 ? ElevatorSetpoint.posThree : elevatorSetpoint; elevatorSetpoint = heightTwo && (position == 1 || position == 4) ? ElevatorSetpoint.posFour : elevatorSetpoint; elevatorSetpoint = heightThree && position != 1 && position != 4 ? ElevatorSetpoint.posFive : elevatorSetpoint; elevatorSetpoint = heightThree && (position == 1 || position == 4) ? ElevatorSetpoint.posSix : elevatorSetpoint; } //Runs periodically during autonomous period public void autonomousPeriodic() { //Call our print function with the current mode print("Autonomous"); } //Runs continuously during autonomous period public void autonomousContinuous() { //Our current step in our list of steps Step currentStep = stepList[stepIndex]; //The last step we did int lastStepIndex = stepIndex; //If we have a step to do if(currentStep != null) { //Switch the type of step switch(currentStep.type) { //If we want to drive forward case AutonomousState.Driving: //If we have reached our value for this step on the left or right side final boolean leftDone = -encLeft.encoder.get() / COUNTS_PER_METRE >= currentStep.get(); final boolean rightDone = encRight.encoder.get() / COUNTS_PER_METRE >= currentStep.get(); //Drive each side until we reach the value for each side if(!leftDone) pidLeft.setSetpoint(-0.4 * SLOW_MAX_ENCODER_RATE); if(!rightDone) pidRight.setSetpoint(0.4 * SLOW_MAX_ENCODER_RATE); //If the value is reached if(leftDone && rightDone) ++stepIndex; break; //If we want to turn case AutonomousState.Turning: //Disable PIDs for smoother turning if(pidLeft.isEnable() || pidRight.isEnable()) { pidLeft.disable(); pidRight.disable(); } //Set the setpoint for the gyro PID to the step's setpoint pidGyro.setSetpoint(currentStep.get()); //Drive the motors with the output from the gyro PID jagLeft.set(-gyroOutput.get()); jagRight.set(-gyroOutput.get()); //Difference between our position and our setpoint final double delta = currentStep.get() - gyro.pidGet(); //If the gyro is below or above the target angle depending on the direction we are turning if(Math.abs(delta) < GYRO_TOLERANCE) ++gyroCounter; if(gyroCounter >= 100) ++stepIndex; break; //If we want to use the elevator case AutonomousState.Hanging: if(elevatorPID()) ++stepIndex; break; //To release the tube case AutonomousState.Release: gripper.set(releaseTube ? Relay.Value.kForward : Relay.Value.kReverse); ++stepIndex; break; //If we are done our autonomous mode case AutonomousState.Done: break; //Sleep state case AutonomousState.Sleep: double time = currentStep.get(); pidLeft.disable(); pidRight.disable(); while(time > 0) { print("Autonomous"); Timer.delay(1); --time; Watchdog.getInstance().feed(); } pidLeft.enable(); pidLeft.enable(); ++stepIndex; break; } } //If we want to go to the next step if(lastStepIndex != stepIndex) { //Reset everything encLeft.reset(); encRight.reset(); gyro.reset(); //Enable PIDs pidLeft.enable(); pidRight.enable(); //Stop pidLeft.setSetpoint(0.0); pidRight.setSetpoint(0.0); //Reset gyro counter to 0 gyroCounter = 0; } } class ElbowState { static final int Horizontal = 0; static final int Middle = 1; static final int Vertical = 2; } class ButtonPress { boolean value = false; boolean lastValue = false; public void feed(boolean val) { if(!lastValue && val) value = true; else value = false; lastValue = val; } public boolean get() { return value; } } //Start time for teleoperated mode double teleopStartTime; //Start time for when the minibot release is triggered double minibotReleaseTime; //Releasing minibot boolean releaseMinibot; //State of elbow int elbowState; ButtonPress elbowUp = new ButtonPress(); ButtonPress elbowDown = new ButtonPress(); //Runs at the beginning of teleoperated period public void teleopInit() { //Initialize variables teleopStartTime = Timer.getFPGATimestamp(); minibotReleaseTime = 0.0; releaseMinibot = false; //Minibot defaults to up minibotVertical.set(Relay.Value.kReverse); minibotHorizontal.set(Relay.Value.kReverse); } //Runs periodically during teleoperated period public void teleopPeriodic() { //Call our print function with the current mode print("Teleoperated"); } //Runs continuously during teleoperated period public void teleopContinuous() { //Don't allow the gyro to be more or less than 360 degrees if(gyro.pidGet() < -360 || gyro.pidGet() > 360) gyro.reset(); //The elevator setpoint based on the corresponding button elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_GROUND) ? ElevatorSetpoint.ground : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_ONE) ? ElevatorSetpoint.posOne : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_TWO) ? ElevatorSetpoint.posTwo : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_THREE) ? ElevatorSetpoint.posThree : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_FOUR) ? ElevatorSetpoint.posFour : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_FIVE) ? ElevatorSetpoint.posFive : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_SIX) ? ElevatorSetpoint.posSix : elevatorSetpoint; elevatorSetpoint = stickOperator.getRawButton(Operator.ELEVATOR_STATE_FEED) ? ElevatorSetpoint.feed : elevatorSetpoint; //Feed the toggle on the manual/automated elevator control manualElevatorToggle.feed(stickOperator.getRawButton(Operator.ELEVATOR_MANUAL_TOGGLE)); //Manual or automated elevator control if(manualElevatorToggle.get()) { double axis = -stickOperator.getAxis(Joystick.AxisType.kY); //If we are below 0 then dont allow the elevator to go down if(encElevator.pidGet() <= 0) axis = Math.max(0, axis); if(encElevator.pidGet() >= MAX_ELEVATOR_COUNTS) axis = Math.min(0, axis); vicElevator.set(axis); } else { elevatorPID(); } //Feed the toggle on the transmission shifter button transToggle.feed(stickDriver.getRawButton(Driver.TRANS_TOGGLE)); //Set the transmission shifter to open or closed based on the state of the toggle if(!PRACTISE_ROBOT) transShiftSingle.set(transToggle.get()); else transShiftDouble.set(transToggle.get() ? DoubleSolenoid.Value.kForward : DoubleSolenoid.Value.kReverse); //Determine the input range to use (max encoder rate) to use depending on the transmission state we are in double maxEncoderRate = transToggle.get() ? FAST_MAX_ENCODER_RATE : SLOW_MAX_ENCODER_RATE; pidLeft.setInputRange(-maxEncoderRate, maxEncoderRate); pidRight.setInputRange(-maxEncoderRate, maxEncoderRate); //Feed the toggle on the gripper button gripperToggle.feed(stickOperator.getRawButton(Operator.GRIPPER_TOGGLE)); //Set the gripper to open or closed based on the state of the toggle gripper.set(gripperToggle.get() ? Relay.Value.kForward : Relay.Value.kReverse); //Feed the buttons elbowUp.feed(stickOperator.getRawButton(Operator.ELBOW_UP)); elbowDown.feed(stickOperator.getRawButton(Operator.ELBOW_DOWN)); if(elbowUp.get()) elbowState += elbowState < ElbowState.Vertical ? 1 : 0; if(elbowDown.get()) elbowState -= elbowState > ElbowState.Horizontal ? 1 : 0; elbowOne.set(elbowState == ElbowState.Horizontal ? Relay.Value.kForward : Relay.Value.kReverse); elbowTwo.set(elbowState <= ElbowState.Middle ? Relay.Value.kForward : Relay.Value.kReverse); //Feed the toggle on the arcade/tank drive button arcadeToggle.feed(stickDriver.getRawButton(Driver.ARCADE_TOGGLE)); //Drive arcade or tank based on the state of the toggle if(arcadeToggle.get()) { //If PID is enabled if(pidLeft.isEnable() || pidRight.isEnable()) { //Disable PID pidLeft.disable(); pidRight.disable(); } //Move axis is first y-axis and rotate axis is second x-axis //Let the robotdrive class calculate arcade drive for us //robotDrive.arcadeDrive(stickDriver, Driver.Y_AXIS_LEFT, stickDriver, Driver.X_AXIS_RIGHT); jagLeft.set(stickDriver.getRawAxis(Driver.Y_AXIS_LEFT)); jagRight.set(stickDriver.getRawAxis(Driver.Y_AXIS_RIGHT)); } else if (!arcadeToggle.get()) { //If PID is disabled if(!pidLeft.isEnable() || !pidRight.isEnable()) { //Enable PID pidLeft.enable(); pidRight.enable(); } //Left axis double leftAxis = stickDriver.getRawAxis(Driver.Y_AXIS_LEFT); //Any value less than 0.2 is set to 0.0 to create a dead zone leftAxis = Math.abs(leftAxis) < 0.2 ? 0.0 : leftAxis; //Right axis double rightAxis = stickDriver.getRawAxis(Driver.Y_AXIS_RIGHT); //Any value less than 0.2 is set to 0.0 to create a dead zone rightAxis = Math.abs(rightAxis) < 0.2 ? 0.0 : rightAxis; //Set the setpoint as a percentage of the maximum encoder rate pidLeft.setSetpoint(leftAxis * maxEncoderRate); pidRight.setSetpoint(-rightAxis * maxEncoderRate); } //If there are 10 seconds left if(Timer.getFPGATimestamp() - teleopStartTime >= MINIBOT_RELEASE_TIME) { //If we triggered the release, set the release to true, otherwise just leave it //Creates a one-way toggle releaseMinibot = stickOperator.getRawButton(Operator.MINIBOT_RELEASE_ONE) && stickOperator.getRawButton(Operator.MINIBOT_RELEASE_TWO) ? true : releaseMinibot; //If we want to release if(releaseMinibot) { //Set the vertical relay to released minibotVertical.set(Relay.Value.kForward); //If the release time is 0 (we haven't set the release time yet) then set the release time //Allows us to set the release time only once minibotReleaseTime = minibotReleaseTime == 0.0 ? Timer.getFPGATimestamp() : minibotReleaseTime; //If it's been at least 2 seconds since the release was triggered if(Timer.getFPGATimestamp() - minibotReleaseTime >= MINIBOT_HORIZONTAL_DELAY) { //Set the horizontal relay to released minibotHorizontal.set(Relay.Value.kForward); } } } } }
package org.apache.commons.dbcp; import junit.framework.*; import java.sql.*; import org.apache.commons.pool.*; import org.apache.commons.pool.impl.*; /** * * @author Rodney Waldhoff * @author Sean C. Sullivan * * @version $Id: TestManual.java,v 1.11 2002/11/07 21:06:57 rwaldhoff Exp $ */ public class TestManual extends TestCase { public TestManual(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestManual.class); } public static void main(String args[]) { String[] testCaseName = { TestManual.class.getName() }; junit.textui.TestRunner.main(testCaseName); } public void setUp() throws Exception { GenericObjectPool pool = new GenericObjectPool(null, 10, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, 2000L, 10, true, true, 10000L, 5, 5000L, true); DriverConnectionFactory cf = new DriverConnectionFactory(new TesterDriver(),"jdbc:apache:commons:testdriver",null); GenericKeyedObjectPoolFactory opf = new GenericKeyedObjectPoolFactory(null, 10, GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK, 2000L, 10, true, true, 10000L, 5, 5000L, true); PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, pool, opf, "SELECT COUNT(*) FROM DUAL", false, true); PoolingDriver driver = new PoolingDriver(); driver.registerPool("test",pool); DriverManager.registerDriver(driver); } public void testIsClosed() throws Exception { for(int i=0;i<10;i++) { Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(null != conn); assertTrue(!conn.isClosed()); PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); conn.close(); assertTrue(conn.isClosed()); } } public void testCantCloseConnectionTwice() throws Exception { for(int i=0;i<2;i++) { // loop to show we *can* close again once we've borrowed it from the pool again Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(null != conn); assertTrue(!conn.isClosed()); conn.close(); assertTrue(conn.isClosed()); try { conn.close(); fail("Expected SQLException on second attempt to close"); } catch(SQLException e) { // expected } assertTrue(conn.isClosed()); } } public void testCantCloseStatementTwice() throws Exception { Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(null != conn); assertTrue(!conn.isClosed()); for(int i=0;i<2;i++) { // loop to show we *can* close again once we've borrowed it from the pool again PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); stmt.close(); try { stmt.close(); fail("Expected SQLException on second attempt to close"); } catch(SQLException e) { // expected } } conn.close(); } public void testSimple() throws Exception { Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(null != conn); PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); conn.close(); } public void testSimple2() throws Exception { Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(null != conn); { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } conn.close(); try { conn.createStatement(); fail("Can't use closed connections"); } catch(SQLException e) { ; // expected } conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(null != conn); { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } { PreparedStatement stmt = conn.prepareStatement("select * from dual"); assertTrue(null != stmt); ResultSet rset = stmt.executeQuery(); assertTrue(null != rset); assertTrue(rset.next()); rset.close(); stmt.close(); } conn.close(); conn = null; } public void testPooling() throws Exception { Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(conn != null); Connection conn2 = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue(conn2 != null); assertTrue(conn != conn2); conn2.close(); conn.close(); Connection conn3 = DriverManager.getConnection("jdbc:apache:commons:dbcp:test"); assertTrue( conn3 == conn || conn3 == conn2 ); } public void testAutoCommitBehavior() throws Exception { final String strDriverUrl = "jdbc:apache:commons:dbcp:test"; Connection conn = DriverManager.getConnection(strDriverUrl); assertTrue(conn != null); assertTrue(conn.getAutoCommit()); conn.setAutoCommit(false); conn.close(); Connection conn2 = DriverManager.getConnection(strDriverUrl); assertTrue( conn2.getAutoCommit() ); Connection conn3 = DriverManager.getConnection(strDriverUrl); assertTrue( conn3.getAutoCommit() ); conn2.close(); conn3.close(); } public void testReportedBug12400() throws Exception { ObjectPool connectionPool = new GenericObjectPool( null, 70, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, 60000, 10); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( "jdbc:apache:commons:testdriver", "username", "password"); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, connectionPool, null, null, false, true); PoolingDriver driver = new PoolingDriver(); driver.registerPool("neusoftim",connectionPool); Connection[] conn = new Connection[25]; for(int i=0;i<25;i++) { conn[i] = DriverManager.getConnection("jdbc:apache:commons:dbcp:neusoftim"); for(int j=0;j<i;j++) { assertTrue(conn[j] != conn[i]); assertTrue(!conn[j].equals(conn[i])); } } for(int i=0;i<25;i++) { conn[i].close(); } } }
package testsuite.manager; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.Vector; import org.xml.sax.SAXException; import testsuite.group.Group; import testsuite.result.AbstractResult; import testsuite.result.ResultsCollections; import testsuite.test.FunctionalTest; /** * @author Alexandre di Costanzo * */ public abstract class FunctionalTestManager extends AbstractManager { private int runs = 0; private int errors = 0; public FunctionalTestManager() { super("FunctionalTestManager with no name", "FunctionalTestManager with no description"); } /** * @param name * @param description */ public FunctionalTestManager(String name, String description) { super(name, description); } public FunctionalTestManager(File xmlDescriptor) throws IOException, SAXException { super(xmlDescriptor); this.loadAttributes(getProperties()); } /** * @see testsuite.manager.AbstractManager#execute() */ public void execute(boolean useAttributesFile) { if (logger.isInfoEnabled()) { logger.info("Starting ..."); } ResultsCollections results = getResults(); Vector listOfFailed = new Vector(); if (useAttributesFile) { try { loadAttributes(); } catch (IOException e1) { if (logger.isInfoEnabled()) { logger.info(e1); } } } results.add(AbstractResult.IMP_MSG, "Starting ..."); try { initManager(); } catch (Exception e) { logger.fatal("Can't init the manager", e); results.add(AbstractResult.ERROR, "Can't init the manager", e); return; } if (logger.isInfoEnabled()) { logger.info("Init Manager with success"); } results.add(AbstractResult.IMP_MSG, "Init Manager with success"); Iterator itGroup = iterator(); while (itGroup.hasNext()) { Group group = (Group) itGroup.next(); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Cannot initialize group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Cannot initialize group of tests: " + group.getName(), e); continue; } for (int i = 0; i < getNbRuns(); i++) { Iterator itTest = group.iterator(); while (itTest.hasNext()) { FunctionalTest test = (FunctionalTest) itTest.next(); if (logger.isInfoEnabled()) { logger.info(" test.getName()); } AbstractResult result = test.runTest(); if (result != null) { resultsGroup.add(result); if (test.isFailed()) { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [FAILED]"); } listOfFailed.add(test.getName()); this.errors++; } else { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [SUCCESS]"); } this.runs++; } } } } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Cannot end group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Cannot end group of tests: " + group.getName(), e); continue; } results.addAll(resultsGroup); } if (this.interLinkedGroups != null) { // runs interlinked test Iterator itInterGroup = this.interLinkedGroups.iterator(); while (itInterGroup.hasNext()) { Group group = (Group) itInterGroup.next(); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Cannot initialize group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Cannot initialize group of tests: " + group.getName(), e); continue; } for (int i = 0; i < getNbRuns(); i++) { Iterator itTest = group.iterator(); while (itTest.hasNext()) { FunctionalTest test = (FunctionalTest) itTest.next(); AbstractResult result = test.runTestCascading(); resultsGroup.add(result); if (test.isFailed()) { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [FAILED]"); } listOfFailed.add(test.getName()); this.errors++; } else { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [SUCCESS]"); } this.runs++; } } } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group of tests: " + group.getName(), e); continue; } results.addAll(resultsGroup); this.add(group); } } // end Manager try { endManager(); } catch (Exception e) { logger.fatal("Can't ending the manager", e); results.add(AbstractResult.ERROR, "Can't ending the manager", e); return; } results.add(AbstractResult.IMP_MSG, "... Finish"); if (logger.isInfoEnabled()) { logger.info("... Finish"); logger.info(">>> Succeeded tests: " + this.runs + " / " + (this.runs + this.errors)); } if (this.errors > 0) { logger.fatal(" logger.fatal(">>> FAILED TESTS: "); Iterator it = listOfFailed.iterator(); while (it.hasNext()) { logger.fatal("\t" + it.next()); } logger.fatal(" } // Show Results this.showResult(); } private void execCascadingTests(ResultsCollections results, FunctionalTest test) { FunctionalTest[] tests = test.getTests(); int length = (tests != null) ? tests.length : 0; for (int i = 0; i < length; i++) execCascadingTests(results, tests[i]); results.add(test.runTestCascading()); if (test.isFailed()) { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [FAILED]"); } this.errors++; } else { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [SUCCESS]"); } this.runs++; } } public void execute(Group group, FunctionalTest lastestTest, boolean useAttributesFile) { if (logger.isInfoEnabled()) { logger.info("Starting with interlinked Tests ..."); } ResultsCollections results = getResults(); if (useAttributesFile) { try { loadAttributes(); } catch (IOException e1) { if (logger.isInfoEnabled()) { logger.info(e1); } } } results.add(AbstractResult.IMP_MSG, "Starting with interlinked Tests ..."); try { initManager(); } catch (Exception e) { logger.fatal("Can't init the manager", e); results.add(AbstractResult.ERROR, "Can't init the manager", e); return; } if (logger.isInfoEnabled()) { logger.info("Init Manager with success"); } results.add(AbstractResult.IMP_MSG, "Init Manager with success"); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Can't init group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't init group of tests: " + group.getName(), e); } for (int i = 0; i < getNbRuns(); i++) { execCascadingTests(resultsGroup, lastestTest); } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group of tests: " + group.getName(), e); } results.addAll(resultsGroup); try { endManager(); } catch (Exception e) { logger.fatal("Can't ending the manager", e); results.add(AbstractResult.ERROR, "Can't ending the manager", e); return; } results.add(AbstractResult.IMP_MSG, "... Finish"); results.add(AbstractResult.IMP_MSG, "... Finish"); if (logger.isInfoEnabled()) { logger.info("... Finish"); logger.info(">>> Succeeded tests: " + this.runs + " / " + (this.runs + this.errors)); } if (this.errors > 0) { logger.fatal(">>> Failed tests: " + this.errors); } } public void executeInterLinkedTest() { if (logger.isInfoEnabled()) { logger.info("Starting ..."); } ResultsCollections results = getResults(); Vector listOfFailed = new Vector(); results.add(AbstractResult.IMP_MSG, "Starting ..."); try { initManager(); } catch (Exception e) { logger.fatal("Can't init the manager", e); results.add(AbstractResult.ERROR, "Can't init the manager", e); return; } if (logger.isInfoEnabled()) { logger.info("Init Manager with success"); } results.add(AbstractResult.IMP_MSG, "Init Manager with success"); Iterator itGroup = this.interLinkedGroups.iterator(); while (itGroup.hasNext()) { Group group = (Group) itGroup.next(); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Can't init group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't init group of tests: " + group.getName(), e); continue; } for (int i = 0; i < getNbRuns(); i++) { Iterator itTest = group.iterator(); while (itTest.hasNext()) { FunctionalTest test = (FunctionalTest) itTest.next(); AbstractResult result = test.runTestCascading(); resultsGroup.add(result); if (test.isFailed()) { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [FAILED]"); } listOfFailed.add(test.getName()); errors++; } else { if (logger.isDebugEnabled()) { logger.debug("Result from test " + test.getName() + " is [SUCCESS]"); } runs++; } } } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group of tests: " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group of tests: " + group.getName(), e); continue; } results.addAll(resultsGroup); } try { endManager(); } catch (Exception e) { logger.fatal("Can't ending the manager", e); results.add(AbstractResult.ERROR, "Can't ending the manager", e); return; } results.add(AbstractResult.IMP_MSG, "... Finish"); results.add(AbstractResult.IMP_MSG, "... Finish"); if (logger.isInfoEnabled()) { logger.info("... Finish"); logger.info(">>> Succeeded tests: " + this.runs + " / " + (this.runs + this.errors)); } if (this.errors > 0) { logger.fatal(" logger.fatal(">>> FAILED TESTS: "); Iterator it = listOfFailed.iterator(); while (it.hasNext()) { logger.fatal("\t" + it.next()); } logger.fatal(" } this.showResult(); } public void addInterLinkedGroup(Group group) { this.interLinkedGroups.add(group); } /** * @return */ public ArrayList getInterLinkedGroups() { return this.interLinkedGroups; } /** * @param list */ public void setInterLinkedGroups(ArrayList list) { this.interLinkedGroups = list; } /** * @see testsuite.manager.AbstractManager#execute() */ public void execute() { super.execute(); } }
package railo.runtime.orm.hibernate; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import railo.commons.lang.StringUtil; import railo.runtime.db.DataSource; import railo.runtime.type.KeyImpl; import railo.runtime.type.List; import railo.runtime.type.Struct; import railo.runtime.type.StructImpl; public class Dialect { private static Struct dialects=new StructImpl(); private static Struct dialects2=new StructImpl(); static { // if this list change, also update list in web-cfmtaglibrary_1 for "application-ormsettings-dialect" dialects.setEL("Cache71", org.hibernate.dialect.Cache71Dialect.class.getName()); dialects.setEL("Cach 2007.1", org.hibernate.dialect.Cache71Dialect.class.getName()); dialects.setEL("Cache 2007.1", org.hibernate.dialect.Cache71Dialect.class.getName()); dialects.setEL("DataDirectOracle9", org.hibernate.dialect.DataDirectOracle9Dialect.class.getName()); dialects.setEL("DB2390", org.hibernate.dialect.DB2390Dialect.class.getName()); dialects.setEL("DB2/390", org.hibernate.dialect.DB2390Dialect.class.getName()); dialects.setEL("DB2OS390", org.hibernate.dialect.DB2390Dialect.class.getName()); dialects.setEL("DB2400", org.hibernate.dialect.DB2400Dialect.class.getName()); dialects.setEL("DB2/400", org.hibernate.dialect.DB2400Dialect.class.getName()); dialects.setEL("DB2AS400", org.hibernate.dialect.DB2400Dialect.class.getName()); dialects.setEL("DB2", org.hibernate.dialect.DB2Dialect.class.getName()); dialects.setEL("com.ddtek.jdbc.db2.DB2Driver", org.hibernate.dialect.DB2Dialect.class.getName()); dialects.setEL("Derby", org.hibernate.dialect.DerbyDialect.class.getName()); dialects.setEL("Firebird", org.hibernate.dialect.FirebirdDialect.class.getName()); dialects.setEL("org.firebirdsql.jdbc.FBDriver", org.hibernate.dialect.FirebirdDialect.class.getName()); dialects.setEL("FrontBase", org.hibernate.dialect.FrontBaseDialect.class.getName()); dialects.setEL("H2", org.hibernate.dialect.H2Dialect.class.getName()); dialects.setEL("org.h2.Driver", org.hibernate.dialect.H2Dialect.class.getName()); dialects.setEL("H2DB", org.hibernate.dialect.H2Dialect.class.getName()); dialects.setEL("HSQL", org.hibernate.dialect.HSQLDialect.class.getName()); dialects.setEL("HSQLDB", org.hibernate.dialect.HSQLDialect.class.getName()); dialects.setEL("org.hsqldb.jdbcDriver", org.hibernate.dialect.HSQLDialect.class.getName()); dialects.setEL("Informix", org.hibernate.dialect.InformixDialect.class.getName()); dialects.setEL("Ingres", org.hibernate.dialect.IngresDialect.class.getName()); dialects.setEL("Interbase", org.hibernate.dialect.InterbaseDialect.class.getName()); dialects.setEL("JDataStore", org.hibernate.dialect.JDataStoreDialect.class.getName()); dialects.setEL("Mckoi", org.hibernate.dialect.MckoiDialect.class.getName()); dialects.setEL("MckoiSQL", org.hibernate.dialect.MckoiDialect.class.getName()); dialects.setEL("Mimer", org.hibernate.dialect.MimerSQLDialect.class.getName()); dialects.setEL("MimerSQL", org.hibernate.dialect.MimerSQLDialect.class.getName()); dialects.setEL("MySQL5", org.hibernate.dialect.MySQL5Dialect.class.getName()); dialects.setEL("MySQL5InnoDB", org.hibernate.dialect.MySQL5InnoDBDialect.class.getName()); dialects.setEL("MySQL5/InnoDB", org.hibernate.dialect.MySQL5InnoDBDialect.class.getName()); dialects.setEL("MySQL", org.hibernate.dialect.MySQLDialect.class.getName()); dialects.setEL("org.gjt.mm.mysql.Driver", org.hibernate.dialect.MySQLDialect.class.getName()); dialects.setEL("MySQLInnoDB", org.hibernate.dialect.MySQLInnoDBDialect.class.getName()); dialects.setEL("MySQL/InnoDB", org.hibernate.dialect.MySQLInnoDBDialect.class.getName()); dialects.setEL("MySQLwithInnoDB", org.hibernate.dialect.MySQLInnoDBDialect.class.getName()); dialects.setEL("MySQLMyISAM", org.hibernate.dialect.MySQLMyISAMDialect.class.getName()); dialects.setEL("MySQL/MyISAM", org.hibernate.dialect.MySQLMyISAMDialect.class.getName()); dialects.setEL("MySQLwithMyISAM", org.hibernate.dialect.MySQLMyISAMDialect.class.getName()); dialects.setEL("Oracle10g", org.hibernate.dialect.Oracle10gDialect.class.getName()); dialects.setEL("Oracle8i", org.hibernate.dialect.Oracle8iDialect.class.getName()); dialects.setEL("Oracle9", org.hibernate.dialect.Oracle9Dialect.class.getName()); dialects.setEL("Oracle9i", org.hibernate.dialect.Oracle9iDialect.class.getName()); dialects.setEL("Oracle", org.hibernate.dialect.OracleDialect.class.getName()); dialects.setEL("oracle.jdbc.driver.OracleDriver", org.hibernate.dialect.OracleDialect.class.getName()); dialects.setEL("Pointbase", org.hibernate.dialect.PointbaseDialect.class.getName()); dialects.setEL("PostgresPlus", org.hibernate.dialect.PostgresPlusDialect.class.getName()); dialects.setEL("PostgreSQL", org.hibernate.dialect.PostgreSQLDialect.class.getName()); dialects.setEL("org.postgresql.Driver", org.hibernate.dialect.PostgreSQLDialect.class.getName()); dialects.setEL("Progress", org.hibernate.dialect.ProgressDialect.class.getName()); dialects.setEL("SAPDB", org.hibernate.dialect.SAPDBDialect.class.getName()); dialects.setEL("SQLServer", org.hibernate.dialect.SQLServerDialect.class.getName()); dialects.setEL("MSSQL", org.hibernate.dialect.SQLServerDialect.class.getName()); dialects.setEL("MicrosoftSQLServer", org.hibernate.dialect.SQLServerDialect.class.getName()); dialects.setEL("com.microsoft.jdbc.sqlserver.SQLServerDriver", org.hibernate.dialect.SQLServerDialect.class.getName()); dialects.setEL("Sybase11", org.hibernate.dialect.Sybase11Dialect.class.getName()); dialects.setEL("SybaseAnywhere", org.hibernate.dialect.SybaseAnywhereDialect.class.getName()); dialects.setEL("SybaseASE15", org.hibernate.dialect.SybaseASE15Dialect.class.getName()); dialects.setEL("Sybase", org.hibernate.dialect.SybaseDialect.class.getName()); Iterator it = dialects.entrySet().iterator(); String value; Map.Entry entry; while(it.hasNext()){ entry=(Entry) it.next(); value=(String) entry.getValue(); dialects2.setEL(KeyImpl.init(value), value); dialects2.setEL(KeyImpl.init(List.last(value, ".")), value); } } /** * return a SQL dialect that match the given Name * @param name * @return */ public static String getDialect(DataSource ds){ String name=ds.getClazz().getName(); if("net.sourceforge.jtds.jdbc.Driver".equals(name)){ String dsn=ds.getDsnTranslated(); if(StringUtil.indexOfIgnoreCase(dsn, "sybase")!=-1) return getDialect("SQLServer"); } return getDialect(name); } public static String getDialect(String name){ if(StringUtil.isEmpty(name))return null; String dialect= (String) dialects.get(KeyImpl.init(name), null); if(dialect==null)dialect= (String) dialects2.get(KeyImpl.init(name), null); return dialect; } public static String[] listDialectNames(){ return dialects.keysAsString(); } /*public static void main(String[] args) { String[] arr = listDialectNames(); Arrays.sort(arr); print.o(List.arrayToList(arr, ", ")); }*/ }
package com.yahoo.squidb.data; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.text.TextUtils; import android.util.Log; import com.yahoo.squidb.Beta; import com.yahoo.squidb.data.adapter.DefaultOpenHelperWrapper; import com.yahoo.squidb.data.adapter.SQLExceptionWrapper; import com.yahoo.squidb.data.adapter.SQLiteDatabaseWrapper; import com.yahoo.squidb.data.adapter.SQLiteOpenHelperWrapper; import com.yahoo.squidb.data.adapter.SquidTransactionListener; import com.yahoo.squidb.sql.CompiledStatement; import com.yahoo.squidb.sql.Criterion; import com.yahoo.squidb.sql.Delete; import com.yahoo.squidb.sql.Field; import com.yahoo.squidb.sql.Index; import com.yahoo.squidb.sql.Insert; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Property.PropertyVisitor; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.sql.SqlStatement; import com.yahoo.squidb.sql.SqlTable; import com.yahoo.squidb.sql.Table; import com.yahoo.squidb.sql.TableStatement; import com.yahoo.squidb.sql.Update; import com.yahoo.squidb.sql.View; import com.yahoo.squidb.sql.VirtualTable; import com.yahoo.squidb.utility.VersionCode; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * SquidDatabase is a database abstraction which wraps a SQLite database. * <p> * Use this class to control the lifecycle of your database where you would normally use a * {@link android.database.sqlite.SQLiteOpenHelper}. The first call to a read or write operation will open the database. * You can close it again using {@link #close()}. * <p> * SquidDatabase provides typesafe reads and writes using model classes. For example, rather than using rawQuery to * get a Cursor, use {@link #query(Class, Query)}. * <p> * By convention, methods beginning with "try" (e.g. {@link #tryCreateTable(Table) tryCreateTable}) return true * if the operation succeeded and false if it failed for any reason. If it fails, there will also be a call to * {@link #onError(String, Throwable) onError}. * <p> * Methods that use String arrays for where clause arguments ({@link #update(String, ContentValues, String, String[]) * update}, {@link #updateWithOnConflict(String, ContentValues, String, String[], int) updateWithOnConflict}, and * {@link #delete(String, String, String[]) delete}) are wrappers around Android's {@link SQLiteDatabase} methods. * However, Android's default behavior of binding all arguments as strings can have unexpected bugs, particularly when * working with SQLite functions. For example: * * <pre> * select * from t where _id = '1'; // Returns the first row * select * from t where abs(_id) = '1'; // Always returns empty set * </pre> * * For this reason, these methods are protected rather than public. You can choose to expose them in your database * subclass if you wish, but we recommend that you instead use the typesafe, public, model-bases methods, such as * {@link #update(Criterion, TableModel)}, {@link #updateWithOnConflict(Criterion, TableModel, * TableStatement.ConflictAlgorithm)}, {@link #delete(Class, long)}, and {@link #deleteWhere(Class, Criterion)}. * <p> * As a convenience, when calling the {@link #query(Class, Query) query} and {@link #fetchByQuery(Class, Query) * fetchByQuery} methods, if the <code>query</code> argument does not have a FROM clause, the table or view to select * from will be inferred from the provided <code>modelClass</code> argument (if possible). This allows for invocations * where {@link Query#from(com.yahoo.squidb.sql.SqlTable) Query.from} is never explicitly called: * * <pre> * SquidCursor&lt;Person&gt; cursor = * db.query(Person.class, Query.select().orderBy(Person.NAME.asc())); * </pre> * * By convention, the <code>fetch...</code> methods return a single model instance corresponding to the first record * found, or null if no records are found for that particular form of fetch. */ public abstract class SquidDatabase { /** * @return the database name */ public abstract String getName(); /** * @return the database version */ protected abstract int getVersion(); /** * @return all {@link Table Tables} and {@link VirtualTable VirtualTables} and that should be created when the * database is created */ protected abstract Table[] getTables(); /** * @return all {@link View Views} that should be created when the database is created. Views will be created after * all Tables have been created. */ protected View[] getViews() { return null; } /** * @return all {@link Index Indexes} that should be created when the database is created. Indexes will be created * after Tables and Views have been created. */ protected Index[] getIndexes() { return null; } /** * Called after the database has been created. At this time, all {@link Table Tables} and {@link * VirtualTable VirtualTables} returned from {@link #getTables()}, all {@link View Views} from {@link #getViews()}, * and all {@link Index Indexes} from {@link #getIndexes()} will have been created. Any additional database setup * should be done here, e.g. creating other views, indexes, triggers, or inserting data. * * @param db the {@link SQLiteDatabaseWrapper} being created */ protected void onTablesCreated(SQLiteDatabaseWrapper db) { } /** * Called when the database should be upgraded from one version to another. The most common pattern to use is a * fall-through switch statement with calls to the tryAdd/Create/Drop methods: * * <pre> * switch(oldVersion) { * case 1: * tryAddColumn(MyModel.NEW_COL_1); * case 2: * tryCreateTable(MyNewModel.TABLE); * </pre> * * @param db the {@link SQLiteDatabaseWrapper} being upgraded * @param oldVersion the current database version * @param newVersion the database version being upgraded to * @return true if the upgrade was handled successfully, false otherwise */ protected abstract boolean onUpgrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion); /** * Called when the database should be downgraded from one version to another * * @param db the {@link SQLiteDatabaseWrapper} being upgraded * @param oldVersion the current database version * @param newVersion the database version being downgraded to * @return true if the downgrade was handled successfully, false otherwise. The default implementation returns true. */ protected boolean onDowngrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { return true; } /** * Called to notify of a failure in {@link #onUpgrade(SQLiteDatabaseWrapper, int, int) onUpgrade()} or * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int) onDowngrade()}, either because it returned false or because * an unexpected exception occurred. Subclasses can take drastic corrective action here, e.g. recreating the * database with {@link #recreate()}. The default implementation throws an exception. * <p> * Note that taking no action here leaves the database in whatever state it was in when the error occurred, which * can result in unexpected errors if callers are allowed to invoke further operations on the database. * * @param failure details about the upgrade or downgrade that failed */ protected void onMigrationFailed(MigrationFailedException failure) { throw failure; } /** * Called when the database connection is being configured, to enable features such as write-ahead logging or * foreign key support. * * This method may be called at different points in the database lifecycle depending on the environment. When using * a custom SQLite build with the squidb-sqlite-bindings project, or when running on Android API >= 16, it is * called before {@link #onTablesCreated(SQLiteDatabaseWrapper) onTablesCreated}, * {@link #onUpgrade(SQLiteDatabaseWrapper, int, int) onUpgrade}, * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int) onDowngrade}, * and {@link #onOpen(SQLiteDatabaseWrapper) onOpen}. If it is running on stock Android SQLite and API < 16, it * is called immediately before onOpen but after the other callbacks. The discrepancy is because onConfigure was * only introduced as a callback in API 16, but the ordering should not matter much for most use cases. * <p> * This method should only call methods that configure the parameters of the database connection, such as * {@link SQLiteDatabaseWrapper#enableWriteAheadLogging}, {@link SQLiteDatabaseWrapper#setForeignKeyConstraintsEnabled}, * {@link SQLiteDatabaseWrapper#setLocale}, {@link SQLiteDatabaseWrapper#setMaximumSize}, or executing PRAGMA statements. * * @param db the {@link SQLiteDatabaseWrapper} being configured */ protected void onConfigure(SQLiteDatabaseWrapper db) { } /** * Called when the database has been opened. This method is called after the database connection has been * configured and after the database schema has been created, upgraded, or downgraded as necessary. * * @param db the {@link SQLiteDatabaseWrapper} being opened */ protected void onOpen(SQLiteDatabaseWrapper db) { } /** * Called when an error occurs. This is primarily for clients to log notable errors, not for taking corrective * action on them. The default implementation prints a warning log. * * @param message an error message * @param error the error that was encountered */ protected void onError(String message, Throwable error) { Log.w(getClass().getSimpleName(), message, error); } private static final int STRING_BUILDER_INITIAL_CAPACITY = 128; private final Context context; private SquidDatabase attachedTo = null; private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); /** * SQLiteOpenHelperWrapper that takes care of database operations */ private SQLiteOpenHelperWrapper helper = null; /** * Internal pointer to open database. Hides the fact that there is a database and a wrapper by making a single * monolithic interface */ private SQLiteDatabaseWrapper database = null; /** * Cached version code */ private VersionCode sqliteVersion = null; /** * Map of class objects to corresponding tables */ private Map<Class<? extends AbstractModel>, SqlTable<?>> tableMap; private boolean isInMigration; /** * Create a new SquidDatabase * * @param context the Context, must not be null */ public SquidDatabase(Context context) { if (context == null) { throw new NullPointerException("Null context creating SquidDatabase"); } this.context = context.getApplicationContext(); initializeTableMap(); } private void initializeTableMap() { tableMap = new HashMap<Class<? extends AbstractModel>, SqlTable<?>>(); registerTableModels(getTables()); registerTableModels(getViews()); } private <T extends SqlTable<?>> void registerTableModels(T[] tables) { if (tables != null) { for (SqlTable<?> table : tables) { if (table.getModelClass() != null && !tableMap.containsKey(table.getModelClass())) { tableMap.put(table.getModelClass(), table); } } } } /** * @return the path to the underlying database file. */ public String getDatabasePath() { return context.getDatabasePath(getName()).getAbsolutePath(); } /** * Return the {@link SqlTable} corresponding to the specified model type * * @param modelClass the model class * @return the corresponding data source for the model. May be a table, view, or subquery * @throws UnsupportedOperationException if the model class is unknown to this database */ protected final SqlTable<?> getSqlTable(Class<? extends AbstractModel> modelClass) { Class<?> type = modelClass; SqlTable<?> table; //noinspection SuspiciousMethodCalls while ((table = tableMap.get(type)) == null && type != AbstractModel.class && type != Object.class) { type = type.getSuperclass(); } if (table != null) { return table; } throw new UnsupportedOperationException("Unknown model class " + modelClass); } /** * Return the {@link Table} corresponding to the specified TableModel class * * @param modelClass the model class * @return the corresponding table for the model * @throws UnsupportedOperationException if the model class is unknown to this database */ protected final Table getTable(Class<? extends TableModel> modelClass) { return (Table) getSqlTable(modelClass); } /** * Gets the underlying SQLiteDatabaseWrapper instance. Most users should not need to call this. If you call this * from your AbstractDatabase subclass with the intention of executing SQL, you should wrap the calls with a lock, * probably the non-exclusive one: * * <pre> * public void execSql(String sql) { * acquireNonExclusiveLock(); * try { * getDatabase().execSQL(sql); * } finally { * releaseNonExclusiveLock(); * } * } * </pre> * * You only need to acquire the exclusive lock if you truly need exclusive access to the database connection. * * @return the underlying {@link SQLiteDatabaseWrapper}, which will be opened if it is not yet opened * @see #acquireExclusiveLock() * @see #acquireNonExclusiveLock() */ protected synchronized final SQLiteDatabaseWrapper getDatabase() { // If we get here, we should already have the non-exclusive lock if (database == null) { // Open the DB for writing if (helper == null) { helper = getOpenHelper(context, getName(), new OpenHelperDelegate(), getVersion()); } boolean performRecreate = false; try { setDatabase(helper.openForWriting()); } catch (RecreateDuringMigrationException recreate) { performRecreate = true; } catch (MigrationFailedException fail) { onError(fail.getMessage(), fail); onMigrationFailed(fail); } catch (RuntimeException e) { onError("Failed to open database: " + getName(), e); throw e; } if (performRecreate) { closeUnsafe(); // OK to call this here, locks are already held context.deleteDatabase(getName()); getDatabase(); } } return database; } @Beta @TargetApi(VERSION_CODES.JELLY_BEAN) public final String attachDatabase(SquidDatabase other) { if (attachedTo != null) { throw new IllegalStateException("Can't attach a database to a database that is itself attached"); } if (inTransaction()) { throw new IllegalStateException("Can't attach a database while in a transaction on the current thread"); } boolean walEnabled; acquireNonExclusiveLock(); try { walEnabled = (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) && getDatabase().isWriteAheadLoggingEnabled(); } finally { releaseNonExclusiveLock(); } if (walEnabled) { // need to wait for transactions to finish acquireExclusiveLock(); } try { return other.attachTo(this); } finally { if (walEnabled) { releaseExclusiveLock(); } } } /** * Detaches a database previously attached with {@link #attachDatabase(SquidDatabase)} * * @return true if the other database was successfully detached */ @Beta public final boolean detachDatabase(SquidDatabase other) { if (other.attachedTo != this) { throw new IllegalArgumentException("Database " + other.getName() + " is not attached to " + getName()); } return other.detachFrom(this); } private String attachTo(SquidDatabase attachTo) { if (attachedTo != null) { throw new IllegalArgumentException( "Database " + getName() + " is already attached to " + attachedTo.getName()); } if (inTransaction()) { throw new IllegalStateException( "Cannot attach database " + getName() + " to " + attachTo.getName() + " -- " + getName() + " is in a transaction on the calling thread"); } acquireExclusiveLock(); String attachedAs = getAttachedName(); if (!attachTo.tryExecSql("ATTACH '" + getDatabasePath() + "' AS '" + attachedAs + "'")) { releaseExclusiveLock(); // Failed return null; } else { attachedTo = attachTo; return attachedAs; } } private boolean detachFrom(SquidDatabase detachFrom) { if (detachFrom.tryExecSql("DETACH '" + getAttachedName() + "'")) { attachedTo = null; releaseExclusiveLock(); return true; } return false; } private String getAttachedName() { return getName().replace('.', '_'); } /** * Subclasses can override this method to enable connecting to a different version of SQLite than the default * version shipped with Android. For example, the squidb-sqlite-bindings project provides a class * SQLiteBindingsDatabaseOpenHelper to facilitate binding to a custom native build of SQLite. Overriders of this * method could simply <code>return new SQLiteBindingsDatabaseOpenHelper(context, databaseName, delegate, version);</code> * if they wanted to bypass Android's version of SQLite and use the version included with that project. * <p> * If you don't override this method, the stock Android SQLite build will be used. This is generally fine unless you * have a specific reason to prefer some other version of SQLite. */ protected SQLiteOpenHelperWrapper getOpenHelper(Context context, String databaseName, OpenHelperDelegate delegate, int version) { return new DefaultOpenHelperWrapper(context, databaseName, delegate, version); } /** * @return true if a connection to the {@link SQLiteDatabase} is open, false otherwise */ public synchronized final boolean isOpen() { return database != null && database.isOpen(); } /** * Close the database if it has been opened previously. This method acquires the exclusive lock before closing the * db -- it will block if other threads are in transactions. This method will throw an exception if called from * within a transaction. */ public final void close() { acquireExclusiveLock(); try { closeUnsafe(); } finally { releaseExclusiveLock(); } } private synchronized void closeUnsafe() { if (isOpen()) { database.close(); } helper = null; setDatabase(null); } /** * Clear all data in the database. This method acquires the exclusive lock before closing the db -- it will block * if other threads are in transactions. This method will throw an exception if called from within a transaction. * <p> * WARNING: Any open database resources (e.g. Cursors) will be abruptly closed. Do not call this method if other * threads may be accessing the database. The existing database file will be deleted and all data will be lost. */ public final void clear() { acquireExclusiveLock(); try { close(); context.deleteDatabase(getName()); } finally { releaseExclusiveLock(); } } /** * Clears the database and recreates an empty version of it. This method acquires the exclusive lock before closing * the db -- it will block if other threads are in transactions. This method will throw an exception if called from * within a transaction. * <p> * WARNING: Any open connections to the database will be abruptly closed. Do not call this method if other threads * may be accessing the database. * * @see #clear() */ public final void recreate() { if (isInMigration) { throw new RecreateDuringMigrationException(); } else { acquireExclusiveLock(); try { clear(); getDatabase(); } finally { releaseExclusiveLock(); } } } /** * @return a human-readable database name for debugging */ @Override public String toString() { return "DB:" + getName(); } /** * Execute a raw sqlite query. This method takes an Object[] for the arguments because Android's default behavior * of binding all arguments as strings can have unexpected bugs, particularly when working with functions. For * example: * * <pre> * select * from t where _id = '1'; // Returns the first row * select * from t where abs(_id) = '1'; // Always returns empty set * </pre> * * To eliminate this class of bugs, we bind all arguments as their native types, not as strings. Any object in the * array that is not a basic type (Number, String, Boolean, etc.) will be converted to a sanitized string before * binding. * * @param sql a sql statement * @param sqlArgs arguments to bind to the sql statement * @return a {@link Cursor} containing results of the query */ public Cursor rawQuery(String sql, Object[] sqlArgs) { acquireNonExclusiveLock(); try { return getDatabase().rawQuery(sql, sqlArgs); } finally { releaseNonExclusiveLock(); } } // For use only when validating queries private void compileStatement(String sql) { acquireNonExclusiveLock(); try { getDatabase().ensureSqlCompiles(sql); } finally { releaseNonExclusiveLock(); } } /** * @see SQLiteDatabase#insert(String table, String nullColumnHack, ContentValues values) */ protected long insert(String table, String nullColumnHack, ContentValues values) { acquireNonExclusiveLock(); try { return getDatabase().insert(table, nullColumnHack, values); } finally { releaseNonExclusiveLock(); } } /** * @see SQLiteDatabase#insertOrThrow(String table, String nullColumnHack, ContentValues values) */ protected long insertOrThrow(String table, String nullColumnHack, ContentValues values) { acquireNonExclusiveLock(); try { return getDatabase().insertOrThrow(table, nullColumnHack, values); } finally { releaseNonExclusiveLock(); } } /** * @see SQLiteDatabase#insertWithOnConflict(String, String, android.content.ContentValues, int) */ protected long insertWithOnConflict(String table, String nullColumnHack, ContentValues values, int conflictAlgorithm) { acquireNonExclusiveLock(); try { return getDatabase().insertWithOnConflict(table, nullColumnHack, values, conflictAlgorithm); } finally { releaseNonExclusiveLock(); } } /** * Execute a SQL {@link com.yahoo.squidb.sql.Insert} statement * * @return the row id of the last row inserted on success, -1 on failure */ private long insertInternal(Insert insert) { CompiledStatement compiled = insert.compile(getSqliteVersion()); acquireNonExclusiveLock(); try { return getDatabase().executeInsert(compiled.sql, compiled.sqlArgs); } finally { releaseNonExclusiveLock(); } } /** * See the note at the top of this file about the potential bugs when using String[] whereArgs * * @see SQLiteDatabase#delete(String, String, String[]) */ protected int delete(String table, String whereClause, String[] whereArgs) { acquireNonExclusiveLock(); try { return getDatabase().delete(table, whereClause, whereArgs); } finally { releaseNonExclusiveLock(); } } /** * Execute a SQL {@link com.yahoo.squidb.sql.Delete} statement * * @return the number of rows deleted on success, -1 on failure */ private int deleteInternal(Delete delete) { CompiledStatement compiled = delete.compile(getSqliteVersion()); acquireNonExclusiveLock(); try { return getDatabase().executeUpdateDelete(compiled.sql, compiled.sqlArgs); } finally { releaseNonExclusiveLock(); } } /** * See the note at the top of this file about the potential bugs when using String[] whereArgs * * @see SQLiteDatabase#update(String table, ContentValues values, String whereClause, String[] whereArgs) */ protected int update(String table, ContentValues values, String whereClause, String[] whereArgs) { acquireNonExclusiveLock(); try { return getDatabase().update(table, values, whereClause, whereArgs); } finally { releaseNonExclusiveLock(); } } /** * See the note at the top of this file about the potential bugs when using String[] whereArgs * * @see SQLiteDatabase#updateWithOnConflict(String table, ContentValues values, String whereClause, String[] * whereArgs, int conflictAlgorithm) */ protected int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm) { acquireNonExclusiveLock(); try { return getDatabase().updateWithOnConflict(table, values, whereClause, whereArgs, conflictAlgorithm); } finally { releaseNonExclusiveLock(); } } /** * Execute a SQL {@link com.yahoo.squidb.sql.Update} statement * * @return the number of rows updated on success, -1 on failure */ private int updateInternal(Update update) { CompiledStatement compiled = update.compile(getSqliteVersion()); acquireNonExclusiveLock(); try { return getDatabase().executeUpdateDelete(compiled.sql, compiled.sqlArgs); } finally { releaseNonExclusiveLock(); } } /** * Begin a transaction. This acquires a non-exclusive lock. * * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransaction() */ public void beginTransaction() { acquireNonExclusiveLock(); getDatabase().beginTransaction(); transactionSuccessState.get().beginTransaction(); } /** * Begin a non-exclusive transaction. This acquires a non-exclusive lock. * * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransactionNonExclusive() */ public void beginTransactionNonExclusive() { acquireNonExclusiveLock(); getDatabase().beginTransactionNonExclusive(); transactionSuccessState.get().beginTransaction(); } /** * Begin a transaction with a listener. This acquires a non-exclusive lock. * * @param listener the transaction listener * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransactionWithListener(android.database.sqlite.SQLiteTransactionListener) */ public void beginTransactionWithListener(SquidTransactionListener listener) { acquireNonExclusiveLock(); getDatabase().beginTransactionWithListener(listener); transactionSuccessState.get().beginTransaction(); } /** * Begin a non-exclusive transaction with a listener. This acquires a non-exclusive lock. * * @param listener the transaction listener * @see #acquireNonExclusiveLock() * @see SQLiteDatabase#beginTransactionWithListenerNonExclusive(android.database.sqlite.SQLiteTransactionListener) */ public void beginTransactionWithListenerNonExclusive(SquidTransactionListener listener) { acquireNonExclusiveLock(); getDatabase().beginTransactionWithListenerNonExclusive(listener); transactionSuccessState.get().beginTransaction(); } /** * Mark the current transaction as successful * * @see SQLiteDatabase#setTransactionSuccessful() */ public void setTransactionSuccessful() { getDatabase().setTransactionSuccessful(); transactionSuccessState.get().setTransactionSuccessful(); } /** * @return true if a transaction is active * @see SQLiteDatabase#inTransaction() */ public synchronized boolean inTransaction() { return database != null && database.inTransaction(); } /** * End the current transaction * * @see SQLiteDatabase#endTransaction() */ public void endTransaction() { getDatabase().endTransaction(); releaseNonExclusiveLock(); TransactionSuccessState successState = transactionSuccessState.get(); successState.endTransaction(); if (!inTransaction()) { flushAccumulatedNotifications(successState.outerTransactionSuccess); successState.reset(); } } // Tracks nested transaction success or failure state. If any // nested transaction fails, the entire outer transaction // is also considered to have failed. private static class TransactionSuccessState { Deque<Boolean> nestedSuccessStack = new LinkedList<Boolean>(); boolean outerTransactionSuccess = true; private void beginTransaction() { nestedSuccessStack.push(false); } private void setTransactionSuccessful() { nestedSuccessStack.pop(); nestedSuccessStack.push(true); } private void endTransaction() { Boolean mostRecentTransactionSuccess = nestedSuccessStack.pop(); if (!mostRecentTransactionSuccess) { outerTransactionSuccess = false; } } private void reset() { nestedSuccessStack.clear(); outerTransactionSuccess = true; } } private ThreadLocal<TransactionSuccessState> transactionSuccessState = new ThreadLocal<TransactionSuccessState>() { protected TransactionSuccessState initialValue() { return new TransactionSuccessState(); } }; /** * Yield the current transaction * * @see SQLiteDatabase#yieldIfContendedSafely() */ public boolean yieldIfContendedSafely() { return getDatabase().yieldIfContendedSafely(); } /** * Convenience method for calling {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver) * ContentResolver.notifyChange(uri, null)}. * * @param uri the Uri to notify */ public void notifyChange(Uri uri) { context.getContentResolver().notifyChange(uri, null); } /** * Convenience method for calling {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver) * ContentResolver.notifyChange(uri, null)} on all the provided Uris. * * @param uris the Uris to notify */ public void notifyChange(Collection<Uri> uris) { if (uris != null && !uris.isEmpty()) { ContentResolver resolver = context.getContentResolver(); for (Uri uri : uris) { resolver.notifyChange(uri, null); } } } /** * Acquires an exclusive lock on the database. This is semantically similar to acquiring a write lock in a {@link * java.util.concurrent.locks.ReadWriteLock ReadWriteLock} but it is not generally necessary for protecting actual * database writes--it's only necessary when exclusive use of the database connection is required (e.g. while the * database is attached to another database). * <p> * Only one thread can hold an exclusive lock at a time. Calling this while on a thread that already holds a non- * exclusive lock is an error and will deadlock! We will throw an exception if this method is called while the * calling thread is in a transaction. Otherwise, this method will block until all non-exclusive locks * acquired with {@link #acquireNonExclusiveLock()} have been released, but will prevent any new non-exclusive * locks from being acquired while it blocks. */ @Beta protected void acquireExclusiveLock() { if (inTransaction()) { throw new IllegalStateException( "Can't acquire an exclusive lock when the calling thread is in a transaction"); } readWriteLock.writeLock().lock(); } /** * Release the exclusive lock acquired by {@link #acquireExclusiveLock()} */ @Beta protected void releaseExclusiveLock() { readWriteLock.writeLock().unlock(); } /** * Acquire a non-exclusive lock on the database. This is semantically similar to acquiring a read lock in a {@link * java.util.concurrent.locks.ReadWriteLock ReadWriteLock} but may also be used in most cases to protect database * writes (see {@link #acquireExclusiveLock()} for why this is true). This will block if the exclusive lock is held * by some other thread. Many threads can hold non-exclusive locks as long as no thread holds the exclusive lock. */ @Beta protected void acquireNonExclusiveLock() { readWriteLock.readLock().lock(); } /** * Releases a non-exclusive lock acquired with {@link #acquireNonExclusiveLock()} */ @Beta protected void releaseNonExclusiveLock() { readWriteLock.readLock().unlock(); } /** * Delegate class passed to a {@link SQLiteOpenHelperWrapper} instance that allows the SQLiteOpenHelperWrapper to call back * into its owning SquidDatabase after the database has been created or opened. */ public final class OpenHelperDelegate { private OpenHelperDelegate() { // No public instantiation } /** * Called to create the database tables */ public void onCreate(SQLiteDatabaseWrapper db) { setDatabase(db); StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor(); // create tables Table[] tables = getTables(); if (tables != null) { for (Table table : tables) { table.appendCreateTableSql(getSqliteVersion(), sql, sqlVisitor); db.execSQL(sql.toString()); sql.setLength(0); } } View[] views = getViews(); if (views != null) { for (View view : views) { view.createViewSql(getSqliteVersion(), sql); db.execSQL(sql.toString()); sql.setLength(0); } } Index[] indexes = getIndexes(); if (indexes != null) { for (Index idx : indexes) { tryCreateIndex(idx); } } // post-table-creation SquidDatabase.this.onTablesCreated(db); } /** * Called to upgrade the database to a new version */ public void onUpgrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { setDatabase(db); boolean success = false; Throwable thrown = null; isInMigration = true; try { success = SquidDatabase.this.onUpgrade(db, oldVersion, newVersion); } catch (Throwable t) { thrown = t; success = false; } finally { isInMigration = false; } if (thrown instanceof RecreateDuringMigrationException) { throw (RecreateDuringMigrationException) thrown; } else if (thrown instanceof MigrationFailedException) { throw (MigrationFailedException) thrown; } else if (!success) { throw new MigrationFailedException(getName(), oldVersion, newVersion, thrown); } } /** * Called to downgrade the database to an older version */ public void onDowngrade(SQLiteDatabaseWrapper db, int oldVersion, int newVersion) { setDatabase(db); boolean success = false; Throwable thrown = null; isInMigration = true; try { success = SquidDatabase.this.onDowngrade(db, oldVersion, newVersion); } catch (Throwable t) { thrown = t; success = false; } finally { isInMigration = false; } if (thrown instanceof RecreateDuringMigrationException) { throw (RecreateDuringMigrationException) thrown; } else if (thrown instanceof MigrationFailedException) { throw (MigrationFailedException) thrown; } else if (!success) { throw new MigrationFailedException(getName(), oldVersion, newVersion, thrown); } } public void onConfigure(SQLiteDatabaseWrapper db) { setDatabase(db); SquidDatabase.this.onConfigure(db); } public void onOpen(SQLiteDatabaseWrapper db) { setDatabase(db); SquidDatabase.this.onOpen(db); } } private synchronized void setDatabase(SQLiteDatabaseWrapper db) { // If we're already holding a reference to the same object, don't need to update or recalculate the version if (database != null && db != null && db.getWrappedDatabase() == database.getWrappedDatabase()) { return; } database = db; sqliteVersion = database != null ? readSqliteVersionUnsafe(db) : null; } // Reads the SQLite version from the database. This method is "unsafe" because it does not itself acquire // either the exclusive or non-exclusive lock -- it is assumed that the calling thread already holds the // correct lock. Violating this assumption would be bad, possibly cause deadlocks, etc. private VersionCode readSqliteVersionUnsafe(SQLiteDatabaseWrapper db) { try { String versionString = db.simpleQueryForString("select sqlite_version()", null); return VersionCode.parse(versionString); } catch (RuntimeException e) { onError("Failed to read sqlite version", e); throw new RuntimeException("Failed to read sqlite version", e); } } /** * Add a column to a table by specifying the corresponding {@link Property} * * @param property the Property associated with the column to add * @return true if the statement executed without error, false otherwise */ protected boolean tryAddColumn(Property<?> property) { if (!(property.table instanceof Table)) { throw new IllegalArgumentException("Can't alter table: property does not belong to a Table"); } SqlConstructorVisitor visitor = new SqlConstructorVisitor(); StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); sql.append("ALTER TABLE ").append(property.table.getExpression()).append(" ADD "); property.accept(visitor, sql); return tryExecSql(sql.toString()); } /** * Create a new {@link Table} or {@link VirtualTable} in the database * * @param table the Table or VirtualTable to create * @return true if the statement executed without error, false otherwise */ protected boolean tryCreateTable(Table table) { SqlConstructorVisitor sqlVisitor = new SqlConstructorVisitor(); StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); table.appendCreateTableSql(getSqliteVersion(), sql, sqlVisitor); return tryExecSql(sql.toString()); } /** * Drop a {@link Table} or {@link VirtualTable} in the database if it exists * * @param table the Table or VirtualTable to drop * @return true if the statement executed without error, false otherwise */ protected boolean tryDropTable(Table table) { return tryExecSql("DROP TABLE IF EXISTS " + table.getExpression()); } /** * Create a new {@link View} in the database * * @param view the View to create * @return true if the statement executed without error, false otherwise * @see com.yahoo.squidb.sql.View#fromQuery(com.yahoo.squidb.sql.Query, String) * @see com.yahoo.squidb.sql.View#temporaryFromQuery(com.yahoo.squidb.sql.Query, String) */ public boolean tryCreateView(View view) { StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); view.createViewSql(getSqliteVersion(), sql); return tryExecSql(sql.toString()); } /** * Drop a {@link View} in the database if it exists * * @param view the View to drop * @return true if the statement executed without error, false otherwise */ public boolean tryDropView(View view) { return tryExecSql("DROP VIEW IF EXISTS " + view.getExpression()); } /** * Create a new {@link Index} in the database * * @param index the Index to create * @return true if the statement executed without error, false otherwise * @see com.yahoo.squidb.sql.Table#index(String, com.yahoo.squidb.sql.Property[]) * @see com.yahoo.squidb.sql.Table#uniqueIndex(String, com.yahoo.squidb.sql.Property[]) */ protected boolean tryCreateIndex(Index index) { return tryCreateIndex(index.getName(), index.getTable(), index.isUnique(), index.getProperties()); } /** * Create a new {@link Index} in the database * * @param indexName name for the Index * @param table the table to create the index on * @param unique true if the index is a unique index on the specified columns * @param properties the columns to create the index on * @return true if the statement executed without error, false otherwise */ protected boolean tryCreateIndex(String indexName, Table table, boolean unique, Property<?>... properties) { if (properties == null || properties.length == 0) { onError(String.format("Cannot create index %s: no properties specified", indexName), null); return false; } StringBuilder sql = new StringBuilder(STRING_BUILDER_INITIAL_CAPACITY); sql.append("CREATE "); if (unique) { sql.append("UNIQUE "); } sql.append("INDEX IF NOT EXISTS ").append(indexName).append(" ON ").append(table.getExpression()) .append("("); for (Property<?> p : properties) { sql.append(p.getName()).append(","); } sql.deleteCharAt(sql.length() - 1); sql.append(")"); return tryExecSql(sql.toString()); } /** * Drop an {@link Index} if it exists * * @param index the Index to drop * @return true if the statement executed without error, false otherwise */ protected boolean tryDropIndex(Index index) { return tryDropIndex(index.getName()); } /** * Drop an {@link Index} if it exists * * @param indexName the name of the Index to drop * @return true if the statement executed without error, false otherwise */ protected boolean tryDropIndex(String indexName) { return tryExecSql("DROP INDEX IF EXISTS " + indexName); } /** * Execute a {@link SqlStatement} * * @param statement the statement to execute * @return true if the statement executed without error, false otherwise */ public boolean tryExecStatement(SqlStatement statement) { CompiledStatement compiled = statement.compile(getSqliteVersion()); return tryExecSql(compiled.sql, compiled.sqlArgs); } /** * Execute a raw SQL statement * * @param sql the statement to execute * @return true if the statement executed without an error * @see SQLiteDatabase#execSQL(String) */ public boolean tryExecSql(String sql) { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql); return true; } catch (SQLExceptionWrapper e) { onError("Failed to execute statement: " + sql, e); return false; } finally { releaseNonExclusiveLock(); } } /** * Execute a raw SQL statement * * @param sql the statement to execute * @throws SQLExceptionWrapper if there is an error parsing the SQL or some other error * @see SQLiteDatabase#execSQL(String) */ public void execSqlOrThrow(String sql) throws SQLExceptionWrapper { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql); } finally { releaseNonExclusiveLock(); } } /** * Execute a raw SQL statement with optional arguments. The sql string may contain '?' placeholders for the * arguments. * * @param sql the statement to execute * @param bindArgs the arguments to bind to the statement * @return true if the statement executed without an error * @see SQLiteDatabase#execSQL(String, Object[]) */ public boolean tryExecSql(String sql, Object[] bindArgs) { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql, bindArgs); return true; } catch (SQLExceptionWrapper e) { onError("Failed to execute statement: " + sql, e); return false; } finally { releaseNonExclusiveLock(); } } /** * Execute a raw SQL statement with optional arguments. The sql string may contain '?' placeholders for the * arguments. * * @param sql the statement to execute * @param bindArgs the arguments to bind to the statement * @throws SQLExceptionWrapper if there is an error parsing the SQL or some other error * @see SQLiteDatabase#execSQL(String, Object[]) */ public void execSqlOrThrow(String sql, Object[] bindArgs) throws SQLExceptionWrapper { acquireNonExclusiveLock(); try { getDatabase().execSQL(sql, bindArgs); } finally { releaseNonExclusiveLock(); } } /** * @return the current SQLite version as a {@link VersionCode} * @throws RuntimeException if the version could not be read */ public VersionCode getSqliteVersion() { VersionCode toReturn = sqliteVersion; if (toReturn == null) { acquireNonExclusiveLock(); try { synchronized (this) { if (sqliteVersion == null) { sqliteVersion = readSqliteVersionUnsafe(getDatabase()); } toReturn = sqliteVersion; } } finally { releaseNonExclusiveLock(); } } return toReturn; } /** * Visitor that builds column definitions for {@link Property}s */ private static class SqlConstructorVisitor implements PropertyVisitor<Void, StringBuilder> { private Void appendColumnDefinition(String type, Property<?> property, StringBuilder sql) { sql.append(property.getName()).append(" ").append(type); if (!TextUtils.isEmpty(property.getColumnDefinition())) { sql.append(" ").append(property.getColumnDefinition()); } return null; } @Override public Void visitDouble(Property<Double> property, StringBuilder sql) { return appendColumnDefinition("REAL", property, sql); } @Override public Void visitInteger(Property<Integer> property, StringBuilder sql) { return appendColumnDefinition("INTEGER", property, sql); } @Override public Void visitLong(Property<Long> property, StringBuilder sql) { return appendColumnDefinition("INTEGER", property, sql); } @Override public Void visitString(Property<String> property, StringBuilder sql) { return appendColumnDefinition("TEXT", property, sql); } @Override public Void visitBoolean(Property<Boolean> property, StringBuilder sql) { return appendColumnDefinition("INTEGER", property, sql); } @Override public Void visitBlob(Property<byte[]> property, StringBuilder sql) { return appendColumnDefinition("BLOB", property, sql); } } private static class RecreateDuringMigrationException extends RuntimeException { /* suppress compiler warning */ private static final long serialVersionUID = 480910684116077495L; } /** * Exception thrown when an upgrade or downgrade fails for any reason. Clients that want to provide more * information about why an upgrade or downgrade failed can subclass this class and throw it intentionally in * {@link #onUpgrade(SQLiteDatabaseWrapper, int, int) onUpgrade()} or * {@link #onDowngrade(SQLiteDatabaseWrapper, int, int) onDowngrade()}, and it will be forwarded to * {@link #onMigrationFailed(MigrationFailedException) onMigrationFailed()}. */ public static class MigrationFailedException extends RuntimeException { /* suppress compiler warning */ private static final long serialVersionUID = 2949995666882182744L; public final String dbName; public final int oldVersion; public final int newVersion; public MigrationFailedException(String dbName, int oldVersion, int newVersion) { this(dbName, oldVersion, newVersion, null); } public MigrationFailedException(String dbName, int oldVersion, int newVersion, Throwable throwable) { super(throwable); this.dbName = dbName; this.oldVersion = oldVersion; this.newVersion = newVersion; } @Override @SuppressLint("DefaultLocale") public String getMessage() { return String.format("Failed to migrate db \"%s\" from version %d to %d", dbName, oldVersion, newVersion); } } /** * Query the database * * @param modelClass the type to parameterize the cursor by. If the query does not contain a FROM clause, the table * or view corresponding to this model class will be used. * @param query the query to execute * @return a {@link SquidCursor} containing the query results */ public <TYPE extends AbstractModel> SquidCursor<TYPE> query(Class<TYPE> modelClass, Query query) { if (!query.hasTable() && modelClass != null) { SqlTable<?> table = getSqlTable(modelClass); if (table == null) { throw new IllegalArgumentException("Query has no FROM clause and model class " + modelClass.getSimpleName() + " has no associated table"); } query = query.from(table); // If argument was frozen, we may get a new object } CompiledStatement compiled = query.compile(getSqliteVersion()); if (compiled.needsValidation) { String validateSql = query.sqlForValidation(getSqliteVersion()); compileStatement(validateSql); // throws if the statement fails to compile } Cursor cursor = rawQuery(compiled.sql, compiled.sqlArgs); return new SquidCursor<TYPE>(cursor, query.getFields()); } /** * Fetch the specified model object with the given row ID * * @param modelClass the model class to fetch * @param id the row ID of the item * @param properties the {@link Property properties} to read * @return an instance of the model with the given ID, or null if no record was found */ public <TYPE extends TableModel> TYPE fetch(Class<TYPE> modelClass, long id, Property<?>... properties) { SquidCursor<TYPE> cursor = fetchItemById(modelClass, id, properties); return returnFetchResult(modelClass, cursor); } /** * Fetch the first model matching the given {@link Criterion}. This is useful if you expect uniqueness of models * with respect to the given criterion. * * @param modelClass the model class to fetch * @param properties the {@link Property properties} to read * @param criterion the criterion to match * @return an instance of the model matching the given criterion, or null if no record was found */ public <TYPE extends AbstractModel> TYPE fetchByCriterion(Class<TYPE> modelClass, Criterion criterion, Property<?>... properties) { SquidCursor<TYPE> cursor = fetchFirstItem(modelClass, criterion, properties); return returnFetchResult(modelClass, cursor); } /** * Fetch the first model matching the query. This is useful if you expect uniqueness of models with respect to the * given query. * * @param modelClass the model class to fetch * @param query the query to execute * @return an instance of the model returned by the given query, or null if no record was found */ public <TYPE extends AbstractModel> TYPE fetchByQuery(Class<TYPE> modelClass, Query query) { SquidCursor<TYPE> cursor = fetchFirstItem(modelClass, query); return returnFetchResult(modelClass, cursor); } protected <TYPE extends AbstractModel> TYPE returnFetchResult(Class<TYPE> modelClass, SquidCursor<TYPE> cursor) { try { if (cursor.getCount() == 0) { return null; } TYPE toReturn = modelClass.newInstance(); toReturn.readPropertiesFromCursor(cursor); return toReturn; } catch (SecurityException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } finally { cursor.close(); } } /** * Delete the row with the given row ID * * @param modelClass the model class corresponding to the table to delete from * @param id the row ID of the record * @return true if delete was successful */ public boolean delete(Class<? extends TableModel> modelClass, long id) { Table table = getTable(modelClass); int rowsUpdated = deleteInternal(Delete.from(table).where(table.getIdProperty().eq(id))); if (rowsUpdated > 0) { notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, table, id); } return rowsUpdated > 0; } /** * Delete all rows matching the given {@link Criterion} * * @param modelClass model class for the table to delete from * @param where the Criterion to match. Note: passing null will delete all rows! * @return the number of deleted rows */ public int deleteWhere(Class<? extends TableModel> modelClass, Criterion where) { Table table = getTable(modelClass); Delete delete = Delete.from(table); if (where != null) { delete.where(where); } int rowsUpdated = deleteInternal(delete); if (rowsUpdated > 0) { notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, table, TableModel.NO_ID); } return rowsUpdated; } /** * Delete all rows for table corresponding to the given model class * * @param modelClass model class for the table to delete from * @return the number of deleted rows */ public int deleteAll(Class<? extends TableModel> modelClass) { return deleteWhere(modelClass, null); } /** * Executes a {@link Delete} statement. * <p> * Note: Generally speaking, you should prefer to use {@link #delete(Class, long) delete} or * {@link #deleteWhere(Class, Criterion) deleteWhere} for deleting database rows. This is provided as a convenience * in case there exists a non-ORM case where a more traditional SQL delete statement is required. * * @param delete the statement to execute * @return the number of rows deleted on success, -1 on failure */ public int delete(Delete delete) { int result = deleteInternal(delete); if (result > 0) { notifyForTable(DataChangedNotifier.DBOperation.DELETE, null, delete.getTable(), TableModel.NO_ID); } return result; } /** * Update all rows matching the given {@link Criterion}, setting values based on the provided template model. For * example, this code would change all persons' names from "joe" to "bob": * * <pre> * Person template = new Person(); * template.setName(&quot;bob&quot;); * update(Person.NAME.eq(&quot;joe&quot;), template); * </pre> * * @param where the criterion to match. Note: passing null will update all rows! * @param template a model containing new values for the properties (columns) that should be updated. The template * class implicitly defines the table to be updated. * @return the number of updated rows */ public int update(Criterion where, TableModel template) { return updateWithOnConflict(where, template, null); } /** * Update all rows in the table corresponding to the class of the given template * * @param template a model containing new values for the properties (columns) that should be updated. The template * class implicitly defines the table to be updated. * @return the number of updated rows */ public int updateAll(TableModel template) { return update(null, template); } /** * Update all rows matching the given {@link Criterion}, setting values based on the provided template model. Any * constraint violations will be resolved using the specified {@link TableStatement.ConflictAlgorithm}. * * @param where the criterion to match. Note: passing null will update all rows! * @param template a model containing new values for the properties (columns) that should be updated * @param conflictAlgorithm the conflict algorithm to use * @return the number of updated rows * @see #update(Criterion, TableModel) */ public int updateWithOnConflict(Criterion where, TableModel template, TableStatement.ConflictAlgorithm conflictAlgorithm) { Class<? extends TableModel> modelClass = template.getClass(); Table table = getTable(modelClass); Update update = Update.table(table).fromTemplate(template); if (where != null) { update.where(where); } if (conflictAlgorithm != null) { update.onConflict(conflictAlgorithm); } int rowsUpdated = updateInternal(update); if (rowsUpdated > 0) { notifyForTable(DataChangedNotifier.DBOperation.UPDATE, template, table, TableModel.NO_ID); } return rowsUpdated; } /** * Update all rows in the table corresponding to the class of the given template * * @param template a model containing new values for the properties (columns) that should be updated. The template * class implicitly defines the table to be updated. * @param conflictAlgorithm the conflict algorithm to use * @return the number of updated rows */ public int updateAllWithOnConflict(TableModel template, TableStatement.ConflictAlgorithm conflictAlgorithm) { return updateWithOnConflict(null, template, conflictAlgorithm); } /** * Executes an {@link Update} statement. * <p> * Note: Generally speaking, you should prefer to use {@link #update(Criterion, TableModel)} * or {@link #updateWithOnConflict(Criterion, TableModel, com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm)} * for bulk database updates. This is provided as a convenience in case there exists a non-ORM case where a more * traditional SQL update statement is required for some reason. * * @param update statement to execute * @return the number of rows updated on success, -1 on failure */ public int update(Update update) { int result = updateInternal(update); if (result > 0) { notifyForTable(DataChangedNotifier.DBOperation.UPDATE, null, update.getTable(), TableModel.NO_ID); } return result; } /** * Save a model to the database. Creates a new row if the model does not have an ID, otherwise updates the row with * the corresponding row ID. If a new row is inserted, the model will have its ID set to the corresponding row ID. * * @param item the model to save * @return true if current the model data is stored in the database */ public boolean persist(TableModel item) { return persistWithOnConflict(item, null); } /** * Save a model to the database. Creates a new row if the model does not have an ID, otherwise updates the row with * the corresponding row ID. If a new row is inserted, the model will have its ID set to the corresponding row ID. * Any constraint violations will be resolved using the specified {@link TableStatement.ConflictAlgorithm}. * * @param item the model to save * @param conflictAlgorithm the conflict algorithm to use * @return true if current the model data is stored in the database * @see #persist(TableModel) */ public boolean persistWithOnConflict(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) { if (!item.isSaved()) { return insertRow(item, conflictAlgorithm); } if (!item.isModified()) { return true; } return updateRow(item, conflictAlgorithm); } /** * Save a model to the database. This method always inserts a new row and sets the ID of the model to the * corresponding row ID. * * @param item the model to save * @return true if current the model data is stored in the database */ public boolean createNew(TableModel item) { item.setId(TableModel.NO_ID); return insertRow(item, null); } /** * Save a model to the database. This method always updates an existing row with a row ID corresponding to the * model's ID. If the model doesn't have an ID, or the corresponding row no longer exists in the database, this * will return false. * * @param item the model to save * @return true if current the model data is stored in the database */ public boolean saveExisting(TableModel item) { return updateRow(item, null); } /** * Inserts a new row using the item's merged values into the DB. * <p> * Note: unlike {@link #createNew(TableModel)}, which will always create a new row even if an id is set on the * model, this method will blindly attempt to insert the primary key id value if it is provided. This may cause * conflicts, throw exceptions, etc. if the row id already exists, so be sure to check for such cases if you * expect they may happen. * * @param item the model to insert * @return true if success, false otherwise */ protected final boolean insertRow(TableModel item) { return insertRow(item, null); } /** * Same as {@link #insertRow(TableModel)} with the ability to specify a ConflictAlgorithm for handling constraint * violations * * @param item the model to insert * @param conflictAlgorithm the conflict algorithm to use * @return true if success, false otherwise */ protected final boolean insertRow(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) { Class<? extends TableModel> modelClass = item.getClass(); Table table = getTable(modelClass); long newRow; ContentValues mergedValues = item.getMergedValues(); if (mergedValues.size() == 0) { return false; } if (conflictAlgorithm == null) { newRow = insertOrThrow(table.getExpression(), null, mergedValues); } else { newRow = insertWithOnConflict(table.getExpression(), null, mergedValues, conflictAlgorithm.getAndroidValue()); } boolean result = newRow > 0; if (result) { notifyForTable(DataChangedNotifier.DBOperation.INSERT, item, table, newRow); item.setId(newRow); item.markSaved(); } return result; } /** * Update an existing row in the database using the item's setValues. The item must have the primary key id set; * if it does not, the method will return false. * * @param item the model to save * @return true if success, false otherwise */ protected final boolean updateRow(TableModel item) { return updateRow(item, null); } /** * Same as {@link #updateRow(TableModel)} with the ability to specify a ConflictAlgorithm for handling constraint * violations * * @param item the model to save * @param conflictAlgorithm the conflict algorithm to use * @return true if success, false otherwise */ protected final boolean updateRow(TableModel item, TableStatement.ConflictAlgorithm conflictAlgorithm) { if (!item.isModified()) { // nothing changed return true; } if (!item.isSaved()) { return false; } Class<? extends TableModel> modelClass = item.getClass(); Table table = getTable(modelClass); Update update = Update.table(table).fromTemplate(item).where(table.getIdProperty().eq(item.getId())); if (conflictAlgorithm != null) { update.onConflict(conflictAlgorithm); } boolean result = updateInternal(update) > 0; if (result) { notifyForTable(DataChangedNotifier.DBOperation.UPDATE, item, table, item.getId()); item.markSaved(); } return result; } /** * Executes an {@link Insert} statement. * <p> * Note: Generally speaking, you should prefer to use {@link #persist(TableModel) persist} or * {@link #createNew(TableModel) createNew} for inserting database rows. This is provided as a convenience in case * there exists a non-ORM case where a more traditional SQL insert statement is required. * * @param insert the statement to execute * @return the row id of the last row inserted on success, 0 on failure */ public long insert(Insert insert) { long result = insertInternal(insert); if (result > TableModel.NO_ID) { int numInserted = insert.getNumRows(); notifyForTable(DataChangedNotifier.DBOperation.INSERT, null, insert.getTable(), numInserted == 1 ? result : TableModel.NO_ID); } return result; } protected <TYPE extends TableModel> SquidCursor<TYPE> fetchItemById(Class<TYPE> modelClass, long id, Property<?>... properties) { Table table = getTable(modelClass); return fetchFirstItem(modelClass, table.getIdProperty().eq(id), properties); } protected <TYPE extends AbstractModel> SquidCursor<TYPE> fetchFirstItem(Class<TYPE> modelClass, Criterion criterion, Property<?>... properties) { return fetchFirstItem(modelClass, Query.select(properties).where(criterion)); } protected <TYPE extends AbstractModel> SquidCursor<TYPE> fetchFirstItem(Class<TYPE> modelClass, Query query) { boolean immutableQuery = query.isImmutable(); Field<Integer> beforeLimit = query.getLimit(); SqlTable<?> beforeTable = query.getTable(); query = query.limit(1); // If argument was frozen, we may get a new object SquidCursor<TYPE> cursor = query(modelClass, query); if (!immutableQuery) { query.from(beforeTable).limit(beforeLimit); // Reset for user } cursor.moveToFirst(); return cursor; } /** * Count the number of rows matching a given {@link Criterion}. Use null to count all rows. * * @param modelClass the model class corresponding to the table * @param criterion the criterion to match * @return the number of rows matching the given criterion */ public int count(Class<? extends AbstractModel> modelClass, Criterion criterion) { Property.IntegerProperty countProperty = Property.IntegerProperty.countProperty(); Query query = Query.select(countProperty); if (criterion != null) { query.where(criterion); } SquidCursor<?> cursor = query(modelClass, query); try { cursor.moveToFirst(); return cursor.get(countProperty); } finally { cursor.close(); } } /** * Count the number of rows in the given table. * * @param modelClass the model class corresponding to the table * @return the number of rows in the table */ public int countAll(Class<? extends AbstractModel> modelClass) { return count(modelClass, null); } private final Object notifiersLock = new Object(); private boolean dataChangedNotificationsEnabled = true; private List<DataChangedNotifier<?>> globalNotifiers = new ArrayList<DataChangedNotifier<?>>(); private Map<SqlTable<?>, List<DataChangedNotifier<?>>> tableNotifiers = new HashMap<SqlTable<?>, List<DataChangedNotifier<?>>>(); // Using a ThreadLocal makes it easy to have one accumulator set per transaction, since // transactions are also associated with the thread they run on private ThreadLocal<Set<DataChangedNotifier<?>>> notifierAccumulator = new ThreadLocal<Set<DataChangedNotifier<?>>>() { protected Set<DataChangedNotifier<?>> initialValue() { return new HashSet<DataChangedNotifier<?>>(); } }; /** * Register a {@link DataChangedNotifier} to listen for database changes. The DataChangedNotifier object will be * notified whenever a table it is interested is modified, and can accumulate a set of notifications to send when * the current transaction or statement completes successfully. * * @param notifier the DataChangedNotifier to register */ public void registerDataChangedNotifier(DataChangedNotifier<?> notifier) { if (notifier == null) { return; } synchronized (notifiersLock) { Collection<SqlTable<?>> tables = notifier.whichTables(); if (tables == null || tables.isEmpty()) { globalNotifiers.add(notifier); } else { for (SqlTable<?> table : tables) { List<DataChangedNotifier<?>> notifiersForTable = tableNotifiers.get(table); if (notifiersForTable == null) { notifiersForTable = new ArrayList<DataChangedNotifier<?>>(); tableNotifiers.put(table, notifiersForTable); } notifiersForTable.add(notifier); } } } } /** * Unregister a {@link DataChangedNotifier} previously registered by * {@link #registerDataChangedNotifier(DataChangedNotifier)} * * @param notifier the DataChangedNotifier to unregister */ public void unregisterDataChangedNotifier(DataChangedNotifier<?> notifier) { if (notifier == null) { return; } synchronized (notifiersLock) { Collection<SqlTable<?>> tables = notifier.whichTables(); if (tables == null || tables.isEmpty()) { globalNotifiers.remove(notifier); } else { for (SqlTable<?> table : tables) { List<DataChangedNotifier<?>> notifiersForTable = tableNotifiers.get(table); if (notifiersForTable != null) { notifiersForTable.remove(notifier); } } } } } /** * Unregister all {@link DataChangedNotifier}s previously registered by * {@link #registerDataChangedNotifier(DataChangedNotifier)} */ public void unregisterAllDataChangedNotifiers() { synchronized (notifiersLock) { globalNotifiers.clear(); tableNotifiers.clear(); } } /** * Set a flag to enable or disable data change notifications. No {@link DataChangedNotifier}s will be notified * (or accumulated during transactions) while the flag is set to false. */ public void setDataChangedNotificationsEnabled(boolean enabled) { dataChangedNotificationsEnabled = enabled; } private void notifyForTable(DataChangedNotifier.DBOperation op, AbstractModel modelValues, SqlTable<?> table, long rowId) { if (!dataChangedNotificationsEnabled) { return; } synchronized (notifiersLock) { onDataChanged(globalNotifiers, op, modelValues, table, rowId); onDataChanged(tableNotifiers.get(table), op, modelValues, table, rowId); } if (!inTransaction()) { flushAccumulatedNotifications(true); } } private void onDataChanged(List<DataChangedNotifier<?>> notifiers, DataChangedNotifier.DBOperation op, AbstractModel modelValues, SqlTable<?> table, long rowId) { if (notifiers != null) { for (DataChangedNotifier<?> notifier : notifiers) { if (notifier.onDataChanged(table, this, op, modelValues, rowId)) { notifierAccumulator.get().add(notifier); } } } } private void flushAccumulatedNotifications(boolean transactionSuccess) { Set<DataChangedNotifier<?>> accumulatedNotifiers = notifierAccumulator.get(); if (!accumulatedNotifiers.isEmpty()) { for (DataChangedNotifier<?> notifier : accumulatedNotifiers) { notifier.flushAccumulatedNotifications(this, transactionSuccess && dataChangedNotificationsEnabled); } accumulatedNotifiers.clear(); } } }
package blue.mesh; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Handler; public class RouterObject { private Handler handler; private BluetoothAdapter adapter; RouterObject( Handler mHandler, BluetoothAdapter mAdapter) { handler = mHandler; adapter= mAdapter; } //TODO: MAKE THIS CALL SYNCHRONIZED public int beginConnection(BluetoothSocket mSocket) { //Great Success! return 1; } public int route(byte buff[]) { //Great Success! return 1; } public byte [] getNextMessage() { byte arr[] = null; return arr; } int getDeviceState( BluetoothDevice device ){ return 0; } public int stop() { //Great Success! return 1; } }
package com.huit.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicLong; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisMonitor; /** * java -cp redis-cluster-manager-jar-with-dependencies.jar com.jumei.util.MonitorUtil cmdFilter=ZREVRANGE isKeyStat=true isCmdDetail=true showTop=1000 host=172.20.16.48 port=5001 maxCountLine=5 * * @author huit */ public class MonitorUtil { static int cmdTotal = 0; static Map<String, AtomicLong> cmdStat = new HashMap<String, AtomicLong>(); static Map<String, AtomicLong> hostStat = new HashMap<String, AtomicLong>(); static Map<String, AtomicLong> keyStat = new HashMap<String, AtomicLong>(); static List<String> cmdList = new ArrayList<String>(); static boolean isCmdDetail = false, isKeyStat; static int showTop = 10, port = SystemConf.get("REDIS_PORT", Integer.class); static String filePath = "", ipFilter = "", cmdFilter = "", host = SystemConf.get("REDIS_HOST"); static long monitorTime = 0; public static String helpInfo = "ipFilter=10.0 cmdFilter=ZREVRANGE isKeyStat=true isCmdDetail=true showTop=1000 host=172.20.16.48 port=5001 maxCountLine=5"; public static void main(String[] args) throws Exception { // args = "filePath=D:/20171019.log isKeyStat=true showTop=5".split(" "); // args = "filePath=D:/fc-redis.log isKeyStat=true showTop=5".split(" "); //args = "filePath=D:/redislog/ ipFilter=10.1.29.41 keyStat=false isCmdDetail=false".split(" "); //args = "filePath=D:/redislog/ keyStat=false isCmdDetail=true showTop=10".split(" "); //args = "filePath=D:/redislog/ cmdFilter=ZREVRANGE isKeyStat=true isCmdDetail=true showTop=1000".split(" "); //args = "filePath=D:/redislog/ cmdFilter=ZREVRANGE keyStat=false isCmdDetail=true showTop=10".split(" "); //args = "filePath=D:/redislog/ ipFilter=10.0.238.18 isCmdDetail=true".split(" "); // args = "filePath=D://monitor_redis_20170213095506.log ipFilter=10.16.31.135 isCmdDetail=true".split(" "); //args = helpInfo.split(" "); for (String arg : args) { if (arg.split("=").length != 2) { continue; } if (arg.startsWith("filePath=")) { filePath = arg.split("=")[1]; } else if (arg.startsWith("ipFilter=")) { ipFilter = arg.split("=")[1]; } else if (arg.startsWith("cmdFilter=")) { cmdFilter = arg.split("=")[1]; } else if (arg.startsWith("isCmdDetail=")) { isCmdDetail = Boolean.valueOf(arg.split("=")[1]); } else if (arg.startsWith("isKeyStat=")) { isKeyStat = Boolean.valueOf(arg.split("=")[1]); } else if (arg.startsWith("showTop=")) { showTop = Integer.valueOf(arg.split("=")[1]); } else if (arg.startsWith("host=")) { host = arg.split("=")[1]; } else if (arg.startsWith("port=")) { port = Integer.valueOf(arg.split("=")[1]); } else if (arg.startsWith("maxCountLine=")) { monitorTime = Long.valueOf(arg.split("=")[1]) * 1000; } else { System.out.println(helpInfo); System.exit(0); } } System.out.println("filePath=" + filePath + " ipFilter=" + ipFilter + " cmdFilter=" + cmdFilter + " isKeyStat=" + isKeyStat + " isCmdDetail=" + isCmdDetail); if (monitorTime > 0 && port > 0) { onlineMonitor(); } else { long beginTime = System.currentTimeMillis(); File dir = new File(filePath); if (dir.isDirectory()) { for (File file : dir.listFiles()) { loadData(file); } } else if (dir.isFile()) { loadData(dir); } printStat(); System.out.println("useTime:" + (System.currentTimeMillis() - beginTime)); } } public static void onlineMonitor() { @SuppressWarnings("resource") Jedis jedis = new Jedis(host, Integer.valueOf(port)); JedisMonitor monitor = new JedisMonitor() { @Override public void onCommand(String command) { parseData(command); } }; final long beginTime = System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(monitorTime); } catch (InterruptedException e) { e.printStackTrace(); } finally { printStat(); System.out.println("useTime:" + (System.currentTimeMillis() - beginTime)); System.exit(0); } } }, "monitorTimer").start(); jedis.monitor(monitor); } public static void printStat() { if ("".equals(cmdFilter)) { System.out.println(""); printStatMap(cmdStat); } if ("".equals(ipFilter)) { System.out.println(""); printStatMap(hostStat); } System.out.println("Key"); printStatMap(keyStat); if (!cmdList.isEmpty()) { int showCount = 0; synchronized (cmdList) { for (String cmdInfo : cmdList) { System.out.println(cmdInfo); showCount++; if (showCount > showTop) { break; } } } } } public static void parseData(String data) { if ("OK".equals(data)) { return; } int hostBegin = data.indexOf("["); int hostEnd = data.indexOf("]"); double time; String clientIp = null; String clientIpPort; String cmdDetail = null; String[] cmdInfo = null; if (hostBegin > 0 && hostBegin > 0) { time = Double.valueOf(data.substring(0, hostBegin)); clientIpPort = data.substring(hostBegin + 1, hostEnd).split(" ")[1]; clientIp = clientIpPort.split(":")[0]; cmdDetail = data.substring(hostEnd + 2); cmdInfo = cmdDetail.split(" "); } if (null != ipFilter && !clientIp.startsWith(ipFilter)) { return; } if (cmdInfo.length >= 1) { String key = cmdInfo[0].replace("\"", ""); if (null != cmdFilter && !key.startsWith(cmdFilter)) { return; } cmdTotal++; if (isKeyStat && cmdInfo.length >= 2) { addstat(keyStat, cmdInfo[1]); } if (isCmdDetail) { synchronized (cmdList) { cmdList.add(cmdDetail); } } addstat(cmdStat, key); addstat(hostStat, clientIp); } else { System.out.println(); } } public static void loadData(File file) throws IOException, FileNotFoundException { String data = null, key = null; //1476754442.972956 [0 10.0.238.18:9131] "PING" BufferedReader br = new BufferedReader(new FileReader(file)); while ((data = br.readLine()) != null) { parseData(data); } br.close(); } public static void addstat(Map<String, AtomicLong> stat, String key) { AtomicLong count = stat.get(key); if (null == count) { count = new AtomicLong(); stat.put(key, count); } count.incrementAndGet(); } public static void printStatMap(Map<String, AtomicLong> cmdStat) { if (cmdStat.isEmpty()) { return; } String cmd; List<Entry<String, AtomicLong>> arrayList = new ArrayList<Entry<String, AtomicLong>>(cmdStat.entrySet()); Collections.sort(arrayList, new Comparator<Object>() { @SuppressWarnings("unchecked") public int compare(Object o1, Object o2) { Map.Entry<String, AtomicLong> obj1 = (Map.Entry<String, AtomicLong>) o1; Map.Entry<String, AtomicLong> obj2 = (Map.Entry<String, AtomicLong>) o2; if (obj2.getValue().longValue() > obj1.getValue().longValue()) { return 1; } else if (obj1.getValue().longValue() == obj2.getValue().longValue()) { return 0; } else { return -1; } } }); Iterator<Entry<String, AtomicLong>> it = arrayList.iterator(); double hitRatio = 0; int showCount = 0; while (it.hasNext()) { Entry<String, AtomicLong> entry = it.next(); cmd = entry.getKey(); Long count = entry.getValue().longValue(); if (count > 0) { hitRatio = count / 0.01 / cmdTotal; } System.out.println(cmd + "->" + count + "(" + new DecimalFormat("#0.00").format(hitRatio) + "%)"); showCount++; if (showCount > showTop) { break; } } System.out.println(); } }
package org.epics.graphene; import java.time.ZoneId; import java.util.Arrays; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.epics.util.time.TimeDuration; import org.epics.util.time.TimeInterval; import org.epics.util.time.Timestamp; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.Matchers.*; import static org.epics.graphene.TimeScales.TimePeriod; import static java.util.GregorianCalendar.*; import java.util.TimeZone; import org.junit.Ignore; /** * * @author carcassi */ public class TimeScalesTest { @Test public void nextUp1() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 1)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 2))); } @Test public void nextUp2() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 2)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 5))); } @Test public void nextUp3() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 5)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 10))); } @Test public void nextUp4() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 10)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 15))); } @Test public void nextUp5() { TimeScales.TimePeriod nextUp = TimeScales.nextUp(new TimePeriod(SECOND, 15)); assertThat(nextUp, equalTo(new TimePeriod(SECOND, 30))); } @Test public void roundSeconds1() { TimeScales.TimePeriod period = TimeScales.toTimePeriod(30.0); assertThat(period, equalTo(new TimePeriod(SECOND, 30.0))); } @Test public void roundSeconds2() { TimeScales.TimePeriod period = TimeScales.toTimePeriod(61.0); assertThat(period, equalTo(new TimePeriod(MINUTE, 61.0/60.0))); } @Test public void nextDown1() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(SECOND, 15)); assertThat(period, equalTo(new TimePeriod(SECOND, 10))); } @Test public void nextDown2() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(SECOND, 2)); assertThat(period, equalTo(new TimePeriod(SECOND, 1))); } @Test public void nextDown3() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(SECOND, 5)); assertThat(period, equalTo(new TimePeriod(SECOND, 2))); } @Test public void nextDown4() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(SECOND, 10)); assertThat(period, equalTo(new TimePeriod(SECOND, 5))); } @Test public void nextDown5() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(SECOND, 15)); assertThat(period, equalTo(new TimePeriod(SECOND, 10))); } @Test public void nextDown6() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(SECOND, 30)); assertThat(period, equalTo(new TimePeriod(SECOND, 15))); } @Test public void nextDown7() { TimeScales.TimePeriod period = TimeScales.nextDown(new TimePeriod(MINUTE, 1)); assertThat(period, equalTo(new TimePeriod(SECOND, 30))); } //TODO nextDown and nextUp for minutes, hours, weeks, months, //Test createReferences() for any time interval and period //Leap years, crazy stuff @Test public void round1() { GregorianCalendar cal = new GregorianCalendar(2013, 3, 14, 14, 23, 15); cal.set(GregorianCalendar.MILLISECOND, 123); Date date = cal.getTime(); TimeScales.round(cal, GregorianCalendar.MILLISECOND); assertThat(cal.getTime(), equalTo(date)); TimeScales.round(cal, GregorianCalendar.SECOND); assertThat(cal, equalTo(new GregorianCalendar(2013, 3, 14, 14, 23, 15))); TimeScales.round(cal, GregorianCalendar.MINUTE); assertThat(cal, equalTo(new GregorianCalendar(2013, 3, 14, 14, 23, 0))); } @Test public void createReferences1() { GregorianCalendar cal = new GregorianCalendar(2013, 2, 14, 14, 23, 15); cal.set(GregorianCalendar.MILLISECOND, 123); Timestamp start = Timestamp.of(cal.getTime()); TimeInterval timeInterval = TimeInterval.between(start, start.plus(TimeDuration.ofSeconds(2))); List<Timestamp> references = TimeScales.createReferences(timeInterval, new TimePeriod(MILLISECOND, 50)); assertThat(references.size(), equalTo(40)); assertThat(references.get(0), equalTo(create(2013, 3, 14, 14, 23, 15, 150))); assertThat(references.get(1), equalTo(create(2013, 3, 14, 14, 23, 15, 200))); assertThat(references.get(39), equalTo(create(2013, 3, 14, 14, 23, 17, 100))); } @Test public void createReferences2() { GregorianCalendar cal = new GregorianCalendar(2013, 2, 14, 14, 23, 15); cal.set(GregorianCalendar.MILLISECOND, 123); Timestamp start = Timestamp.of(cal.getTime()); TimeInterval timeInterval = TimeInterval.between(start, start.plus(TimeDuration.ofSeconds(2))); List<Timestamp> references = TimeScales.createReferences(timeInterval, new TimePeriod(MILLISECOND, 100)); assertThat(references.size(), equalTo(20)); assertThat(references.get(0), equalTo(create(2013, 3, 14, 14, 23, 15, 200))); assertThat(references.get(1), equalTo(create(2013, 3, 14, 14, 23, 15, 300))); assertThat(references.get(19), equalTo(create(2013, 3, 14, 14, 23, 17, 100))); } @Test public void createReferences3() { GregorianCalendar cal = new GregorianCalendar(2013, 2, 14, 14, 23, 15); cal.set(GregorianCalendar.MILLISECOND, 123); Timestamp start = Timestamp.of(cal.getTime()); TimeInterval timeInterval = TimeInterval.between(start, start.plus(TimeDuration.ofSeconds(30))); List<Timestamp> references = TimeScales.createReferences(timeInterval, new TimePeriod(SECOND, 10)); assertThat(references.size(), equalTo(3)); assertThat(references.get(0), equalTo(create(2013, 3, 14, 14, 23, 20, 0))); assertThat(references.get(1), equalTo(create(2013, 3, 14, 14, 23, 30, 0))); assertThat(references.get(2), equalTo(create(2013, 3, 14, 14, 23, 40, 0))); } @Test public void createReferencesLowerBoundary1() { //test lower boundary case: 2 references 1 millisecond apart GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 1 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 1 ) ) ); } @Test public void createReferencesLowerBoundary2() { //test lower boundary case: 2 references, milliseconds roll over to next second GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 1 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 999 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test public void createReferencesLowerBoundary3() { //test lower boundary case: 2 references, milliseconds roll over to next second GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 2 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 2 ) ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test public void createReferencesLowerBoundary4() { GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 3 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 999 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 2 ) ) ); } @Test public void createReferencesLowerBoundary5() { GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 998 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 4 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test public void createReferencesLowerBoundary6() { GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 4 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test public void createReferencesLowerBoundary7() { //test two references, doesn't fit perfectly into time periods GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 998 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 6 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 4 ) ) ); } @Test public void createReferencesLowerBoundary8() { //test two references, doesn't fit perfectly, but start happens //to be a perfect multiple of the time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 996 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 6 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 996 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test public void createReferencesBoundary9() { //test two references, doesn't fit perfectly, but start happens //to be a perfect multiple of the time period, and so does the time interval GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 996 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 8 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(3) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 996 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 4 ) ) ); } @Test public void createReferencesBoundary10() { //test two references, that don't fit perfectly so that we have //one unit extra space on each side of the graph GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 6 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 4 ) ) ); } @Test public void createReferencesBoundary11() { //test two references, that don't fit perfectly so that we have //one unit extra space on left (smaller numbers) side only GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 5 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 4 ) ) ); } @Test public void createReferencesBoundary12() { //test two references, that don't fit perfectly so that we have //one unit extra space on right (larger numbers) side only GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 5 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 4 ) ) ); } @Test public void createReferenceBad1() { //test end before start GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( -5 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(0) ); } @Test public void createReferenceBad2() { //test end equals start and is not a multiple of the time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 1 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 0 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(0) ); } @Test public void createReferenceBad3() { //test end equals start and is a multiple of the time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 0 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test @Ignore //TODO uncaught / by 0 exception public void createReferenceBad4() { //time period is 0 GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 1 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 0 ) ); assertThat( references.size() , equalTo(0) ); } @Test public void createReferenceBad5() { //test negative timer interval (i.e. end is before start) //test end equals start and is a multiple of the time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 0 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 4 ) ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); } @Test public void createReferencesEmpty1() { //test time period too big GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 1 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( -5 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1 ) ); assertThat( references.size() , equalTo(0) ); } @Test public void createReferencesEmpty2() { //test units do not get mixed up GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( SECOND , 3 ) ); assertThat( references.size() , equalTo(0) ); } @Test public void createReferencesEmpty3() { //test units do not get mixed up GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMillis( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 3000 ) ); assertThat( references.size() , equalTo(0) ); } @Test public void createReferencesOverflowMilliseconds1() { //test units do not get mixed up //and they can overflow into a larger unit GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 3000 ) ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 3 , 0 ) ) ); } @Test public void createReferencesOverflowMilliseconds2() { //test units do not get mixed up and they can overflow into //a larger unit GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 999 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1333 ) ); assertThat( references.size() , equalTo(3) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 333 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 2 , 666 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 3 , 999 ) ) ); } @Test public void createReferencesOverflowMilliseconds3() { //test units do not get mixed up and they can overflow into //a larger unit. also test when we are 1 millisecond off from next //reference line GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 998 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1333 ) ); assertThat( references.size() , equalTo(2) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 333 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 2 , 666 ) ) ); } @Test public void createReferencesOverflowMilliseconds4() { //test units do not get mixed up and they can overflow into //a larger unit. also test when we are 1 millisecond after next //reference line GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 1 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MILLISECOND , 1333 ) ); assertThat( references.size() , equalTo(3) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 2 , 333 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 3 , 666 ) ) ); } @Test public void createReferencesSeconds1() { //test seconds: straightforward, 5 seconds interval over 1 second periods GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 5 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( SECOND , 1 ) ); assertThat( references.size() , equalTo(6) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 1 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 2 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 3 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 4 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 5 , 0 ) ) ); } @Test public void createReferencesSeconds2() { //test seconds: straightforward, 10 second interval over 2 second periods GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 10 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( SECOND , 2 ) ); assertThat( references.size() , equalTo(6) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 2 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 4 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 6 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 8 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 10 , 0 ) ) ); } @Test public void createReferencesSeconds3() { //test seconds: straightforward, 30 second interval over 5 second periods, //but does not start on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 1 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 30 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( SECOND , 5 ) ); assertThat( references.size() , equalTo(6) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 5 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 10 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 15 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 20 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 25 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 30 , 0 ) ) ); } @Test public void createReferencesSeconds4() { //test seconds: straightforward, 50 second interval over 10 second periods, //but does not start on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 500 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofSeconds( 50 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( SECOND , 10 ) ); assertThat( references.size() , equalTo(5) ); assertThat( references.get( 0 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 10 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 20 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 30 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 40 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create(2014 , 11 , 22 , 11 , 30 , 50 , 0 ) ) ); } @Test public void createReferencesMinutes1() { //test minutes: straightforward, 10 minutes interval over 1 minute periods, //but does not start on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 500 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMinutes( 10 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MINUTE , 1 ) ); assertThat( references.size() , equalTo(10) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 22 , 11 , 31 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 22 , 11 , 32 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 22 , 11 , 33 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2014 , 11 , 22 , 11 , 34 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2014 , 11 , 22 , 11 , 35 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2014 , 11 , 22 , 11 , 36 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2014 , 11 , 22 , 11 , 37 , 0 , 0 ) ) ); assertThat( references.get( 7 ) , equalTo( create( 2014 , 11 , 22 , 11 , 38 , 0 , 0 ) ) ); assertThat( references.get( 8 ) , equalTo( create( 2014 , 11 , 22 , 11 , 39 , 0 , 0 ) ) ); assertThat( references.get( 9 ) , equalTo( create( 2014 , 11 , 22 , 11 , 40 , 0 , 0 ) ) ); } @Test public void createReferencesMinutes2() { //test minutes: straightforward, 50 minutes interval over 10 minute periods, //starts on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofMinutes( 50 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MINUTE , 10 ) ); assertThat( references.size() , equalTo(6) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 22 , 11 , 30 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 22 , 11 , 40 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 22 , 11 , 50 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2014 , 11 , 22 , 12 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2014 , 11 , 22 , 12 , 10 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2014 , 11 , 22 , 12 , 20 , 0 , 0 ) ) ); } @Test public void createReferencesHours1() { //test hours: straightforward, 3 hours interval over 1 hour periods, //but does not start on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 679 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.HOUR_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo(3) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 22 , 12 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 22 , 13 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 22 , 14 , 0 , 0 , 0 ) ) ); } @Test //Note: this only works if hour type is set to HOUR_OF_DAY //This failes if hour type is set to HOUR public void createReferencesHours2() { //test hours: straightforward, 30 hour interval over 5 hour periods, //starts on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 0 , 0 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 30 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.HOUR_FIELD_ID , 5 ) ); assertThat( references.size() , equalTo(7) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 22 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 22 , 5 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 22 , 10 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2014 , 11 , 22 , 15 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2014 , 11 , 22 , 20 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2014 , 11 , 23 , 1 , 0 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2014 , 11 , 23 , 6 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesHoursDST1() { //Test spring forward daylight savings time (DST) //Start: Sat Mar 07 23:00:00 EST 2015 //End: Sun Mar 08 3:00:00 EST 2015 (right after spring forward DST) Timestamp start = create( 2015 , 3 , 7 , 23 , 0 , 0 , 0 ); Timestamp end = start.plus( TimeDuration.ofHours( 3 ) ); TimeInterval timeInterval = TimeInterval.between( start , end ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.HOUR_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 4 ) ); assertThat( references.get( 0 ) , equalTo( create( 2015 , 3 , 7 , 23 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2015 , 3 , 8 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2015 , 3 , 8 , 1 , 0 , 0 , 0 ) ) ); //DST makes us skip hour 2 assertThat( references.get( 3 ) , equalTo( create( 2015 , 3 , 8 , 3 , 0 , 0 , 0 ) ) ); } @Test //@Ignore //create() does not use EDT/EST correctly public void createReferencesHoursDST2() { //Test fall back daylight savings time (DST) //Start: Sun Nov 02 00:00:00 EST 2014 //End: Sun Nov 02 3:00:00 EST 2014 (right after fall back DST) Timestamp start = create( 2014 , 11 , 2 , 0 , 0 , 0 , 0 ); Timestamp end = start.plus( TimeDuration.ofHours( 4 ) ); TimeInterval timeInterval = TimeInterval.between( start , end ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.HOUR_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 5 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 2 , 0 , 0 , 0 , 0 ) ) ); //TODO resolve GregorianCalendar functioning improperly //I do not know why when changing time zone, GregorianCalendar's hours //remain in GMT time. For example, if you set time zone to GMT-5, setting the hours //still sets the GMT hours. Therefore, we must add an additional four hours. //The first two times November 2, 1:00 AM and November 2, 2:00 AM must be created //as November 5, 5:00 AM GMT and November 5, 6:00 AM GMT because //we have to manually change the time zone to EDT assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 2 , 5 , 0 , 0 , 0 , "EDT" ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 2 , 6 , 0 , 0 , 0 , "EDT" ) ) ); //hour 1 is repeated due to DST assertThat( references.get( 3 ) , equalTo( create( 2014 , 11 , 2 , 2 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2014 , 11 , 2 , 3 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesDays1() { //test days: straightforward, 7 day interval over 1 hour periods, //but does not start on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 27 , 4 , 12 , 24 ); cal.set( GregorianCalendar.MILLISECOND , 234 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*7 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.DAY_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 7 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 28 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 29 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 30 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2014 , 12 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2014 , 12 , 2 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2014 , 12 , 3 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2014 , 12 , 4 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesDays2() { //test days: straightforward, 30 day interval over 5 day periods, //starts on perfect multiple of time period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 20 , 0 , 0 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*30 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.DAY_FIELD_ID , 5 ) ); assertThat( references.size() , equalTo( 7 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 20 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 11 , 25 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 11 , 30 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2014 , 12 , 5 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2014 , 12 , 10 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2014 , 12 , 15 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2014 , 12 , 20 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesDays3() { //test days wrapping over to next year GregorianCalendar cal = new GregorianCalendar( 2014 , 11 , 27 , 4 , 12 , 24 ); cal.set( GregorianCalendar.MILLISECOND , 234 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*7 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.DAY_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 7 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 12 , 28 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 12 , 29 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 12 , 30 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2014 , 12 , 31 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2015 , 1 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2015 , 1 , 2 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2015 , 1 , 3 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesLeapDay() { //test days wrapping over to March when Feburary is of a leap year Timestamp start = create(2012, 2, 27, 4, 12, 24, 234); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*7 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.DAY_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 7 ) ); assertThat( references.get( 0 ) , equalTo( create( 2012 , 2 , 28 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2012 , 2 , 29 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2012 , 3 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2012 , 3 , 2 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2012 , 3 , 3 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2012 , 3 , 4 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2012 , 3 , 5 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesWeeks1() { //test weeks: straightforward, 3 weeks interval over 1 week periods //not starting on perfect multiple of period GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 27 , 4 , 12 , 24 ); cal.set( GregorianCalendar.MILLISECOND , 234 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*7*3 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.WEEK_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 3 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 30 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2014 , 12 , 7 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2014 , 12 , 14 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesWeeks2() { //test weeks: month has a last week that fully spans Sunday to Saturday //Start: Thu Jan 01 00:00:00 EST 2015 //End: Thu Feb 12 00:00:00 EST 2015 Timestamp start = create( 2015 , 1 , 1 , 0 , 0 , 0 , 0 ); Timestamp end = start.plus( TimeDuration.ofHours( 24*7*6 ) ); TimeInterval timeInterval = TimeInterval.between( start , end ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.WEEK_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 6 ) ); assertThat( references.get( 0 ) , equalTo( create( 2015 , 1 , 4 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2015 , 1 , 11 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2015 , 1 , 18 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2015 , 1 , 25 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2015 , 2 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2015 , 2 , 8 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesWeeks3() { //test weeks: month has a first week that fully spans Sunday to Saturday //and does not need to be rounded down to a week in previous month //Start: Sun Feb 01 00:00:00 EST 2015 //End: Sun Mar 08 00:00:00 EST 2015 Timestamp start = create( 2015 , 2 , 1 , 0 , 0 , 0 , 0 ); Timestamp end = start.plus( TimeDuration.ofHours( 24*7*5 ) ); System.out.println( start.toDate() ); System.out.println( end.toDate() ); TimeInterval timeInterval = TimeInterval.between( start , end ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( TimeScales.WEEK_FIELD_ID , 1 ) ); assertThat( references.size() , equalTo( 6 ) ); assertThat( references.get( 0 ) , equalTo( create( 2015 , 2 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2015 , 2 , 8 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2015 , 2 , 15 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2015 , 2 , 22 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2015 , 3 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2015 , 3 , 8 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesMonths1() { //test months: straightforward, 5 months interval over 1 month periods //not starting on perfect multiple of period //Start: Thu Nov 27 04:12:24 EST 2014 //End: Thu May 21 05:12:24 EDT 2015 GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 27 , 4 , 12 , 24 ); cal.set( GregorianCalendar.MILLISECOND , 234 ); Timestamp start = Timestamp.of( cal.getTime() ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*7*5*5 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MONTH , 1 ) ); assertThat( references.size() , equalTo( 6 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 12 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2015 , 1 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2015 , 2 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2015 , 3 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2015 , 4 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2015 , 5 , 1 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesMonths2() { //test months: 13 months over 2 month periods //starting on perfect multiple of period //Start: Sat Nov 01 00:00:00 EDT 2014 //End: Fri Dec 25 23:00:00 EST 2015 Timestamp start = create( 2014 , 11 , 1 , 0 , 0 , 0 , 0 ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*7*5*12 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( MONTH , 2 ) ); assertThat( references.size() , equalTo( 7 ) ); assertThat( references.get( 0 ) , equalTo( create( 2014 , 11 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create( 2015 , 1 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create( 2015 , 3 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create( 2015 , 5 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create( 2015 , 7 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 5 ) , equalTo( create( 2015 , 9 , 1 , 0 , 0 , 0 , 0 ) ) ); assertThat( references.get( 6 ) , equalTo( create( 2015 , 11 , 1 , 0 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesYears1() { //test years: straightforward, 50 years interval over 10 year period, //but does not start on perfect multiple of time period //Start: Sat Nov 22 11:30:00 EST 2014 //End: Mon Dec 29 11:30:00 EST 2064 Timestamp start = create( 2014 , 11 , 22 , 11 , 30 , 0 , 500 ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( 24*366*50 ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( YEAR , 10 ) ); assertThat( references.size() , equalTo( 5 ) ); assertThat( references.get( 0 ) , equalTo( create(2020 , 1 , TimeScales.FIRST_DAY , TimeScales.FIRST_HOUR , 0 , 0 , 0 ) ) ); assertThat( references.get( 1 ) , equalTo( create(2030 , 1 , TimeScales.FIRST_DAY , TimeScales.FIRST_HOUR , 0 , 0 , 0 ) ) ); assertThat( references.get( 2 ) , equalTo( create(2040 , 1 , TimeScales.FIRST_DAY , TimeScales.FIRST_HOUR , 0 , 0 , 0 ) ) ); assertThat( references.get( 3 ) , equalTo( create(2050 , 1 , TimeScales.FIRST_DAY , TimeScales.FIRST_HOUR , 0 , 0 , 0 ) ) ); assertThat( references.get( 4 ) , equalTo( create(2060 , 1 , TimeScales.FIRST_DAY , TimeScales.FIRST_HOUR , 0 , 0 , 0 ) ) ); } @Test @Ignore //What's the maximum bound on years? public void createReferencesOverflow() { //test trying to overflow years GregorianCalendar cal = new GregorianCalendar( 2014 , 10 , 22 , 11 , 30 , 0 ); cal.set( GregorianCalendar.MILLISECOND , 0 ); Timestamp start = Timestamp.of( cal.getTime() ); long hours = 24l * 366l * 999999999l; System.out.println( hours ); TimeInterval timeInterval = TimeInterval.between( start , start.plus( TimeDuration.ofHours( hours ) ) ); List<Timestamp> references = TimeScales.createReferences( timeInterval , new TimePeriod( YEAR , 999999999l ) ); System.out.println( new TimePeriod( YEAR , 999999999l ) ); System.out.println( TimeDuration.ofHours( hours ) ); System.out.println( hours + " " + Double.valueOf( hours ).doubleValue() ); assertThat( references.size() , equalTo(1) ); assertThat( references.get( 0 ) , equalTo( create( 2014+999999999 , 11 , 22 , 11 , 0 , 0 , 0 ) ) ); } @Test public void createReferencesStructureTest1() { //test the structure of the createReferences() method //case 1: while (endCal.compareTo(cal) >= 0) exectures and //if (timeInterval.contains(newTime)) executes. //this is achieved in a prior test case: createReferencesSeconds1(); } @Test public void createReferencesStructureTest2() { //test the structure of the createReferences() method //case 2: while (endCal.compareTo(cal) >= 0) does not execute //this is acheived in a prior test case: createReferencesEmpty3(); } @Test public void createLabels1() { List<String> labels = TimeScales.createLabels(Arrays.asList(create(2013,03,12,1,30,15,123), create(2013,03,12,1,30,16,123), create(2013,03,12,1,30,17,123))); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:15.123000000", "2013/03/12 01:30:16.123000000", "2013/03/12 01:30:17.123000000"))); } @Test public void trimLabelsRight1() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:15.123000000", "2013/03/12 01:30:16.123000000", "2013/03/12 01:30:17.123000000")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:15.123", "2013/03/12 01:30:16.123", "2013/03/12 01:30:17.123"))); } @Test public void trimLabelsRight2() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:15.123456789", "2013/03/12 01:30:16.123456790", "2013/03/12 01:30:17.123456791")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:15.123456789", "2013/03/12 01:30:16.123456790", "2013/03/12 01:30:17.123456791"))); } @Test public void trimLabelsRight3() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:15.123000000", "2013/03/12 01:30:16.123100000", "2013/03/12 01:30:17.123200000")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:15.1230", "2013/03/12 01:30:16.1231", "2013/03/12 01:30:17.1232"))); } @Test public void trimLabelsRight4() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:15.100000000", "2013/03/12 01:30:16.200000000", "2013/03/12 01:30:17.300000000")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:15.1", "2013/03/12 01:30:16.2", "2013/03/12 01:30:17.3"))); } @Test public void trimLabelsRight5() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:15.000000000", "2013/03/12 01:30:16.000000000", "2013/03/12 01:30:17.000000000")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:15", "2013/03/12 01:30:16", "2013/03/12 01:30:17"))); } @Test public void trimLabelsRight6() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:00.000000000", "2013/03/12 01:30:10.000000000", "2013/03/12 01:30:20.000000000")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30:00", "2013/03/12 01:30:10", "2013/03/12 01:30:20"))); } @Test public void trimLabelsRightRight7() { List<String> labels = TimeScales.trimLabelsRight(Arrays.asList("2013/03/12 01:30:00.000000000", "2013/03/12 01:31:00.000000000", "2013/03/12 01:32:00.000000000")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30", "2013/03/12 01:31", "2013/03/12 01:32"))); } @Test public void trimLabelsRightLeft1() { List<String> labels = TimeScales.trimLabelsLeft(Arrays.asList("2013/03/12 01:30", "2013/03/12 01:31", "2013/03/12 01:32")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 01:30", "01:31", "01:32"))); } @Test public void trimLabelsRightLeft2() { List<String> labels = TimeScales.trimLabelsLeft(Arrays.asList("2013/03/12 00:00", "2013/03/12 12:00", "2013/03/13 00:00")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 00:00", "12:00", "2013/03/13 00:00"))); } @Test public void trimLabelsRightLeft3() { List<String> labels = TimeScales.trimLabelsLeft(Arrays.asList("2013/03/12 00:00:00.9", "2013/03/12 00:00:01.0", "2013/03/12 00:00:01.1")); assertThat(labels, equalTo(Arrays.asList("2013/03/12 00:00:00.9", "00:00:01.0", ".1"))); } @Test public void trimLabels1() { //Tests just 1 label. Since there is only 1 label, there should not //be any common parts, and the entire thing should be displayed List< String > input = Arrays.asList( "2014/11/26 09:50:00.000000000" ); List< String > expected = Arrays.asList( "2014/11/26 09:50" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsMinutes1() { //Test when the unique parts are in the middle of the labels. //In this case, the hours and minutes should be displayed. Although //the hour is common to all labels, it is meaningless to display //just the minutes as 1, 2, 3, 4, ... List< String > input = Arrays.asList( "2014/11/26 09:01:00.000000000" , "2014/11/26 09:02:00.000000000" , "2014/11/26 09:03:00.000000000" , "2014/11/26 09:04:00.000000000" , "2014/11/26 09:05:00.000000000" ); List< String > expected = Arrays.asList( "2014/11/26 09:01" , "9:02" , "9:03" , "9:04" , "9:05" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsMinutes2() { //Test when the unique parts are in the middle of the labels. //and the tenths place of the minute is changing List< String > input = Arrays.asList( "2014/11/26 09:17:00.000000000" , "2014/11/26 09:18:00.000000000" , "2014/11/26 09:19:00.000000000" , "2014/11/26 09:20:00.000000000" , "2014/11/26 09:21:00.000000000" ); List< String > expected = Arrays.asList( "2014/11/26 09:17" , "9:18" , "9:19" , "9:20" , "9:21" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsDays1() { //Test when the unique parts are at the front of the labels. //Although the month is common to all the labels, it would be //meaningless to just display days as 5, 6, 7, 8, 9. //The days need the month in order to be meaningful List< String > input = Arrays.asList( "2014/11/05 00:00:00.000000000" , "2014/11/06 00:00:00.000000000" , "2014/11/07 00:00:00.000000000" , "2014/11/08 00:00:00.000000000" , "2014/11/09 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/11/05" , "11/06" , "11/07" , "11/08" , "11/09" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsDays2() { //Test when the unique parts are at the front of the labels. //Although the month is common to all the labels, it would be //meaningless to just display days as 7, 8, 9, 10, 11. //The days need the month in order to be meaningful. List< String > input = Arrays.asList( "2014/11/07 00:00:00.000000000" , "2014/11/08 00:00:00.000000000" , "2014/11/09 00:00:00.000000000" , "2014/11/10 00:00:00.000000000" , "2014/11/11 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/11/07" , "11/08" , "11/09" , "11/10" , "11/11" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsDays3() { //Test when the unique parts are at the front of the labels. //In this case, it is the month that is changing List< String > input = Arrays.asList( "2014/05/11 00:00:00.000000000" , "2014/06/11 00:00:00.000000000" , "2014/07/11 00:00:00.000000000" , "2014/08/11 00:00:00.000000000" , "2014/09/11 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/05/11" , "06/11" , "07/11" , "08/11" , "09/11" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsDays4() { //Test when the unique parts are at the front of the labels. //Here, the days wrap around to the next month List< String > input = Arrays.asList( "2014/11/28 00:00:00.000000000" , "2014/11/29 00:00:00.000000000" , "2014/11/30 00:00:00.000000000" , "2014/12/01 00:00:00.000000000" , "2014/12/02 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/11/28" , "11/29" , "11/30" , "12/01" , "12/02" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsDays5() { //Test when the unique parts are at the front of the labels. //Here, the days wrap around to the next year. Although the year //is not common to all the labels, it would be redundant to display //2014/12/28 then followed by 2014/12/29; however, it would be necesary //to show that the year has become 2015 on 2015/01/01 List< String > input = Arrays.asList( "2014/12/28 00:00:00.000000000" , "2014/12/29 00:00:00.000000000" , "2014/12/30 00:00:00.000000000" , "2014/12/31 00:00:00.000000000" , "2015/01/01 00:00:00.000000000" , "2015/01/02 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/12/28" , "12/29" , "12/30" , "12/31" , "2015/01/01" , "2015/01/02" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsMonths1() { //Test when the unique parts are at the front of the labels. //Here, the months are changing, but nothing else. Since it would be //meaningless to just display 05, 06, 07, 08, 09, 10, because it would //not be clear whether these are seconds, days, months, etc., //the year is also necessary to clarify List< String > input = Arrays.asList( "2014/05/01 00:00:00.000000000" , "2014/06/01 00:00:00.000000000" , "2014/07/01 00:00:00.000000000" , "2014/08/01 00:00:00.000000000" , "2014/09/01 00:00:00.000000000" , "2014/10/01 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/05" , "2014/06" , "2014/07" , "2014/08" , "2014/09" , "2014/10" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsMonths2() { //Test when the unique parts are at the front of the labels. //Here, the months are changing, but they wrap around to the next year List< String > input = Arrays.asList( "2014/09/01 00:00:00.000000000" , "2014/10/01 00:00:00.000000000" , "2014/11/01 00:00:00.000000000" , "2014/12/01 00:00:00.000000000" , "2015/01/01 00:00:00.000000000" , "2015/02/01 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014/09" , "2014/10" , "2014/11" , "2014/12" , "2015/01" , "2015/02" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } @Test public void trimLabelsYears1() { //Test when just the years are changing List< String > input = Arrays.asList( "2014/01/01 00:00:00.000000000" , "2015/01/01 00:00:00.000000000" , "2016/01/01 00:00:00.000000000" , "2017/01/01 00:00:00.000000000" , "2018/01/01 00:00:00.000000000" , "2019/01/01 00:00:00.000000000" ); List< String > expected = Arrays.asList( "2014" , "2015" , "2016" , "2017" , "2018" , "2019" ); List< String > found = TimeScales.trimLabels( input ); assertThat( found , equalTo( expected ) ); } static String toDateString( int year , int month , int day , int hour , int minute , int second , int nanosecond ) { String yearText = createNumericalString( year , 4 ); String monthText = createNumericalString( month , 2 ); String dayText = createNumericalString( day , 2 ); String hourText = createNumericalString( hour , 2 ); String minuteText = createNumericalString( minute , 2 ); String secondText = createNumericalString( second , 2 ); String nanosecondText = createNumericalString( nanosecond , 9 ); return yearText + "/" + monthText + "/" + dayText + " " + hourText + ":" + minuteText + ":" + secondText + "." + nanosecondText; } /** * Creates a string from an integer value that has at least the * specified length. The integer is padded with 0s to ensure the * specified length. * * @param value the value to convert to a string * @param minLength the minimum length the string must have * @return the given value as a string with length at least the specified * minimum */ static String createNumericalString( int value , int minLength ) { String rtn = String.valueOf( value ); while( rtn.length() < minLength ) { rtn = "0" + rtn; } return rtn; } static Timestamp create(int year, int month, int day, int hour, int minute, int second, int millisecond) { GregorianCalendar cal = new GregorianCalendar(year, month - 1, day, hour, minute, second); cal.set(GregorianCalendar.MILLISECOND, millisecond); return Timestamp.of(cal.getTime()); } /** * Creates the timestamp corresponding to the given time in GMT, * but with the specified timezone. If you wish to use times in * your own timezone, you must add or subtract the GMT difference * to your day and hours parameter. * * @param year * @param month * @param day * @param hour * @param minute * @param second * @param millisecond * @param timezone * @return */ static Timestamp create(int year , int month , int day , int hour , int minute , int second , int millisecond , String timezone ) { GregorianCalendar cal = new GregorianCalendar( TimeZone.getTimeZone( timezone ) ); cal.set( YEAR , year ); cal.set( MONTH , month-1 ); cal.set( GregorianCalendar.DAY_OF_MONTH , day ); cal.set( HOUR_OF_DAY , hour ); cal.get( HOUR_OF_DAY ); cal.set( MINUTE , minute ); cal.set( SECOND , second ); cal.set( MILLISECOND , millisecond ); return Timestamp.of( cal.getTime() ); }
package msf; import java.util.*; import java.sql.*; import java.io.*; import graph.Route; /* implement the old MSF RPC database calls in a way Armitage likes */ public class DatabaseImpl implements RpcConnection { protected Connection db; protected Map queries; protected String workspaceid = "0"; protected String hFilter = null; protected String sFilter = null; protected String[] lFilter = null; protected Route[] rFilter = null; protected String[] oFilter = null; protected int hindex = 0; protected int sindex = 0; /* keep track of labels associated with each host */ protected Map labels = new HashMap(); /* define the maximum hosts in a workspace */ protected int maxhosts = 512; /* define the maximum services in a workspace */ protected int maxservices = 512 * 24; public void resetHostsIndex() { hindex = 0; queries = build(); } public void resetServicesIndex() { sindex = 0; queries = build(); } public void nextHostsIndex() { hindex += 1; queries = build(); } public void nextServicesIndex() { sindex += 1; queries = build(); } private static String join(List items, String delim) { StringBuffer result = new StringBuffer(); Iterator i = items.iterator(); while (i.hasNext()) { result.append(i.next()); if (i.hasNext()) { result.append(delim); } } return result.toString(); } public void setWorkspace(String name) { try { List spaces = executeQuery("SELECT DISTINCT * FROM workspaces"); Iterator i = spaces.iterator(); while (i.hasNext()) { Map temp = (Map)i.next(); if (name.equals(temp.get("name"))) { workspaceid = temp.get("id") + ""; queries = build(); } } } catch (Exception ex) { throw new RuntimeException(ex); } } public void setDebug(boolean d) { } public DatabaseImpl() { queries = build(); } private static long tzfix = 0; static { Calendar now = Calendar.getInstance(); tzfix = now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET); } /* marshall the type into something we'd rather deal with */ protected Object fixResult(Object o) { if (o instanceof java.sql.Timestamp) { return new Long( ((Timestamp)o).getTime() + tzfix ); } else if (o instanceof org.postgresql.util.PGobject) { return o.toString(); } return o; } protected int executeUpdate(String query) throws Exception { Statement s = db.createStatement(); return s.executeUpdate(query); } /* execute the query and return a linked list of the results..., whee?!? */ protected List executeQuery(String query) throws Exception { List results = new LinkedList(); Statement s = db.createStatement(); ResultSet r = s.executeQuery(query); while (r.next()) { Map row = new HashMap(); ResultSetMetaData m = r.getMetaData(); int c = m.getColumnCount(); for (int i = 1; i <= c; i++) { row.put(m.getColumnLabel(i), fixResult(r.getObject(i))); } results.add(row); } return results; } private boolean checkRoute(String address) { for (int x = 0; x < rFilter.length; x++) { if (rFilter[x].shouldRoute(address)) return true; } return false; } private boolean checkLabel(String host) { if (!labels.containsKey(host)) return false; String label_l = (labels.get(host) + "").toLowerCase(); for (int x = 0; x < lFilter.length; x++) { if (label_l.indexOf(lFilter[x]) != -1) { return true; } } return false; } private boolean checkOS(String os) { String os_l = os.toLowerCase(); for (int x = 0; x < oFilter.length; x++) { if (os_l.indexOf(oFilter[x]) != -1) return true; } return false; } protected void loadLabels() { try { /* query database for label data */ List rows = executeQuery("SELECT DISTINCT data FROM notes WHERE ntype = 'armitage.labels'"); if (rows.size() == 0) return; /* extract our BASE64 encoded data */ String data = ((Map)rows.get(0)).get("data") + ""; System.err.println("Read: " + data.length() + " bytes"); /* turn our data into raw data */ byte[] raw = Base64.decode(data); /* deserialize our notes data */ ByteArrayInputStream store = new ByteArrayInputStream(raw); ObjectInputStream handle = new ObjectInputStream(store); Map temp = (Map)(handle.readObject()); handle.close(); store.close(); /* merge with our new map */ labels.putAll(temp); } catch (Exception ex) { ex.printStackTrace(); } } protected void mergeLabels(Map l) { /* accept any label values and merge them into our global data set */ Iterator i = l.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); if ("".equals(entry.getValue())) { labels.remove(entry.getKey() + ""); } else { labels.put(entry.getKey() + "", entry.getValue() + ""); } } } /* add labels to our hosts */ public List addLabels(List rows) { if (labels.size() == 0) return rows; Iterator i = rows.iterator(); while (i.hasNext()) { Map entry = (Map)i.next(); String address = (entry.containsKey("address") ? entry.get("address") : entry.get("host")) + ""; if (labels.containsKey(address)) { entry.put("label", labels.get(address) + ""); } else { entry.put("label", ""); } } return rows; } public List filterByRoute(List rows, int max) { if (rFilter != null || oFilter != null || lFilter != null) { Iterator i = rows.iterator(); while (i.hasNext()) { Map entry = (Map)i.next(); /* make sure the address is within a route we care about */ if (rFilter != null && entry.containsKey("address")) { if (!checkRoute(entry.get("address") + "")) { i.remove(); continue; } } else if (rFilter != null && entry.containsKey("host")) { if (!checkRoute(entry.get("host") + "")) { i.remove(); continue; } } /* make sure the host is something we care about too */ if (oFilter != null && entry.containsKey("os_name")) { if (!checkOS(entry.get("os_name") + "")) { i.remove(); continue; } } /* make sure the host has the right label */ if (lFilter != null && entry.containsKey("address")) { if (!checkLabel(entry.get("address") + "")) { i.remove(); continue; } } else if (lFilter != null && entry.containsKey("host")) { if (!checkLabel(entry.get("host") + "")) { i.remove(); continue; } } } if (rows.size() > max) { rows.subList(max, rows.size()).clear(); } } return rows; } public void connect(String dbstring, String user, String password) throws Exception { db = DriverManager.getConnection(dbstring, user, password); setWorkspace("default"); loadLabels(); } public Object execute(String methodName) throws IOException { return execute(methodName, new Object[0]); } protected Map build() { Map temp = new HashMap(); /* this is an optimization. If we have a network or OS filter, we need to pull back all host/service records and filter them here. If we do not have these types of filters, then we can let the database do the heavy lifting and limit the size of the final result there. */ int limit1 = rFilter == null && oFilter == null && lFilter == null ? maxhosts : 30000; int limit2 = rFilter == null && oFilter == null && lFilter == null ? maxservices : 100000; temp.put("db.creds", "SELECT DISTINCT creds.*, hosts.address as host, services.name as sname, services.port as port, services.proto as proto FROM creds, services, hosts WHERE services.id = creds.service_id AND hosts.id = services.host_id AND hosts.workspace_id = " + workspaceid); /* db.creds2 exists to prevent duplicate entries for the stuff I care about */ temp.put("db.creds2", "SELECT DISTINCT creds.user, creds.pass, hosts.address as host, services.name as sname, services.port as port, services.proto as proto, creds.ptype FROM creds, services, hosts WHERE services.id = creds.service_id AND hosts.id = services.host_id AND hosts.workspace_id = " + workspaceid); if (hFilter != null) { List tables = new LinkedList(); tables.add("hosts"); if (hFilter.indexOf("services.") >= 0) tables.add("services"); if (hFilter.indexOf("sessions.") >= 0) tables.add("sessions"); temp.put("db.hosts", "SELECT DISTINCT hosts.* FROM " + join(tables, ", ") + " WHERE hosts.workspace_id = " + workspaceid + " AND " + hFilter + " ORDER BY hosts.id ASC LIMIT " + limit1 + " OFFSET " + (limit1 * hindex)); } else { temp.put("db.hosts", "SELECT DISTINCT hosts.* FROM hosts WHERE hosts.workspace_id = " + workspaceid + " ORDER BY hosts.id ASC LIMIT " + limit1 + " OFFSET " + (hindex * limit1)); } temp.put("db.services", "SELECT DISTINCT services.*, hosts.address as host FROM services, (" + temp.get("db.hosts") + ") as hosts WHERE hosts.id = services.host_id AND services.state = 'open' ORDER BY services.id ASC LIMIT " + limit2 + " OFFSET " + (limit2 * sindex)); temp.put("db.loots", "SELECT DISTINCT loots.*, hosts.address as host FROM loots, hosts WHERE hosts.id = loots.host_id AND hosts.workspace_id = " + workspaceid); temp.put("db.workspaces", "SELECT DISTINCT * FROM workspaces"); temp.put("db.notes", "SELECT DISTINCT notes.*, hosts.address as host FROM notes, hosts WHERE hosts.id = notes.host_id AND hosts.workspace_id = " + workspaceid); temp.put("db.clients", "SELECT DISTINCT clients.*, hosts.address as host FROM clients, hosts WHERE hosts.id = clients.host_id AND hosts.workspace_id = " + workspaceid); temp.put("db.sessions", "SELECT DISTINCT sessions.*, hosts.address as host FROM sessions, hosts WHERE hosts.id = sessions.host_id AND hosts.workspace_id = " + workspaceid); temp.put("db.events", "SELECT DISTINCT id, username, info, created_at FROM events WHERE events.name = 'armitage.event' ORDER BY id ASC"); return temp; } public Object execute(String methodName, Object[] params) throws IOException { try { if (queries.containsKey(methodName)) { String query = queries.get(methodName) + ""; Map result = new HashMap(); if (methodName.equals("db.services")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), maxservices)); } else if (methodName.equals("db.hosts")) { result.put(methodName.substring(3), addLabels(filterByRoute(executeQuery(query), maxhosts))); } else { result.put(methodName.substring(3), executeQuery(query)); } return result; } else if (methodName.equals("db.vulns")) { //List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto FROM vulns, hosts, services WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id"); //List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host FROM vulns, hosts WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL"); List a = executeQuery("SELECT DISTINCT vulns.*, vulns.id as vid, hosts.address as host, services.port as port, services.proto as proto, refs.name as refs FROM vulns, hosts, services, vulns_refs, refs WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); List b = executeQuery("SELECT DISTINCT vulns.*, vulns.id as vid, hosts.address as host, refs.name as refs FROM vulns, hosts, refs, vulns_refs WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); a.addAll(b); Map result = new HashMap(); result.put("vulns", a); return result; } else if (methodName.equals("db.log_event")) { PreparedStatement stmt = null; stmt = db.prepareStatement("INSERT INTO events (name, username, info, created_at) VALUES ('armitage.event', ?, ?, now() AT TIME ZONE 'GMT')"); stmt.setString(1, params[0] + ""); stmt.setString(2, params[1] + ""); stmt.executeUpdate(); return new HashMap(); } else if (methodName.equals("db.key_add")) { PreparedStatement stmt = null; stmt = db.prepareStatement("INSERT INTO notes (ntype, data) VALUES (?, ?)"); stmt.setString(1, params[0] + ""); stmt.setString(2, params[1] + ""); stmt.executeUpdate(); return new HashMap(); } else if (methodName.equals("db.key_delete")) { PreparedStatement stmt = null; stmt = db.prepareStatement("DELETE FROM notes WHERE id = ?"); stmt.setString(1, params[0] + ""); stmt.executeUpdate(); return new HashMap(); } else if (methodName.equals("db.key_clear")) { PreparedStatement stmt = null; stmt = db.prepareStatement("DELETE FROM notes WHERE ntype = ?"); stmt.setString(1, params[0] + ""); stmt.executeUpdate(); return new HashMap(); } else if (methodName.equals("db.key_values")) { Map results = new HashMap(); String key = params[0] + ""; if (!key.matches("[0-9a-zA-Z\\._]+")) { System.err.println("Key '" + key + "' did not validate!"); return new HashMap(); } results.put("values", executeQuery("SELECT DISTINCT * FROM notes WHERE ntype = '" + key + "' ORDER BY id ASC")); return results; } else if (methodName.equals("db.clear_cache")) { /* force a clear of the module cache */ executeUpdate( "BEGIN;" + "DELETE FROM module_details;" + "DELETE FROM module_details;" + "DELETE FROM module_targets;" + "DELETE FROM module_authors;" + "DELETE FROM module_actions;" + "DELETE FROM module_mixins;" + "DELETE FROM module_platforms;" + "DELETE FROM module_archs;" + "DELETE FROM module_refs;" + "COMMIT"); return new HashMap(); } else if (methodName.equals("db.clear")) { executeUpdate( "BEGIN;" + "DELETE FROM hosts;" + "DELETE FROM services;" + "DELETE FROM events;" + "DELETE FROM notes;" + "DELETE FROM creds;" + "DELETE FROM loots;" + "DELETE FROM vulns;" + "DELETE FROM sessions;" + "DELETE FROM clients;" + "COMMIT"); return new HashMap(); } else if (methodName.equals("db.filter")) { /* I'd totally do parameterized queries if I wasn't building this damned query dynamically. Hence it'll have to do. */ Map values = (Map)params[0]; rFilter = null; oFilter = null; lFilter = null; List hosts = new LinkedList(); List srvcs = new LinkedList(); if ((values.get("session") + "").equals("1")) { hosts.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL AND sessions.close_reason IS NULL"); //srvcs.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL"); } if (values.containsKey("size")) { try { maxhosts = Integer.parseInt(values.get("size") + ""); maxservices = maxhosts * 24; } catch (Exception ex) { } } if (values.containsKey("hosts") && (values.get("hosts") + "").length() > 0) { String h = values.get("hosts") + ""; if (!h.matches("[0-9a-fA-F\\.:\\%\\_/, ]+")) { System.err.println("Host value did not validate!"); return new HashMap(); } String[] routes = h.split(",\\s*"); rFilter = new Route[routes.length]; for (int x = 0; x < routes.length; x++) { rFilter[x] = new Route(routes[x]); } } if (values.containsKey("ports") && (values.get("ports") + "").length() > 0) { List ports = new LinkedList(); List ports2 = new LinkedList(); String[] p = (values.get("ports") + "").split(",\\s*"); for (int x = 0; x < p.length; x++) { if (!p[x].matches("[0-9]+")) { return new HashMap(); } ports.add("services.port = " + p[x]); //ports2.add("s.port = " + p[x]); } hosts.add("services.host_id = hosts.id"); hosts.add("services.state = 'open'"); hosts.add("(" + join(ports, " OR ") + ")"); } if (values.containsKey("os") && (values.get("os") + "").length() > 0) { oFilter = (values.get("os") + "").toLowerCase().split(",\\s*"); } /* label filter */ if (values.containsKey("labels") && (values.get("labels") + "").length() > 0) { lFilter = (values.get("labels") + "").toLowerCase().split(",\\s*"); } if (hosts.size() == 0) { hFilter = null; } else { hFilter = join(hosts, " AND "); } queries = build(); return new HashMap(); } else if (methodName.equals("db.fix_creds")) { Map values = (Map)params[0]; PreparedStatement stmt = null; stmt = db.prepareStatement("UPDATE creds SET ptype = 'smb_hash' WHERE creds.user = ? AND creds.pass = ?"); stmt.setString(1, values.get("user") + ""); stmt.setString(2, values.get("pass") + ""); Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else if (methodName.equals("db.report_labels")) { /* merge out global label data */ Map values = (Map)params[0]; mergeLabels(values); /* delete our saved label data */ executeUpdate("DELETE FROM notes WHERE notes.ntype = 'armitage.labels'"); /* serialize our notes data */ ByteArrayOutputStream store = new ByteArrayOutputStream(labels.size() * 128); ObjectOutputStream handle = new ObjectOutputStream(store); handle.writeObject(labels); handle.close(); store.close(); String data = Base64.encode(store.toByteArray()); /* save our label data */ PreparedStatement stmt = null; stmt = db.prepareStatement("INSERT INTO notes (ntype, data) VALUES ('armitage.labels', ?)"); stmt.setString(1, data); stmt.executeUpdate(); return new HashMap(); } else if (methodName.equals("db.report_host")) { Map values = (Map)params[0]; String host = values.get("host") + ""; PreparedStatement stmt = null; /* before we change this hosts info, kill its notes. We do this so future normalized data isn't ignored */ executeUpdate("DELETE FROM notes WHERE EXISTS (SELECT id, address FROM hosts WHERE notes.host_id = id AND address = '" + host + "'::text::inet AND workspace_id = " + workspaceid + ")"); if (values.containsKey("os_name") && values.containsKey("os_flavor")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = ?, os_sp = '' WHERE hosts.address = ?::text::inet AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, values.get("os_flavor") + ""); stmt.setString(3, host); } else if (values.containsKey("os_name")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = '', os_sp = '' WHERE hosts.address = ?::text::inet AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, host); } else if (values.containsKey("purpose")) { stmt = db.prepareStatement("UPDATE hosts SET purpose = ? WHERE hosts.address = ?::text::inet AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("purpose") + ""); stmt.setString(2, host); } else { return new HashMap(); } Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else { System.err.println("Need to implement: " + methodName); } } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return new HashMap(); } }
package explorviz.visualization.timeshift; import java.util.Map; import java.util.Map.Entry; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; public class TimeShiftJS { public static native void init() /*-{ var firstDataDone = false; Date.prototype.ddhhmmss = function() { var weekday = new Array(7); weekday[0] = "Su"; weekday[1] = "Mo"; weekday[2] = "Tu"; weekday[3] = "We"; weekday[4] = "Th"; weekday[5] = "Fr"; weekday[6] = "Sa"; var n = weekday[this.getDay()]; var hh = this.getHours().toString(); var mm = this.getMinutes().toString(); var ss = this.getSeconds().toString(); return n + " " + (hh[1] ? hh : "0" + hh[0]) + ":" + (mm[1] ? mm : "0" + mm[0]) + ":" + (ss[1] ? ss : "0" + ss[0]); }; var currentTime = new Date(1463499327511).getTime(); var timeshiftChartDiv = $wnd.jQuery("#timeshiftChartDiv"); //$doc.getElementById('timeshiftChartDiv').style.height = '100px'; //$doc.getElementById('timeshiftChartDiv').style.width = '500px'; var dataSet = [ { data : [], label : "Method Calls", color : '#058DC7' } ]; var options = { series : { lines : { show : true, fill : true, fillColor : "rgba(86, 137, 191, 0.8)" }, points : { show : true, radius : 2 }, downsample : { threshold : 0 // 0 disables downsampling for this series. }, shadowSize : 0 }, axisLabels : { show : true }, legend : { show : false }, grid : { hoverable : true, clickable : true }, xaxis : { axisLabel: "Time", mode : "time", timezone : "browser" }, yaxis : { position: 'left', axisLabel: 'Method Calls', tickFormatter: function(x) {return x >= 1000 ? (x/1000)+"k": x;}, ticks : 1, tickDecimals : 0 }, zoom : { interactive : true }, pan : { interactive : true } }; var plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); function addTooltipDiv() { $wnd.jQuery("<div id='timeshiftTooltip'></div>").css({ position : "absolute", display : "none", border : "1px solid #fdd", padding : "2px", "background-color" : "#fee", opacity : 0.80 }).appendTo("#timeshiftChartDiv"); } addTooltipDiv(); $wnd.jQuery("#timeshiftChartDiv").bind("dblclick", onDblclick); $wnd.jQuery("#timeshiftChartDiv").bind("plotzoom", onZoom); $wnd.jQuery("#timeshiftChartDiv").bind("plothover", onHover); $wnd.jQuery("#timeshiftChartDiv").bind("plotclick", onPointSelection); function onPointSelection(event, pos, item) { if (item) { console.log(item); @explorviz.visualization.landscapeexchange.LandscapeExchangeManager::stopAutomaticExchange(Ljava/lang/String;)(item.datapoint[0].toString()); @explorviz.visualization.interaction.Usertracking::trackFetchedSpecifcLandscape(Ljava/lang/String;)(item.datapoint[0].toString()); @explorviz.visualization.landscapeexchange.LandscapeExchangeManager::fetchSpecificLandscape(Ljava/lang/String;)(item.datapoint[0].toString()); } } function onDblclick() { options.xaxis.min = dataSet[0].data[0][0]; options.xaxis.max = dataSet[0].data[dataSet[0].data.length - 1][0]; plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); addTooltipDiv(); } function onHover(event, pos, item) { if (item) { var x = item.datapoint[0]; var y = item.datapoint[1]; // view-div offset var offset = $wnd.jQuery("#view").offset().top; // timechart-div offset offset += $wnd.jQuery("#timeshiftChartDiv").position().top; showTooltip(item.pageX + 15, (item.pageY - offset), "Method Calls: " + y); } else { $wnd.jQuery("#timeshiftTooltip").hide(); } } function onZoom() { console.log("zooming"); } function showTooltip(x, y, contents) { $wnd.jQuery("#timeshiftTooltip").html(contents).css({ top : y, left : x }).fadeIn(200); } //var cnt = 0; // // function update() { // options.xaxis.min = sampleData[cnt][0]; // //options.xaxis.max = sampleData[sampleData.length - 1][0]; // options.xaxis.max = sampleData[cnt + 30][0]; // cnt += 31; // //plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); // setTimeout(update, 2000); // } // //update(); $wnd.jQuery.fn.updateTimeshiftChart = function(data) { var values = data[0].values; var convertedValues = values.map(function(o) { return [ o.x, o.y ]; }); var dataLength = convertedValues.length; var newXMin = convertedValues[0][0]; var newXMax = convertedValues[dataLength - 1][0]; var oldXMin = firstDataDone ? dataSet[0].data[0][0] : newXMin; var newYMax = Math.max.apply(Math, convertedValues.map(function(o) { return o[1]; })); if (!firstDataDone) firstDataDone = true options.xaxis.min = newXMin; options.xaxis.max = newXMax; options.xaxis.panRange = [ oldXMin, newXMax ]; options.yaxis.panRange = [ 0, newYMax ]; options.yaxis.zoomRange = [ newYMax, newYMax ]; options.yaxis.max = newYMax; var innerWidth = $wnd.innerWidth; var dataPointPixelRatio = 17; options.series.downsample.threshold = parseInt(innerWidth / dataPointPixelRatio); dataSet[0].data = dataSet[0].data.concat(convertedValues); plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options); addTooltipDiv(); } }-*/; public static void updateTimeshiftChart(final Map<Long, Long> data) { final JavaScriptObject jsObj = convertToJSHashMap(data); nativeUpdateTimeshiftChart(jsObj); } private static JavaScriptObject convertToJSHashMap(final Map<Long, Long> data) { final JSONObject obj = new JSONObject(); for (final Entry<Long, Long> entry : data.entrySet()) { obj.put(entry.getKey().toString(), new JSONString(entry.getValue().toString())); } final JavaScriptObject jsObj = obj.getJavaScriptObject(); return jsObj; } public static native void nativeUpdateTimeshiftChart(JavaScriptObject jsObj) /*-{ var keys = Object.keys(jsObj); var series1 = []; keys.forEach(function(entry) { series1.push({ x : Number(entry), y : Number(jsObj[entry]) }); }) // $wnd.jQuery(this).updatettimeline([ { // key : "Timeseries", // values : series1, // color : "#366eff", // area : true // } ]); $wnd.jQuery(this).updateTimeshiftChart([ { key : "Timeseries", values : series1, color : "#366eff", area : true } ]); }-*/; }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jibble.pircbot.PircBot; import uk.co.uwcs.choob.modules.Modules; import uk.co.uwcs.choob.support.IRCInterface; import uk.co.uwcs.choob.support.events.*; public class Where { Modules mods; IRCInterface irc; //ignore hosts people screen from that we can't finger. //hardcoding ftw. private final static String[] IGNORED_HOSTS = { //raw "137.205.210.18/32", "raw.sunion.warwick.ac.uk/.*" }; private final String channels[] = { "#compsoc", "#wuglug", "#bots", "#wug", "#choob" }; private enum Location { Campus, DCS }; abstract class Callback { Callback(ContextEvent con) { target = con; } final ContextEvent target; abstract void complete(Details d); } Callback fromPredicate(ContextEvent con, final Predicate p, final String msg) { return new Callback(con) { void complete(Details d) { List<String> hitted = new ArrayList<String>(); for (Entry<String, Set<InetAddress>> entr : d.users.entrySet()) for (InetAddress add : entr.getValue()) if (p.hit(add)) hitted.add(entr.getKey()); Collections.sort(hitted); irc.sendContextReply(target, hitted.size() + " " + (hitted.size() == 1 ? "person" : "people") + " (" + hrList(hitted) + ") " + (hitted.size() == 1 ? "is" : "are") + " " + msg + "."); } }; } abstract class Predicate { abstract boolean hit(InetAddress add); } class Details { Details(Callback c) { users = new HashMap<String, Set<InetAddress>>(); callback = c; localmap = buildLocalMap(); } Callback callback; // Username -> addresses Map<String, Set<InetAddress>> localmap; // Nick -> host. Map<String, Set<InetAddress>> users; } // (Target) channel -> Outstanding queries in it. Map<String, Queue<Details>> outst = Collections.synchronizedMap(new HashMap<String, Queue<Details>>()); public Where(Modules mods, IRCInterface irc) { this.irc = irc; this.mods = mods; whatExtract = Pattern.compile("^" + irc.getNickname() + " ([^ ]+) (.*)$"); } final Pattern whatExtract; <T> boolean matches(Pattern p, T o) { return p.matcher(o.toString()).find(); } // InetAddress.getByName doesn't resolve textual ips (to addresses) by default, trigger it (and discard the result) such that toString() returns the hostname. // Note that the reverse lookups are cached (indefinitely) by Java, so that's not duplicated here. private InetAddress getByName(String name) throws UnknownHostException { InetAddress temp = InetAddress.getByName(name); temp.getHostName(); return temp; } // "User", hostname, server, nick, ... final Pattern splitUp = Pattern.compile("^([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) .*"); public void onServerResponse(ServerResponse resp) { // Ensure resp is related to WHO, and remember if we're at the end. I'm sure there's a sane way to write this. final boolean atend = resp.getCode() == PircBot.RPL_ENDOFWHO; if (!(atend || resp.getCode() == PircBot.RPL_WHOREPLY)) return; Matcher ma; if (!(ma = whatExtract.matcher(resp.getResponse())).matches()) return; // Lol whut. final String aboutWhat = ma.group(1); final String tail = ma.group(2); Queue<Details> detst = outst.get(aboutWhat); if (detst == null || detst.isEmpty()) { // The server has sent us a "WHO" line for a channel we don't care about. // Ignoring when it hates us, and we're hitting a RAAAAAAACE CONDITIONS.. // it does this when we asked for a WHO nick. Assume that this is the only one we're going to get. if (!(ma = splitUp.matcher(tail)).matches() || (detst = outst.get(ma.group(4))) == null) // Read the nick. return; // If we wern't looking for this either, just bail. } Details d = detst.peek(); if (d == null) return; // Lol whut. if (atend) { d.callback.complete(d); detst.remove(); } else { if (!(ma = splitUp.matcher(tail)).matches()) return; // Lol whut. try { // D.users is Nick -> Ip. // If the user is local, attempt to hax their real ip. InetAddress toStore = getByName(ma.group(2)); final String nick = ma.group(4); //ignore hosts we can't/don't want to check. if (shouldIgnore(toStore)) return; Set<InetAddress> newones; Set<InetAddress> addto; if ((addto = d.users.get(nick)) == null) d.users.put(nick, addto = new HashSet<InetAddress>()); if (!isLocal(toStore) || (newones = d.localmap.get(ma.group(1))) == null) addto.add(toStore); else addto.addAll(newones); } catch (UnknownHostException e) { // Ignore, abort the put. } } } boolean isLocal(InetAddress add) { return matches(Pattern.compile("^localhost/127"), add) || matches(Pattern.compile("compsoc.sunion.warwick.ac.uk/.*"), add); } boolean shouldIgnore(InetAddress add) { for (String ignoreHost : IGNORED_HOSTS) { if (matches(Pattern.compile(ignoreHost),add)) { return true; } } return false; } boolean isCampus(InetAddress add) { return !isLocal(add) && matches(Pattern.compile("/137.205"), add); } boolean isDCS(InetAddress add) { return matches(Pattern.compile("/137\\.205\\.11"), add); } // Username -> set of addresses. Map<String, Set<InetAddress>> buildLocalMap() { Map<String, Set<InetAddress>> ret = new HashMap<String, Set<InetAddress>>(); try { Process proc = Runtime.getRuntime().exec("/usr/bin/finger"); // There's a nefarious reason why this is here. if (proc.waitFor() != 0) return ret; BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); br.readLine(); // Discard header. String s; Matcher ma; while ((s = br.readLine()) != null) { if ((ma = Pattern.compile("^([^ ]+) .* \\((.*?)(?::S\\.[0-9]+)?\\)$").matcher(s)).matches()) { final String un = ma.group(1); if (ret.get(un) == null) ret.put(un, new HashSet<InetAddress>()); ret.get(un).add(getByName(ma.group(2))); } } } catch (Throwable t) { // Discard: } return ret; // Don't care about part results. } <T> String hrList(List<T> el) { return hrList(el, " and "); } <T> String hrList(List<T> el, String inclusor) { String ret = ""; for (int i=0; i<el.size(); ++i) { ret += el.get(i).toString(); if (i == el.size() - 2) ret += inclusor; else if (i == el.size() - 1) ret += ""; else ret += ", "; } return ret; } // mes only for command line. void goDo( Message mes, Callback c ) { String what = mods.util.getParamString(mes).trim().intern(); if (what.length() == 0) what = mes.getContext(); goDo(what, c); } void goDo( String what, Callback c ) { Queue<Details> d = outst.get(what); if (d == null) d = new LinkedList<Details>(); d.add(new Details(c)); outst.put(what, d); irc.sendRawLine("WHO " + what); } public void commandDebug(Message mes) { goDo(mes, new Callback(mes) { public void complete(Details d) { List<String> unres = new ArrayList<String>(), wcampus = new ArrayList<String>(); for (Entry<String, Set<InetAddress>> entr : d.users.entrySet()) for (InetAddress add : entr.getValue()) if (isCampus(add)) wcampus.add(entr.getKey()); else if (isLocal(add)) unres.add(entr.getKey()); else System.out.println(add.toString()); irc.sendContextReply(target, "Found " + d.users.size() + " people, " + wcampus.size() + " are on campus (" + hrList(wcampus) + "), " + hrList(unres) + " are unresolvable."); } } ); } private void hint(Message mes) { if ((!(mes instanceof ChannelMessage)) && (mods.util.getParams(mes,2).size() < 2)) irc.sendContextReply(mes,"Hint, try " + mods.util.getParams(mes,2).get(0) + " <ChannelName> for relevant results in PM"); } public String[] helpCommandOnCampus = { "Displays a list of people connected to IRC from IPs in the university of warwick IP range. Also works properly for those using screens on the server on which the plugin is running.", "[<ChannelName>]", "<ChannelName> is the name of the channel to return results for." }; public void commandOnCampus(Message mes) { hint(mes); goDo(mes, fromPredicate(mes, new Predicate() { boolean hit(InetAddress add) { return isCampus(add); } }, "on campus")); } public String[] helpCommandInDCS = { "Displays a list of people connected to IRC from IPs in the university of warwick department of computer science IP range. Also works properly for those using screens on the server on which the plugin is running.", "[<ChannelName>]", "<ChannelName> is the name of the channel to return results for." }; public void commandInDCS(Message mes) { hint(mes); goDo(mes, fromPredicate(mes, new Predicate() { boolean hit(InetAddress add) { return isDCS(add); } }, "in DCS")); } public String[] helpCommandRegex = { "Displays a list of people connected to IRC from IPs matching the specified regex", "<regex> [<ChannelName>]", "<Regex> is the regex to match people's IPs against", "<ChannelName> is the name of the channel to return results for." }; public void commandRegex(Message mes) { Matcher ma = Pattern.compile("^(.+?)((?: [^ ]+)?)$").matcher(mods.util.getParamString(mes).trim()); if (!ma.matches()) { irc.sendContextReply(mes, "Expected: regex [what]"); return; } String what = ma.group(2).trim(); if (what.length() == 0) what = mes.getContext(); final Pattern p = Pattern.compile(ma.group(1)); goDo(what, fromPredicate(mes, new Predicate() { boolean hit(InetAddress add) { return matches(p, add); } }, "matching")); } class MutableInteger { private int value; public MutableInteger(int value) { this.value = value; } public int preDecrement() { return --value; } } public void commandGlobalDCS(Message mes) { global(mes, Location.DCS, "in DCS"); } public void commandGlobalCampus(Message mes) { global(mes, Location.Campus, "on campus"); } public void commandHostname(Message mes) throws UnknownHostException { final List<String> params = mods.util.getParams(mes); String context = mes.getContext(); if (params.size() < 2) { irc.sendContextReply(mes, "Usage: " + params.get(0) + " address [[address...] context]"); return; } params.remove(0); // Command name. if (params.size() >= 2) context = params.remove(params.size()-1); final Set<InetAddress> ipees = new HashSet<InetAddress>(); for (String host : params) ipees.add(InetAddress.getByName(host)); final String finalContext = context; goDo(context, fromPredicate(mes, new Predicate() { boolean hit(InetAddress add) { // Compares the IPs alone, ignoring the host string. for (InetAddress ip : ipees) if (add.equals(ip)) return true; return false; } }, "at the same place as " + hrList(params, " and/or ") + (finalContext.charAt(0) != '#' ? " (Did you really mean to look in " + finalContext + "?)" : ""))); } private void global(Message mes, final Location loc, final String str) { final Set<String> users = new HashSet<String>(); final MutableInteger count = new MutableInteger(channels.length); for (String channel : channels) { goDo(channel, new Callback(mes) { public void complete(Details d) { for (Entry<String, Set<InetAddress>> entr : d.users.entrySet()) { for (InetAddress add : entr.getValue()) { boolean flag = false; switch (loc) { case DCS: flag = isDCS(add); break; case Campus: flag = isCampus(add); break; } if (flag) { users.add(entr.getKey()); } } } synchronized (count) { if (count.preDecrement() == 0) { irc.sendContextReply(target, "Total users " + str + ": " + users.size()); } } } } ); } } }
package org.objectweb.proactive.core; import org.apache.log4j.Logger; import org.objectweb.proactive.annotation.PublicAPI; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * <p> * UniqueID is a unique object identifier across all jvm. It is made of a unique VMID combined * with a unique UID on that VM. * </p><p> * The UniqueID is used to identify object globally, even in case of migration. * </p> * @author The ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * */ @PublicAPI public class UniqueID implements java.io.Serializable, Comparable<UniqueID> { private java.rmi.server.UID id; private java.rmi.dgc.VMID vmID; //the Unique ID of the JVM private static java.rmi.dgc.VMID uniqueVMID = new java.rmi.dgc.VMID(); final protected static Logger logger = ProActiveLogger.getLogger(Loggers.CORE); // Optim private transient String cachedShortString; private transient String cachedCanonString; /** * Creates a new UniqueID */ public UniqueID() { this.id = new java.rmi.server.UID(); this.vmID = uniqueVMID; } /** * Returns the VMID of the current VM in which this class has been loaded. * @return the VMID of the current VM */ public static java.rmi.dgc.VMID getCurrentVMID() { return uniqueVMID; } /** * Returns the VMID of this UniqueID. Note that the VMID of one UniqueID may differ * from the local VMID (that one can get using <code>getCurrentVMID()</code> in case * this UniqueID is attached to an object that has migrated. * @return the VMID part of this UniqueID */ public java.rmi.dgc.VMID getVMID() { return this.vmID; } /** * Returns the UID part of this UniqueID. * @return the UID part of this UniqueID */ public java.rmi.server.UID getUID() { return this.id; } /** * Returns a string representation of this UniqueID. * @return a string representation of this UniqueID */ @Override public String toString() { return getCanonString(); } public String shortString() { // Date-race initialization. Initialization in the ctor is to heavy String s = this.cachedShortString; if (s == null) { s = "" + Math.abs(this.getCanonString().hashCode() % 100000); this.cachedShortString = s; } return s; } public String getCanonString() { // Date-race initialization. Initialization in the ctor is to heavy String s = this.cachedCanonString; if (s == null) { s = ("" + this.id + "--" + this.vmID).replace(':', '-'); this.cachedCanonString = s; } return s; } public int compareTo(UniqueID u) { return getCanonString().compareTo(u.getCanonString()); } /** * Overrides hashCode to take into account the two part of this UniqueID. * @return the hashcode of this object */ @Override public int hashCode() { return this.id.hashCode() + this.vmID.hashCode(); } /** * Overrides equals to take into account the two part of this UniqueID. * @return the true if and only if o is an UniqueID equals to this UniqueID */ @Override public boolean equals(Object o) { //System.out.println("Now checking for equality"); if (o instanceof UniqueID) { return ((this.id.equals(((UniqueID) o).getUID())) && (this.vmID.equals(((UniqueID) o).getVMID()))); } else { return false; } } /** * for debug purpose */ public void echo() { logger.info("UniqueID The Id is " + this.id + " and the address is " + this.vmID); } }
package org.lwjgl.system; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import java.nio.*; import java.util.Arrays; import static org.lwjgl.system.Checks.*; import static org.lwjgl.system.MathUtil.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.Pointer.*; import static org.lwjgl.system.ThreadLocalUtil.*; /** * An off-heap memory stack. * * <p>This class should be used in a thread-local manner for stack allocations.</p> */ public class MemoryStack { private static final int DEFAULT_STACK_SIZE = Configuration.STACK_SIZE.get(32) * 1024; static { if ( DEFAULT_STACK_SIZE < 0 ) throw new IllegalStateException("Invalid stack size."); } private final ByteBuffer buffer; private final long address; private final int size; private int pointer; private int[] frames; private int frameIndex; /** Creates a new {@link MemoryStack} with the default size. */ public MemoryStack() { this(DEFAULT_STACK_SIZE); } /** * Creates a new {@link MemoryStack} with the specified size. * * @param size the maximum number of bytes that may be allocated on the stack */ public MemoryStack(int size) { this.buffer = BufferUtils.createByteBuffer(size); this.address = memAddress(buffer); this.size = size; this.pointer = size; this.frames = new int[16]; } /** Returns the stack of the current thread. */ public static MemoryStack stackGet() { return tlsGet().stack; } /** * Calls {@link #push} on the stack of the current thread. * * @return the stack of the current thread. */ public static MemoryStack stackPush() { return tlsGet().stack.push(); } /** * Calls {@link #pop} on the stack of the current thread. * * @return the stack of the current thread. */ public static MemoryStack stackPop() { return tlsGet().stack.pop(); } /** * Stores the current stack pointer and pushes a new frame to the stack. * * <p>This method should be called when entering a method, before doing any stack allocations. When exiting a method, call the {@link #pop} method to * restore the previous stack frame.</p> * * <p>Pairs of push/pop calls may be nested. Care must be taken to:</p> * <ul> * <li>match every push with a pop</li> * <li>not call pop before push has been called at least once</li> * <li>not nest push calls to more than the maximum supported depth</li> * </ul> * * @return this stack */ public MemoryStack push() { if ( frameIndex == frames.length ) frames = Arrays.copyOf(frames, frames.length * 2); frames[frameIndex++] = pointer; return this; } /** * Pops the current stack frame and moves the stack pointer to the end of the previous stack frame. * * @return this stack */ public MemoryStack pop() { pointer = frames[--frameIndex]; return this; } /** * Returns the address of the backing off-heap memory. * * <p>The stack grows "downwards", so the bottom of the stack is at {@code address + size}, while the top is at {@code address}.</p> */ public long getAddress() { return address; } /** * Returns the size of the backing off-heap memory. * * <p>This is the maximum number of bytes that may be allocated on the stack.</p> */ public int getSize() { return size; } /** * Returns the current frame index. * * <p>This is the current number of nested {@link #push} calls.</p> */ public int getFrameIndex() { return frameIndex; } /** * Returns the current stack pointer. * * <p>The stack grows "downwards", so when the stack is empty {@code pointer} is equal to {@code size}. On every allocation {@code pointer} is reduced by * the allocated size (after alignment) and {@code address + pointers} points to the last byte of the last allocation.</p> * * <p>Effectively, this methods returns how many more bytes may be allocated on the stack.</p> */ public int getPointer() { return pointer; } private static void checkAlignment(int alignment) { if ( !mathIsPoT(alignment) ) throw new IllegalArgumentException("Alignment must be a power-of-two value."); } private static void checkPointer(int offset) { if ( offset < 0 ) throw new OutOfMemoryError("Out of stack space."); } /** * Calls {@link #nmalloc(int, int)} with {@code alignment} equal to 1. * * @param size the allocation size * * @return the memory address on the stack for the requested allocation */ public long nmalloc(int size) { return nmalloc(1, size); } /** * Allocates a block of {@code size} bytes of memory on the stack. The content of the newly allocated block of memory is not initialized, remaining with * indeterminate values. * * @param alignment the required alignment * @param size the allocation size * * @return the memory address on the stack for the requested allocation */ public long nmalloc(int alignment, int size) { if ( frameIndex == 0 ) throw new IllegalStateException("A frame has not been pushed to the stack yet."); int newPointer = pointer - size; if ( CHECKS ) { checkAlignment(alignment); checkPointer(newPointer); } // Align pointer to the specified alignment newPointer &= ~(alignment - 1); pointer = newPointer; return this.address + newPointer; } /** * Allocates a block of memory on the stack for an array of {@code num} elements, each of them {@code size} bytes long, and initializes all its bits to * zero. * * @param alignment the required element alignment * @param num num the number of elements to allocate * @param size the size of each element * * @return the memory address on the stack for the requested allocation */ public long ncalloc(int alignment, int num, int size) { int bytes = num * size; long address = nmalloc(alignment, bytes); memSet(address, 0, bytes); return address; } /** * Allocates a {@link ByteBuffer} on the stack. * * @param size the number of elements in the buffer * * @return the allocated buffer */ public ByteBuffer malloc(int size) { return memByteBuffer(nmalloc(size), size); } /** Calloc version of {@link #malloc(int)}. */ public ByteBuffer calloc(int size) { return memByteBuffer(ncalloc(1, size, 1), size); } /** Short version of {@link #malloc(int)}. */ public ShortBuffer mallocShort(int size) { return memShortBuffer(nmalloc(2, size << 1), size); } /** Short version of {@link #calloc(int)}. */ public ShortBuffer callocShort(int size) { return memShortBuffer(ncalloc(2, size, 2), size); } /** Int version of {@link #malloc(int)}. */ public IntBuffer mallocInt(int size) { return memIntBuffer(nmalloc(4, size << 2), size); } /** Int version of {@link #calloc(int)}. */ public IntBuffer callocInt(int size) { return memIntBuffer(ncalloc(4, size, 4), size); } /** Long version of {@link #malloc(int)}. */ public LongBuffer mallocLong(int size) { return memLongBuffer(nmalloc(8, size << 3), size); } /** Long version of {@link #calloc(int)}. */ public LongBuffer callocLong(int size) { return memLongBuffer(ncalloc(8, size, 8), size); } /** Float version of {@link #malloc(int)}. */ public FloatBuffer mallocFloat(int size) { return memFloatBuffer(nmalloc(4, size << 2), size); } /** Float version of {@link #calloc(int)}. */ public FloatBuffer callocFloat(int size) { return memFloatBuffer(ncalloc(4, size, 4), size); } /** Double version of {@link #malloc(int)}. */ public DoubleBuffer mallocDouble(int size) { return memDoubleBuffer(nmalloc(8, size << 3), size); } /** Double version of {@link #calloc(int)}. */ public DoubleBuffer callocDouble(int size) { return memDoubleBuffer(ncalloc(8, size, 8), size); } /** Pointer version of {@link #malloc(int)}. */ public PointerBuffer mallocPointer(int size) { return memPointerBuffer(nmalloc(POINTER_SIZE, size << POINTER_SHIFT), size); } /** Pointer version of {@link #calloc(int)}. */ public PointerBuffer callocPointer(int size) { return memPointerBuffer(ncalloc(POINTER_SIZE, size, POINTER_SHIFT), size); } }
package org.lichess.clockencoder; public class LinearEstimator { public static void encode(int[] dest, int startTime) { int maxIdx = dest.length - 1; encode(dest, -1, startTime, maxIdx, dest[maxIdx]); } public static void decode(int[] dest, int startTime) { int maxIdx = dest.length - 1; decode(dest, -1, startTime, maxIdx, dest[maxIdx]); } private static void encode(int[] dest, int startIdx, int start, int endIdx, int end) { // Bitshift always rounds down, even for negative numbers. int midIdx = (startIdx + endIdx) >> 1; if (startIdx == midIdx) return; int mid = dest[midIdx]; dest[midIdx] = mid - ((start + end) >> 1); encode(dest, startIdx, start, midIdx, mid); encode(dest, midIdx, mid, endIdx, end); } private static void decode(int[] dest, int startIdx, int start, int endIdx, int end) { int midIdx = (startIdx + endIdx) >> 1; if (startIdx == midIdx) return; dest[midIdx] += (start + end) >> 1; int mid = dest[midIdx]; decode(dest, startIdx, start, midIdx, mid); decode(dest, midIdx, mid, endIdx, end); } }
package dynamake; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import dynamake.LiveModel.LivePanel; import dynamake.LiveModel.ProductionPanel; import dynamake.LiveModel.SetOutput; public class PlotTool implements Tool { @Override public String getName() { return "Plot"; } @Override public void mouseMoved(ProductionPanel productionPanel, MouseEvent e, ModelComponent modelOver) { } @Override public void mouseExited(ProductionPanel productionPanel, MouseEvent e) { } @Override public void mouseReleased(final ProductionPanel productionPanel, MouseEvent e, ModelComponent modelOver) { if(mouseDown != null) { JPopupMenu factoryPopopMenu = new JPopupMenu(); final Rectangle creationBoundsInProductionPanel = productionPanel.editPanelMouseAdapter.getPlotBounds(mouseDown, e.getPoint()); final Rectangle creationBoundsInSelection = SwingUtilities.convertRectangle(productionPanel, creationBoundsInProductionPanel, productionPanel.selectionFrame); // Find components within the creation bounds of the selection final ArrayList<ModelComponent> componentsWithinBounds = new ArrayList<ModelComponent>(); for(Component c: ((JComponent)productionPanel.editPanelMouseAdapter.selection).getComponents()) { if(creationBoundsInSelection.contains(c.getBounds())) { // Add in reverse order because views are positioned in the reverse order in the CanvasModel // This way, the views are sorted ascending index-wise componentsWithinBounds.add(0, (ModelComponent)c); } } final PrevaylerServiceBranch<Model> branchStep2 = branch.branch(); branchStep2.setOnFinishedBuilder(new RepaintRunBuilder(productionPanel.livePanel)); if(componentsWithinBounds.size() > 0) { JMenuItem factoryMenuItem = new JMenuItem(); factoryMenuItem.setText("Wrap"); factoryMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Find the selected model and attempt an add model transaction // HACK: Models can only be added to canvases if(productionPanel.editPanelMouseAdapter.selection.getModelBehind() instanceof CanvasModel) { PropogationContext propCtx = new PropogationContext(); branchStep2.execute(propCtx, new DualCommandFactory<Model>() { @Override public void createDualCommands(List<DualCommand<Model>> dualCommands) { CanvasModel target = (CanvasModel)productionPanel.editPanelMouseAdapter.selection.getModelBehind(); Location targetLocation = productionPanel.editPanelMouseAdapter.selection.getTransactionFactory().getModelLocation(); int indexOfWrapper = target.getModelCount() - componentsWithinBounds.size(); ModelLocation wrapperLocationInTarget = new CanvasModel.IndexLocation(indexOfWrapper); ModelLocation wrapperLocation = productionPanel.editPanelMouseAdapter.selection.getTransactionFactory().extendLocation(wrapperLocationInTarget); // Each of the model locations should be moved from target to wrapper Location[] modelLocations = new Location[componentsWithinBounds.size()]; int[] modelIndexes = new int[componentsWithinBounds.size()]; for(int i = 0; i < modelLocations.length; i++) { ModelComponent view = componentsWithinBounds.get(i); modelLocations[i] = view.getTransactionFactory().getModelLocation(); modelIndexes[i] = target.indexOfModel(view.getModelBehind()); } dualCommands.add(new DualCommandPair<Model>( new Wrap2Transaction(targetLocation, creationBoundsInSelection, modelLocations), new Unwrap2Transaction(targetLocation, wrapperLocationInTarget, modelIndexes, creationBoundsInSelection) )); dualCommands.add(LiveModel.SetOutput.createDual(productionPanel.livePanel, wrapperLocation)); } }); productionPanel.editPanelMouseAdapter.clearEffectFrameOnBranch(branchStep2); branchStep2.close(); branch.close(); } } }); factoryPopopMenu.add(factoryMenuItem); } for(final Factory factory: productionPanel.livePanel.getFactories()) { JMenuItem factoryMenuItem = new JMenuItem(); factoryMenuItem.setText(factory.getName()); factoryMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Find the selected model and attempt an add model transaction // HACK: Models can only be added to canvases if(productionPanel.editPanelMouseAdapter.selection.getModelBehind() instanceof CanvasModel) { PropogationContext propCtx = new PropogationContext(); branchStep2.execute(propCtx, new DualCommandFactory<Model>() { @Override public void createDualCommands(List<DualCommand<Model>> dualCommands) { ModelComponent target = productionPanel.editPanelMouseAdapter.selection; CanvasModel canvasModel = (CanvasModel)target.getModelBehind(); Location canvasModelLocation = target.getTransactionFactory().getModelLocation(); int index = canvasModel.getModelCount(); Location addedModelLocation = target.getTransactionFactory().extendLocation(new CanvasModel.IndexLocation(index)); // The location for Output depends on the side effect of add dualCommands.add(new DualCommandPair<Model>( new CanvasModel.AddModel2Transaction(canvasModelLocation, creationBoundsInSelection, factory), new CanvasModel.RemoveModelTransaction(canvasModelLocation, index) // Relative location )); dualCommands.add(LiveModel.SetOutput.createDual(productionPanel.livePanel, addedModelLocation)); } }); productionPanel.editPanelMouseAdapter.clearEffectFrameOnBranch(branchStep2); branchStep2.close(); branch.close(); } } }); factoryPopopMenu.add(factoryMenuItem); } factoryPopopMenu.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } @Override public void popupMenuCanceled(PopupMenuEvent e) { productionPanel.editPanelMouseAdapter.clearEffectFrameOnBranch(branchStep2); branch.reject(); } }); Point selectionReleasePointInSelection = SwingUtilities.convertPoint(((JComponent)(e.getSource())), e.getPoint(), productionPanel); factoryPopopMenu.show(productionPanel, selectionReleasePointInSelection.x + 10, selectionReleasePointInSelection.y); mouseDown = null; } } private PrevaylerServiceBranch<Model> branch; private Point mouseDown; @Override public void mousePressed(final ProductionPanel productionPanel, final MouseEvent e, ModelComponent modelOver) { PropogationContext propCtx = new PropogationContext(); branch = productionPanel.livePanel.getTransactionFactory().createBranch(); PrevaylerServiceBranch<Model> branchStep1 = branch.branch(); branchStep1.setOnFinishedBuilder(new RepaintRunBuilder(productionPanel.livePanel)); if(productionPanel.editPanelMouseAdapter.output != null) { branchStep1.execute(propCtx, new DualCommandFactory<Model>() { @Override public void createDualCommands(List<DualCommand<Model>> dualCommands) { ModelLocation currentOutputLocation = productionPanel.editPanelMouseAdapter.output.getTransactionFactory().getModelLocation(); dualCommands.add( new DualCommandPair<Model>( new SetOutput(productionPanel.livePanel.getTransactionFactory().getModelLocation(), null), new SetOutput(productionPanel.livePanel.getTransactionFactory().getModelLocation(), currentOutputLocation) ) ); } }); } if(modelOver.getModelBehind() instanceof CanvasModel) { mouseDown = e.getPoint(); Point referencePoint = SwingUtilities.convertPoint((JComponent)e.getSource(), e.getPoint(), (JComponent)modelOver); productionPanel.editPanelMouseAdapter.selectFromEmpty(modelOver, referencePoint, branchStep1); } branchStep1.close(); } @Override public void mouseDragged(final ProductionPanel productionPanel, final MouseEvent e, ModelComponent modelOver) { if(mouseDown != null) { final Rectangle plotBoundsInProductionPanel = productionPanel.editPanelMouseAdapter.getPlotBounds(mouseDown, e.getPoint()); RepaintRunBuilder runBuilder = new RepaintRunBuilder(productionPanel.livePanel); productionPanel.editPanelMouseAdapter.changeEffectFrameDirect2(plotBoundsInProductionPanel, runBuilder); runBuilder.execute(); } } }
package org.intermine.task; import org.intermine.metadata.Model; import junit.framework.*; import java.sql.SQLException; import java.util.List; import java.util.ArrayList; import java.util.Properties; import java.io.InputStream; import org.intermine.metadata.Model; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.StoreDataTestCase; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreSummary; import org.intermine.objectstore.ObjectStoreFactory; /** * Tests for PrecomputeTask. * * @author Kim Rutherford */ public class PrecomputeTaskTest extends StoreDataTestCase { public PrecomputeTaskTest (String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); } public static void oneTimeSetUp() throws Exception { StoreDataTestCase.oneTimeSetUp(); } public void executeTest(String type) { } public static Test suite() { return buildSuite(PrecomputeTaskTest.class); } /** * Test that PrecomputeTask creates the */ public void testExecute() throws Exception { DummyPrecomputeTask task = new DummyPrecomputeTask(); task.setAlias("os.unittest"); task.setTestMode(Boolean.FALSE); task.setMinRows(new Integer(1)); Properties summaryProperties; String configFile = "objectstoresummary.config.properties"; InputStream is = PrecomputeTask.class.getClassLoader().getResourceAsStream(configFile); if (is == null) { throw new Exception("Cannot find " + configFile + " in the class path"); } summaryProperties = new Properties(); summaryProperties.load(is); ObjectStore os = ObjectStoreFactory.getObjectStore("os.unittest"); ObjectStoreSummary oss = new ObjectStoreSummary(os, summaryProperties); task.precomputeAll(os, oss); assertEquals(14, task.queries.size()); String[] expectedQueries = new String[] { "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.name AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a5_ WHERE a1_.departments CONTAINS a5_ ORDER BY a1_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE a1_.departments CONTAINS a2_ ORDER BY a1_", "SELECT DISTINCT a1_, a1_.vatNumber AS a2_, a1_.name AS a3_, a1_.id AS a4_, a5_, a5_.address AS a6_, a5_.id AS a7_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a5_ WHERE a1_.address CONTAINS a5_ ORDER BY a1_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Address AS a2_ WHERE a1_.address CONTAINS a2_ ORDER BY a1_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.salary AS a5_, a4_.title AS a6_, a4_.age AS a7_, a4_.end AS a8_, a4_.fullTime AS a9_, a4_.name AS a10_, a4_.id AS a11_, a4_.seniority AS a12_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.CEO AS a2_ WHERE a1_.employees CONTAINS a2_ ORDER BY a1_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.age AS a5_, a4_.end AS a6_, a4_.fullTime AS a7_, a4_.name AS a8_, a4_.id AS a9_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a2_ WHERE a1_.employees CONTAINS a2_ ORDER BY a1_", "SELECT DISTINCT a1_, a1_.name AS a2_, a1_.id AS a3_, a4_, a4_.title AS a5_, a4_.age AS a6_, a4_.end AS a7_, a4_.fullTime AS a8_, a4_.name AS a9_, a4_.id AS a10_, a4_.seniority AS a11_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a4_ WHERE a1_.employees CONTAINS a4_ ORDER BY a1_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Manager AS a2_ WHERE a1_.employees CONTAINS a2_ ORDER BY a1_", "SELECT DISTINCT a1_, a1_.id AS a2_, a3_, a3_.name AS a4_, a3_.id AS a5_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a3_ WHERE a1_.secretarys CONTAINS a3_ ORDER BY a1_", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.HasSecretarys AS a1_, org.intermine.model.testmodel.Secretary AS a2_ WHERE a1_.secretarys CONTAINS a2_ ORDER BY a1_", "SELECT DISTINCT emp, add FROM org.intermine.model.testmodel.Employee AS emp, org.intermine.model.testmodel.Address AS add WHERE emp.address CONTAINS add", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Employee AS a2_ WHERE a1_.employees CONTAINS a2_", }; for (int i = 0; i < expectedQueries.length; i++) { assertEquals(expectedQueries[i], "" + task.queries.get(i)); } } public void testQueries() { } class DummyPrecomputeTask extends PrecomputeTask { protected List queries = new ArrayList(); protected void precompute(ObjectStore os, Query query) { queries.add(query); } } }
package org.noear.weed; import org.noear.weed.cache.CacheUsing; import org.noear.weed.cache.ICacheController; import org.noear.weed.cache.ICacheService; import org.noear.weed.ext.Act1; import org.noear.weed.ext.Act2; import org.noear.weed.utils.StringUtils; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.noear.weed.WeedConfig.isUsingTableSpace; public class DbTableQueryBase<T extends DbTableQueryBase> implements ICacheController<DbTableQueryBase> { String _table; DbContext _context; SQLBuilder _builder; int _isLog=0; protected String formatObject(String name){ return _context.formater().formatObject(name); } protected String formatField(String name){ return _context.formater().formatField(name); } protected String formatColumns(String columns){ return _context.formater().formatColumns(columns); } protected String formatCondition(String condition){ return _context.formater().formatCondition(condition); } public DbTableQueryBase(DbContext context) { _context = context; _builder = new SQLBuilder(); } public T log(boolean isLog) { _isLog = isLog ? 1 : -1; return (T) this; } public T expre(Act1<T> action){ action.run((T)this); return (T)this; } protected T table(String table) { // from if(table.startsWith(" _table = table.replace(" }else { if (table.indexOf('.') > 0) { _table = table; } else { if(isUsingTableSpace){ _table = "$." + table; }else{ _table = formatObject(table); //"$." + table; } } } return (T) this; } public T where(String where, Object... args) { _builder.append(" WHERE ").append(formatCondition(where), args); return (T)this; } public T where() { _builder.append(" WHERE "); return (T)this; } public T and(String and, Object... args) { _builder.append(" AND ").append(formatCondition(and), args); return (T)this; } public T and() { _builder.append(" AND "); return (T)this; } public T or(String or, Object... args) { _builder.append(" OR ").append(formatCondition(or), args); return (T)this; } public T or() { _builder.append(" OR "); return (T)this; } public T begin() { _builder.append(" ( "); return (T)this; } public T begin(String and, Object... args) { _builder.append(" ( ").append(formatCondition(and), args); return (T)this; } public T end() { _builder.append(" ) "); return (T)this; } public T from(String table){ _builder.append(" FROM ").append(table); return (T)this; } public long insert(IDataItem data) throws SQLException { if (data == null || data.count() == 0) { return 0; } List<Object> args = new ArrayList<Object>(); StringBuilder sb = StringUtils.borrowBuilder(); sb.append(" INSERT INTO ").append(_table).append(" ("); data.forEach((key, value) -> { if(value==null) { if(_usingNull == false) { return; } } sb.append(formatField(key)).append(","); }); sb.deleteCharAt(sb.length() - 1); sb.append(") "); sb.append("VALUES"); sb.append("("); data.forEach((key, value) -> { if (value == null) { if(_usingNull) { sb.append("null,"); //null } } else { if (value instanceof String) { String val2 = (String) value; if (isSqlExpr(val2)) { //SQL sb.append(val2.substring(1)).append(","); } else { sb.append("?,"); args.add(value); } } else { sb.append("?,"); args.add(value); } } }); sb.deleteCharAt(sb.length() - 1); sb.append(");"); _builder.clear(); _builder.append(StringUtils.releaseBuilder(sb), args.toArray()); return compile().insert(); } public <T> boolean insertList(Collection<T> valuesList, Act2<T,DataItem> hander) throws SQLException { List<DataItem> list2 = new ArrayList<>(); for (T values : valuesList) { DataItem item = new DataItem(); hander.run(values, item); list2.add(item); } if (list2.size() > 0) { return insertList(list2.get(0), list2); }else{ return false; } } public boolean insertList(List<DataItem> valuesList) throws SQLException { if (valuesList == null) { return false; } return insertList(valuesList.get(0), valuesList); } protected <T extends GetHandler> boolean insertList(IDataItem cols, Collection<T> valuesList)throws SQLException { if (valuesList == null) { return false; } if (cols == null || cols.count() == 0) { return false; } List<Object> args = new ArrayList<Object>(); StringBuilder sb = new StringBuilder(); sb.append(" INSERT INTO ").append(_table).append(" ("); for (String key : cols.keys()) { sb.append(formatField(key)).append(","); } sb.deleteCharAt(sb.length() - 1); sb.append(") "); sb.append("VALUES"); int sb_len = sb.length(); for (GetHandler item : valuesList) { sb.append("("); for (String key : cols.keys()) { Object val = item.get(key); if (val == null) { sb.append("null,"); } else { if (val instanceof String) { String val2 = (String) val; if (isSqlExpr(val2)) { //SQL sb.append(val2.substring(1)).append(","); } else { sb.append("?,"); args.add(val); } } else { sb.append("?,"); args.add(val); } } } sb.deleteCharAt(sb.length() - 1); sb.append("),"); } if(sb_len == sb.length()){ return false; } sb.deleteCharAt(sb.length() - 1); sb.append(";"); _builder.append(sb.toString(), args.toArray()); return compile().execute() > 0; } public long insert(Act1<IDataItem> fun) throws SQLException { DataItem item = new DataItem(); fun.run(item); return insert(item); } public void updateExt(IDataItem data, String constraints) throws SQLException { String[] ff = constraints.split(","); if(ff.length==0){ throw new RuntimeException("Please enter constraints"); } this.where("1=1"); for (String f : ff) { this.and(f + "=?", data.get(f)); } if (this.exists()) { for (String f : ff) { data.remove(f); } this.update(data); } else { this.insert(data); } } public int update(Act1<IDataItem> fun) throws SQLException { DataItem item = new DataItem(); fun.run(item); return update(item); } public int update(IDataItem data) throws SQLException{ if (data == null || data.count() == 0) { return 0; } List<Object> args = new ArrayList<Object>(); StringBuilder sb = StringUtils.borrowBuilder(); sb.append("UPDATE ").append(_table).append(" SET "); data.forEach((key,value)->{ if(value==null) { if (_usingNull) { sb.append(formatField(key)).append("=null,"); } return; } if (value instanceof String) { String val2 = (String)value; if (isSqlExpr(val2)) { sb.append(formatField(key)).append("=").append(val2.substring(1)).append(","); } else { sb.append(formatField(key)).append("=?,"); args.add(value); } } else { sb.append(formatField(key)).append("=?,"); args.add(value); } }); sb.deleteCharAt(sb.length() - 1); _builder.backup(); _builder.insert(StringUtils.releaseBuilder(sb), args.toArray()); if(WeedConfig.isUpdateMustConditional && _builder.indexOf(" WHERE ")<0){ throw new RuntimeException("Lack of update condition!!!"); } int rst = compile().execute(); _builder.restore(); return rst; } public int delete() throws SQLException { StringBuilder sb = new StringBuilder(); sb.append("DELETE "); if(_builder.indexOf(" FROM ")<0){ sb.append(" FROM ").append(_table); }else{ sb.append(_table); } _builder.insert(sb.toString()); return compile().execute(); } public T innerJoin(String table) { _builder.append(" INNER JOIN ").append(formatObject(table)); return (T)this; } public T leftJoin(String table) { _builder.append(" LEFT JOIN ").append(formatObject(table)); return (T)this; } public T rightJoin(String table) { _builder.append(" RIGHT JOIN ").append(formatObject(table)); return (T)this; } public T append(String code, Object... args){ _builder.append(code, args); return (T)this; } public T on(String on) { _builder.append(" ON ").append(on); return (T)this; } public T groupBy(String groupBy) { _builder.append(" GROUP BY ").append(formatColumns(groupBy)); return (T)this; } public T having(String having){ _builder.append(" HAVING ").append(having); return (T)this; } public T orderBy(String orderBy) { _builder.append(" ORDER BY ").append(formatColumns(orderBy)); return (T)this; } public T limit(int start, int rows) { _builder.append(" LIMIT " + start + "," + rows + " "); return (T)this; } public T limit(int rows) { _builder.append(" LIMIT " + rows + " "); return (T)this; } private int _top = 0; public T top(int num) { _top = num; //_builder.append(" TOP " + num + " "); return (T)this; } public boolean exists() throws SQLException { StringBuilder sb = StringUtils.borrowBuilder(); sb.append("SELECT 1 FROM ").append(_table); _builder.backup(); _builder.insert(StringUtils.releaseBuilder(sb)); _builder.append(" LIMIT 1"); //1.sql if(_hint!=null) { _builder.insert(_hint); _hint = null; } DbQuery rst = compile(); if(_cache != null){ rst.cache(_cache); } _builder.restore(); return rst.getValue() != null; } String _hint = null; public T hint(String hint){ _hint = hint; return (T)this; } public long count() throws SQLException{ return count("COUNT(*)"); } public long count(String expr) throws SQLException{ return select(expr).getVariate().longValue(0l); } public IQuery select(String columns) { StringBuilder sb = new StringBuilder(); //1.sql if(_hint!=null) { sb.append(_hint); _hint = null; } sb.append("SELECT "); if(_top>0){ sb.append(" TOP ").append(_top).append(" "); } sb.append(formatColumns(columns)).append(" FROM ").append(_table); _builder.backup(); _builder.insert(sb.toString()); DbQuery rst = compile(); if(_cache != null){ rst.cache(_cache); } _builder.restore(); return rst; } protected DbTran _tran = null; public T tran(DbTran transaction) { _tran = transaction; return (T)this; } public T tran() { _tran = _context.tran(); return (T)this; } //DbQuery private DbQuery compile() { DbQuery temp = new DbQuery(_context).sql(_builder); _builder.clear(); if(_tran!=null) { temp.tran(_tran); } return temp.onCommandBuilt((cmd)->{ cmd.isLog = _isLog; cmd.tag = _table; }); } private boolean _usingNull = WeedConfig.isUsingValueNull; public T usingNull(boolean isUsing){ _usingNull = isUsing; return (T)this; } private boolean _usingExpression = WeedConfig.isUsingValueExpression; public T usingExpr(boolean isUsing){ _usingExpression = isUsing; return (T)this; } private boolean isSqlExpr(String txt) { if (_usingExpression == false) { return false; } if (txt.startsWith("$") && txt.indexOf(" ") < 0 && txt.length() < 100) { //100 return true; } else { return false; } } protected CacheUsing _cache = null; public T caching(ICacheService service) { _cache = new CacheUsing(service); return (T)this; } public T usingCache (boolean isCache) { _cache.usingCache(isCache); return (T)this; } public T usingCache (int seconds) { _cache.usingCache(seconds); return (T)this; } public T cacheTag(String tag) { _cache.cacheTag(tag); return (T)this; } }
package javaslang.collection; import javaslang.*; import javaslang.control.Option; import java.util.*; import java.util.function.*; /** * An abstract {@link Map} implementation (not intended to be public). * * @param <K> Key type * @param <V> Value type * @param <M> Map type * @author Ruslan Sennov * @since 2.0.0 */ abstract class AbstractMap<K, V, M extends AbstractMap<K, V, M>> implements Map<K, V> { private static final long serialVersionUID = 1L; abstract M createFromEntries(Iterable<? extends Tuple2<? extends K, ? extends V>> entries); /** * Returns an empty version of this traversable, i.e. {@code empty().isEmpty() == true}. * * @return an empty instance of this Map. */ abstract M emptyInstance(); @SuppressWarnings("unchecked") @Override public M put(Tuple2<? extends K, ? extends V> entry) { Objects.requireNonNull(entry, "entry is null"); return (M) put(entry._1, entry._2); } @SuppressWarnings("unchecked") @Override public <U extends V> M put(K key, U value, BiFunction<? super V, ? super U, ? extends V> merge) { Objects.requireNonNull(merge, "the merge function is null"); final Option<V> currentValue = get(key); if (currentValue.isEmpty()) { return (M) put(key, value); } else { return (M) put(key, merge.apply(currentValue.get(), value)); } } @Override public <U extends V> M put(Tuple2<? extends K, U> entry, BiFunction<? super V, ? super U, ? extends V> merge) { Objects.requireNonNull(merge, "the merge function is null"); final Option<V> currentValue = get(entry._1); if (currentValue.isEmpty()) { return put(entry); } else { return put(entry.map2( value -> merge.apply(currentValue.get(), value))); } } @SuppressWarnings("unchecked") @Override public M distinct() { return (M) this; } @Override public M distinctBy(Comparator<? super Tuple2<K, V>> comparator) { Objects.requireNonNull(comparator, "comparator is null"); return createFromEntries(iterator().distinctBy(comparator)); } @Override public <U> M distinctBy(Function<? super Tuple2<K, V>, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); return createFromEntries(iterator().distinctBy(keyExtractor)); } @SuppressWarnings("unchecked") @Override public M drop(long n) { if (n <= 0) { return (M) this; } else if (n >= length()) { return emptyInstance(); } else { return createFromEntries(iterator().drop(n)); } } @SuppressWarnings("unchecked") @Override public M dropRight(long n) { if (n <= 0) { return (M) this; } else if (n >= length()) { return emptyInstance(); } else { return createFromEntries(iterator().dropRight(n)); } } @Override public M dropUntil(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return dropWhile(predicate.negate()); } @Override public M dropWhile(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return createFromEntries(iterator().dropWhile(predicate)); } @Override public M filter(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return createFromEntries(iterator().filter(predicate)); } @Override public M filter(BiPredicate<? super K, ? super V> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filter(t -> predicate.test(t._1(), t._2())); } @Override public M filterKeys(Predicate<? super K> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filter(t -> predicate.test(t._1())); } @Override public M filterValues(Predicate<? super V> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filter(t -> predicate.test(t._2())); } @Override public M removeAll(BiPredicate<? super K, ? super V> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filter(predicate.negate()); } @Override public M removeKeys(Predicate<? super K> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filterKeys(predicate.negate()); } @Override public M removeValues(Predicate<? super V> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filterValues(predicate.negate()); } @SuppressWarnings("unchecked") @Override public <C> Map<C, M> groupBy(Function<? super Tuple2<K, V>, ? extends C> classifier) { return Collections.groupBy(this, classifier, this::createFromEntries); } @Override public Iterator<M> grouped(long size) { return sliding(size, size); } @Override public abstract M init(); @Override public Option<M> initOption() { return isEmpty() ? Option.none() : Option.some(init()); } @Override public abstract M tail(); @Override public Option<M> tailOption() { return isEmpty() ? Option.none() : Option.some(tail()); } @SuppressWarnings("unchecked") @Override public M take(long n) { if (size() <= n) { return (M) this; } else { return createFromEntries(iterator().take(n)); } } @SuppressWarnings("unchecked") @Override public M takeRight(long n) { if (size() <= n) { return (M) this; } else { return createFromEntries(iterator().takeRight(n)); } } @Override public M takeUntil(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return takeWhile(predicate.negate()); } @SuppressWarnings("unchecked") @Override public M takeWhile(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final M taken = createFromEntries(iterator().takeWhile(predicate)); return taken.length() == length() ? (M) this : taken; } @SuppressWarnings("unchecked") @Override public M merge(Map<? extends K, ? extends V> that) { Objects.requireNonNull(that, "that is null"); if (isEmpty()) { return createFromEntries(that); } else if (that.isEmpty()) { return (M) this; } else { return that.foldLeft((M) this, (map, entry) -> !map.containsKey(entry._1) ? map.put(entry) : map); } } @SuppressWarnings("unchecked") @Override public <U extends V> M merge(Map<? extends K, U> that, BiFunction<? super V, ? super U, ? extends V> collisionResolution) { Objects.requireNonNull(that, "that is null"); Objects.requireNonNull(collisionResolution, "collisionResolution is null"); if (isEmpty()) { return createFromEntries(that); } else if (that.isEmpty()) { return (M) this; } else { return that.foldLeft((M) this, (map, entry) -> { final K key = entry._1; final U value = entry._2; final V newValue = map.get(key).map(v -> (V) collisionResolution.apply(v, value)).getOrElse(value); return (M) map.put(key, newValue); }); } } @Override public Tuple2<M, M> partition(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final Tuple2<Iterator<Tuple2<K, V>>, Iterator<Tuple2<K, V>>> p = iterator().partition(predicate); return Tuple.of(createFromEntries(p._1), createFromEntries(p._2)); } @SuppressWarnings("unchecked") @Override public M peek(Consumer<? super Tuple2<K, V>> action) { Objects.requireNonNull(action, "action is null"); if (!isEmpty()) { action.accept(head()); } return (M) this; } @SuppressWarnings("unchecked") @Override public M replace(Tuple2<K, V> currentElement, Tuple2<K, V> newElement) { Objects.requireNonNull(currentElement, "currentElement is null"); Objects.requireNonNull(newElement, "newElement is null"); return (M) (containsKey(currentElement._1) ? remove(currentElement._1).put(newElement) : this); } @Override public M replaceAll(Tuple2<K, V> currentElement, Tuple2<K, V> newElement) { return replace(currentElement, newElement); } @Override public M scan(Tuple2<K, V> zero, BiFunction<? super Tuple2<K, V>, ? super Tuple2<K, V>, ? extends Tuple2<K, V>> operation) { Objects.requireNonNull(operation, "operation is null"); return Collections.scanLeft(this, zero, operation, emptyInstance(), (m, e) -> m.put(e), Function.identity()); } @Override public Iterator<M> sliding(long size) { return sliding(size, 1); } @Override public Iterator<M> sliding(long size, long step) { return iterator().sliding(size, step).map(this::createFromEntries); } @Override public Tuple2<M, M> span(Predicate<? super Tuple2<K, V>> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final Tuple2<Iterator<Tuple2<K, V>>, Iterator<Tuple2<K, V>>> t = iterator().span(predicate); return Tuple.of(createFromEntries(t._1), createFromEntries(t._2)); } }
package io.searchbox.client; import com.google.gson.Gson; import io.searchbox.client.config.HttpClientConfig; import io.searchbox.client.config.discovery.NodeChecker; import io.searchbox.client.config.idle.HttpReapableConnectionManager; import io.searchbox.client.config.idle.IdleConnectionReaper; import io.searchbox.client.http.JestHttpClient; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.impl.nio.reactor.IOReactorConfig; import org.apache.http.nio.conn.NHttpClientConnectionManager; import org.apache.http.nio.conn.SchemeIOSessionStrategy; import org.apache.http.nio.reactor.IOReactorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * @author Dogukan Sonmez */ public class JestClientFactory { final static Logger log = LoggerFactory.getLogger(JestClientFactory.class); private HttpClientConfig httpClientConfig; public JestClient getObject() { JestHttpClient client = new JestHttpClient(); if (httpClientConfig == null) { log.debug("There is no configuration to create http client. Going to create simple client with default values"); httpClientConfig = new HttpClientConfig.Builder("http://localhost:9200").build(); } client.setRequestCompressionEnabled(httpClientConfig.isRequestCompressionEnabled()); client.setServers(httpClientConfig.getServerList()); final HttpClientConnectionManager connectionManager = getConnectionManager(); final NHttpClientConnectionManager asyncConnectionManager = getAsyncConnectionManager(); client.setHttpClient(createHttpClient(connectionManager)); client.setAsyncClient(createAsyncHttpClient(asyncConnectionManager)); // set custom gson instance Gson gson = httpClientConfig.getGson(); if (gson == null) { log.info("Using default GSON instance"); } else { log.info("Using custom GSON instance"); client.setGson(gson); } // set discovery (should be set after setting the httpClient on jestClient) if (httpClientConfig.isDiscoveryEnabled()) { log.info("Node Discovery enabled..."); NodeChecker nodeChecker = createNodeChecker(client, httpClientConfig); client.setNodeChecker(nodeChecker); nodeChecker.startAsync(); nodeChecker.awaitRunning(); } else { log.info("Node Discovery disabled..."); } // schedule idle connection reaping if configured if (httpClientConfig.getMaxConnectionIdleTime() > 0) { log.info("Idle connection reaping enabled..."); IdleConnectionReaper reaper = new IdleConnectionReaper(httpClientConfig, new HttpReapableConnectionManager(connectionManager, asyncConnectionManager)); client.setIdleConnectionReaper(reaper); reaper.startAsync(); reaper.awaitRunning(); } else { log.info("Idle connection reaping disabled..."); } HttpHost preemptiveAuthTargetHost = httpClientConfig.getPreemptiveAuthTargetHost(); if (preemptiveAuthTargetHost != null) { log.info("Authentication cache set for preemptive authentication"); client.setHttpClientContextTemplate(createPreemptiveAuthContext(preemptiveAuthTargetHost)); } return client; } public void setHttpClientConfig(HttpClientConfig httpClientConfig) { this.httpClientConfig = httpClientConfig; } private CloseableHttpClient createHttpClient(HttpClientConnectionManager connectionManager) { return configureHttpClient( HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(getRequestConfig()) .setProxyAuthenticationStrategy(httpClientConfig.getProxyAuthenticationStrategy()) .setRoutePlanner(getRoutePlanner()) .setDefaultCredentialsProvider(httpClientConfig.getCredentialsProvider()) ).build(); } private CloseableHttpAsyncClient createAsyncHttpClient(NHttpClientConnectionManager connectionManager) { return configureHttpClient( HttpAsyncClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(getRequestConfig()) .setProxyAuthenticationStrategy(httpClientConfig.getProxyAuthenticationStrategy()) .setRoutePlanner(getRoutePlanner()) .setDefaultCredentialsProvider(httpClientConfig.getCredentialsProvider()) ).build(); } /** * Extension point * <p> * Example: * </p> * <pre> * final JestClientFactory factory = new JestClientFactory() { * {@literal @Override} * protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) { * return builder.setDefaultHeaders(...); * } * } * </pre> */ protected HttpClientBuilder configureHttpClient(final HttpClientBuilder builder) { return builder; } /** * Extension point for async client */ protected HttpAsyncClientBuilder configureHttpClient(final HttpAsyncClientBuilder builder) { return builder; } // Extension point protected HttpRoutePlanner getRoutePlanner() { return httpClientConfig.getHttpRoutePlanner(); } // Extension point protected RequestConfig getRequestConfig() { return RequestConfig.custom() .setConnectTimeout(httpClientConfig.getConnTimeout()) .setSocketTimeout(httpClientConfig.getReadTimeout()) .build(); } // Extension point protected NHttpClientConnectionManager getAsyncConnectionManager() { PoolingNHttpClientConnectionManager retval; IOReactorConfig ioReactorConfig = IOReactorConfig.custom() .setConnectTimeout(httpClientConfig.getConnTimeout()) .setSoTimeout(httpClientConfig.getReadTimeout()) .build(); Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create() .register("http", httpClientConfig.getHttpIOSessionStrategy()) .register("https", httpClientConfig.getHttpsIOSessionStrategy()) .build(); try { retval = new PoolingNHttpClientConnectionManager( new DefaultConnectingIOReactor(ioReactorConfig), sessionStrategyRegistry ); } catch (IOReactorException e) { throw new IllegalStateException(e); } final Integer maxTotal = httpClientConfig.getMaxTotalConnection(); if (maxTotal != null) { retval.setMaxTotal(maxTotal); } final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute(); if (defaultMaxPerRoute != null) { retval.setDefaultMaxPerRoute(defaultMaxPerRoute); } final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute(); for (Map.Entry<HttpRoute, Integer> entry : maxPerRoute.entrySet()) { retval.setMaxPerRoute(entry.getKey(), entry.getValue()); } return retval; } // Extension point protected HttpClientConnectionManager getConnectionManager() { HttpClientConnectionManager retval; Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", httpClientConfig.getPlainSocketFactory()) .register("https", httpClientConfig.getSslSocketFactory()) .build(); if (httpClientConfig.isMultiThreaded()) { log.info("Using multi thread/connection supporting pooling connection manager"); final PoolingHttpClientConnectionManager poolingConnMgr = new PoolingHttpClientConnectionManager(registry); final Integer maxTotal = httpClientConfig.getMaxTotalConnection(); if (maxTotal != null) { poolingConnMgr.setMaxTotal(maxTotal); } final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute(); if (defaultMaxPerRoute != null) { poolingConnMgr.setDefaultMaxPerRoute(defaultMaxPerRoute); } final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute(); for (Map.Entry<HttpRoute, Integer> entry : maxPerRoute.entrySet()) { poolingConnMgr.setMaxPerRoute(entry.getKey(), entry.getValue()); } retval = poolingConnMgr; } else { log.info("Using single thread/connection supporting basic connection manager"); retval = new BasicHttpClientConnectionManager(registry); } return retval; } // Extension point protected NodeChecker createNodeChecker(JestHttpClient client, HttpClientConfig httpClientConfig) { return new NodeChecker(client, httpClientConfig); } // Extension point protected HttpClientContext createPreemptiveAuthContext(HttpHost targetHost) { HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(httpClientConfig.getCredentialsProvider()); context.setAuthCache(createBasicAuthCache(targetHost)); return context; } private AuthCache createBasicAuthCache(HttpHost targetHost) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); return authCache; } }
package com.fsck.k9.activity; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.IntentSender.SendIntentException; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v7.app.ActionBar; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.Window; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.MessageFormat; import com.fsck.k9.Identity; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.MessageLoaderHelper.MessageLoaderCallbacks; import com.fsck.k9.activity.compose.AttachmentPresenter; import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentMvpView; import com.fsck.k9.activity.compose.AttachmentPresenter.WaitingAction; import com.fsck.k9.activity.compose.ComposeCryptoStatus; import com.fsck.k9.activity.compose.ComposeCryptoStatus.SendErrorState; import com.fsck.k9.activity.compose.IdentityAdapter; import com.fsck.k9.activity.compose.IdentityAdapter.IdentityContainer; import com.fsck.k9.activity.compose.PgpEnabledErrorDialog.OnOpenPgpDisableListener; import com.fsck.k9.activity.compose.PgpInlineDialog.OnOpenPgpInlineChangeListener; import com.fsck.k9.activity.compose.PgpSignOnlyDialog.OnOpenPgpSignOnlyChangeListener; import com.fsck.k9.activity.compose.RecipientMvpView; import com.fsck.k9.activity.compose.RecipientPresenter; import com.fsck.k9.activity.compose.SaveMessageTask; import com.fsck.k9.activity.misc.Attachment; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.controller.SimpleMessagingListener; import com.fsck.k9.fragment.AttachmentDownloadDialogFragment; import com.fsck.k9.fragment.AttachmentDownloadDialogFragment.AttachmentDownloadCancelListener; import com.fsck.k9.fragment.ProgressDialogFragment; import com.fsck.k9.fragment.ProgressDialogFragment.CancelListener; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.IdentityHelper; import com.fsck.k9.helper.MailTo; import com.fsck.k9.helper.ReplyToParser; import com.fsck.k9.helper.SimpleTextWatcher; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.mailstore.MessageViewInfo; import com.fsck.k9.message.AutocryptStatusInteractor; import com.fsck.k9.message.ComposePgpEnableByDefaultDecider; import com.fsck.k9.message.ComposePgpInlineDecider; import com.fsck.k9.message.IdentityField; import com.fsck.k9.message.IdentityHeaderParser; import com.fsck.k9.message.MessageBuilder; import com.fsck.k9.message.PgpMessageBuilder; import com.fsck.k9.message.QuotedTextMode; import com.fsck.k9.message.SimpleMessageBuilder; import com.fsck.k9.message.SimpleMessageFormat; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.ui.EolConvertingEditText; import com.fsck.k9.ui.compose.QuotedMessageMvpView; import com.fsck.k9.ui.compose.QuotedMessagePresenter; import org.openintents.openpgp.OpenPgpApiManager; import org.openintents.openpgp.util.OpenPgpApi; import timber.log.Timber; @SuppressWarnings("deprecation") // TODO get rid of activity dialogs and indeterminate progress bars public class MessageCompose extends K9Activity implements OnClickListener, CancelListener, AttachmentDownloadCancelListener, OnFocusChangeListener, OnOpenPgpInlineChangeListener, OnOpenPgpSignOnlyChangeListener, MessageBuilder.Callback, AttachmentPresenter.AttachmentsChangedListener, RecipientPresenter.RecipientsChangedListener, OnOpenPgpDisableListener { private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1; private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 2; private static final int DIALOG_CHOOSE_IDENTITY = 3; private static final int DIALOG_CONFIRM_DISCARD = 4; private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID; public static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE"; public static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY"; public static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL"; public static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD"; public static final String ACTION_FORWARD_AS_ATTACHMENT = "com.fsck.k9.intent.action.FORWARD_AS_ATTACHMENT"; public static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT"; private static final String ACTION_AUTOCRYPT_PEER = "org.autocrypt.PEER_ACTION"; public static final String EXTRA_ACCOUNT = "account"; public static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; public static final String EXTRA_MESSAGE_DECRYPTION_RESULT = "message_decryption_result"; private static final String STATE_KEY_SOURCE_MESSAGE_PROCED = "com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced"; private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId"; private static final String STATE_IDENTITY_CHANGED = "com.fsck.k9.activity.MessageCompose.identityChanged"; private static final String STATE_IDENTITY = "com.fsck.k9.activity.MessageCompose.identity"; private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo"; private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references"; private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt"; private static final String STATE_KEY_CHANGES_MADE_SINCE_LAST_SAVE = "com.fsck.k9.activity.MessageCompose.changesMadeSinceLastSave"; private static final String STATE_ALREADY_NOTIFIED_USER_OF_EMPTY_SUBJECT = "alreadyNotifiedUserOfEmptySubject"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment"; private static final int MSG_PROGRESS_ON = 1; private static final int MSG_PROGRESS_OFF = 2; public static final int MSG_SAVED_DRAFT = 4; private static final int MSG_DISCARDED_DRAFT = 5; private static final int REQUEST_MASK_RECIPIENT_PRESENTER = (1 << 8); private static final int REQUEST_MASK_LOADER_HELPER = (1 << 9); private static final int REQUEST_MASK_ATTACHMENT_PRESENTER = (1 << 10); private static final int REQUEST_MASK_MESSAGE_BUILDER = (1 << 11); /** * Regular expression to remove the first localized "Re:" prefix in subjects. * * Currently: * - "Aw:" (german: abbreviation for "Antwort") */ private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE); private QuotedMessagePresenter quotedMessagePresenter; private MessageLoaderHelper messageLoaderHelper; private AttachmentPresenter attachmentPresenter; private Contacts contacts; /** * The account used for message composition. */ private Account account; private Identity identity; private boolean identityChanged = false; private boolean signatureChanged = false; // relates to the message being replied to, forwarded, or edited TODO split up? private MessageReference relatedMessageReference; /** * Indicates that the source message has been processed at least once and should not * be processed on any subsequent loads. This protects us from adding attachments that * have already been added from the restore of the view state. */ private boolean relatedMessageProcessed = false; private RecipientPresenter recipientPresenter; private MessageBuilder currentMessageBuilder; private boolean finishAfterDraftSaved; private boolean alreadyNotifiedUserOfEmptySubject = false; private boolean changesMadeSinceLastSave = false; /** * The database ID of this message's draft. This is used when saving drafts so the message in * the database is updated instead of being created anew. This property is INVALID_DRAFT_ID * until the first save. */ private long draftId = INVALID_DRAFT_ID; private Action action; private boolean requestReadReceipt = false; private TextView chooseIdentityButton; private EditText subjectView; private EolConvertingEditText signatureView; private EolConvertingEditText messageContentView; private LinearLayout attachmentsView; private String referencedMessageIds; private String repliedToMessageId; // The currently used message format. private SimpleMessageFormat currentMessageFormat; private boolean isInSubActivity = false; private boolean navigateUp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (K9.getK9ComposerThemeSetting() != K9.Theme.USE_GLOBAL) { // theme the whole content according to the theme (except the action bar) ContextThemeWrapper themeContext = new ContextThemeWrapper(this, K9.getK9ThemeResourceId(K9.getK9ComposerTheme())); @SuppressLint("InflateParams") // this is the top level activity element, it has no root View v = LayoutInflater.from(themeContext).inflate(R.layout.message_compose, null); TypedValue outValue = new TypedValue(); // background color needs to be forced themeContext.getTheme().resolveAttribute(R.attr.messageViewBackgroundColor, outValue, true); v.setBackgroundColor(outValue.data); setContentView(v); } else { setContentView(R.layout.message_compose); } initializeActionBar(); // on api level 15, setContentView() shows the progress bar for some reason... setProgressBarIndeterminateVisibility(false); final Intent intent = getIntent(); String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE); relatedMessageReference = MessageReference.parse(messageReferenceString); final String accountUuid = (relatedMessageReference != null) ? relatedMessageReference.getAccountUuid() : intent.getStringExtra(EXTRA_ACCOUNT); account = Preferences.getPreferences(this).getAccount(accountUuid); if (account == null) { account = Preferences.getPreferences(this).getDefaultAccount(); } if (account == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); changesMadeSinceLastSave = false; finish(); return; } contacts = Contacts.getInstance(MessageCompose.this); chooseIdentityButton = (TextView) findViewById(R.id.identity); chooseIdentityButton.setOnClickListener(this); RecipientMvpView recipientMvpView = new RecipientMvpView(this); ComposePgpInlineDecider composePgpInlineDecider = new ComposePgpInlineDecider(); ComposePgpEnableByDefaultDecider composePgpEnableByDefaultDecider = new ComposePgpEnableByDefaultDecider(); OpenPgpApiManager openPgpApiManager = new OpenPgpApiManager(getApplicationContext(), getLifecycle()); recipientPresenter = new RecipientPresenter(getApplicationContext(), getLoaderManager(), openPgpApiManager, recipientMvpView, account, composePgpInlineDecider, composePgpEnableByDefaultDecider, AutocryptStatusInteractor.getInstance(), new ReplyToParser(), this ); recipientPresenter.asyncUpdateCryptoStatus(); subjectView = (EditText) findViewById(R.id.subject); subjectView.getInputExtras(true).putBoolean("allowEmoji", true); EolConvertingEditText upperSignature = (EolConvertingEditText) findViewById(R.id.upper_signature); EolConvertingEditText lowerSignature = (EolConvertingEditText) findViewById(R.id.lower_signature); QuotedMessageMvpView quotedMessageMvpView = new QuotedMessageMvpView(this); quotedMessagePresenter = new QuotedMessagePresenter(this, quotedMessageMvpView, account); attachmentPresenter = new AttachmentPresenter(getApplicationContext(), attachmentMvpView, getLoaderManager(), this); messageContentView = (EolConvertingEditText) findViewById(R.id.message_content); messageContentView.getInputExtras(true).putBoolean("allowEmoji", true); attachmentsView = (LinearLayout) findViewById(R.id.attachments); TextWatcher draftNeedsChangingTextWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { changesMadeSinceLastSave = true; } }; TextWatcher signTextWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { changesMadeSinceLastSave = true; signatureChanged = true; } }; recipientMvpView.addTextChangedListener(draftNeedsChangingTextWatcher); quotedMessageMvpView.addTextChangedListener(draftNeedsChangingTextWatcher); subjectView.addTextChangedListener(draftNeedsChangingTextWatcher); messageContentView.addTextChangedListener(draftNeedsChangingTextWatcher); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ quotedMessagePresenter.showOrHideQuotedText(QuotedTextMode.NONE); subjectView.setOnFocusChangeListener(this); messageContentView.setOnFocusChangeListener(this); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreInstanceState */ relatedMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } if (initFromIntent(intent)) { action = Action.COMPOSE; changesMadeSinceLastSave = true; } else { String action = intent.getAction(); if (ACTION_COMPOSE.equals(action)) { this.action = Action.COMPOSE; } else if (ACTION_REPLY.equals(action)) { this.action = Action.REPLY; } else if (ACTION_REPLY_ALL.equals(action)) { this.action = Action.REPLY_ALL; } else if (ACTION_FORWARD.equals(action)) { this.action = Action.FORWARD; } else if (ACTION_FORWARD_AS_ATTACHMENT.equals(action)) { this.action = Action.FORWARD_AS_ATTACHMENT; } else if (ACTION_EDIT_DRAFT.equals(action)) { this.action = Action.EDIT_DRAFT; } else { // This shouldn't happen Timber.w("MessageCompose was started with an unsupported action"); this.action = Action.COMPOSE; } } if (identity == null) { identity = account.getIdentity(0); } if (account.isSignatureBeforeQuotedText()) { signatureView = upperSignature; lowerSignature.setVisibility(View.GONE); } else { signatureView = lowerSignature; upperSignature.setVisibility(View.GONE); } updateSignature(); signatureView.addTextChangedListener(signTextWatcher); if (!identity.getSignatureUse()) { signatureView.setVisibility(View.GONE); } requestReadReceipt = account.isMessageReadReceiptAlways(); updateFrom(); if (!relatedMessageProcessed) { if (action == Action.REPLY || action == Action.REPLY_ALL || action == Action.FORWARD || action == Action.FORWARD_AS_ATTACHMENT || action == Action.EDIT_DRAFT) { messageLoaderHelper = new MessageLoaderHelper(this, getLoaderManager(), getFragmentManager(), messageLoaderCallbacks); internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_ON); if (action == Action.FORWARD_AS_ATTACHMENT) { messageLoaderHelper.asyncStartOrResumeLoadingMessageMetadata(relatedMessageReference); } else { Parcelable cachedDecryptionResult = intent.getParcelableExtra(EXTRA_MESSAGE_DECRYPTION_RESULT); messageLoaderHelper.asyncStartOrResumeLoadingMessage( relatedMessageReference, cachedDecryptionResult); } } if (action != Action.EDIT_DRAFT) { String alwaysBccString = account.getAlwaysBcc(); if (!TextUtils.isEmpty(alwaysBccString)) { recipientPresenter.addBccAddresses(Address.parse(alwaysBccString)); } } } if (action == Action.REPLY || action == Action.REPLY_ALL) { relatedMessageReference = relatedMessageReference.withModifiedFlag(Flag.ANSWERED); } if (action == Action.REPLY || action == Action.REPLY_ALL || action == Action.EDIT_DRAFT) { //change focus to message body. messageContentView.requestFocus(); } else { // Explicitly set focus to "To:" input field (see issue 2998) recipientMvpView.requestFocusOnToField(); } if (action == Action.FORWARD || action == Action.FORWARD_AS_ATTACHMENT) { relatedMessageReference = relatedMessageReference.withModifiedFlag(Flag.FORWARDED); } updateMessageFormat(); // Set font size of input controls int fontSize = K9.getFontSizes().getMessageComposeInput(); recipientMvpView.setFontSizes(K9.getFontSizes(), fontSize); quotedMessageMvpView.setFontSizes(K9.getFontSizes(), fontSize); K9.getFontSizes().setViewTextSize(subjectView, fontSize); K9.getFontSizes().setViewTextSize(messageContentView, fontSize); K9.getFontSizes().setViewTextSize(signatureView, fontSize); updateMessageFormat(); setTitle(); currentMessageBuilder = (MessageBuilder) getLastCustomNonConfigurationInstance(); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.reattachCallback(this); } } /** * Handle external intents that trigger the message compose activity. * * <p> * Supported external intents: * <ul> * <li>{@link Intent#ACTION_VIEW}</li> * <li>{@link Intent#ACTION_SENDTO}</li> * <li>{@link Intent#ACTION_SEND}</li> * <li>{@link Intent#ACTION_SEND_MULTIPLE}</li> * </ul> * </p> * * @param intent * The (external) intent that started the activity. * * @return {@code true}, if this activity was started by an external intent. {@code false}, * otherwise. */ private boolean initFromIntent(final Intent intent) { boolean startedByExternalIntent = false; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { /* * Someone has clicked a mailto: link. The address is in the URI. */ if (intent.getData() != null) { Uri uri = intent.getData(); if (MailTo.isMailTo(uri)) { MailTo mailTo = MailTo.parse(uri); initializeFromMailto(mailTo); } } /* * Note: According to the documentation ACTION_VIEW and ACTION_SENDTO don't accept * EXTRA_* parameters. * And previously we didn't process these EXTRAs. But it looks like nobody bothers to * read the official documentation and just copies wrong sample code that happens to * work with the AOSP Email application. And because even big players get this wrong, * we're now finally giving in and read the EXTRAs for those actions (below). */ } if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) || Intent.ACTION_SENDTO.equals(action) || Intent.ACTION_VIEW.equals(action)) { startedByExternalIntent = true; /* * Note: Here we allow a slight deviation from the documented behavior. * EXTRA_TEXT is used as message body (if available) regardless of the MIME * type of the intent. In addition one or multiple attachments can be added * using EXTRA_STREAM. */ CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI if (text != null && messageContentView.getText().length() == 0) { messageContentView.setCharacters(text); } String type = intent.getType(); if (Intent.ACTION_SEND.equals(action)) { Uri stream = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null) { attachmentPresenter.addAttachment(stream, type); } } else { List<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Parcelable parcelable : list) { Uri stream = (Uri) parcelable; if (stream != null) { attachmentPresenter.addAttachment(stream, type); } } } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); // Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI if (subject != null && subjectView.getText().length() == 0) { subjectView.setText(subject); } recipientPresenter.initFromSendOrViewIntent(intent); } if (ACTION_AUTOCRYPT_PEER.equals(action)) { String trustId = intent.getStringExtra(OpenPgpApi.EXTRA_AUTOCRYPT_PEER_ID); if (trustId != null) { recipientPresenter.initFromTrustIdAction(trustId); startedByExternalIntent = true; } } return startedByExternalIntent; } @Override protected void onResume() { super.onResume(); MessagingController.getInstance(this).addListener(messagingListener); } @Override public void onPause() { super.onPause(); MessagingController.getInstance(this).removeListener(messagingListener); boolean isPausingOnConfigurationChange = (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == ActivityInfo.CONFIG_ORIENTATION; boolean isCurrentlyBuildingMessage = currentMessageBuilder != null; if (isPausingOnConfigurationChange || isCurrentlyBuildingMessage || isInSubActivity) { return; } checkToSaveDraftImplicitly(); } /** * The framework handles most of the fields, but we need to handle stuff that we * dynamically show and hide: * Attachment list, * Cc field, * Bcc field, * Quoted text, */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, relatedMessageProcessed); outState.putLong(STATE_KEY_DRAFT_ID, draftId); outState.putSerializable(STATE_IDENTITY, identity); outState.putBoolean(STATE_IDENTITY_CHANGED, identityChanged); outState.putString(STATE_IN_REPLY_TO, repliedToMessageId); outState.putString(STATE_REFERENCES, referencedMessageIds); outState.putBoolean(STATE_KEY_READ_RECEIPT, requestReadReceipt); outState.putBoolean(STATE_KEY_CHANGES_MADE_SINCE_LAST_SAVE, changesMadeSinceLastSave); outState.putBoolean(STATE_ALREADY_NOTIFIED_USER_OF_EMPTY_SUBJECT, alreadyNotifiedUserOfEmptySubject); recipientPresenter.onSaveInstanceState(outState); quotedMessagePresenter.onSaveInstanceState(outState); attachmentPresenter.onSaveInstanceState(outState); } @Override public Object onRetainCustomNonConfigurationInstance() { if (currentMessageBuilder != null) { currentMessageBuilder.detachCallback(); } return currentMessageBuilder; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); attachmentsView.removeAllViews(); requestReadReceipt = savedInstanceState.getBoolean(STATE_KEY_READ_RECEIPT); recipientPresenter.onRestoreInstanceState(savedInstanceState); quotedMessagePresenter.onRestoreInstanceState(savedInstanceState); attachmentPresenter.onRestoreInstanceState(savedInstanceState); draftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID); identity = (Identity) savedInstanceState.getSerializable(STATE_IDENTITY); identityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED); repliedToMessageId = savedInstanceState.getString(STATE_IN_REPLY_TO); referencedMessageIds = savedInstanceState.getString(STATE_REFERENCES); changesMadeSinceLastSave = savedInstanceState.getBoolean(STATE_KEY_CHANGES_MADE_SINCE_LAST_SAVE); alreadyNotifiedUserOfEmptySubject = savedInstanceState.getBoolean(STATE_ALREADY_NOTIFIED_USER_OF_EMPTY_SUBJECT); updateFrom(); updateMessageFormat(); } private void setTitle() { setTitle(action.getTitleResource()); } @Nullable private MessageBuilder createMessageBuilder(boolean isDraft) { MessageBuilder builder; ComposeCryptoStatus cryptoStatus = recipientPresenter.getCurrentCachedCryptoStatus(); if (cryptoStatus == null) { return null; } // TODO encrypt drafts for storage if (!isDraft && cryptoStatus.shouldUsePgpMessageBuilder()) { SendErrorState maybeSendErrorState = cryptoStatus.getSendErrorStateOrNull(); if (maybeSendErrorState != null) { recipientPresenter.showPgpSendError(maybeSendErrorState); return null; } PgpMessageBuilder pgpBuilder = PgpMessageBuilder.newInstance(); recipientPresenter.builderSetProperties(pgpBuilder, cryptoStatus); builder = pgpBuilder; } else { builder = SimpleMessageBuilder.newInstance(); recipientPresenter.builderSetProperties(builder); } builder.setSubject(Utility.stripNewLines(subjectView.getText().toString())) .setSentDate(new Date()) .setHideTimeZone(K9.hideTimeZone()) .setInReplyTo(repliedToMessageId) .setReferences(referencedMessageIds) .setRequestReadReceipt(requestReadReceipt) .setIdentity(identity) .setMessageFormat(currentMessageFormat) .setText(messageContentView.getCharacters()) .setAttachments(attachmentPresenter.createAttachmentList()) .setSignature(signatureView.getCharacters()) .setSignatureBeforeQuotedText(account.isSignatureBeforeQuotedText()) .setIdentityChanged(identityChanged) .setSignatureChanged(signatureChanged) .setCursorPosition(messageContentView.getSelectionStart()) .setMessageReference(relatedMessageReference) .setDraft(isDraft) .setIsPgpInlineEnabled(cryptoStatus.isPgpInlineModeEnabled()); quotedMessagePresenter.builderSetProperties(builder); return builder; } private void checkToSendMessage() { if (subjectView.getText().length() == 0 && !alreadyNotifiedUserOfEmptySubject) { Toast.makeText(this, R.string.empty_subject, Toast.LENGTH_LONG).show(); alreadyNotifiedUserOfEmptySubject = true; return; } if (recipientPresenter.checkRecipientsOkForSending()) { return; } if (attachmentPresenter.checkOkForSendingOrDraftSaving()) { return; } performSendAfterChecks(); } private void checkToSaveDraftAndSave() { if (!account.hasDraftsFolder()) { Toast.makeText(this, R.string.compose_error_no_draft_folder, Toast.LENGTH_SHORT).show(); return; } if (attachmentPresenter.checkOkForSendingOrDraftSaving()) { return; } finishAfterDraftSaved = true; performSaveAfterChecks(); } private void checkToSaveDraftImplicitly() { if (!account.hasDraftsFolder()) { return; } if (!changesMadeSinceLastSave) { return; } finishAfterDraftSaved = false; performSaveAfterChecks(); } private void performSaveAfterChecks() { currentMessageBuilder = createMessageBuilder(true); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } private void onDiscard() { if (draftId != INVALID_DRAFT_ID) { MessagingController.getInstance(getApplication()).deleteDraft(account, draftId); draftId = INVALID_DRAFT_ID; } internalMessageHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT); changesMadeSinceLastSave = false; if (navigateUp) { openAutoExpandFolder(); } else { finish(); } } private void onReadReceipt() { CharSequence txt; if (!requestReadReceipt) { txt = getString(R.string.read_receipt_enabled); requestReadReceipt = true; } else { txt = getString(R.string.read_receipt_disabled); requestReadReceipt = false; } Context context = getApplicationContext(); Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT); toast.show(); } public void showContactPicker(int requestCode) { requestCode |= REQUEST_MASK_RECIPIENT_PRESENTER; isInSubActivity = true; startActivityForResult(contacts.contactPickerIntent(), requestCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { isInSubActivity = false; if ((requestCode & REQUEST_MASK_MESSAGE_BUILDER) == REQUEST_MASK_MESSAGE_BUILDER) { requestCode ^= REQUEST_MASK_MESSAGE_BUILDER; if (currentMessageBuilder == null) { Timber.e("Got a message builder activity result for no message builder, " + "this is an illegal state!"); return; } currentMessageBuilder.onActivityResult(requestCode, resultCode, data, this); return; } if ((requestCode & REQUEST_MASK_RECIPIENT_PRESENTER) == REQUEST_MASK_RECIPIENT_PRESENTER) { requestCode ^= REQUEST_MASK_RECIPIENT_PRESENTER; recipientPresenter.onActivityResult(requestCode, resultCode, data); return; } if ((requestCode & REQUEST_MASK_LOADER_HELPER) == REQUEST_MASK_LOADER_HELPER) { requestCode ^= REQUEST_MASK_LOADER_HELPER; messageLoaderHelper.onActivityResult(requestCode, resultCode, data); return; } if ((requestCode & REQUEST_MASK_ATTACHMENT_PRESENTER) == REQUEST_MASK_ATTACHMENT_PRESENTER) { requestCode ^= REQUEST_MASK_ATTACHMENT_PRESENTER; attachmentPresenter.onActivityResult(resultCode, requestCode, data); } } private void onAccountChosen(Account account, Identity identity) { if (!this.account.equals(account)) { Timber.v("Switching account from %s to %s", this.account, account); // on draft edit, make sure we don't keep previous message UID if (action == Action.EDIT_DRAFT) { relatedMessageReference = null; } // test whether there is something to save if (changesMadeSinceLastSave || (draftId != INVALID_DRAFT_ID)) { final long previousDraftId = draftId; final Account previousAccount = this.account; // make current message appear as new draftId = INVALID_DRAFT_ID; // actual account switch this.account = account; Timber.v("Account switch, saving new draft in new account"); checkToSaveDraftImplicitly(); if (previousDraftId != INVALID_DRAFT_ID) { Timber.v("Account switch, deleting draft from previous account: %d", previousDraftId); MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftId); } } else { this.account = account; } // Show CC/BCC text input field when switching to an account that always wants them // displayed. // Please note that we're not hiding the fields if the user switches back to an account // that doesn't have this setting checked. recipientPresenter.onSwitchAccount(this.account); quotedMessagePresenter.onSwitchAccount(this.account); // not sure how to handle mFolder, mSourceMessage? } switchToIdentity(identity); } private void switchToIdentity(Identity identity) { this.identity = identity; identityChanged = true; changesMadeSinceLastSave = true; updateFrom(); updateSignature(); updateMessageFormat(); recipientPresenter.onSwitchIdentity(identity); } private void updateFrom() { chooseIdentityButton.setText(identity.getEmail()); } private void updateSignature() { if (identity.getSignatureUse()) { signatureView.setCharacters(identity.getSignature()); signatureView.setVisibility(View.VISIBLE); } else { signatureView.setVisibility(View.GONE); } } @Override public void onFocusChange(View v, boolean hasFocus) { switch (v.getId()) { case R.id.message_content: case R.id.subject: if (hasFocus) { recipientPresenter.onNonRecipientFieldFocused(); } break; } } @Override public void onOpenPgpInlineChange(boolean enabled) { recipientPresenter.onCryptoPgpInlineChanged(enabled); } @Override public void onOpenPgpSignOnlyChange(boolean enabled) { recipientPresenter.onCryptoPgpSignOnlyDisabled(); } @Override public void onOpenPgpClickDisable() { recipientPresenter.onCryptoPgpClickDisable(); } @Override public void onAttachmentAdded() { changesMadeSinceLastSave = true; } @Override public void onAttachmentRemoved() { changesMadeSinceLastSave = true; } @Override public void onRecipientsChanged() { changesMadeSinceLastSave = true; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.identity: showDialog(DIALOG_CHOOSE_IDENTITY); break; } } private void askBeforeDiscard() { if (K9.confirmDiscardMessage()) { showDialog(DIALOG_CONFIRM_DISCARD); } else { onDiscard(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: prepareToFinish(true); break; case R.id.send: checkToSendMessage(); break; case R.id.save: checkToSaveDraftAndSave(); break; case R.id.discard: askBeforeDiscard(); break; case R.id.add_from_contacts: recipientPresenter.onMenuAddFromContacts(); break; case R.id.openpgp_encrypt_disable: recipientPresenter.onMenuToggleEncryption(); updateMessageFormat(); break; case R.id.openpgp_encrypt_enable: recipientPresenter.onMenuToggleEncryption(); updateMessageFormat(); break; case R.id.openpgp_inline_enable: recipientPresenter.onMenuSetPgpInline(true); updateMessageFormat(); break; case R.id.openpgp_inline_disable: recipientPresenter.onMenuSetPgpInline(false); updateMessageFormat(); break; case R.id.openpgp_sign_only: recipientPresenter.onMenuSetSignOnly(true); break; case R.id.openpgp_sign_only_disable: recipientPresenter.onMenuSetSignOnly(false); break; case R.id.add_attachment: attachmentPresenter.onClickAddAttachment(recipientPresenter); break; case R.id.read_receipt: onReadReceipt(); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (isFinishing()) { return false; } getMenuInflater().inflate(R.menu.message_compose_option, menu); // Disable the 'Save' menu option if Drafts folder is set to -NONE- if (!account.hasDraftsFolder()) { menu.findItem(R.id.save).setEnabled(false); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); recipientPresenter.onPrepareOptionsMenu(menu); return true; } @Override public void onBackPressed() { prepareToFinish(false); } private void prepareToFinish(boolean shouldNavigateUp) { navigateUp = shouldNavigateUp; if (changesMadeSinceLastSave && draftIsNotEmpty()) { if (!account.hasDraftsFolder()) { showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } else { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); } } else { // Check if editing an existing draft. if (draftId == INVALID_DRAFT_ID) { onDiscard(); } else { if (navigateUp) { openAutoExpandFolder(); } else { super.onBackPressed(); } } } } private void openAutoExpandFolder() { String folder = account.getAutoExpandFolder(); LocalSearch search = new LocalSearch(folder); search.addAccountUuid(account.getUuid()); search.addAllowedFolder(folder); MessageList.actionDisplaySearch(this, search, false, true); finish(); } private boolean draftIsNotEmpty() { if (messageContentView.getText().length() != 0) { return true; } if (!attachmentPresenter.createAttachmentList().isEmpty()) { return true; } if (subjectView.getText().length() != 0) { return true; } return !recipientPresenter.getToAddresses().isEmpty() || !recipientPresenter.getCcAddresses().isEmpty() || !recipientPresenter.getBccAddresses().isEmpty(); } @Override public void onProgressCancel(AttachmentDownloadDialogFragment fragment) { attachmentPresenter.attachmentProgressDialogCancelled(); } public void onProgressCancel(ProgressDialogFragment fragment) { attachmentPresenter.attachmentProgressDialogCancelled(); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.save_or_discard_draft_message_dlg_title) .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); checkToSaveDraftAndSave(); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onDiscard(); } }) .create(); case DIALOG_CONFIRM_DISCARD_ON_BACK: return new AlertDialog.Builder(this) .setTitle(R.string.confirm_discard_draft_message_title) .setMessage(R.string.confirm_discard_draft_message) .setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); Toast.makeText(MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); onDiscard(); } }) .create(); case DIALOG_CHOOSE_IDENTITY: Context context = new ContextThemeWrapper(this, (K9.getK9Theme() == K9.Theme.LIGHT) ? R.style.Theme_K9_Dialog_Light : R.style.Theme_K9_Dialog_Dark); Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.send_as); final IdentityAdapter adapter = new IdentityAdapter(context); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { IdentityContainer container = (IdentityContainer) adapter.getItem(which); onAccountChosen(container.account, container.identity); } }); return builder.create(); case DIALOG_CONFIRM_DISCARD: { return new AlertDialog.Builder(this) .setTitle(R.string.dialog_confirm_delete_title) .setMessage(R.string.dialog_confirm_delete_message) .setPositiveButton(R.string.dialog_confirm_delete_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { onDiscard(); } }) .setNegativeButton(R.string.dialog_confirm_delete_cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create(); } } return super.onCreateDialog(id); } public void saveDraftEventually() { changesMadeSinceLastSave = true; } public void loadQuotedTextForEdit() { if (relatedMessageReference == null) { // shouldn't happen... throw new IllegalStateException("tried to edit quoted message with no referenced message"); } messageLoaderHelper.asyncStartOrResumeLoadingMessage(relatedMessageReference, null); } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * * @param messageViewInfo * The source message used to populate the various text fields. */ private void processSourceMessage(MessageViewInfo messageViewInfo) { try { switch (action) { case REPLY: case REPLY_ALL: { processMessageToReplyTo(messageViewInfo); break; } case FORWARD: { processMessageToForward(messageViewInfo, false); break; } case FORWARD_AS_ATTACHMENT: { processMessageToForward(messageViewInfo, true); break; } case EDIT_DRAFT: { processDraftMessage(messageViewInfo); break; } default: { Timber.w("processSourceMessage() called with unsupported action"); break; } } } catch (MessagingException e) { /* * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. */ Timber.e(e, "Error while processing source message: "); } finally { relatedMessageProcessed = true; changesMadeSinceLastSave = false; } updateMessageFormat(); } private void processMessageToReplyTo(MessageViewInfo messageViewInfo) throws MessagingException { Message message = messageViewInfo.message; if (messageViewInfo.subject != null) { final String subject = PREFIX.matcher(messageViewInfo.subject).replaceFirst(""); if (!subject.toLowerCase(Locale.US).startsWith("re:")) { subjectView.setText("Re: " + subject); } else { subjectView.setText(subject); } } else { subjectView.setText(""); } /* * If a reply-to was included with the message use that, otherwise use the from * or sender address. */ boolean isReplyAll = action == Action.REPLY_ALL; recipientPresenter.initFromReplyToMessage(message, isReplyAll); if (message.getMessageId() != null && message.getMessageId().length() > 0) { repliedToMessageId = message.getMessageId(); String[] refs = message.getReferences(); if (refs != null && refs.length > 0) { referencedMessageIds = TextUtils.join("", refs) + " " + repliedToMessageId; } else { referencedMessageIds = repliedToMessageId; } } else { Timber.d("could not get Message-ID."); } // Quote the message and setup the UI. quotedMessagePresenter.initFromReplyToMessage(messageViewInfo, action); if (action == Action.REPLY || action == Action.REPLY_ALL) { Identity useIdentity = IdentityHelper.getRecipientIdentityFromMessage(account, message); Identity defaultIdentity = account.getIdentity(0); if (useIdentity != defaultIdentity) { switchToIdentity(useIdentity); } } } private void processMessageToForward(MessageViewInfo messageViewInfo, boolean asAttachment) throws MessagingException { Message message = messageViewInfo.message; String subject = messageViewInfo.subject; if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) { subjectView.setText("Fwd: " + subject); } else { subjectView.setText(subject); } // "Be Like Thunderbird" - on forwarded messages, set the message ID // of the forwarded message in the references and the reply to. TB // only includes ID of the message being forwarded in the reference, // even if there are multiple references. if (!TextUtils.isEmpty(message.getMessageId())) { repliedToMessageId = message.getMessageId(); referencedMessageIds = repliedToMessageId; } else { Timber.d("could not get Message-ID."); } // Quote the message and setup the UI. if (asAttachment) { attachmentPresenter.processMessageToForwardAsAttachment(messageViewInfo); } else { quotedMessagePresenter.processMessageToForward(messageViewInfo); attachmentPresenter.processMessageToForward(messageViewInfo); } } private void processDraftMessage(MessageViewInfo messageViewInfo) { Message message = messageViewInfo.message; draftId = MessagingController.getInstance(getApplication()).getId(message); subjectView.setText(messageViewInfo.subject); recipientPresenter.initFromDraftMessage(message); // Read In-Reply-To header from draft final String[] inReplyTo = message.getHeader("In-Reply-To"); if (inReplyTo.length >= 1) { repliedToMessageId = inReplyTo[0]; } // Read References header from draft final String[] references = message.getHeader("References"); if (references.length >= 1) { referencedMessageIds = references[0]; } if (!relatedMessageProcessed) { attachmentPresenter.loadNonInlineAttachments(messageViewInfo); } // Decode the identity header when loading a draft. // See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob. Map<IdentityField, String> k9identity = new HashMap<>(); String[] identityHeaders = message.getHeader(K9.IDENTITY_HEADER); if (identityHeaders.length > 0 && identityHeaders[0] != null) { k9identity = IdentityHeaderParser.parse(identityHeaders[0]); } Identity newIdentity = new Identity(); if (k9identity.containsKey(IdentityField.SIGNATURE)) { newIdentity.setSignatureUse(true); newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE)); signatureChanged = true; } else { if (message instanceof LocalMessage) { newIdentity.setSignatureUse(((LocalMessage) message).getFolder().getSignatureUse()); } newIdentity.setSignature(identity.getSignature()); } if (k9identity.containsKey(IdentityField.NAME)) { newIdentity.setName(k9identity.get(IdentityField.NAME)); identityChanged = true; } else { newIdentity.setName(identity.getName()); } if (k9identity.containsKey(IdentityField.EMAIL)) { newIdentity.setEmail(k9identity.get(IdentityField.EMAIL)); identityChanged = true; } else { newIdentity.setEmail(identity.getEmail()); } if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) { relatedMessageReference = null; String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE); MessageReference messageReference = MessageReference.parse(originalMessage); if (messageReference != null) { // Check if this is a valid account in our database Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.getAccountUuid()); if (account != null) { relatedMessageReference = messageReference; } } } identity = newIdentity; updateSignature(); updateFrom(); quotedMessagePresenter.processDraftMessage(messageViewInfo, k9identity); } static class SendMessageTask extends AsyncTask<Void, Void, Void> { final Context context; final Account account; final Contacts contacts; final Message message; final Long draftId; final MessageReference messageReference; SendMessageTask(Context context, Account account, Contacts contacts, Message message, Long draftId, MessageReference messageReference) { this.context = context; this.account = account; this.contacts = contacts; this.message = message; this.draftId = draftId; this.messageReference = messageReference; } @Override protected Void doInBackground(Void... params) { try { contacts.markAsContacted(message.getRecipients(RecipientType.TO)); contacts.markAsContacted(message.getRecipients(RecipientType.CC)); contacts.markAsContacted(message.getRecipients(RecipientType.BCC)); updateReferencedMessage(); } catch (Exception e) { Timber.e(e, "Failed to mark contact as contacted."); } MessagingController.getInstance(context).sendMessage(account, message, null); if (draftId != null) { // TODO set draft id to invalid in MessageCompose! MessagingController.getInstance(context).deleteDraft(account, draftId); } return null; } /** * Set the flag on the referenced message(indicated we replied / forwarded the message) **/ private void updateReferencedMessage() { if (messageReference != null && messageReference.getFlag() != null) { Timber.d("Setting referenced message (%s, %s) flag to %s", messageReference.getFolderServerId(), messageReference.getUid(), messageReference.getFlag()); final Account account = Preferences.getPreferences(context) .getAccount(messageReference.getAccountUuid()); final String folderServerId = messageReference.getFolderServerId(); final String sourceMessageUid = messageReference.getUid(); MessagingController.getInstance(context).setFlag(account, folderServerId, sourceMessageUid, messageReference.getFlag(), true); } } } /** * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. * * @param mailTo * The MailTo object we use to initialize message field */ private void initializeFromMailto(MailTo mailTo) { recipientPresenter.initFromMailto(mailTo); String subject = mailTo.getSubject(); if (subject != null && !subject.isEmpty()) { subjectView.setText(subject); } String body = mailTo.getBody(); if (body != null && !body.isEmpty()) { messageContentView.setCharacters(body); } } private void setCurrentMessageFormat(SimpleMessageFormat format) { // This method will later be used to enable/disable the rich text editing mode. currentMessageFormat = format; } public void updateMessageFormat() { MessageFormat origMessageFormat = account.getMessageFormat(); SimpleMessageFormat messageFormat; if (origMessageFormat == MessageFormat.TEXT) { // The user wants to send text/plain messages. We don't override that choice under // any circumstances. messageFormat = SimpleMessageFormat.TEXT; } else if (quotedMessagePresenter.isForcePlainText() && quotedMessagePresenter.includeQuotedText()) { // Right now we send a text/plain-only message when the quoted text was edited, no // matter what the user selected for the message format. messageFormat = SimpleMessageFormat.TEXT; } else if (recipientPresenter.isForceTextMessageFormat()) { // Right now we only support PGP inline which doesn't play well with HTML. So force // plain text in those cases. messageFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { if (action == Action.COMPOSE || quotedMessagePresenter.isQuotedTextText() || !quotedMessagePresenter.includeQuotedText()) { // If the message format is set to "AUTO" we use text/plain whenever possible. That // is, when composing new messages and replying to or forwarding text/plain // messages. messageFormat = SimpleMessageFormat.TEXT; } else { messageFormat = SimpleMessageFormat.HTML; } } else { // In all other cases use HTML messageFormat = SimpleMessageFormat.HTML; } setCurrentMessageFormat(messageFormat); } @Override public void onMessageBuildSuccess(MimeMessage message, boolean isDraft) { if (isDraft) { changesMadeSinceLastSave = false; currentMessageBuilder = null; if (action == Action.EDIT_DRAFT && relatedMessageReference != null) { message.setUid(relatedMessageReference.getUid()); } boolean saveRemotely = recipientPresenter.shouldSaveRemotely(); new SaveMessageTask(getApplicationContext(), account, contacts, internalMessageHandler, message, draftId, saveRemotely).execute(); if (finishAfterDraftSaved) { finish(); } else { setProgressBarIndeterminateVisibility(false); } } else { currentMessageBuilder = null; new SendMessageTask(getApplicationContext(), account, contacts, message, draftId != INVALID_DRAFT_ID ? draftId : null, relatedMessageReference).execute(); finish(); } } @Override public void onMessageBuildCancel() { currentMessageBuilder = null; setProgressBarIndeterminateVisibility(false); } @Override public void onMessageBuildException(MessagingException me) { Timber.e(me, "Error sending message"); Toast.makeText(MessageCompose.this, getString(R.string.send_failed_reason, me.getLocalizedMessage()), Toast.LENGTH_LONG).show(); currentMessageBuilder = null; setProgressBarIndeterminateVisibility(false); } @Override public void onMessageBuildReturnPendingIntent(PendingIntent pendingIntent, int requestCode) { requestCode |= REQUEST_MASK_MESSAGE_BUILDER; try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { Timber.e(e, "Error starting pending intent from builder!"); } } public void launchUserInteractionPendingIntent(PendingIntent pendingIntent, int requestCode) { requestCode |= REQUEST_MASK_RECIPIENT_PRESENTER; try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { e.printStackTrace(); } } public void loadLocalMessageForDisplay(MessageViewInfo messageViewInfo, Action action) { // We check to see if we've previously processed the source message since this // could be called when switching from HTML to text replies. If that happens, we // only want to update the UI with quoted text (which picks the appropriate // part). if (relatedMessageProcessed) { try { quotedMessagePresenter.populateUIWithQuotedMessage(messageViewInfo, true, action); } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? quotedMessagePresenter.showOrHideQuotedText(QuotedTextMode.HIDE); Timber.e(e, "Could not re-process source message; deleting quoted text to be safe."); } updateMessageFormat(); } else { processSourceMessage(messageViewInfo); relatedMessageProcessed = true; } } private MessageLoaderCallbacks messageLoaderCallbacks = new MessageLoaderCallbacks() { @Override public void onMessageDataLoadFinished(LocalMessage message) { // nothing to do here, we don't care about message headers } @Override public void onMessageDataLoadFailed() { internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_OFF); Toast.makeText(MessageCompose.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } @Override public void onMessageViewInfoLoadFinished(MessageViewInfo messageViewInfo) { internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_OFF); loadLocalMessageForDisplay(messageViewInfo, action); } @Override public void onMessageViewInfoLoadFailed(MessageViewInfo messageViewInfo) { internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_OFF); Toast.makeText(MessageCompose.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } @Override public void setLoadingProgress(int current, int max) { // nvm - we don't have a progress bar } @Override public void startIntentSenderForMessageLoaderHelper(IntentSender si, int requestCode, Intent fillIntent, int flagsMask, int flagValues, int extraFlags) { try { requestCode |= REQUEST_MASK_LOADER_HELPER; startIntentSenderForResult(si, requestCode, fillIntent, flagsMask, flagValues, extraFlags); } catch (SendIntentException e) { Timber.e(e, "Irrecoverable error calling PendingIntent!"); } } @Override public void onDownloadErrorMessageNotFound() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MessageCompose.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } }); } @Override public void onDownloadErrorNetworkError() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MessageCompose.this, R.string.status_network_error, Toast.LENGTH_LONG).show(); } }); } }; private void initializeActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } // TODO We miss callbacks for this listener if they happens while we are paused! public MessagingListener messagingListener = new SimpleMessagingListener() { @Override public void messageUidChanged(Account account, String folderServerId, String oldUid, String newUid) { if (relatedMessageReference == null) { return; } Account sourceAccount = Preferences.getPreferences(MessageCompose.this) .getAccount(relatedMessageReference.getAccountUuid()); String sourceFolder = relatedMessageReference.getFolderServerId(); String sourceMessageUid = relatedMessageReference.getUid(); boolean changedMessageIsCurrent = account.equals(sourceAccount) && folderServerId.equals(sourceFolder) && oldUid.equals(sourceMessageUid); if (changedMessageIsCurrent) { relatedMessageReference = relatedMessageReference.withModifiedUid(newUid); } } }; AttachmentMvpView attachmentMvpView = new AttachmentMvpView() { private HashMap<Uri, View> attachmentViews = new HashMap<>(); @Override public void showWaitingForAttachmentDialog(WaitingAction waitingAction) { String title; switch (waitingAction) { case SEND: { title = getString(R.string.fetching_attachment_dialog_title_send); break; } case SAVE: { title = getString(R.string.fetching_attachment_dialog_title_save); break; } default: { return; } } ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title, getString(R.string.fetching_attachment_dialog_message)); fragment.show(getFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT); } @Override public void dismissWaitingForAttachmentDialog() { ProgressDialogFragment fragment = (ProgressDialogFragment) getFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT); if (fragment != null) { fragment.dismiss(); } } @Override @SuppressLint("InlinedApi") public void showPickAttachmentDialog(int requestCode) { requestCode |= REQUEST_MASK_ATTACHMENT_PRESENTER; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); isInSubActivity = true; startActivityForResult(Intent.createChooser(i, null), requestCode); } @Override public void addAttachmentView(final Attachment attachment) { View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, attachmentsView, false); attachmentViews.put(attachment.uri, view); View deleteButton = view.findViewById(R.id.attachment_delete); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attachmentPresenter.onClickRemoveAttachment(attachment.uri); } }); updateAttachmentView(attachment); attachmentsView.addView(view); } @Override public void updateAttachmentView(Attachment attachment) { View view = attachmentViews.get(attachment.uri); if (view == null) { throw new IllegalArgumentException(); } TextView nameView = (TextView) view.findViewById(R.id.attachment_name); boolean hasMetadata = (attachment.state != Attachment.LoadingState.URI_ONLY); if (hasMetadata) { nameView.setText(attachment.name); } else { nameView.setText(R.string.loading_attachment); } View progressBar = view.findViewById(R.id.progressBar); boolean isLoadingComplete = (attachment.state == Attachment.LoadingState.COMPLETE); progressBar.setVisibility(isLoadingComplete ? View.GONE : View.VISIBLE); } @Override public void removeAttachmentView(Attachment attachment) { View view = attachmentViews.get(attachment.uri); attachmentsView.removeView(view); attachmentViews.remove(attachment.uri); } @Override public void performSendAfterChecks() { MessageCompose.this.performSendAfterChecks(); } @Override public void performSaveAfterChecks() { MessageCompose.this.performSaveAfterChecks(); } @Override public void showMissingAttachmentsPartialMessageWarning() { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_attachments_skipped_toast), Toast.LENGTH_LONG).show(); } @Override public void showMissingAttachmentsPartialMessageForwardWarning() { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_attachments_forward_toast), Toast.LENGTH_LONG).show(); } }; private Handler internalMessageHandler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_PROGRESS_ON: setProgressBarIndeterminateVisibility(true); break; case MSG_PROGRESS_OFF: setProgressBarIndeterminateVisibility(false); break; case MSG_SAVED_DRAFT: draftId = (Long) msg.obj; Toast.makeText( MessageCompose.this, getString(R.string.message_saved_toast), Toast.LENGTH_LONG).show(); break; case MSG_DISCARDED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); break; default: super.handleMessage(msg); break; } } }; public enum Action { COMPOSE(R.string.compose_title_compose), REPLY(R.string.compose_title_reply), REPLY_ALL(R.string.compose_title_reply_all), FORWARD(R.string.compose_title_forward), FORWARD_AS_ATTACHMENT(R.string.compose_title_forward_as_attachment), EDIT_DRAFT(R.string.compose_title_compose); private final int titleResource; Action(@StringRes int titleResource) { this.titleResource = titleResource; } @StringRes public int getTitleResource() { return titleResource; } } }
package com.fsck.k9.activity; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.IntentSender.SendIntentException; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.app.NavUtils; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.Window; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.MessageFormat; import com.fsck.k9.Identity; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.MessageLoaderHelper.MessageLoaderCallbacks; import com.fsck.k9.activity.compose.AttachmentPresenter; import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentMvpView; import com.fsck.k9.activity.compose.AttachmentPresenter.WaitingAction; import com.fsck.k9.activity.compose.ComposeCryptoStatus; import com.fsck.k9.activity.compose.ComposeCryptoStatus.SendErrorState; import com.fsck.k9.activity.compose.CryptoSettingsDialog.OnCryptoModeChangedListener; import com.fsck.k9.activity.compose.IdentityAdapter; import com.fsck.k9.activity.compose.IdentityAdapter.IdentityContainer; import com.fsck.k9.activity.compose.PgpInlineDialog.OnOpenPgpInlineChangeListener; import com.fsck.k9.activity.compose.PgpSignOnlyDialog.OnOpenPgpSignOnlyChangeListener; import com.fsck.k9.activity.compose.RecipientMvpView; import com.fsck.k9.activity.compose.RecipientPresenter; import com.fsck.k9.activity.compose.RecipientPresenter.CryptoMode; import com.fsck.k9.activity.compose.SaveMessageTask; import com.fsck.k9.activity.misc.Attachment; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.fragment.ProgressDialogFragment; import com.fsck.k9.fragment.ProgressDialogFragment.CancelListener; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.IdentityHelper; import com.fsck.k9.helper.MailTo; import com.fsck.k9.helper.ReplyToParser; import com.fsck.k9.helper.SimpleTextWatcher; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.mailstore.MessageViewInfo; import com.fsck.k9.message.ComposePgpInlineDecider; import com.fsck.k9.message.IdentityField; import com.fsck.k9.message.IdentityHeaderParser; import com.fsck.k9.message.MessageBuilder; import com.fsck.k9.message.PgpMessageBuilder; import com.fsck.k9.message.QuotedTextMode; import com.fsck.k9.message.SimpleMessageBuilder; import com.fsck.k9.message.SimpleMessageFormat; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.ui.EolConvertingEditText; import com.fsck.k9.ui.compose.QuotedMessageMvpView; import com.fsck.k9.ui.compose.QuotedMessagePresenter; import static com.fsck.k9.R.id.folder; import static com.fsck.k9.R.id.search; @SuppressWarnings("deprecation") // TODO get rid of activity dialogs and indeterminate progress bars public class MessageCompose extends K9Activity implements OnClickListener, CancelListener, OnFocusChangeListener, OnCryptoModeChangedListener, OnOpenPgpInlineChangeListener, OnOpenPgpSignOnlyChangeListener, MessageBuilder.Callback, AttachmentPresenter.AttachmentsChangedListener, RecipientPresenter.RecipientsChangedListener { private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1; private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 2; private static final int DIALOG_CHOOSE_IDENTITY = 3; private static final int DIALOG_CONFIRM_DISCARD = 4; private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID; public static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE"; public static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY"; public static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL"; public static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD"; public static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT"; public static final String EXTRA_ACCOUNT = "account"; public static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; public static final String EXTRA_MESSAGE_DECRYPTION_RESULT = "message_decryption_result"; private static final String STATE_KEY_SOURCE_MESSAGE_PROCED = "com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced"; private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId"; private static final String STATE_IDENTITY_CHANGED = "com.fsck.k9.activity.MessageCompose.identityChanged"; private static final String STATE_IDENTITY = "com.fsck.k9.activity.MessageCompose.identity"; private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo"; private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references"; private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt"; private static final String STATE_KEY_CHANGES_MADE_SINCE_LAST_SAVE = "com.fsck.k9.activity.MessageCompose.changesMadeSinceLastSave"; private static final String STATE_ALREADY_NOTIFIED_USER_OF_EMPTY_SUBJECT = "alreadyNotifiedUserOfEmptySubject"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment"; private static final int MSG_PROGRESS_ON = 1; private static final int MSG_PROGRESS_OFF = 2; public static final int MSG_SAVED_DRAFT = 4; private static final int MSG_DISCARDED_DRAFT = 5; private static final int REQUEST_MASK_RECIPIENT_PRESENTER = (1 << 8); private static final int REQUEST_MASK_LOADER_HELPER = (1 << 9); private static final int REQUEST_MASK_ATTACHMENT_PRESENTER = (1 << 10); private static final int REQUEST_MASK_MESSAGE_BUILDER = (1 << 11); /** * Regular expression to remove the first localized "Re:" prefix in subjects. * * Currently: * - "Aw:" (german: abbreviation for "Antwort") */ private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE); private QuotedMessagePresenter quotedMessagePresenter; private MessageLoaderHelper messageLoaderHelper; private AttachmentPresenter attachmentPresenter; private Contacts contacts; /** * The account used for message composition. */ private Account account; private Identity identity; private boolean identityChanged = false; private boolean signatureChanged = false; // relates to the message being replied to, forwarded, or edited TODO split up? private MessageReference relatedMessageReference; /** * Indicates that the source message has been processed at least once and should not * be processed on any subsequent loads. This protects us from adding attachments that * have already been added from the restore of the view state. */ private boolean relatedMessageProcessed = false; private RecipientPresenter recipientPresenter; private MessageBuilder currentMessageBuilder; private boolean finishAfterDraftSaved; private boolean alreadyNotifiedUserOfEmptySubject = false; private boolean changesMadeSinceLastSave = false; /** * The database ID of this message's draft. This is used when saving drafts so the message in * the database is updated instead of being created anew. This property is INVALID_DRAFT_ID * until the first save. */ private long draftId = INVALID_DRAFT_ID; private Action action; private boolean requestReadReceipt = false; private TextView chooseIdentityButton; private EditText subjectView; private EolConvertingEditText signatureView; private EolConvertingEditText messageContentView; private LinearLayout attachmentsView; private String referencedMessageIds; private String repliedToMessageId; // The currently used message format. private SimpleMessageFormat currentMessageFormat; private boolean isInSubActivity = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (K9.getK9ComposerThemeSetting() != K9.Theme.USE_GLOBAL) { // theme the whole content according to the theme (except the action bar) ContextThemeWrapper themeContext = new ContextThemeWrapper(this, K9.getK9ThemeResourceId(K9.getK9ComposerTheme())); @SuppressLint("InflateParams") // this is the top level activity element, it has no root View v = LayoutInflater.from(themeContext).inflate(R.layout.message_compose, null); TypedValue outValue = new TypedValue(); // background color needs to be forced themeContext.getTheme().resolveAttribute(R.attr.messageViewBackgroundColor, outValue, true); v.setBackgroundColor(outValue.data); setContentView(v); } else { setContentView(R.layout.message_compose); } ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // on api level 15, setContentView() shows the progress bar for some reason... setProgressBarIndeterminateVisibility(false); final Intent intent = getIntent(); String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE); relatedMessageReference = MessageReference.parse(messageReferenceString); final String accountUuid = (relatedMessageReference != null) ? relatedMessageReference.getAccountUuid() : intent.getStringExtra(EXTRA_ACCOUNT); account = Preferences.getPreferences(this).getAccount(accountUuid); if (account == null) { account = Preferences.getPreferences(this).getDefaultAccount(); } if (account == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); changesMadeSinceLastSave = false; finish(); return; } contacts = Contacts.getInstance(MessageCompose.this); chooseIdentityButton = (TextView) findViewById(R.id.identity); chooseIdentityButton.setOnClickListener(this); RecipientMvpView recipientMvpView = new RecipientMvpView(this); ComposePgpInlineDecider composePgpInlineDecider = new ComposePgpInlineDecider(); recipientPresenter = new RecipientPresenter(getApplicationContext(), getLoaderManager(), recipientMvpView, account, composePgpInlineDecider, new ReplyToParser(), this); recipientPresenter.updateCryptoStatus(); subjectView = (EditText) findViewById(R.id.subject); subjectView.getInputExtras(true).putBoolean("allowEmoji", true); EolConvertingEditText upperSignature = (EolConvertingEditText) findViewById(R.id.upper_signature); EolConvertingEditText lowerSignature = (EolConvertingEditText) findViewById(R.id.lower_signature); QuotedMessageMvpView quotedMessageMvpView = new QuotedMessageMvpView(this); quotedMessagePresenter = new QuotedMessagePresenter(this, quotedMessageMvpView, account); attachmentPresenter = new AttachmentPresenter(getApplicationContext(), attachmentMvpView, getLoaderManager(), this); messageContentView = (EolConvertingEditText) findViewById(R.id.message_content); messageContentView.getInputExtras(true).putBoolean("allowEmoji", true); attachmentsView = (LinearLayout) findViewById(R.id.attachments); TextWatcher draftNeedsChangingTextWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { changesMadeSinceLastSave = true; } }; TextWatcher signTextWatcher = new SimpleTextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { changesMadeSinceLastSave = true; signatureChanged = true; } }; recipientMvpView.addTextChangedListener(draftNeedsChangingTextWatcher); quotedMessageMvpView.addTextChangedListener(draftNeedsChangingTextWatcher); subjectView.addTextChangedListener(draftNeedsChangingTextWatcher); messageContentView.addTextChangedListener(draftNeedsChangingTextWatcher); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ quotedMessagePresenter.showOrHideQuotedText(QuotedTextMode.NONE); subjectView.setOnFocusChangeListener(this); messageContentView.setOnFocusChangeListener(this); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreInstanceState */ relatedMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } if (initFromIntent(intent)) { action = Action.COMPOSE; changesMadeSinceLastSave = true; } else { String action = intent.getAction(); if (ACTION_COMPOSE.equals(action)) { this.action = Action.COMPOSE; } else if (ACTION_REPLY.equals(action)) { this.action = Action.REPLY; } else if (ACTION_REPLY_ALL.equals(action)) { this.action = Action.REPLY_ALL; } else if (ACTION_FORWARD.equals(action)) { this.action = Action.FORWARD; } else if (ACTION_EDIT_DRAFT.equals(action)) { this.action = Action.EDIT_DRAFT; } else { // This shouldn't happen Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action"); this.action = Action.COMPOSE; } } if (identity == null) { identity = account.getIdentity(0); } if (account.isSignatureBeforeQuotedText()) { signatureView = upperSignature; lowerSignature.setVisibility(View.GONE); } else { signatureView = lowerSignature; upperSignature.setVisibility(View.GONE); } updateSignature(); signatureView.addTextChangedListener(signTextWatcher); if (!identity.getSignatureUse()) { signatureView.setVisibility(View.GONE); } requestReadReceipt = account.isMessageReadReceiptAlways(); updateFrom(); if (!relatedMessageProcessed) { if (action == Action.REPLY || action == Action.REPLY_ALL || action == Action.FORWARD || action == Action.EDIT_DRAFT) { messageLoaderHelper = new MessageLoaderHelper(this, getLoaderManager(), getFragmentManager(), messageLoaderCallbacks); internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_ON); Parcelable cachedDecryptionResult = intent.getParcelableExtra(EXTRA_MESSAGE_DECRYPTION_RESULT); messageLoaderHelper.asyncStartOrResumeLoadingMessage(relatedMessageReference, cachedDecryptionResult); } if (action != Action.EDIT_DRAFT) { String alwaysBccString = account.getAlwaysBcc(); if (!TextUtils.isEmpty(alwaysBccString)) { recipientPresenter.addBccAddresses(Address.parse(alwaysBccString)); } } } if (action == Action.REPLY || action == Action.REPLY_ALL) { relatedMessageReference = relatedMessageReference.withModifiedFlag(Flag.ANSWERED); } if (action == Action.REPLY || action == Action.REPLY_ALL || action == Action.EDIT_DRAFT) { //change focus to message body. messageContentView.requestFocus(); } else { // Explicitly set focus to "To:" input field (see issue 2998) recipientMvpView.requestFocusOnToField(); } if (action == Action.FORWARD) { relatedMessageReference = relatedMessageReference.withModifiedFlag(Flag.FORWARDED); } updateMessageFormat(); // Set font size of input controls int fontSize = K9.getFontSizes().getMessageComposeInput(); recipientMvpView.setFontSizes(K9.getFontSizes(), fontSize); quotedMessageMvpView.setFontSizes(K9.getFontSizes(), fontSize); K9.getFontSizes().setViewTextSize(subjectView, fontSize); K9.getFontSizes().setViewTextSize(messageContentView, fontSize); K9.getFontSizes().setViewTextSize(signatureView, fontSize); updateMessageFormat(); setTitle(); currentMessageBuilder = (MessageBuilder) getLastNonConfigurationInstance(); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.reattachCallback(this); } } @Override public void onDestroy() { super.onDestroy(); if (recipientPresenter != null) { recipientPresenter.onActivityDestroy(); } } /** * Handle external intents that trigger the message compose activity. * * <p> * Supported external intents: * <ul> * <li>{@link Intent#ACTION_VIEW}</li> * <li>{@link Intent#ACTION_SENDTO}</li> * <li>{@link Intent#ACTION_SEND}</li> * <li>{@link Intent#ACTION_SEND_MULTIPLE}</li> * </ul> * </p> * * @param intent * The (external) intent that started the activity. * * @return {@code true}, if this activity was started by an external intent. {@code false}, * otherwise. */ private boolean initFromIntent(final Intent intent) { boolean startedByExternalIntent = false; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { /* * Someone has clicked a mailto: link. The address is in the URI. */ if (intent.getData() != null) { Uri uri = intent.getData(); if (MailTo.isMailTo(uri)) { MailTo mailTo = MailTo.parse(uri); initializeFromMailto(mailTo); } } /* * Note: According to the documentation ACTION_VIEW and ACTION_SENDTO don't accept * EXTRA_* parameters. * And previously we didn't process these EXTRAs. But it looks like nobody bothers to * read the official documentation and just copies wrong sample code that happens to * work with the AOSP Email application. And because even big players get this wrong, * we're now finally giving in and read the EXTRAs for those actions (below). */ } if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) || Intent.ACTION_SENDTO.equals(action) || Intent.ACTION_VIEW.equals(action)) { startedByExternalIntent = true; /* * Note: Here we allow a slight deviation from the documented behavior. * EXTRA_TEXT is used as message body (if available) regardless of the MIME * type of the intent. In addition one or multiple attachments can be added * using EXTRA_STREAM. */ CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI if (text != null && messageContentView.getText().length() == 0) { messageContentView.setCharacters(text); } String type = intent.getType(); if (Intent.ACTION_SEND.equals(action)) { Uri stream = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null) { attachmentPresenter.addAttachment(stream, type); } } else { List<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Parcelable parcelable : list) { Uri stream = (Uri) parcelable; if (stream != null) { attachmentPresenter.addAttachment(stream, type); } } } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); // Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI if (subject != null && subjectView.getText().length() == 0) { subjectView.setText(subject); } recipientPresenter.initFromSendOrViewIntent(intent); } return startedByExternalIntent; } @Override protected void onResume() { super.onResume(); MessagingController.getInstance(this).addListener(messagingListener); } @Override public void onPause() { super.onPause(); MessagingController.getInstance(this).removeListener(messagingListener); boolean isPausingOnConfigurationChange = (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == ActivityInfo.CONFIG_ORIENTATION; boolean isCurrentlyBuildingMessage = currentMessageBuilder != null; if (isPausingOnConfigurationChange || isCurrentlyBuildingMessage || isInSubActivity) { return; } checkToSaveDraftImplicitly(); } /** * The framework handles most of the fields, but we need to handle stuff that we * dynamically show and hide: * Attachment list, * Cc field, * Bcc field, * Quoted text, */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, relatedMessageProcessed); outState.putLong(STATE_KEY_DRAFT_ID, draftId); outState.putSerializable(STATE_IDENTITY, identity); outState.putBoolean(STATE_IDENTITY_CHANGED, identityChanged); outState.putString(STATE_IN_REPLY_TO, repliedToMessageId); outState.putString(STATE_REFERENCES, referencedMessageIds); outState.putBoolean(STATE_KEY_READ_RECEIPT, requestReadReceipt); outState.putBoolean(STATE_KEY_CHANGES_MADE_SINCE_LAST_SAVE, changesMadeSinceLastSave); outState.putBoolean(STATE_ALREADY_NOTIFIED_USER_OF_EMPTY_SUBJECT, alreadyNotifiedUserOfEmptySubject); recipientPresenter.onSaveInstanceState(outState); quotedMessagePresenter.onSaveInstanceState(outState); attachmentPresenter.onSaveInstanceState(outState); } @Override public Object onRetainNonConfigurationInstance() { if (currentMessageBuilder != null) { currentMessageBuilder.detachCallback(); } return currentMessageBuilder; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); attachmentsView.removeAllViews(); requestReadReceipt = savedInstanceState.getBoolean(STATE_KEY_READ_RECEIPT); recipientPresenter.onRestoreInstanceState(savedInstanceState); quotedMessagePresenter.onRestoreInstanceState(savedInstanceState); attachmentPresenter.onRestoreInstanceState(savedInstanceState); draftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID); identity = (Identity) savedInstanceState.getSerializable(STATE_IDENTITY); identityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED); repliedToMessageId = savedInstanceState.getString(STATE_IN_REPLY_TO); referencedMessageIds = savedInstanceState.getString(STATE_REFERENCES); changesMadeSinceLastSave = savedInstanceState.getBoolean(STATE_KEY_CHANGES_MADE_SINCE_LAST_SAVE); alreadyNotifiedUserOfEmptySubject = savedInstanceState.getBoolean(STATE_ALREADY_NOTIFIED_USER_OF_EMPTY_SUBJECT); updateFrom(); updateMessageFormat(); } private void setTitle() { setTitle(action.getTitleResource()); } @Nullable private MessageBuilder createMessageBuilder(boolean isDraft) { MessageBuilder builder; recipientPresenter.updateCryptoStatus(); ComposeCryptoStatus cryptoStatus = recipientPresenter.getCurrentCryptoStatus(); // TODO encrypt drafts for storage if (!isDraft && cryptoStatus.shouldUsePgpMessageBuilder()) { SendErrorState maybeSendErrorState = cryptoStatus.getSendErrorStateOrNull(); if (maybeSendErrorState != null) { recipientPresenter.showPgpSendError(maybeSendErrorState); return null; } PgpMessageBuilder pgpBuilder = PgpMessageBuilder.newInstance(); recipientPresenter.builderSetProperties(pgpBuilder); builder = pgpBuilder; } else { builder = SimpleMessageBuilder.newInstance(); } builder.setSubject(Utility.stripNewLines(subjectView.getText().toString())) .setSentDate(new Date()) .setHideTimeZone(K9.hideTimeZone()) .setTo(recipientPresenter.getToAddresses()) .setCc(recipientPresenter.getCcAddresses()) .setBcc(recipientPresenter.getBccAddresses()) .setInReplyTo(repliedToMessageId) .setReferences(referencedMessageIds) .setRequestReadReceipt(requestReadReceipt) .setIdentity(identity) .setMessageFormat(currentMessageFormat) .setText(messageContentView.getCharacters()) .setAttachments(attachmentPresenter.createAttachmentList()) .setSignature(signatureView.getCharacters()) .setSignatureBeforeQuotedText(account.isSignatureBeforeQuotedText()) .setIdentityChanged(identityChanged) .setSignatureChanged(signatureChanged) .setCursorPosition(messageContentView.getSelectionStart()) .setMessageReference(relatedMessageReference) .setDraft(isDraft) .setIsPgpInlineEnabled(cryptoStatus.isPgpInlineModeEnabled()); quotedMessagePresenter.builderSetProperties(builder); return builder; } private void checkToSendMessage() { if (subjectView.getText().length() == 0 && !alreadyNotifiedUserOfEmptySubject) { Toast.makeText(this, R.string.empty_subject, Toast.LENGTH_LONG).show(); alreadyNotifiedUserOfEmptySubject = true; return; } if (recipientPresenter.checkRecipientsOkForSending()) { return; } if (attachmentPresenter.checkOkForSendingOrDraftSaving()) { return; } performSendAfterChecks(); } private void checkToSaveDraftAndSave() { if (!account.hasDraftsFolder()) { Toast.makeText(this, R.string.compose_error_no_draft_folder, Toast.LENGTH_SHORT).show(); return; } if (attachmentPresenter.checkOkForSendingOrDraftSaving()) { return; } finishAfterDraftSaved = true; performSaveAfterChecks(); } private void checkToSaveDraftImplicitly() { if (!account.hasDraftsFolder()) { return; } if (!changesMadeSinceLastSave) { return; } finishAfterDraftSaved = false; performSaveAfterChecks(); } private void performSaveAfterChecks() { currentMessageBuilder = createMessageBuilder(true); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } private void onDiscard() { onDiscardChanges(); finish(); } private void onReadReceipt() { CharSequence txt; if (!requestReadReceipt) { txt = getString(R.string.read_receipt_enabled); requestReadReceipt = true; } else { txt = getString(R.string.read_receipt_disabled); requestReadReceipt = false; } Context context = getApplicationContext(); Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT); toast.show(); } public void showContactPicker(int requestCode) { requestCode |= REQUEST_MASK_RECIPIENT_PRESENTER; isInSubActivity = true; startActivityForResult(contacts.contactPickerIntent(), requestCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { isInSubActivity = false; if ((requestCode & REQUEST_MASK_MESSAGE_BUILDER) == REQUEST_MASK_MESSAGE_BUILDER) { requestCode ^= REQUEST_MASK_MESSAGE_BUILDER; if (currentMessageBuilder == null) { Log.e(K9.LOG_TAG, "Got a message builder activity result for no message builder, " + "this is an illegal state!"); return; } currentMessageBuilder.onActivityResult(requestCode, resultCode, data, this); return; } if ((requestCode & REQUEST_MASK_RECIPIENT_PRESENTER) == REQUEST_MASK_RECIPIENT_PRESENTER) { requestCode ^= REQUEST_MASK_RECIPIENT_PRESENTER; recipientPresenter.onActivityResult(requestCode, resultCode, data); return; } if ((requestCode & REQUEST_MASK_LOADER_HELPER) == REQUEST_MASK_LOADER_HELPER) { requestCode ^= REQUEST_MASK_LOADER_HELPER; messageLoaderHelper.onActivityResult(requestCode, resultCode, data); return; } if ((requestCode & REQUEST_MASK_ATTACHMENT_PRESENTER) == REQUEST_MASK_ATTACHMENT_PRESENTER) { requestCode ^= REQUEST_MASK_ATTACHMENT_PRESENTER; attachmentPresenter.onActivityResult(resultCode, requestCode, data); } } private void onAccountChosen(Account account, Identity identity) { if (!this.account.equals(account)) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Switching account from " + this.account + " to " + account); } // on draft edit, make sure we don't keep previous message UID if (action == Action.EDIT_DRAFT) { relatedMessageReference = null; } // test whether there is something to save if (changesMadeSinceLastSave || (draftId != INVALID_DRAFT_ID)) { final long previousDraftId = draftId; final Account previousAccount = this.account; // make current message appear as new draftId = INVALID_DRAFT_ID; // actual account switch this.account = account; if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account"); } checkToSaveDraftImplicitly(); if (previousDraftId != INVALID_DRAFT_ID) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: " + previousDraftId); } MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftId); } } else { this.account = account; } // Show CC/BCC text input field when switching to an account that always wants them // displayed. // Please note that we're not hiding the fields if the user switches back to an account // that doesn't have this setting checked. recipientPresenter.onSwitchAccount(this.account); quotedMessagePresenter.onSwitchAccount(this.account); // not sure how to handle mFolder, mSourceMessage? } switchToIdentity(identity); } private void switchToIdentity(Identity identity) { this.identity = identity; identityChanged = true; changesMadeSinceLastSave = true; updateFrom(); updateSignature(); updateMessageFormat(); recipientPresenter.onSwitchIdentity(identity); } private void updateFrom() { chooseIdentityButton.setText(identity.getEmail()); } private void updateSignature() { if (identity.getSignatureUse()) { signatureView.setCharacters(identity.getSignature()); signatureView.setVisibility(View.VISIBLE); } else { signatureView.setVisibility(View.GONE); } } @Override public void onFocusChange(View v, boolean hasFocus) { switch (v.getId()) { case R.id.message_content: case R.id.subject: if (hasFocus) { recipientPresenter.onNonRecipientFieldFocused(); } break; } } @Override public void onCryptoModeChanged(CryptoMode cryptoMode) { recipientPresenter.onCryptoModeChanged(cryptoMode); } @Override public void onOpenPgpInlineChange(boolean enabled) { recipientPresenter.onCryptoPgpInlineChanged(enabled); } @Override public void onOpenPgpSignOnlyChange(boolean enabled) { recipientPresenter.onCryptoPgpSignOnlyDisabled(); } @Override public void onAttachmentAdded() { changesMadeSinceLastSave = true; } @Override public void onAttachmentRemoved() { changesMadeSinceLastSave = true; } @Override public void onRecipientsChanged() { changesMadeSinceLastSave = true; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.identity: showDialog(DIALOG_CHOOSE_IDENTITY); break; } } private void askBeforeDiscard() { if (K9.confirmDiscardMessage()) { showDialog(DIALOG_CONFIRM_DISCARD); } else { onDiscard(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: goBack(); return true; case R.id.send: checkToSendMessage(); break; case R.id.save: checkToSaveDraftAndSave(); break; case R.id.discard: askBeforeDiscard(); break; case R.id.add_from_contacts: recipientPresenter.onMenuAddFromContacts(); break; case R.id.openpgp_inline_enable: recipientPresenter.onMenuSetPgpInline(true); updateMessageFormat(); break; case R.id.openpgp_inline_disable: recipientPresenter.onMenuSetPgpInline(false); updateMessageFormat(); break; case R.id.openpgp_sign_only: recipientPresenter.onMenuSetSignOnly(true); break; case R.id.openpgp_sign_only_disable: recipientPresenter.onMenuSetSignOnly(false); break; case R.id.add_attachment: attachmentPresenter.onClickAddAttachment(recipientPresenter); break; case R.id.read_receipt: onReadReceipt(); break; default: return super.onOptionsItemSelected(item); } return true; } private void goBack() { if (changesMadeSinceLastSave && draftIsNotEmpty()) { showDialogDraft(); } else { onDiscardChanges(); String inbox = account.getInboxFolderName(); LocalSearch localSearch = new LocalSearch(inbox); localSearch.addAccountUuid(account.getUuid()); localSearch.addAllowedFolder(inbox); MessageList.actionDisplaySearch(this, localSearch, false, false); } } private void onDiscardChanges() { if (draftId != INVALID_DRAFT_ID) { MessagingController.getInstance(getApplication()).deleteDraft(account, draftId); draftId = INVALID_DRAFT_ID; } internalMessageHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT); changesMadeSinceLastSave = false; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (isFinishing()) { return false; } getMenuInflater().inflate(R.menu.message_compose_option, menu); // Disable the 'Save' menu option if Drafts folder is set to -NONE- if (!account.hasDraftsFolder()) { menu.findItem(R.id.save).setEnabled(false); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); recipientPresenter.onPrepareOptionsMenu(menu); return true; } @Override public void onBackPressed() { if (changesMadeSinceLastSave && draftIsNotEmpty()) { showDialogDraft(); } else { // Check if editing an existing draft. if (draftId == INVALID_DRAFT_ID) { onDiscard(); } else { super.onBackPressed(); } } } private void showDialogDraft() { if (!account.hasDraftsFolder()) { showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } else { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); } } private boolean draftIsNotEmpty() { if (messageContentView.getText().length() != 0) { return true; } if (!attachmentPresenter.createAttachmentList().isEmpty()) { return true; } if (subjectView.getText().length() != 0) { return true; } if (!recipientPresenter.getToAddresses().isEmpty() || !recipientPresenter.getCcAddresses().isEmpty() || !recipientPresenter.getBccAddresses().isEmpty()) { return true; } return false; } public void onProgressCancel(ProgressDialogFragment fragment) { attachmentPresenter.attachmentProgressDialogCancelled(); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.save_or_discard_draft_message_dlg_title) .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); checkToSaveDraftAndSave(); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onDiscard(); } }) .create(); case DIALOG_CONFIRM_DISCARD_ON_BACK: return new AlertDialog.Builder(this) .setTitle(R.string.confirm_discard_draft_message_title) .setMessage(R.string.confirm_discard_draft_message) .setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); Toast.makeText(MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); onDiscard(); } }) .create(); case DIALOG_CHOOSE_IDENTITY: Context context = new ContextThemeWrapper(this, (K9.getK9Theme() == K9.Theme.LIGHT) ? R.style.Theme_K9_Dialog_Light : R.style.Theme_K9_Dialog_Dark); Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.send_as); final IdentityAdapter adapter = new IdentityAdapter(context); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { IdentityContainer container = (IdentityContainer) adapter.getItem(which); onAccountChosen(container.account, container.identity); } }); return builder.create(); case DIALOG_CONFIRM_DISCARD: { return new AlertDialog.Builder(this) .setTitle(R.string.dialog_confirm_delete_title) .setMessage(R.string.dialog_confirm_delete_message) .setPositiveButton(R.string.dialog_confirm_delete_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { onDiscard(); } }) .setNegativeButton(R.string.dialog_confirm_delete_cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create(); } } return super.onCreateDialog(id); } public void saveDraftEventually() { changesMadeSinceLastSave = true; } public void loadQuotedTextForEdit() { if (relatedMessageReference == null) { // shouldn't happen... throw new IllegalStateException("tried to edit quoted message with no referenced message"); } messageLoaderHelper.asyncStartOrResumeLoadingMessage(relatedMessageReference, null); } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * * @param messageViewInfo * The source message used to populate the various text fields. */ private void processSourceMessage(MessageViewInfo messageViewInfo) { try { switch (action) { case REPLY: case REPLY_ALL: { processMessageToReplyTo(messageViewInfo); break; } case FORWARD: { processMessageToForward(messageViewInfo); break; } case EDIT_DRAFT: { processDraftMessage(messageViewInfo); break; } default: { Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action"); break; } } } catch (MessagingException me) { /* * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. */ Log.e(K9.LOG_TAG, "Error while processing source message: ", me); } finally { relatedMessageProcessed = true; changesMadeSinceLastSave = false; } updateMessageFormat(); } private void processMessageToReplyTo(MessageViewInfo messageViewInfo) throws MessagingException { Message message = messageViewInfo.message; if (message.getSubject() != null) { final String subject = PREFIX.matcher(message.getSubject()).replaceFirst(""); if (!subject.toLowerCase(Locale.US).startsWith("re:")) { subjectView.setText("Re: " + subject); } else { subjectView.setText(subject); } } else { subjectView.setText(""); } /* * If a reply-to was included with the message use that, otherwise use the from * or sender address. */ boolean isReplyAll = action == Action.REPLY_ALL; recipientPresenter.initFromReplyToMessage(message, isReplyAll); if (message.getMessageId() != null && message.getMessageId().length() > 0) { repliedToMessageId = message.getMessageId(); String[] refs = message.getReferences(); if (refs != null && refs.length > 0) { referencedMessageIds = TextUtils.join("", refs) + " " + repliedToMessageId; } else { referencedMessageIds = repliedToMessageId; } } else { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "could not get Message-ID."); } } // Quote the message and setup the UI. quotedMessagePresenter.initFromReplyToMessage(messageViewInfo, action); if (action == Action.REPLY || action == Action.REPLY_ALL) { Identity useIdentity = IdentityHelper.getRecipientIdentityFromMessage(account, message); Identity defaultIdentity = account.getIdentity(0); if (useIdentity != defaultIdentity) { switchToIdentity(useIdentity); } } } private void processMessageToForward(MessageViewInfo messageViewInfo) throws MessagingException { Message message = messageViewInfo.message; String subject = message.getSubject(); if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) { subjectView.setText("Fwd: " + subject); } else { subjectView.setText(subject); } // "Be Like Thunderbird" - on forwarded messages, set the message ID // of the forwarded message in the references and the reply to. TB // only includes ID of the message being forwarded in the reference, // even if there are multiple references. if (!TextUtils.isEmpty(message.getMessageId())) { repliedToMessageId = message.getMessageId(); referencedMessageIds = repliedToMessageId; } else { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "could not get Message-ID."); } } // Quote the message and setup the UI. quotedMessagePresenter.processMessageToForward(messageViewInfo); attachmentPresenter.processMessageToForward(messageViewInfo); } private void processDraftMessage(MessageViewInfo messageViewInfo) { Message message = messageViewInfo.message; draftId = MessagingController.getInstance(getApplication()).getId(message); subjectView.setText(message.getSubject()); recipientPresenter.initFromDraftMessage(message); // Read In-Reply-To header from draft final String[] inReplyTo = message.getHeader("In-Reply-To"); if (inReplyTo.length >= 1) { repliedToMessageId = inReplyTo[0]; } // Read References header from draft final String[] references = message.getHeader("References"); if (references.length >= 1) { referencedMessageIds = references[0]; } if (!relatedMessageProcessed) { attachmentPresenter.loadNonInlineAttachments(messageViewInfo); } // Decode the identity header when loading a draft. // See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob. Map<IdentityField, String> k9identity = new HashMap<>(); String[] identityHeaders = message.getHeader(K9.IDENTITY_HEADER); if (identityHeaders.length > 0 && identityHeaders[0] != null) { k9identity = IdentityHeaderParser.parse(identityHeaders[0]); } Identity newIdentity = new Identity(); if (k9identity.containsKey(IdentityField.SIGNATURE)) { newIdentity.setSignatureUse(true); newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE)); signatureChanged = true; } else { if (message instanceof LocalMessage) { newIdentity.setSignatureUse(((LocalMessage) message).getFolder().getSignatureUse()); } newIdentity.setSignature(identity.getSignature()); } if (k9identity.containsKey(IdentityField.NAME)) { newIdentity.setName(k9identity.get(IdentityField.NAME)); identityChanged = true; } else { newIdentity.setName(identity.getName()); } if (k9identity.containsKey(IdentityField.EMAIL)) { newIdentity.setEmail(k9identity.get(IdentityField.EMAIL)); identityChanged = true; } else { newIdentity.setEmail(identity.getEmail()); } if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) { relatedMessageReference = null; String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE); MessageReference messageReference = MessageReference.parse(originalMessage); if (messageReference != null) { // Check if this is a valid account in our database Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.getAccountUuid()); if (account != null) { relatedMessageReference = messageReference; } } } identity = newIdentity; updateSignature(); updateFrom(); quotedMessagePresenter.processDraftMessage(messageViewInfo, k9identity); } static class SendMessageTask extends AsyncTask<Void, Void, Void> { final Context context; final Account account; final Contacts contacts; final Message message; final Long draftId; final MessageReference messageReference; SendMessageTask(Context context, Account account, Contacts contacts, Message message, Long draftId, MessageReference messageReference) { this.context = context; this.account = account; this.contacts = contacts; this.message = message; this.draftId = draftId; this.messageReference = messageReference; } @Override protected Void doInBackground(Void... params) { try { contacts.markAsContacted(message.getRecipients(RecipientType.TO)); contacts.markAsContacted(message.getRecipients(RecipientType.CC)); contacts.markAsContacted(message.getRecipients(RecipientType.BCC)); updateReferencedMessage(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e); } MessagingController.getInstance(context).sendMessage(account, message, null); if (draftId != null) { // TODO set draft id to invalid in MessageCompose! MessagingController.getInstance(context).deleteDraft(account, draftId); } return null; } /** * Set the flag on the referenced message(indicated we replied / forwarded the message) **/ private void updateReferencedMessage() { if (messageReference != null && messageReference.getFlag() != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Setting referenced message (" + messageReference.getFolderName() + ", " + messageReference.getUid() + ") flag to " + messageReference.getFlag()); } final Account account = Preferences.getPreferences(context) .getAccount(messageReference.getAccountUuid()); final String folderName = messageReference.getFolderName(); final String sourceMessageUid = messageReference.getUid(); MessagingController.getInstance(context).setFlag(account, folderName, sourceMessageUid, messageReference.getFlag(), true); } } } /** * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. * * @param mailTo * The MailTo object we use to initialize message field */ private void initializeFromMailto(MailTo mailTo) { recipientPresenter.initFromMailto(mailTo); String subject = mailTo.getSubject(); if (subject != null && !subject.isEmpty()) { subjectView.setText(subject); } String body = mailTo.getBody(); if (body != null && !body.isEmpty()) { messageContentView.setCharacters(body); } } private void setCurrentMessageFormat(SimpleMessageFormat format) { // This method will later be used to enable/disable the rich text editing mode. currentMessageFormat = format; } public void updateMessageFormat() { MessageFormat origMessageFormat = account.getMessageFormat(); SimpleMessageFormat messageFormat; if (origMessageFormat == MessageFormat.TEXT) { // The user wants to send text/plain messages. We don't override that choice under // any circumstances. messageFormat = SimpleMessageFormat.TEXT; } else if (quotedMessagePresenter.isForcePlainText() && quotedMessagePresenter.includeQuotedText()) { // Right now we send a text/plain-only message when the quoted text was edited, no // matter what the user selected for the message format. messageFormat = SimpleMessageFormat.TEXT; } else if (recipientPresenter.isForceTextMessageFormat()) { // Right now we only support PGP inline which doesn't play well with HTML. So force // plain text in those cases. messageFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { if (action == Action.COMPOSE || quotedMessagePresenter.isQuotedTextText() || !quotedMessagePresenter.includeQuotedText()) { // If the message format is set to "AUTO" we use text/plain whenever possible. That // is, when composing new messages and replying to or forwarding text/plain // messages. messageFormat = SimpleMessageFormat.TEXT; } else { messageFormat = SimpleMessageFormat.HTML; } } else { // In all other cases use HTML messageFormat = SimpleMessageFormat.HTML; } setCurrentMessageFormat(messageFormat); } @Override public void onMessageBuildSuccess(MimeMessage message, boolean isDraft) { if (isDraft) { changesMadeSinceLastSave = false; currentMessageBuilder = null; if (action == Action.EDIT_DRAFT && relatedMessageReference != null) { message.setUid(relatedMessageReference.getUid()); } // TODO more appropriate logic here? not sure boolean saveRemotely = !recipientPresenter.getCurrentCryptoStatus().shouldUsePgpMessageBuilder(); new SaveMessageTask(getApplicationContext(), account, contacts, internalMessageHandler, message, draftId, saveRemotely).execute(); if (finishAfterDraftSaved) { finish(); } else { setProgressBarIndeterminateVisibility(false); } } else { currentMessageBuilder = null; new SendMessageTask(getApplicationContext(), account, contacts, message, draftId != INVALID_DRAFT_ID ? draftId : null, relatedMessageReference).execute(); finish(); } } @Override public void onMessageBuildCancel() { currentMessageBuilder = null; setProgressBarIndeterminateVisibility(false); } @Override public void onMessageBuildException(MessagingException me) { Log.e(K9.LOG_TAG, "Error sending message", me); Toast.makeText(MessageCompose.this, getString(R.string.send_failed_reason, me.getLocalizedMessage()), Toast.LENGTH_LONG).show(); currentMessageBuilder = null; setProgressBarIndeterminateVisibility(false); } @Override public void onMessageBuildReturnPendingIntent(PendingIntent pendingIntent, int requestCode) { requestCode |= REQUEST_MASK_MESSAGE_BUILDER; try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { Log.e(K9.LOG_TAG, "Error starting pending intent from builder!", e); } } public void launchUserInteractionPendingIntent(PendingIntent pendingIntent, int requestCode) { requestCode |= REQUEST_MASK_RECIPIENT_PRESENTER; try { startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (SendIntentException e) { e.printStackTrace(); } } public void loadLocalMessageForDisplay(MessageViewInfo messageViewInfo, Action action) { // We check to see if we've previously processed the source message since this // could be called when switching from HTML to text replies. If that happens, we // only want to update the UI with quoted text (which picks the appropriate // part). if (relatedMessageProcessed) { try { quotedMessagePresenter.populateUIWithQuotedMessage(messageViewInfo, true, action); } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? quotedMessagePresenter.showOrHideQuotedText(QuotedTextMode.HIDE); Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e); } updateMessageFormat(); } else { processSourceMessage(messageViewInfo); relatedMessageProcessed = true; } } private MessageLoaderCallbacks messageLoaderCallbacks = new MessageLoaderCallbacks() { @Override public void onMessageDataLoadFinished(LocalMessage message) { // nothing to do here, we don't care about message headers } @Override public void onMessageDataLoadFailed() { internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_OFF); Toast.makeText(MessageCompose.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } @Override public void onMessageViewInfoLoadFinished(MessageViewInfo messageViewInfo) { internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_OFF); loadLocalMessageForDisplay(messageViewInfo, action); } @Override public void onMessageViewInfoLoadFailed(MessageViewInfo messageViewInfo) { internalMessageHandler.sendEmptyMessage(MSG_PROGRESS_OFF); Toast.makeText(MessageCompose.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } @Override public void setLoadingProgress(int current, int max) { // nvm - we don't have a progress bar } @Override public void startIntentSenderForMessageLoaderHelper(IntentSender si, int requestCode, Intent fillIntent, int flagsMask, int flagValues, int extraFlags) { try { requestCode |= REQUEST_MASK_LOADER_HELPER; startIntentSenderForResult(si, requestCode, fillIntent, flagsMask, flagValues, extraFlags); } catch (SendIntentException e) { Log.e(K9.LOG_TAG, "Irrecoverable error calling PendingIntent!", e); } } @Override public void onDownloadErrorMessageNotFound() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MessageCompose.this, R.string.status_invalid_id_error, Toast.LENGTH_LONG).show(); } }); } @Override public void onDownloadErrorNetworkError() { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MessageCompose.this, R.string.status_network_error, Toast.LENGTH_LONG).show(); } }); } }; // TODO We miss callbacks for this listener if they happens while we are paused! public MessagingListener messagingListener = new MessagingListener() { @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { if (relatedMessageReference == null) { return; } Account sourceAccount = Preferences.getPreferences(MessageCompose.this) .getAccount(relatedMessageReference.getAccountUuid()); String sourceFolder = relatedMessageReference.getFolderName(); String sourceMessageUid = relatedMessageReference.getUid(); boolean changedMessageIsCurrent = account.equals(sourceAccount) && folder.equals(sourceFolder) && oldUid.equals(sourceMessageUid); if (changedMessageIsCurrent) { relatedMessageReference = relatedMessageReference.withModifiedUid(newUid); } } }; AttachmentMvpView attachmentMvpView = new AttachmentMvpView() { private HashMap<Uri, View> attachmentViews = new HashMap<>(); @Override public void showWaitingForAttachmentDialog(WaitingAction waitingAction) { String title; switch (waitingAction) { case SEND: { title = getString(R.string.fetching_attachment_dialog_title_send); break; } case SAVE: { title = getString(R.string.fetching_attachment_dialog_title_save); break; } default: { return; } } ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title, getString(R.string.fetching_attachment_dialog_message)); fragment.show(getFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT); } @Override public void dismissWaitingForAttachmentDialog() { ProgressDialogFragment fragment = (ProgressDialogFragment) getFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT); if (fragment != null) { fragment.dismiss(); } } @Override @SuppressLint("InlinedApi") public void showPickAttachmentDialog(int requestCode) { requestCode |= REQUEST_MASK_ATTACHMENT_PRESENTER; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); isInSubActivity = true; startActivityForResult(Intent.createChooser(i, null), requestCode); } @Override public void addAttachmentView(final Attachment attachment) { View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, attachmentsView, false); attachmentViews.put(attachment.uri, view); View deleteButton = view.findViewById(R.id.attachment_delete); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attachmentPresenter.onClickRemoveAttachment(attachment.uri); } }); updateAttachmentView(attachment); attachmentsView.addView(view); } @Override public void updateAttachmentView(Attachment attachment) { View view = attachmentViews.get(attachment.uri); if (view == null) { throw new IllegalArgumentException(); } TextView nameView = (TextView) view.findViewById(R.id.attachment_name); boolean hasMetadata = (attachment.state != Attachment.LoadingState.URI_ONLY); if (hasMetadata) { nameView.setText(attachment.name); } else { nameView.setText(R.string.loading_attachment); } View progressBar = view.findViewById(R.id.progressBar); boolean isLoadingComplete = (attachment.state == Attachment.LoadingState.COMPLETE); progressBar.setVisibility(isLoadingComplete ? View.GONE : View.VISIBLE); } @Override public void removeAttachmentView(Attachment attachment) { View view = attachmentViews.get(attachment.uri); attachmentsView.removeView(view); attachmentViews.remove(attachment.uri); } @Override public void performSendAfterChecks() { MessageCompose.this.performSendAfterChecks(); } @Override public void performSaveAfterChecks() { MessageCompose.this.performSaveAfterChecks(); } @Override public void showMissingAttachmentsPartialMessageWarning() { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_attachments_skipped_toast), Toast.LENGTH_LONG).show(); } }; private Handler internalMessageHandler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_PROGRESS_ON: setProgressBarIndeterminateVisibility(true); break; case MSG_PROGRESS_OFF: setProgressBarIndeterminateVisibility(false); break; case MSG_SAVED_DRAFT: draftId = (Long) msg.obj; Toast.makeText( MessageCompose.this, getString(R.string.message_saved_toast), Toast.LENGTH_LONG).show(); break; case MSG_DISCARDED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); break; default: super.handleMessage(msg); break; } } }; public enum Action { COMPOSE(R.string.compose_title_compose), REPLY(R.string.compose_title_reply), REPLY_ALL(R.string.compose_title_reply_all), FORWARD(R.string.compose_title_forward), EDIT_DRAFT(R.string.compose_title_compose); private final int titleResource; Action(@StringRes int titleResource) { this.titleResource = titleResource; } @StringRes public int getTitleResource() { return titleResource; } } }
package com.kafkaconsumer.groups; import java.io.File; import java.io.OutputStream; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.FileInputStream; public class LogWriter { private OutputStreamWriter osw; public LogWriter(String path) { File fout = new File(path); FileOutputStream fos = new FileOutputStream(fout); osw = new OutputStreamWriter(fos); } public OutputStreamWriter getWriter() { return osw; } }
package io.katharsis.jpa.query; public interface Tuple { public <T> T get(String name, Class<T> clazz); public <T> T get(int index, Class<T> clazz); }
package jenkins.diagnosis; import com.sun.akuma.JavaVMArguments; import hudson.Extension; import hudson.Functions; import hudson.Util; import hudson.model.AdministrativeMonitor; import hudson.util.jna.Kernel32Utils; import jenkins.model.Jenkins; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.FileSet; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.IOUtils; /** * Finds crash dump reports and show them in the UI. * * @author Kohsuke Kawaguchi */ @Extension(optional=true) // TODO why would an extension using a built-in extension point need to be marked optional? public class HsErrPidList extends AdministrativeMonitor { /** * hs_err_pid files that we think belong to us. */ /*package*/ final List<HsErrPidFile> files = new ArrayList<HsErrPidFile>(); /** * Used to keep a marker file memory-mapped, so that we can find hs_err_pid files that belong to us. */ private MappedByteBuffer map; public HsErrPidList() { if (Functions.getIsUnitTest()) { return; } try { FileChannel ch = null; try { ch = new FileInputStream(getSecretKeyFile()).getChannel(); map = ch.map(MapMode.READ_ONLY,0,1); } finally { if (ch != null) { ch.close(); } } scan("./hs_err_pid%p.log"); if (Functions.isWindows()) { File dir = Kernel32Utils.getTempDir(); if (dir!=null) { scan(dir.getPath() + "\\hs_err_pid%p.log"); } } else { scan("/tmp/hs_err_pid%p.log"); } // on different platforms, rules about the default locations are a lot more subtle. // check our arguments in the very end since this might fail on some platforms JavaVMArguments args = JavaVMArguments.current(); for (String a : args) { if (a.startsWith(ERROR_FILE_OPTION)) { scan(a.substring(ERROR_FILE_OPTION.length())); } } } catch (UnsupportedOperationException e) { // ignore } catch (Throwable e) { LOGGER.log(Level.WARNING, "Failed to list up hs_err_pid files", e); } } @Override public String getDisplayName() { return "JVM Crash Reports"; } /** * Expose files to the URL. */ public List<HsErrPidFile> getFiles() { return files; } private void scan(String pattern) { LOGGER.fine("Scanning "+pattern+" for hs_err_pid files"); pattern = pattern.replace("%p","*").replace("%%","%"); File f = new File(pattern).getAbsoluteFile(); if (!pattern.contains("*")) scanFile(f); else {// GLOB File commonParent = f; while (commonParent!=null && commonParent.getPath().contains("*")) { commonParent = commonParent.getParentFile(); } if (commonParent==null) { LOGGER.warning("Failed to process "+f); return; // huh? } FileSet fs = Util.createFileSet(commonParent, f.getPath().substring(commonParent.getPath().length()+1), null); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); for (String child : ds.getIncludedFiles()) { scanFile(new File(commonParent,child)); } } } private void scanFile(File log) { LOGGER.fine("Scanning "+log); BufferedReader r=null; try { r = new BufferedReader(new FileReader(log)); if (!findHeader(r)) return; // we should find a memory mapped file for secret.key String secretKey = getSecretKeyFile().getAbsolutePath(); String line; while ((line=r.readLine())!=null) { if (line.contains(secretKey)) { files.add(new HsErrPidFile(this,log)); return; } } } catch (IOException e) { // not a big enough deal. LOGGER.log(Level.FINE, "Failed to parse hs_err_pid file: " + log, e); } finally { IOUtils.closeQuietly(r); } } private File getSecretKeyFile() { return new File(Jenkins.getInstance().getRootDir(),"secret.key"); } private boolean findHeader(BufferedReader r) throws IOException { for (int i=0; i<5; i++) { String line = r.readLine(); if (line==null) return false; if (line.startsWith("# A fatal error has been detected by the Java Runtime Environment:")) return true; } return false; } @Override public boolean isActivated() { return !files.isEmpty(); } private static final String ERROR_FILE_OPTION = "-XX:ErrorFile="; private static final Logger LOGGER = Logger.getLogger(HsErrPidList.class.getName()); }
package nl.mpi.flap.model; import java.io.Serializable; import javax.xml.bind.annotation.XmlAttribute; public class DataNodeType implements PluginDataNodeType, Serializable { private String label; private String mimeType; private String typeIdString; public static final String IMDI_RESOURCE = "imdi.resource"; public enum FormatType { xml, imdi_corpus, imdi_catalogue, imdi_session, imdi_info, cmdi, resource_annotation, resource_audio, resource_lexical, resource_other, resource_video; } private FormatType formatType; public DataNodeType() { } public DataNodeType(String label, String mimeType, String typeIdString, FormatType formatType) { this.label = label; this.mimeType = mimeType; this.typeIdString = typeIdString; this.formatType = formatType; } public String getLabel() { return label; } @XmlAttribute(name = "Label") public void setLabel(String label) { this.label = label; } public String getMimeType() { return mimeType; } @XmlAttribute(name = "MimeType") public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getID() { return typeIdString; } @XmlAttribute(name = "ID") public void setID(String ID) { this.typeIdString = ID; } public FormatType getFormat() { return formatType; } @XmlAttribute(name = "Format") public void setFormat(FormatType formatType) { this.formatType = formatType; } @Override public int hashCode() { int hash = 3; hash = 67 * hash + (this.label != null ? this.label.hashCode() : 0); hash = 67 * hash + (this.mimeType != null ? this.mimeType.hashCode() : 0); hash = 67 * hash + (this.typeIdString != null ? this.typeIdString.hashCode() : 0); hash = 67 * hash + (this.formatType != null ? this.formatType.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final DataNodeType other = (DataNodeType) obj; if ((this.label == null) ? (other.label != null) : !this.label.equals(other.label)) { return false; } if ((this.mimeType == null) ? (other.mimeType != null) : !this.mimeType.equals(other.mimeType)) { return false; } if ((this.typeIdString == null) ? (other.typeIdString != null) : !this.typeIdString.equals(other.typeIdString)) { return false; } if (this.formatType != other.formatType) { return false; } return true; } }
package org.vertexium; public abstract class ProgressCallback { public void progress(double progressPercent, Step step) { progress(progressPercent, step, null, null); } public abstract void progress(double progressPercent, Step step, Integer edgeIndex, Integer vertexCount); public static enum Step { COMPLETE("Complete"), SEARCHING_SOURCE_VERTEX_EDGES("Searching source vertex edges"), SEARCHING_DESTINATION_VERTEX_EDGES("Searching destination vertex edges"), MERGING_EDGES("Merging edges"), ADDING_PATHS("Adding paths"), SEARCHING_EDGES("Searching edges %d of %d"), FINDING_PATH("Finding path"); private final String messageFormat; Step(String messageFormat) { this.messageFormat = messageFormat; } public String formatMessage(Integer edgeIndex, Integer vertexCount) { return String.format(this.messageFormat, edgeIndex, vertexCount); } public String getMessageFormat() { return this.messageFormat; } } }
package org.voltcore.messaging; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.json_voltpatches.JSONArray; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltcore.agreement.AgreementSite; import org.voltcore.agreement.InterfaceToMessenger; import org.voltcore.logging.VoltLogger; import org.voltcore.network.VoltNetworkPool; import org.voltcore.utils.COWMap; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.InstanceId; import org.voltcore.utils.PortGenerator; import org.voltcore.zk.CoreZK; import org.voltcore.zk.ZKUtil; import org.voltdb.VoltDB; import org.voltdb.utils.MiscUtils; /** * Host messenger contains all the code necessary to join a cluster mesh, and create mailboxes * that are addressable from anywhere within that mesh. Host messenger also provides * a ZooKeeper instance that is maintained within the mesh that can be used for distributed coordination * and failure detection. */ public class HostMessenger implements SocketJoiner.JoinHandler, InterfaceToMessenger { private static final VoltLogger logger = new VoltLogger("NETWORK"); /** * Configuration for a host messenger. The leader binds to the coordinator ip and * not the internal interface or port. Nodes that fail to become the leader will * connect to the leader using any interface, and will then advertise using the specified * internal interface/port. * * By default all interfaces are used, if one is specified then only that interface will be used. * */ public static class Config { public InetSocketAddress coordinatorIp; public String zkInterface = "127.0.0.1:2181"; public ScheduledExecutorService ses = null; public String internalInterface = ""; public int internalPort = 3021; public int deadHostTimeout = 10000; public long backwardsTimeForgivenessWindow = 1000 * 60 * 60 * 24 * 7; public VoltMessageFactory factory = new VoltMessageFactory(); public int networkThreads = Math.max(2, CoreUtils.availableProcessors() / 4); public Config(String coordIp, int coordPort) { if (coordIp == null || coordIp.length() == 0) { coordinatorIp = new InetSocketAddress(coordPort); } else { coordinatorIp = new InetSocketAddress(coordIp, coordPort); } initNetworkThreads(); } public Config() { this(null, 3021); } public Config(PortGenerator ports) { this(null, 3021); zkInterface = "127.0.0.1:" + ports.next(); internalPort = ports.next(); } public int getZKPort() { return MiscUtils.getPortFromHostnameColonPort(zkInterface, VoltDB.DEFAULT_ZK_PORT); } private void initNetworkThreads() { try { logger.info("Default network thread count: " + this.networkThreads); Integer networkThreadConfig = Integer.getInteger("networkThreads"); if ( networkThreadConfig != null ) { this.networkThreads = networkThreadConfig; logger.info("Overridden network thread count: " + this.networkThreads); } } catch (Exception e) { logger.error("Error setting network thread count", e); } } @Override public String toString() { JSONStringer js = new JSONStringer(); try { js.object(); js.key("coordinatorip").value(coordinatorIp.toString()); js.key("zkinterface").value(zkInterface); js.key("internalinterface").value(internalInterface); js.key("internalport").value(internalPort); js.key("deadhosttimeout").value(deadHostTimeout); js.key("backwardstimeforgivenesswindow").value(backwardsTimeForgivenessWindow); js.key("networkThreads").value(networkThreads); js.endObject(); return js.toString(); } catch (Exception e) { throw new RuntimeException(e); } } } private static final VoltLogger m_logger = new VoltLogger("org.voltdb.messaging.impl.HostMessenger"); private static final VoltLogger hostLog = new VoltLogger("HOST"); public static final int AGREEMENT_SITE_ID = -1; public static final int STATS_SITE_ID = -2; public static final int ASYNC_COMPILER_SITE_ID = -3; // we should never hand out this site ID. Use it as an empty message destination public static final int VALHALLA = Integer.MIN_VALUE; int m_localHostId; private final Config m_config; private final SocketJoiner m_joiner; private final VoltNetworkPool m_network; private volatile boolean m_localhostReady = false; // memoized InstanceId private InstanceId m_instanceId = null; /* * References to other hosts in the mesh. * Updates via COW */ final COWMap<Integer, ForeignHost> m_foreignHosts = new COWMap<Integer, ForeignHost>(); /* * References to all the local mailboxes * Updates via COW */ final COWMap<Long, Mailbox> m_siteMailboxes = new COWMap<Long, Mailbox>(); /* * All failed hosts that have ever been seen. * Used to dedupe failures so that they are only processed once. */ private final Set<Integer> m_knownFailedHosts = Collections.synchronizedSet(new HashSet<Integer>()); private AgreementSite m_agreementSite; private ZooKeeper m_zk; private final AtomicInteger m_nextSiteId = new AtomicInteger(0); public Mailbox getMailbox(long hsId) { return m_siteMailboxes.get(hsId); } /** * * @param network * @param coordinatorIp * @param expectedHosts * @param catalogCRC * @param hostLog */ public HostMessenger( Config config) { m_config = config; m_network = new VoltNetworkPool( m_config.networkThreads, m_config.ses); m_joiner = new SocketJoiner( m_config.coordinatorIp, m_config.internalInterface, m_config.internalPort, this); } /** * Synchronization protects m_knownFailedHosts and ensures that every failed host is only reported * once */ @Override public synchronized void reportForeignHostFailed(int hostId) { if (m_knownFailedHosts.contains(hostId)) { return; } m_knownFailedHosts.add(hostId); long initiatorSiteId = CoreUtils.getHSIdFromHostAndSite(hostId, AGREEMENT_SITE_ID); removeForeignHost(hostId); m_agreementSite.reportFault(initiatorSiteId); } /** * Start the host messenger and connect to the leader, or become the leader * if necessary. */ public void start() throws Exception { /* * SJ uses this barrier if this node becomes the leader to know when ZooKeeper * has been finished bootstrapping. */ CountDownLatch zkInitBarrier = new CountDownLatch(1); /* * If start returns true then this node is the leader, it bound to the coordinator address * It needs to bootstrap its agreement site so that other nodes can join */ if(m_joiner.start(zkInitBarrier)) { m_network.start(); /* * m_localHostId is 0 of course. */ long agreementHSId = getHSIdForLocalSite(AGREEMENT_SITE_ID); /* * A set containing just the leader (this node) */ HashSet<Long> agreementSites = new HashSet<Long>(); agreementSites.add(agreementHSId); /* * A basic site mailbox for the agreement site */ SiteMailbox sm = new SiteMailbox(this, agreementHSId); createMailbox(agreementHSId, sm); /* * Construct the site with just this node */ m_agreementSite = new AgreementSite( agreementHSId, agreementSites, 0, sm, new InetSocketAddress( m_config.zkInterface.split(":")[0], Integer.parseInt(m_config.zkInterface.split(":")[1])), m_config.backwardsTimeForgivenessWindow); m_agreementSite.start(); m_agreementSite.waitForRecovery(); m_zk = org.voltcore.zk.ZKUtil.getClient(m_config.zkInterface, 60 * 1000); if (m_zk == null) { throw new Exception("Timed out trying to connect local ZooKeeper instance"); } CoreZK.createHierarchy(m_zk); /* * This creates the ephemeral sequential node with host id 0 which * this node already used for itself. Just recording that fact. */ final int selectedHostId = selectNewHostId(m_config.coordinatorIp.toString()); if (selectedHostId != 0) { org.voltdb.VoltDB.crashLocalVoltDB("Selected host id for coordinator was not 0, " + selectedHostId, false, null); } // Store the components of the instance ID in ZK JSONObject instance_id = new JSONObject(); instance_id.put("coord", ByteBuffer.wrap(m_config.coordinatorIp.getAddress().getAddress()).getInt()); instance_id.put("timestamp", System.currentTimeMillis()); hostLog.debug("Cluster will have instance ID:\n" + instance_id.toString(4)); byte[] payload = instance_id.toString(4).getBytes("UTF-8"); m_zk.create(CoreZK.instance_id, payload, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); /* * Store all the hosts and host ids here so that waitForGroupJoin * knows the size of the mesh. This part only registers this host */ byte hostInfoBytes[] = m_config.coordinatorIp.toString().getBytes("UTF-8"); m_zk.create(CoreZK.hosts_host + selectedHostId, hostInfoBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } zkInitBarrier.countDown(); } //For test only protected HostMessenger() { this(new Config()); } /* * The network is only available after start() finishes */ public VoltNetworkPool getNetwork() { return m_network; } public VoltMessageFactory getMessageFactory() { return m_config.factory; } /** * Get a unique ID for this cluster * @return */ public InstanceId getInstanceId() { if (m_instanceId == null) { try { byte[] data = m_zk.getData(CoreZK.instance_id, false, null); JSONObject idJSON = new JSONObject(new String(data, "UTF-8")); m_instanceId = new InstanceId(idJSON.getInt("coord"), idJSON.getLong("timestamp")); } catch (Exception e) { String msg = "Unable to get instance ID info from " + CoreZK.instance_id; hostLog.error(msg); throw new RuntimeException(msg, e); } } return m_instanceId; } /* * Take the new connection (member of the mesh) and create a foreign host for it * and put it in the map of foreign hosts */ @Override public void notifyOfJoin(int hostId, SocketChannel socket, InetSocketAddress listeningAddress) { System.out.println(getHostId() + " notified of " + hostId); prepSocketChannel(socket); ForeignHost fhost = null; try { fhost = new ForeignHost(this, hostId, socket, m_config.deadHostTimeout, listeningAddress); fhost.register(this); putForeignHost(hostId, fhost); fhost.enableRead(); } catch (java.io.IOException e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Set all the default options for sockets */ private void prepSocketChannel(SocketChannel sc) { try { sc.socket().setSendBufferSize(1024*1024*2); sc.socket().setReceiveBufferSize(1024*1024*2); } catch (SocketException e) { e.printStackTrace(); } } /* * Convenience method for doing the verbose COW insert into the map */ private void putForeignHost(int hostId, ForeignHost fh) { m_foreignHosts.put(hostId, fh); } /* * Convenience method for doing the verbose COW remove from the map */ private void removeForeignHost(int hostId) { ForeignHost fh = m_foreignHosts.remove(hostId); if (fh != null) { fh.close(); } } /* * Any node can serve a request to join. The coordination of generating a new host id * is done via ZK */ @Override public void requestJoin(SocketChannel socket, InetSocketAddress listeningAddress) throws Exception { /* * Generate the host id via creating an ephemeral sequential node */ Integer hostId = selectNewHostId(socket.socket().getInetAddress().getHostAddress()); prepSocketChannel(socket); ForeignHost fhost = null; try { try { /* * Write the response that advertises the cluster topology */ writeRequestJoinResponse( hostId, socket); /* * Wait for the a response from the joining node saying that it connected * to all the nodes we just advertised. Use a timeout so that the cluster can't be stuck * on failed joins. */ ByteBuffer finishedJoining = ByteBuffer.allocate(1); socket.configureBlocking(false); long start = System.currentTimeMillis(); while (finishedJoining.hasRemaining() && System.currentTimeMillis() - start < 120000) { int read = socket.read(finishedJoining); if (read == -1) { hostLog.info("New connection was unable to establish mesh"); return; } else if (read < 1) { Thread.sleep(5); } } /* * Now add the host to the mailbox system */ fhost = new ForeignHost(this, hostId, socket, m_config.deadHostTimeout, listeningAddress); fhost.register(this); putForeignHost(hostId, fhost); fhost.enableRead(); } catch (Exception e) { logger.error("Error joining new node", e); m_knownFailedHosts.add(hostId); removeForeignHost(hostId); return; } /* * And the last step is to wait for the new node to join ZooKeeper. * This node is the one to create the txn that will add the new host to the list of hosts * with agreement sites across the cluster. */ long hsId = CoreUtils.getHSIdFromHostAndSite(hostId, AGREEMENT_SITE_ID); if (!m_agreementSite.requestJoin(hsId).await(60, TimeUnit.SECONDS)) { reportForeignHostFailed(hostId); } } catch (Throwable e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Generate a new host id by creating a persistent sequential node */ private Integer selectNewHostId(String address) throws Exception { String node = m_zk.create(CoreZK.hostids_host, address.getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); return Integer.valueOf(node.substring(node.length() - 10)); } /* * Advertise to a newly connecting node the topology of the cluster so that it can connect to * the rest of the nodes */ private void writeRequestJoinResponse(int hostId, SocketChannel socket) throws Exception { JSONObject jsObj = new JSONObject(); /* * Tell the new node what its host id is */ jsObj.put("newHostId", hostId); /* * Echo back the address that the node connected from */ jsObj.put("reportedAddress", ((InetSocketAddress)socket.socket().getRemoteSocketAddress()).getAddress().getHostAddress()); /* * Create an array containing an ad for every node including this one * even though the connection has already been made */ JSONArray jsArray = new JSONArray(); JSONObject hostObj = new JSONObject(); hostObj.put("hostId", getHostId()); hostObj.put("address", m_config.internalInterface.isEmpty() ? socket.socket().getLocalAddress().getHostAddress() : m_config.internalInterface); hostObj.put("port", m_config.internalPort); jsArray.put(hostObj); for (Map.Entry<Integer, ForeignHost> entry : m_foreignHosts.entrySet()) { if (entry.getValue() == null) continue; int hsId = entry.getKey(); ForeignHost fh = entry.getValue(); hostObj = new JSONObject(); hostObj.put("hostId", hsId); hostObj.put("address", fh.m_listeningAddress.getAddress().getHostAddress()); hostObj.put("port", fh.m_listeningAddress.getPort()); jsArray.put(hostObj); } jsObj.put("hosts", jsArray); byte messageBytes[] = jsObj.toString(4).getBytes("UTF-8"); ByteBuffer message = ByteBuffer.allocate(4 + messageBytes.length); message.putInt(messageBytes.length); message.put(messageBytes).flip(); while (message.hasRemaining()) { socket.write(message); } } /* * SJ invokes this method after a node finishes connecting to the entire cluster. * This method constructs all the hosts and puts them in the map */ @Override public void notifyOfHosts( int yourHostId, int[] hosts, SocketChannel[] sockets, InetSocketAddress listeningAddresses[]) throws Exception { m_localHostId = yourHostId; long agreementHSId = getHSIdForLocalSite(AGREEMENT_SITE_ID); /* * Construct the set of agreement sites based on all the hosts that are connected */ HashSet<Long> agreementSites = new HashSet<Long>(); agreementSites.add(agreementHSId); m_network.start();//network must be running for register to work for (int ii = 0; ii < hosts.length; ii++) { System.out.println(yourHostId + " Notified of host " + hosts[ii]); agreementSites.add(CoreUtils.getHSIdFromHostAndSite(hosts[ii], AGREEMENT_SITE_ID)); prepSocketChannel(sockets[ii]); ForeignHost fhost = null; try { fhost = new ForeignHost(this, hosts[ii], sockets[ii], m_config.deadHostTimeout, listeningAddresses[ii]); fhost.register(this); putForeignHost(hosts[ii], fhost); } catch (java.io.IOException e) { org.voltdb.VoltDB.crashLocalVoltDB("", true, e); } } /* * Create the local agreement site. It knows that it is recovering because the number of * prexisting sites is > 0 */ SiteMailbox sm = new SiteMailbox(this, agreementHSId); createMailbox(agreementHSId, sm); m_agreementSite = new AgreementSite( agreementHSId, agreementSites, yourHostId, sm, new InetSocketAddress( m_config.zkInterface.split(":")[0], Integer.parseInt(m_config.zkInterface.split(":")[1])), m_config.backwardsTimeForgivenessWindow); /* * Now that the agreement site mailbox has been created it is safe * to enable read */ for (ForeignHost fh : m_foreignHosts.values()) { fh.enableRead(); } m_agreementSite.start(); /* * Do the usual thing of waiting for the agreement site * to join the cluster and creating the client */ m_agreementSite.waitForRecovery(); m_zk = org.voltcore.zk.ZKUtil.getClient(m_config.zkInterface, 60 * 1000); if (m_zk == null) { throw new Exception("Timed out trying to connect local ZooKeeper instance"); } /* * Publish the address of this node to ZK as seen by the leader * Also allows waitForGroupJoin to know the number of nodes in the cluster */ byte hostInfoBytes[]; if (m_config.internalInterface.isEmpty()) { InetSocketAddress addr = new InetSocketAddress(m_joiner.m_reportedInternalInterface, m_config.internalPort); hostInfoBytes = addr.toString().getBytes("UTF-8"); } else { InetSocketAddress addr = new InetSocketAddress(m_config.internalInterface, m_config.internalPort); hostInfoBytes = addr.toString().getBytes("UTF-8"); } m_zk.create(CoreZK.hosts_host + getHostId(), hostInfoBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } /** * Wait until all the nodes have built a mesh. */ public void waitForGroupJoin(int expectedHosts) { try { while (true) { ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher(); if (m_zk.getChildren(CoreZK.hosts, fw).size() == expectedHosts) { break; } fw.get(); } } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB("Error waiting for hosts to be ready", false, e); } } public int getHostId() { return m_localHostId; } public long getHSIdForLocalSite(int site) { return CoreUtils.getHSIdFromHostAndSite(getHostId(), site); } public String getHostname() { String hostname = org.voltcore.utils.CoreUtils.getHostnameOrAddress(); return hostname; } public List<Integer> getLiveHostIds() throws KeeperException, InterruptedException { List<Integer> hostids = new ArrayList<Integer>(); for (String host : m_zk.getChildren(CoreZK.hosts, false, null)) { hostids.add(Integer.parseInt(host.substring(host.indexOf("host") + "host".length()))); } return hostids; } /** * Given a hostid, return the hostname for it */ @Override public String getHostnameForHostID(int hostId) { ForeignHost fh = m_foreignHosts.get(hostId); return fh == null ? "UNKNOWN" : fh.hostname(); } /** * * @param siteId * @param mailboxId * @param message * @return null if message was delivered locally or a ForeignHost * reference if a message is read to be delivered remotely. */ ForeignHost presend(long hsId, VoltMessage message) { int hostId = (int)hsId; // the local machine case if (hostId == m_localHostId) { Mailbox mbox = m_siteMailboxes.get(hsId); if (mbox != null) { mbox.deliver(message); return null; } } // the foreign machine case ForeignHost fhost = m_foreignHosts.get(hostId); if (fhost == null) { if (!m_knownFailedHosts.contains(hostId)) { hostLog.warn( "Attempted to send a message to foreign host with id " + hostId + " but there is no such host."); } return null; } if (!fhost.isUp()) { //Throwable t = new Throwable(); //java.io.StringWriter sw = new java.io.StringWriter(); //java.io.PrintWriter pw = new java.io.PrintWriter(sw); //t.printStackTrace(pw); //pw.flush(); m_logger.warn("Attempted delivery of message to failed site: " + CoreUtils.hsIdToString(hsId)); //m_logger.warn(sw.toString()); return null; } return fhost; } public void registerMailbox(Mailbox mailbox) { if (!m_siteMailboxes.containsKey(mailbox.getHSId())) { throw new RuntimeException("Can only register a mailbox with an hsid alreadly generated"); } m_siteMailboxes.put(mailbox.getHSId(), mailbox); } /* * Generate a slot for the mailbox and put a noop box there. Can also * supply a value */ public long generateMailboxId(Long mailboxId) { final long hsId = mailboxId == null ? getHSIdForLocalSite(m_nextSiteId.getAndIncrement()) : mailboxId; m_siteMailboxes.put(hsId, new Mailbox() { @Override public void send(long hsId, VoltMessage message) {} @Override public void send(long[] hsIds, VoltMessage message) {} @Override public void deliver(VoltMessage message) { hostLog.info("No-op mailbox(" + CoreUtils.hsIdToString(hsId) + ") dropped message " + message); } @Override public void deliverFront(VoltMessage message) {} @Override public VoltMessage recv() {return null;} @Override public VoltMessage recvBlocking() {return null;} @Override public VoltMessage recvBlocking(long timeout) {return null;} @Override public VoltMessage recv(Subject[] s) {return null;} @Override public VoltMessage recvBlocking(Subject[] s) {return null;} @Override public VoltMessage recvBlocking(Subject[] s, long timeout) { return null;} @Override public long getHSId() {return 0L;} @Override public void setHSId(long hsId) {} }); return hsId; } /* * Create a site mailbox with a generated host id */ public Mailbox createMailbox() { final int siteId = m_nextSiteId.getAndIncrement(); long hsId = getHSIdForLocalSite(siteId); SiteMailbox sm = new SiteMailbox( this, hsId); m_siteMailboxes.put(hsId, sm); return sm; } /** * Discard a mailbox */ public void removeMailbox(long hsId) { m_siteMailboxes.remove(hsId); } public void send(final long destinationHSId, final VoltMessage message) { assert(message != null); ForeignHost host = presend(destinationHSId, message); if (host != null) { Long dests[] = {destinationHSId}; host.send(Arrays.asList(dests), message); } } public void send(long[] destinationHSIds, final VoltMessage message) { assert(message != null); assert(destinationHSIds != null); final HashMap<ForeignHost, ArrayList<Long>> foreignHosts = new HashMap<ForeignHost, ArrayList<Long>>(32); for (long hsId : destinationHSIds) { ForeignHost host = presend(hsId, message); if (host == null) continue; ArrayList<Long> bundle = foreignHosts.get(host); if (bundle == null) { bundle = new ArrayList<Long>(); foreignHosts.put(host, bundle); } bundle.add(hsId); } if (foreignHosts.size() == 0) return; for (Entry<ForeignHost, ArrayList<Long>> e : foreignHosts.entrySet()) { e.getKey().send(e.getValue(), message); } foreignHosts.clear(); } /** * Block on this call until the number of ready hosts is * equal to the number of expected hosts. * * @return True if returning with all hosts ready. False if error. */ public void waitForAllHostsToBeReady(int expectedHosts) { m_localhostReady = true; try { m_zk.create(CoreZK.readyhosts_host, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); while (true) { ZKUtil.FutureWatcher fw = new ZKUtil.FutureWatcher(); if (m_zk.getChildren(CoreZK.readyhosts, fw).size() == expectedHosts) { break; } fw.get(); } } catch (Exception e) { org.voltdb.VoltDB.crashLocalVoltDB("Error waiting for hosts to be ready", false, e); } } public synchronized boolean isLocalHostReady() { return m_localhostReady; } public void shutdown() throws InterruptedException { m_zk.close(); m_agreementSite.shutdown(); for (ForeignHost host : m_foreignHosts.values()) { // null is OK. It means this host never saw this host id up if (host != null) { host.close(); } } m_joiner.shutdown(); m_network.shutdown(); } /* * Register a custom mailbox, optinally specifying what the hsid should be. */ public void createMailbox(Long proposedHSId, Mailbox mailbox) { long hsId = 0; if (proposedHSId != null) { if (m_siteMailboxes.containsKey(proposedHSId)) { org.voltdb.VoltDB.crashLocalVoltDB( "Attempted to create a mailbox for site " + CoreUtils.hsIdToString(proposedHSId) + " twice", true, null); } hsId = proposedHSId; } else { hsId = getHSIdForLocalSite(m_nextSiteId.getAndIncrement()); mailbox.setHSId(hsId); } m_siteMailboxes.put(hsId, mailbox); } /** * Get the number of up foreign hosts. Used for test purposes. * @return The number of up foreign hosts. */ public int countForeignHosts() { int retval = 0; for (ForeignHost host : m_foreignHosts.values()) if ((host != null) && (host.isUp())) retval++; return retval; } /** * Kill a foreign host socket by id. * @param hostId The id of the foreign host to kill. */ public void closeForeignHostSocket(int hostId) { ForeignHost fh = m_foreignHosts.get(hostId); if (fh != null && fh.isUp()) { fh.killSocket(); } reportForeignHostFailed(hostId); } public ZooKeeper getZK() { return m_zk; } public void sendPoisonPill(String err) { for (ForeignHost fh : m_foreignHosts.values()) { if (fh != null && fh.isUp()) { fh.sendPoisonPill(err); } } } }
package distributed.dto; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import distributed.util.SettingsProvider; import java.io.Serializable; import java.util.Objects; /** * * @author steffen */ @DatabaseTable(tableName = "private_message") public class PrivateMessage extends IMessage implements Serializable { public static final String TABLE_NAME = "private_message"; public static final String COL_NAME_RECIVER = "recivier"; @DatabaseField(columnName = COL_NAME_RECIVER) private String receiver; public PrivateMessage() { //Needed by ORMLite } public PrivateMessage(String receiver, byte[] message) { super(SettingsProvider.getInstance().getUserName(), message); this.receiver = receiver; } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public boolean equals(Object o) { return super.equals(o); } }
package org.voltdb; import java.util.Iterator; import java.util.TreeSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.KeeperException.NoNodeException; import org.apache.zookeeper_voltpatches.WatchedEvent; import org.apache.zookeeper_voltpatches.Watcher; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.json_voltpatches.JSONObject; import org.voltcore.logging.VoltLogger; public class SnapshotCompletionMonitor { @SuppressWarnings("unused") private static final VoltLogger LOG = new VoltLogger("LOGGING"); final CopyOnWriteArrayList<SnapshotCompletionInterest> m_interests = new CopyOnWriteArrayList<SnapshotCompletionInterest>(); private ZooKeeper m_zk; private final ExecutorService m_es = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "SnapshotCompletionMonitor"); } }, new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy()); private final Watcher m_newSnapshotWatcher = new Watcher() { @Override public void process(final WatchedEvent event) { switch (event.getType()) { case NodeChildrenChanged: m_es.execute(new Runnable() { @Override public void run() { processSnapshotChildrenChanged(event); } }); default: break; } } }; private TreeSet<String> m_lastKnownSnapshots = new TreeSet<String>(); private void processSnapshotChildrenChanged(final WatchedEvent event) { try { TreeSet<String> children = new TreeSet<String>(m_zk.getChildren( VoltZK.completed_snapshots, m_newSnapshotWatcher)); TreeSet<String> newChildren = new TreeSet<String>(children); newChildren.removeAll(m_lastKnownSnapshots); m_lastKnownSnapshots = children; for (String newSnapshot : newChildren) { String path = VoltZK.completed_snapshots + "/" + newSnapshot; try { byte data[] = m_zk.getData(path, new Watcher() { @Override public void process(final WatchedEvent event) { switch (event.getType()) { case NodeDataChanged: m_es.execute(new Runnable() { @Override public void run() { processSnapshotDataChangedEvent(event); } }); break; default: break; } } }, null); processSnapshotData(data); } catch (NoNodeException e) { } } } catch (Exception e) { VoltDB.crashLocalVoltDB("Exception in snapshot completion monitor", true, e); } } private void processSnapshotDataChangedEvent(final WatchedEvent event) { try { byte data[] = m_zk.getData(event.getPath(), new Watcher() { @Override public void process(final WatchedEvent event) { switch (event.getType()) { case NodeDataChanged: m_es.execute(new Runnable() { @Override public void run() { processSnapshotDataChangedEvent(event); } }); break; default: break; } } }, null); processSnapshotData(data); } catch (NoNodeException e) { } catch (Exception e) { VoltDB.crashLocalVoltDB("Exception in snapshot completion monitor", true, e); } } private void processSnapshotData(byte data[]) throws Exception { if (data == null) { return; } JSONObject jsonObj = new JSONObject(new String(data, "UTF-8")); long txnId = jsonObj.getLong("txnId"); int totalNodes = jsonObj.getInt("hosts"); int totalNodesFinished = jsonObj.getInt("finishedHosts"); String nonce = jsonObj.getString("nonce"); boolean truncation = jsonObj.getBoolean("isTruncation"); if (totalNodes == totalNodesFinished) { Iterator<SnapshotCompletionInterest> iter = m_interests.iterator(); while (iter.hasNext()) { SnapshotCompletionInterest interest = iter.next(); interest.snapshotCompleted(nonce, txnId, truncation); } } } public void addInterest(final SnapshotCompletionInterest interest) { m_interests.add(interest); } public void removeInterest(final SnapshotCompletionInterest interest) { m_interests.remove(interest); } public void shutdown() throws InterruptedException { m_es.shutdown(); m_es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); } public void init(final ZooKeeper zk) { m_es.execute(new Runnable() { @Override public void run() { m_zk = zk; try { m_zk.create(VoltZK.completed_snapshots, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (Exception e){} try { m_lastKnownSnapshots = new TreeSet<String>(m_zk.getChildren(VoltZK.completed_snapshots, m_newSnapshotWatcher)); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e); } } }); } }
package org.bbop.apollo.gwt.client; import com.google.gwt.cell.client.ClickableTextCell; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.cell.client.NumberCell; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.Scheduler; import com.google.gwt.dom.builder.shared.DivBuilder; import com.google.gwt.dom.builder.shared.TableCellBuilder; import com.google.gwt.dom.builder.shared.TableRowBuilder; import com.google.gwt.dom.client.BrowserEvents; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.http.client.*; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.text.shared.AbstractSafeHtmlRenderer; import com.google.gwt.text.shared.SafeHtmlRenderer; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.cellview.client.*; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; import com.google.gwt.view.client.CellPreviewEvent; import com.google.gwt.view.client.ListDataProvider; import org.bbop.apollo.gwt.client.dto.AnnotationInfo; import org.bbop.apollo.gwt.client.dto.UserInfo; import org.bbop.apollo.gwt.client.dto.UserInfoConverter; import org.bbop.apollo.gwt.client.event.*; import org.bbop.apollo.gwt.client.resources.TableResources; import org.bbop.apollo.gwt.client.rest.UserRestService; import org.bbop.apollo.gwt.shared.FeatureStringEnum; import org.bbop.apollo.gwt.shared.PermissionEnum; import org.gwtbootstrap3.client.ui.Container; import org.gwtbootstrap3.client.ui.Label; import org.gwtbootstrap3.client.ui.ListBox; import org.gwtbootstrap3.client.ui.TextBox; import java.util.*; public class AnnotatorPanel extends Composite { interface AnnotatorPanelUiBinder extends UiBinder<com.google.gwt.user.client.ui.Widget, AnnotatorPanel> { } private static AnnotatorPanelUiBinder ourUiBinder = GWT.create(AnnotatorPanelUiBinder.class); private Column<AnnotationInfo, String> nameColumn; private TextColumn<AnnotationInfo> typeColumn; private TextColumn<AnnotationInfo> sequenceColumn; private Column<AnnotationInfo, Number> lengthColumn; long requestIndex = 0; @UiField TextBox nameSearchBox; @UiField(provided = true) SuggestBox sequenceList; DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class); @UiField(provided = true) DataGrid<AnnotationInfo> dataGrid = new DataGrid<>(20, tablecss); @UiField(provided = true) SimplePager pager = null; @UiField ListBox typeList; @UiField static GeneDetailPanel geneDetailPanel; @UiField static TranscriptDetailPanel transcriptDetailPanel; @UiField static ExonDetailPanel exonDetailPanel; @UiField static RepeatRegionDetailPanel repeatRegionDetailPanel; @UiField static TabLayoutPanel tabPanel; @UiField ListBox userField; // @UiField // ListBox groupField; // @UiField // Row userFilterRow; @UiField SplitLayoutPanel splitPanel; @UiField Container northPanelContainer; // @UiField // Button cdsButton; // @UiField // Button stopCodonButton; private MultiWordSuggestOracle sequenceOracle = new ReferenceSequenceOracle(); private static ListDataProvider<AnnotationInfo> dataProvider = new ListDataProvider<>(); private static List<AnnotationInfo> annotationInfoList = new ArrayList<>(); private static List<AnnotationInfo> filteredAnnotationList = dataProvider.getList(); private final Set<String> showingTranscripts = new HashSet<String>(); public AnnotatorPanel() { pager = new SimplePager(SimplePager.TextLocation.CENTER); sequenceList = new SuggestBox(sequenceOracle); sequenceList.getElement().setAttribute("placeHolder", "All Reference Sequences"); dataGrid.setWidth("100%"); dataGrid.setTableBuilder(new CustomTableBuilder()); dataGrid.setLoadingIndicator(new Label("Loading")); dataGrid.setEmptyTableWidget(new Label("No results")); initializeTable(); dataProvider.addDataDisplay(dataGrid); pager.setDisplay(dataGrid); dataGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<AnnotationInfo>() { @Override public void onCellPreview(CellPreviewEvent<AnnotationInfo> event) { AnnotationInfo annotationInfo = event.getValue(); if (event.getNativeEvent().getType().equals(BrowserEvents.CLICK)) { if (event.getContext().getSubIndex() == 0) { // subIndex from dataGrid will be 0 only when top-level cell values are clicked // ie. gene, pseudogene GWT.log("Safe to call updateAnnotationInfo"); updateAnnotationInfo(annotationInfo); } } } }); exportStaticMethod(this); initWidget(ourUiBinder.createAndBindUi(this)); initializeTypes(); initializeUsers(); sequenceList.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() { @Override public void onSelection(SelectionEvent<SuggestOracle.Suggestion> event) { reload(); } }); sequenceList.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if (sequenceList.getText() == null || sequenceList.getText().trim().length() == 0) { reload(); } } }); tabPanel.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { exonDetailPanel.redrawExonTable(); } }); Annotator.eventBus.addHandler(AnnotationInfoChangeEvent.TYPE, new AnnotationInfoChangeEventHandler() { @Override public void onAnnotationChanged(AnnotationInfoChangeEvent annotationInfoChangeEvent) { reload(); } }); Annotator.eventBus.addHandler(UserChangeEvent.TYPE, new UserChangeEventHandler() { @Override public void onUserChanged(UserChangeEvent authenticationEvent) { switch (authenticationEvent.getAction()) { case PERMISSION_CHANGED: PermissionEnum hiPermissionEnum = authenticationEvent.getHighestPermission(); if (MainPanel.getInstance().isCurrentUserAdmin()) { hiPermissionEnum = PermissionEnum.ADMINISTRATE; } boolean editable = false; switch (hiPermissionEnum) { case ADMINISTRATE: case WRITE: editable = true; break; // default is false } transcriptDetailPanel.setEditable(editable); geneDetailPanel.setEditable(editable); exonDetailPanel.setEditable(editable); repeatRegionDetailPanel.setEditable(editable); reload(); break; } } } ); // TODO: not sure if this was necessary, leaving it here until it fails Annotator.eventBus.addHandler(OrganismChangeEvent.TYPE, new OrganismChangeEventHandler() { @Override public void onOrganismChanged(OrganismChangeEvent organismChangeEvent) { if (organismChangeEvent.getAction() == OrganismChangeEvent.Action.LOADED_ORGANISMS) { sequenceList.setText(organismChangeEvent.getCurrentSequence()); reload(); } } }); userField.setVisible(false); // groupField.setVisible(false); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { if (MainPanel.getInstance().isCurrentUserAdmin()) { // splitPanel.setWidgetSize(northPanelContainer, 150); userField.setVisible(true); // groupField.setVisible(true); } else { userField.setVisible(false); // splitPanel.setWidgetSize(northPanelContainer, 100); } } }); } private void initializeUsers() { userField.clear(); userField.addItem("All Users", ""); RequestCallback requestCallback = new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { JSONValue returnValue = JSONParser.parseStrict(response.getText()); JSONArray array = returnValue.isArray(); for (int i = 0; i < array.size(); i++) { JSONObject object = array.get(i).isObject(); UserInfo userInfo = UserInfoConverter.convertToUserInfoFromJSON(object); userField.addItem(userInfo.getName(), userInfo.getEmail()); } } @Override public void onError(Request request, Throwable exception) { Window.alert("Error retrieving users: " + exception.fillInStackTrace()); } }; UserRestService.loadUsers(requestCallback); } private void initializeTypes() { typeList.addItem("All Types", ""); typeList.addItem("Gene"); typeList.addItem("Pseudogene"); typeList.addItem("tRNA"); typeList.addItem("snRNA"); typeList.addItem("snoRNA"); typeList.addItem("ncRNA"); typeList.addItem("rRNA"); typeList.addItem("miRNA"); typeList.addItem("Transposable Element", "transposable_element"); typeList.addItem("Repeat Region", "repeat_region"); // TODO: add rest } private static void updateAnnotationInfo(AnnotationInfo annotationInfo) { String type = annotationInfo.getType(); GWT.log("annotation type: " + type); geneDetailPanel.setVisible(false); transcriptDetailPanel.setVisible(false); repeatRegionDetailPanel.setVisible(false); switch (type) { case "gene": case "pseudogene": geneDetailPanel.updateData(annotationInfo); tabPanel.getTabWidget(1).getParent().setVisible(false); tabPanel.selectTab(0); break; case "Transcript": transcriptDetailPanel.updateData(annotationInfo); tabPanel.getTabWidget(1).getParent().setVisible(true); exonDetailPanel.updateData(annotationInfo); break; case "mRNA": case "miRNA": case "tRNA": case "rRNA": case "snRNA": case "snoRNA": case "ncRNA": transcriptDetailPanel.updateData(annotationInfo); tabPanel.getTabWidget(1).getParent().setVisible(true); exonDetailPanel.updateData(annotationInfo); // exonDetailPanel.setVisible(true); break; case "transposable_element": case "repeat_region": fireAnnotationInfoChangeEvent(annotationInfo); repeatRegionDetailPanel.updateData(annotationInfo); tabPanel.getTabWidget(1).getParent().setVisible(false); break; // case "exon": // exonDetailPanel.updateData(annotationInfo); // break; // case "CDS": // cdsDetailPanel.updateDetailData(AnnotationRestService.convertAnnotationInfoToJSONObject(annotationInfo)); // break; default: GWT.log("not sure what to do with " + type); } } public static void fireAnnotationInfoChangeEvent(AnnotationInfo annotationInfo) { // this method is for firing AnnotationInfoChangeEvent for single level features such as transposable_element and repeat_region AnnotationInfoChangeEvent annotationInfoChangeEvent = new AnnotationInfoChangeEvent(annotationInfo, AnnotationInfoChangeEvent.Action.SET_FOCUS); Annotator.eventBus.fireEvent(annotationInfoChangeEvent); } // @UiHandler("stopCodonButton") // // switch between states // public void handleStopCodonStuff(ClickEvent clickEvent) { // if (stopCodonButton.getIcon().equals(IconType.BAN)) { // stopCodonButton.setIcon(IconType.WARNING); // stopCodonButton.setType(ButtonType.WARNING); // } else if (stopCodonButton.getIcon().equals(IconType.WARNING)) { // stopCodonButton.setIcon(IconType.FILTER); // stopCodonButton.setType(ButtonType.PRIMARY); // } else { // stopCodonButton.setIcon(IconType.BAN); // stopCodonButton.setType(ButtonType.DEFAULT); // filterList(); // @UiHandler("cdsButton") // // switch between states // public void handleCdsStuff(ClickEvent clickEvent) { // if (cdsButton.getIcon().equals(IconType.BAN)) { // cdsButton.setIcon(IconType.WARNING); // cdsButton.setType(ButtonType.WARNING); // } else if (cdsButton.getIcon().equals(IconType.WARNING)) { // cdsButton.setIcon(IconType.FILTER); // cdsButton.setType(ButtonType.PRIMARY); // } else { // cdsButton.setIcon(IconType.BAN); // cdsButton.setType(ButtonType.DEFAULT); // filterList(); private void initializeTable() { // View friends. SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() { @Override public SafeHtml render(String object) { SafeHtmlBuilder sb = new SafeHtmlBuilder(); sb.appendHtmlConstant("<a href=\"javascript:;\">").appendEscaped(object) .appendHtmlConstant("</a>"); return sb.toSafeHtml(); } }; nameColumn = new Column<AnnotationInfo, String>(new ClickableTextCell(anchorRenderer)) { @Override public String getValue(AnnotationInfo annotationInfo) { return annotationInfo.getName(); } }; nameColumn.setFieldUpdater(new FieldUpdater<AnnotationInfo, String>() { @Override public void update(int index, AnnotationInfo annotationInfo, String value) { if (showingTranscripts.contains(annotationInfo.getUniqueName())) { showingTranscripts.remove(annotationInfo.getUniqueName()); } else { showingTranscripts.add(annotationInfo.getUniqueName()); } // Redraw the modified row. dataGrid.redrawRow(index); } }); nameColumn.setSortable(true); sequenceColumn = new TextColumn<AnnotationInfo>() { @Override public String getValue(AnnotationInfo annotationInfo) { return annotationInfo.getSequence(); // return "cats"; } }; sequenceColumn.setSortable(true); sequenceColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); typeColumn = new TextColumn<AnnotationInfo>() { @Override public String getValue(AnnotationInfo annotationInfo) { String type = annotationInfo.getType(); switch (type) { case "repeat_region": return "repeat reg"; case "transposable_element": return "transp elem"; default: return type; } } }; typeColumn.setSortable(true); typeColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); lengthColumn = new Column<AnnotationInfo, Number>(new NumberCell()) { @Override public Integer getValue(AnnotationInfo annotationInfo) { return annotationInfo.getLength(); } }; lengthColumn.setSortable(true); lengthColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); lengthColumn.setCellStyleNames("dataGridLastColumn"); // dataGrid.addColumn(nameColumn, SafeHtmlUtils.fromSafeConstant("<br/>")); dataGrid.addColumn(nameColumn, "Name"); dataGrid.addColumn(sequenceColumn, "Seq"); dataGrid.addColumn(typeColumn, "Type"); dataGrid.addColumn(lengthColumn, "Length"); // dataGrid.addColumn(filterColumn, "Warnings"); dataGrid.setColumnWidth(0, "55%"); dataGrid.setColumnWidth(1, "15%"); dataGrid.setColumnWidth(2, "15%"); dataGrid.setColumnWidth(3, "15%"); ColumnSortEvent.ListHandler<AnnotationInfo> sortHandler = new ColumnSortEvent.ListHandler<AnnotationInfo>(filteredAnnotationList); dataGrid.addColumnSortHandler(sortHandler); // Specify a custom table. // dataGrid.setTableBuilder(new AnnotationInfoTableBuilder(dataGrid,sortHandler,showingTranscripts)); sortHandler.setComparator(nameColumn, new Comparator<AnnotationInfo>() { @Override public int compare(AnnotationInfo o1, AnnotationInfo o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); sortHandler.setComparator(sequenceColumn, new Comparator<AnnotationInfo>() { @Override public int compare(AnnotationInfo o1, AnnotationInfo o2) { return o1.getSequence().compareToIgnoreCase(o2.getSequence()); } }); sortHandler.setComparator(typeColumn, new Comparator<AnnotationInfo>() { @Override public int compare(AnnotationInfo o1, AnnotationInfo o2) { return o1.getType().compareToIgnoreCase(o2.getType()); } }); sortHandler.setComparator(lengthColumn, new Comparator<AnnotationInfo>() { @Override public int compare(AnnotationInfo o1, AnnotationInfo o2) { return o1.getLength() - o2.getLength(); } }); } private String getType(JSONObject internalData) { return internalData.get("type").isObject().get("name").isString().stringValue(); } public void loadOrganismAndSequence(String sequenceName) { String url = Annotator.getRootUrl() + "annotator/findAnnotationsForSequence/?sequenceName=" + sequenceName + "&request=" + requestIndex; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url)); builder.setHeader("Content-type", "application/x-www-form-urlencoded"); RequestCallback requestCallback = new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { JSONValue returnValue = JSONParser.parseStrict(response.getText()); long localRequestValue = (long) returnValue.isObject().get(FeatureStringEnum.REQUEST_INDEX.getValue()).isNumber().doubleValue(); // returns if (localRequestValue <= requestIndex) { return; } else { requestIndex = localRequestValue; } JSONArray array = returnValue.isObject().get("features").isArray(); annotationInfoList.clear(); for (int i = 0; i < array.size(); i++) { JSONObject object = array.get(i).isObject(); AnnotationInfo annotationInfo = generateAnnotationInfo(object); annotationInfoList.add(annotationInfo); } filterList(); dataGrid.redraw(); } @Override public void onError(Request request, Throwable exception) { Window.alert("Error loading organisms"); } }; try { builder.setCallback(requestCallback); builder.send(); } catch (RequestException e) { // Couldn't connect to server Window.alert(e.getMessage()); } } public void reload() { loadOrganismAndSequence(sequenceList.getText()); } private void filterList() { filteredAnnotationList.clear(); for (int i = 0; i < annotationInfoList.size(); i++) { AnnotationInfo annotationInfo = annotationInfoList.get(i); if (searchMatches(annotationInfo)) { filteredAnnotationList.add(annotationInfo); } else { if (searchMatches(annotationInfo.getAnnotationInfoSet())) { filteredAnnotationList.add(annotationInfo); } } } } private boolean searchMatches(Set<AnnotationInfo> annotationInfoSet) { for (AnnotationInfo annotationInfo : annotationInfoSet) { if (searchMatches(annotationInfo)) { return true; } } return false; } private boolean searchMatches(AnnotationInfo annotationInfo) { String nameText = nameSearchBox.getText(); String typeText = typeList.getSelectedValue(); String userText = userField.getSelectedValue(); return ( (annotationInfo.getName().toLowerCase().contains(nameText.toLowerCase())) && annotationInfo.getType().toLowerCase().contains(typeText.toLowerCase()) && annotationInfo.getOwner().toLowerCase().contains(userText) ); } private AnnotationInfo generateAnnotationInfo(JSONObject object) { return generateAnnotationInfo(object, true); } private AnnotationInfo generateAnnotationInfo(JSONObject object, boolean processChildren) { AnnotationInfo annotationInfo = new AnnotationInfo(); annotationInfo.setName(object.get("name").isString().stringValue()); annotationInfo.setType(object.get("type").isObject().get("name").isString().stringValue()); if (object.get("symbol") != null) { annotationInfo.setSymbol(object.get("symbol").isString().stringValue()); } if (object.get("description") != null) { annotationInfo.setDescription(object.get("description").isString().stringValue()); } annotationInfo.setMin((int) object.get("location").isObject().get("fmin").isNumber().doubleValue()); annotationInfo.setMax((int) object.get("location").isObject().get("fmax").isNumber().doubleValue()); annotationInfo.setStrand((int) object.get("location").isObject().get("strand").isNumber().doubleValue()); annotationInfo.setUniqueName(object.get("uniquename").isString().stringValue()); annotationInfo.setSequence(object.get("sequence").isString().stringValue()); if (object.get("owner") != null) { annotationInfo.setOwner(object.get("owner").isString().stringValue()); } List<String> noteList = new ArrayList<>(); if (object.get("notes") != null) { JSONArray jsonArray = object.get("notes").isArray(); for (int i = 0; i < jsonArray.size(); i++) { String note = jsonArray.get(i).isString().stringValue(); noteList.add(note); } } annotationInfo.setNoteList(noteList); if (processChildren && object.get("children") != null) { JSONArray jsonArray = object.get("children").isArray(); for (int i = 0; i < jsonArray.size(); i++) { AnnotationInfo childAnnotation = generateAnnotationInfo(jsonArray.get(i).isObject(), true); annotationInfo.addChildAnnotation(childAnnotation); } } return annotationInfo; } @UiHandler(value = {"typeList", "userField"}) public void searchType(ChangeEvent changeEvent) { filterList(); } @UiHandler("nameSearchBox") public void searchName(KeyUpEvent keyUpEvent) { filterList(); } // @UiHandler("sequenceList") // public void changeRefSequence(SelectionEvent changeEvent) { //// selectedSequenceName = sequenceList.getText(); // reload(); // @UiHandler("sequenceList") // public void changeRefSequence(KeyUpEvent changeEvent) { //// selectedSequenceName = sequenceList.getText(); // reload(); // TODO: need to cache these or retrieve from the backend public static void displayTranscript(int geneIndex, String uniqueName) { // 1 - get the correct gene AnnotationInfo annotationInfo = filteredAnnotationList.get(geneIndex); AnnotationInfoChangeEvent annotationInfoChangeEvent = new AnnotationInfoChangeEvent(annotationInfo, AnnotationInfoChangeEvent.Action.SET_FOCUS); for (AnnotationInfo childAnnotation : annotationInfo.getAnnotationInfoSet()) { if (childAnnotation.getUniqueName().equalsIgnoreCase(uniqueName)) { exonDetailPanel.updateData(childAnnotation); updateAnnotationInfo(childAnnotation); Annotator.eventBus.fireEvent(annotationInfoChangeEvent); return; } } } public static native void exportStaticMethod(AnnotatorPanel annotatorPanel) /*-{ $wnd.displayTranscript = $entry(@org.bbop.apollo.gwt.client.AnnotatorPanel::displayTranscript(ILjava/lang/String;)); }-*/; private class CustomTableBuilder extends AbstractCellTableBuilder<AnnotationInfo> { public CustomTableBuilder() { super(dataGrid); } @Override protected void buildRowImpl(AnnotationInfo rowValue, int absRowIndex) { buildAnnotationRow(rowValue, absRowIndex, false); if (showingTranscripts.contains(rowValue.getUniqueName())) { // add some random rows Set<AnnotationInfo> annotationInfoSet = rowValue.getAnnotationInfoSet(); if (annotationInfoSet.size() > 0) { for (AnnotationInfo annotationInfo : annotationInfoSet) { buildAnnotationRow(annotationInfo, absRowIndex, true); } } } } private void buildAnnotationRow(final AnnotationInfo rowValue, int absRowIndex, boolean showTranscripts) { TableRowBuilder row = startRow(); TableCellBuilder td = row.startTD(); td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle(); if (showTranscripts) { // TODO: this is ugly, but it works // a custom cell rendering might work as well, but not sure String transcriptStyle = "margin-left: 10px; color: green; padding-left: 5px; padding-right: 5px; border-radius: 15px; background-color: #EEEEEE;"; HTML html = new HTML("<a style='" + transcriptStyle + "' onclick=\"displayTranscript(" + absRowIndex + ",'" + rowValue.getUniqueName() + "');\">" + rowValue.getName() + "</a>"); SafeHtml htmlString = new SafeHtmlBuilder().appendHtmlConstant(html.getHTML()).toSafeHtml(); td.html(htmlString); } else { renderCell(td, createContext(0), nameColumn, rowValue); } td.endTD(); // Sequence column. td = row.startTD(); // td.className(cellStyles); td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle(); if (showTranscripts) { DivBuilder div = td.startDiv(); div.style().trustedColor("green").endStyle(); // div.text(rowValue.getSequence()); td.endDiv(); } else { renderCell(td, createContext(1), sequenceColumn, rowValue); } td.endTD(); // Type column. td = row.startTD(); // td.className(cellStyles); td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle(); if (showTranscripts) { DivBuilder div = td.startDiv(); div.style().trustedColor("green").endStyle(); div.text(rowValue.getType()); td.endDiv(); } else { renderCell(td, createContext(1), typeColumn, rowValue); } td.endTD(); // Length column. td = row.startTD(); td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle(); if (showTranscripts) { DivBuilder div = td.startDiv(); div.style().trustedColor("green").endStyle(); div.text(NumberFormat.getDecimalFormat().format(rowValue.getLength())); td.endDiv(); td.endTD(); } else { td.text(NumberFormat.getDecimalFormat().format(rowValue.getLength())).endTD(); } td = row.startTD(); td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle(); // TODO: is it necessary to have two separte ones? // if(showTranscripts){ DivBuilder div = td.startDiv(); SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder(); for (String error : rowValue.getNoteList()) { safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>" + error + "</div>"); } div.html(safeHtmlBuilder.toSafeHtml()); td.endDiv(); td.endTD(); row.endTR(); } } }
package net.kyori.adventure.nbt; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A list of zero or more values of a single tag type. * * @since 4.0.0 */ public interface ListBinaryTag extends ListTagSetter<ListBinaryTag, BinaryTag>, BinaryTag, Iterable<BinaryTag> { /** * Gets an empty list tag. * * @return an empty tag * @since 4.0.0 */ static @NonNull ListBinaryTag empty() { return ListBinaryTagImpl.EMPTY; } static @NonNull ListBinaryTag from(final @NonNull Iterable<? extends BinaryTag> tags) { return builder().add(tags).build(); } /** * Creates a builder. * * @return a new builder * @since 4.0.0 */ static @NonNull Builder<BinaryTag> builder() { return new ListTagBuilder<>(); } static <T extends BinaryTag> @NonNull Builder<T> builder(final @NonNull BinaryTagType<T> type) { if(type == BinaryTagTypes.END) throw new IllegalArgumentException("Cannot create a list of " + BinaryTagTypes.END); return new ListTagBuilder<>(type); } static @NonNull ListBinaryTag of(final @NonNull BinaryTagType<? extends BinaryTag> type, final @NonNull List<BinaryTag> tags) { if(tags.isEmpty()) return empty(); if(type == BinaryTagTypes.END) throw new IllegalArgumentException("Cannot create a list of " + BinaryTagTypes.END); return new ListBinaryTagImpl(type, tags); } @Override default @NonNull BinaryTagType<ListBinaryTag> type() { return BinaryTagTypes.LIST; } /** * Gets the type of element stored in this list. * * @return the type * @since 4.0.0 * @deprecated since 4.4.0, use {@link #elementType()} instead */ @Deprecated default @NonNull BinaryTagType<? extends BinaryTag> listType() { return this.elementType(); } /** * Gets the type of element stored in this list. * * @return the type * @since 4.4.0 */ @NonNull BinaryTagType<? extends BinaryTag> elementType(); /** * Gets the size. * * @return the size * @since 4.0.0 */ int size(); /** * Gets a tag. * * @param index the index * @return the tag * @throws IndexOutOfBoundsException if the index is out of range * @since 4.0.0 */ @NonNull BinaryTag get(final @NonNegative int index); /** * Sets the tag at index {@code index} to {@code tag}, optionally providing {@code removedConsumer} with the tag previously at index {@code index}. * * @param index the index * @param tag the tag * @param removed a consumer which receives the tag being removed at index {@code index} * @return a list tag * @since 4.0.0 */ @NonNull ListBinaryTag set(final int index, final @NonNull BinaryTag tag, final @Nullable Consumer<? super BinaryTag> removed); /** * Removes the tag at index {@code index}, optionally providing {@code removedConsumer} with the tag previously at index {@code index}. * * @param index the index * @param removed a consumer which receives the tag being removed at index {@code index} * @return a list tag * @since 4.0.0 */ @NonNull ListBinaryTag remove(final int index, final @Nullable Consumer<? super BinaryTag> removed); /** * Gets a byte. * * @param index the index * @return the byte value, or {@code 0} * @since 4.0.0 */ default byte getByte(final @NonNegative int index) { return this.getByte(index, (byte) 0); } /** * Gets a byte. * * @param index the index * @param defaultValue the default value * @return the byte value, or {@code defaultValue} * @since 4.0.0 */ default byte getByte(final @NonNegative int index, final byte defaultValue) { final BinaryTag tag = this.get(index); if(tag.type().numeric()) { return ((NumberBinaryTag) tag).byteValue(); } return defaultValue; } /** * Gets a short. * * @param index the index * @return the short value, or {@code 0} * @since 4.0.0 */ default short getShort(final @NonNegative int index) { return this.getShort(index, (short) 0); } /** * Gets a short. * * @param index the index * @param defaultValue the default value * @return the short value, or {@code defaultValue} * @since 4.0.0 */ default short getShort(final @NonNegative int index, final short defaultValue) { final BinaryTag tag = this.get(index); if(tag.type().numeric()) { return ((NumberBinaryTag) tag).shortValue(); } return defaultValue; } /** * Gets an int. * * @param index the index * @return the int value, or {@code 0} * @since 4.0.0 */ default int getInt(final @NonNegative int index) { return this.getInt(index, 0); } /** * Gets an int. * * @param index the index * @param defaultValue the default value * @return the int value, or {@code defaultValue} * @since 4.0.0 */ default int getInt(final @NonNegative int index, final int defaultValue) { final BinaryTag tag = this.get(index); if(tag.type().numeric()) { return ((NumberBinaryTag) tag).intValue(); } return defaultValue; } /** * Gets a long. * * @param index the index * @return the long value, or {@code 0} * @since 4.0.0 */ default long getLong(final @NonNegative int index) { return this.getLong(index, 0L); } /** * Gets a long. * * @param index the index * @param defaultValue the default value * @return the long value, or {@code defaultValue} * @since 4.0.0 */ default long getLong(final @NonNegative int index, final long defaultValue) { final BinaryTag tag = this.get(index); if(tag.type().numeric()) { return ((NumberBinaryTag) tag).longValue(); } return defaultValue; } /** * Gets a float. * * @param index the index * @return the float value, or {@code 0} * @since 4.0.0 */ default float getFloat(final @NonNegative int index) { return this.getFloat(index, 0f); } /** * Gets a float. * * @param index the index * @param defaultValue the default value * @return the float value, or {@code defaultValue} * @since 4.0.0 */ default float getFloat(final @NonNegative int index, final float defaultValue) { final BinaryTag tag = this.get(index); if(tag.type().numeric()) { return ((NumberBinaryTag) tag).floatValue(); } return defaultValue; } /** * Gets a double. * * @param index the index * @return the double value, or {@code 0} * @since 4.0.0 */ default double getDouble(final @NonNegative int index) { return this.getDouble(index, 0d); } /** * Gets a double. * * @param index the index * @param defaultValue the default value * @return the double value, or {@code defaultValue} * @since 4.0.0 */ default double getDouble(final @NonNegative int index, final double defaultValue) { final BinaryTag tag = this.get(index); if(tag.type().numeric()) { return ((NumberBinaryTag) tag).doubleValue(); } return defaultValue; } /** * Gets an array of bytes. * * @param index the index * @return the array of bytes, or a zero-length array * @since 4.0.0 */ default byte@NonNull[] getByteArray(final @NonNegative int index) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.BYTE_ARRAY) { return ((ByteArrayBinaryTag) tag).value(); } return new byte[0]; } /** * Gets an array of bytes. * * @param index the index * @param defaultValue the default value * @return the array of bytes, or {@code defaultValue} * @since 4.0.0 */ default byte@NonNull[] getByteArray(final @NonNegative int index, final byte@NonNull[] defaultValue) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.BYTE_ARRAY) { return ((ByteArrayBinaryTag) tag).value(); } return defaultValue; } /** * Gets a string. * * @param index the index * @return the string value, or {@code ""} * @since 4.0.0 */ default @NonNull String getString(final @NonNegative int index) { return this.getString(index, ""); } /** * Gets a string. * * @param index the index * @param defaultValue the default value * @return the string value, or {@code defaultValue} * @since 4.0.0 */ default @NonNull String getString(final @NonNegative int index, final @NonNull String defaultValue) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.STRING) { return ((StringBinaryTag) tag).value(); } return defaultValue; } /** * Gets a list. * * @param index the index * @return the list, or an empty list if the tag at index {@code index} is not a list tag * @since 4.4.0 */ default @NonNull ListBinaryTag getList(final @NonNegative int index) { return this.getList(index, null, ListBinaryTag.empty()); } /** * Gets a list. * * @param index the index * @param elementType the expected element type of the list at index {@code index} * @return the list, or an empty list if the tag at index {@code index} is not a list tag, or if the list tag's element type is not {@code elementType} * @since 4.4.0 */ default @NonNull ListBinaryTag getList(final @NonNegative int index, final @Nullable BinaryTagType<?> elementType) { return this.getList(index, elementType, ListBinaryTag.empty()); } /** * Gets a list. * * @param index the index * @param defaultValue the default value * @return the list, or {@code defaultValue} if the tag at index {@code index} is not a list tag * @since 4.4.0 */ default @NonNull ListBinaryTag getList(final @NonNegative int index, final @NonNull ListBinaryTag defaultValue) { return this.getList(index, null, defaultValue); } /** * Gets a list. * * <p>If {@code elementType} is non-{@code null} and the {@link ListBinaryTag} at index {@code index} does not match, {@code defaultValue} will be returned.</p> * * @param index the index * @param elementType the expected element type of the list at index {@code index} * @param defaultValue the default value * @return the list, or {@code defaultValue} if the tag at index {@code index} is not a list tag, or if the list tag's element type is not {@code elementType} * @since 4.4.0 */ default @NonNull ListBinaryTag getList(final @NonNegative int index, final @Nullable BinaryTagType<?> elementType, final @NonNull ListBinaryTag defaultValue) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.LIST) { final ListBinaryTag list = (ListBinaryTag) tag; if(elementType == null || list.elementType() == elementType) { return list; } } return defaultValue; } /** * Gets a compound. * * @param index the index * @return the compound, or a new compound * @since 4.0.0 */ default @NonNull CompoundBinaryTag getCompound(final @NonNegative int index) { return this.getCompound(index, CompoundBinaryTag.empty()); } /** * Gets a compound. * * @param index the index * @param defaultValue the default value * @return the compound, or {@code defaultValue} * @since 4.0.0 */ default @NonNull CompoundBinaryTag getCompound(final @NonNegative int index, final @NonNull CompoundBinaryTag defaultValue) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.COMPOUND) { return (CompoundBinaryTag) tag; } return defaultValue; } /** * Gets an array of ints. * * @param index the index * @return the array of ints, or a zero-length array * @since 4.0.0 */ default int@NonNull[] getIntArray(final @NonNegative int index) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.INT_ARRAY) { return ((IntArrayBinaryTag) tag).value(); } return new int[0]; } /** * Gets an array of ints. * * @param index the index * @param defaultValue the default value * @return the array of ints, or {@code defaultValue} * @since 4.0.0 */ default int@NonNull[] getIntArray(final @NonNegative int index, final int@NonNull[] defaultValue) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.INT_ARRAY) { return ((IntArrayBinaryTag) tag).value(); } return defaultValue; } /** * Gets an array of longs. * * @param index the index * @return the array of longs, or a zero-length array * @since 4.0.0 */ default long@NonNull[] getLongArray(final @NonNegative int index) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.LONG_ARRAY) { return ((LongArrayBinaryTag) tag).value(); } return new long[0]; } /** * Gets an array of longs. * * @param index the index * @param defaultValue the default value * @return the array of longs, or {@code defaultValue} * @since 4.0.0 */ default long@NonNull[] getLongArray(final @NonNegative int index, final long@NonNull[] defaultValue) { final BinaryTag tag = this.get(index); if(tag.type() == BinaryTagTypes.LONG_ARRAY) { return ((LongArrayBinaryTag) tag).value(); } return defaultValue; } /** * Creates a stream of the tags contained within this list. * * @return a new stream * @since 4.2.0 */ @NonNull Stream<BinaryTag> stream(); /** * A list tag builder. * * @param <T> the element type * @since 4.0.0 */ interface Builder<T extends BinaryTag> extends ListTagSetter<Builder<T>, T> { /** * Builds. * * @return a list tag * @since 4.0.0 */ @NonNull ListBinaryTag build(); } }
package org.xins.server; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.collections.PropertyReader; import org.xins.util.collections.ProtectedPropertyReader; /** * Simple representation of an XML element. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.119 */ final class Element extends Object { // Class fields /** * The logging category used by this class. This class field is never * <code>null</code>. */ private static final Logger LOG = Logger.getLogger(Element.class.getName()); // Class functions // Constructors public Element(String type) throws IllegalArgumentException { // TODO: Check that name is valid // Check preconditions MandatoryArgumentChecker.check("type", type); _type = type; _attributes = new ProtectedPropertyReader(LOG); } // Fields /** * The parent of this element. Can be <code>null</code>. */ private Element _parent; /** * The type of this element. Cannot be <code>null</code>. */ private String _type; /** * The set of attributes. Cannot be <code>null</code>. */ private ProtectedPropertyReader _attributes; /** * Content of this element. May contain PCDATA (as {@link String} objects) * and other elements (as {@link Element} objects). * * <p>This field is lazily initialized, so it is initially * <code>null</code>. */ private List _content; // Methods /** * Returns the parent element. * * @return * the parent element, or <code>null</code> if this element currently * has no parent. */ public Element getParent() { return _parent; } /** * Returns the type of this element. * * @return * the type of this element, cannot be <code>null</code>. */ public String getType() { return _type; } public void addAttribute(String name, String value) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name, "value", value); // TODO: Check attribute is not yet set _attributes.set(LOG, name, value); } /** * Gets the set of attributes. * * @return * the set of attributes, never <code>null</code>. */ public PropertyReader getAttributes() { return _attributes; } public void add(String pcdata) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("pcdata", pcdata); // Initialize the content list, if necessary if (_content == null) { _content = new ArrayList(7); } // Add the PCDATA _content.add(pcdata); } public void add(Element child) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("child", child); if (child._parent != null) { throw new IllegalArgumentException("child.getParent() != null"); } // Initialize the content list, if necessary if (_content == null) { _content = new ArrayList(7); } // Add the child element _content.add(child); // Set the parent of the child child._parent = this; } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException exception) { throw new Error("Caught unexpected " + exception.getClass() + '.'); } } }
package esg.security.common; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableEntryException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.xml.security.SecurityHelper; import org.opensaml.xml.security.credential.BasicCredential; import org.opensaml.xml.security.credential.Credential; /** * Utility class to manage keystores and trustores for creating/verifying digital signatures. */ public class SecurityManager { private final static Log LOG = LogFactory.getLog(SecurityManager.class); /** * Method to return a map of trusted credentials, indexed by alias, read from a given trustore. * @param trustore : the location of the local trustore * @param password : the password needed to access the trustore * @return */ public static Map<String,Credential> getTrustedCredentials(final File trustore, final String password) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException { // load the trustore //final ClassPathResource trustore = new ClassPathResource(trustoreClasspathLocation); final KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType()); final FileInputStream fis = new java.io.FileInputStream(trustore); ts.load(fis, password.toCharArray()); fis.close(); // loop over content, load all trusted certificates final Map<String,Credential> trustedCredentials = new HashMap<String,Credential>(); final Enumeration<String> aliases = ts.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); if (LOG.isDebugEnabled()) LOG.debug("Trusted Certificate Alias="+alias); final KeyStore.TrustedCertificateEntry tcEntry = (KeyStore.TrustedCertificateEntry)ts.getEntry(alias, null); // no password required if (LOG.isTraceEnabled()) LOG.trace("Trusted Certificate="+tcEntry.getTrustedCertificate()); final PublicKey trustedPublicKey = tcEntry.getTrustedCertificate().getPublicKey(); final KeyPair keyPair = new KeyPair(trustedPublicKey, null); // no private key available final BasicCredential trustedCredential = SecurityHelper.getSimpleCredential(keyPair.getPublic(), keyPair.getPrivate()); trustedCredentials.put(alias, trustedCredential); } return trustedCredentials; } /** * Method to load the local credentials (public + private key) from a known classpath location. * @param keystore : the location of the local keystore * @param password : the password needed to access the keystore * @param alias : the alias of the keystore entry to return */ public static Credential getMyCredential(final File keystore, final String password, final String alias) throws FileNotFoundException, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException { //final ClassPathResource keystore = new ClassPathResource(keystoreClasspathLocation); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); final FileInputStream fis = new FileInputStream(keystore); ks.load(fis, password.toCharArray()); fis.close(); if (LOG.isInfoEnabled()) { final Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { LOG.info("Keystore alias="+aliases.nextElement()); } } // load requested public and private key final KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray())); if (pkEntry==null) { throw new KeyStoreException("Cannot load entry with alias="+alias+" password="+(password == null ? "[NULL]" : "[*******]")+" from keystore="+keystore.getAbsolutePath()); } else { if (LOG.isDebugEnabled()) LOG.info("Used alias="+alias+" password="+(password == null ? "[NULL]" : "[*******]")+" to load keystore entry="+pkEntry.toString()); final PrivateKey myPrivateKey = pkEntry.getPrivateKey(); final PublicKey myPublicKey = pkEntry.getCertificate().getPublicKey(); if (LOG.isDebugEnabled()) LOG.debug("Private key="+myPrivateKey.toString()); if (LOG.isDebugEnabled()) LOG.debug("Public key="+myPublicKey.toString()); final KeyPair keyPair = new KeyPair(myPublicKey, myPrivateKey); final BasicCredential myCredential = SecurityHelper.getSimpleCredential(keyPair.getPublic(), keyPair.getPrivate()); myCredential.setEntityId( ((X509Certificate)pkEntry.getCertificate()).getSubjectDN().toString() ); return myCredential; } } }
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.tokenize; import opennlp.maxent.Event; import opennlp.maxent.EventCollector; import opennlp.maxent.ContextGenerator; import opennlp.tools.util.ObjectIntPair; import java.io.BufferedReader; import java.io.Reader; import java.util.ArrayList; public class TokEventCollector implements EventCollector { private static final ContextGenerator cg = new TokContextGenerator(); private BufferedReader br; /** * Class constructor. */ public TokEventCollector(Reader data) { br = new BufferedReader(data); } /** * Builds up the list of features using the Reader as input. For now, this * should only be used to create training data. */ public Event[] getEvents() { ArrayList elist = new ArrayList(); try { String s = br.readLine(); while (s != null) { String[] spaceToks = s.split(" "); for (int tok = 0; tok < spaceToks.length; tok++) { StringBuffer sb = new StringBuffer(spaceToks[tok]); if (TokenizerME.alphaNumeric.matcher(spaceToks[tok]).matches()) { int lastIndex = sb.length() - 1; for (int id = 0; id < sb.length(); id++) { String[] context = cg.getContext(new ObjectIntPair(sb, id)); if (id == lastIndex) { elist.add(new Event("T", context)); } else { elist.add(new Event("F", context)); } } } } s = br.readLine(); } } catch (Exception e) { e.printStackTrace(); } Event[] events = new Event[elist.size()]; elist.toArray(events); return events; } public Event[] getEvents(boolean evalMode) { return getEvents(); } }
package org.apache.cassandra.hirudinea; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.Iterator; import java.nio.ByteBuffer; import java.util.Date; import org.apache.cassandra.db.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Hirudinea { public static final String KEYSPACE_NAME = "tp"; public static final String TABLE_NAME = "station"; public static final String NUMBER_COLUMN_NAME = "n"; private static final Logger logger = LoggerFactory.getLogger(Hirudinea.class); public static final ConcurrentHashMap<Long, ArrayList<StationEntry>> stations = new ConcurrentHashMap(); /* * Request analyze */ public static void extract(Keyspace ks, Mutation m) { String keyspace_name = ks.getName(); ByteBuffer key = m.key(); String table_name; String cell_name; ByteBuffer cell_value; Collection<ColumnFamily> values = m.getColumnFamilies(); for (ColumnFamily c: values) { table_name = c.metadata().cfName; for (Cell cell: c) { cell_name = c.getComparator().getString(cell.name()); cell_value = cell.value(); analyze(keyspace_name, table_name, key, cell_name, cell_value); } } } public static void analyze(String keyspace_name, String table_name, ByteBuffer key, String cell_name, ByteBuffer cell_value) { Long station_id; Long new_value; Date date; if (keyspace_name.equals(KEYSPACE_NAME) && table_name.equals(TABLE_NAME) && cell_name.equals(NUMBER_COLUMN_NAME)) { station_id = ByteBufferUtil.toLong(key); new_value = ByteBufferUtil.toLong(cell_value); date = new Date(); logger.info("Station {} modified at {}, new value: {}", station_id, date, new_value); addStationEntry(station_id, new_value, date); } } /* * Stations */ public static void addStationEntry(Long station_id, Long value, Date date) { ArrayList<StationEntry> entries; if (stations.get(station_id) == null) { entries = new ArrayList<StationEntry>(); } else { entries = stations.get(station_id); } entries.add(new StationEntry(value, date)); stations.put(station_id, entries); displayStations(); } public static void displayStations() { logger.info("-- Display stations --"); for (Map.Entry<Long, ArrayList<StationEntry>> entry : stations.entrySet()) { Long key = entry.getKey(); ArrayList<StationEntry> value = entry.getValue(); logger.info("\t Station {}", key); logger.info("\t\t Time serie: {}", timeSerieToString(getTimeSerie(key, 1000L*60, 1000L))); for (StationEntry se: value) { logger.info("\t\t {}: {}", se.date, se.value); } } } /* * Time series */ public static ArrayList<Long> getTimeSerie(Long station_id, Date start, Date end, Long interval) { ArrayList<StationEntry> list_entries = stations.get(station_id); ArrayList<Long> time_serie = new ArrayList<Long>(); Long total_number = (end.getTime() - start.getTime()) / interval; for (int i = 0; i < total_number; i++) { time_serie.add(0L); } for (StationEntry se: list_entries) { int index = (int) ((se.date.getTime() - start.getTime()) / interval); for (int i = index; i < time_serie.size(); i++) { if (i >= 0) { time_serie.set(i, se.value); } } } return time_serie; } public static String timeSerieToString(ArrayList<Long> ts) { String s = "["; for (Long l: ts) { s += l + ", "; } s += "]"; return s; } public static ArrayList<Long> getTimeSerie(Long station_id, Long duration, Long interval) { Date start = new Date((new Date()).getTime() - duration); Date end = new Date(); return getTimeSerie(station_id, start, end, interval); } }
/* * $Log: SoapWrapper.java,v $ * Revision 1.3 2005-05-31 09:16:23 europe\L190409 * cosmetic changes * * Revision 1.2 2005/05/31 09:15:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added catch for DomBuilderException * * Revision 1.1 2005/02/24 12:15:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * moved SOAP conversion coding to SOAP-wrapper * */ package nl.nn.adapterframework.http; import java.io.IOException; import java.io.InputStream; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.util.DomBuilderException; import nl.nn.adapterframework.util.TransformerPool; import nl.nn.adapterframework.util.XmlUtils; /** * Utility class that wraps and unwraps messages from (and into) a SOAP Envelope. * * @author Gerrit van Brakel * @version Id */ public class SoapWrapper { public static final String version="$RCSfile: SoapWrapper.java,v $ $Revision: 1.3 $ $Date: 2005-05-31 09:16:23 $"; protected Logger log = Logger.getLogger(this.getClass()); private TransformerPool extractBody; private TransformerPool extractFaultCount; private TransformerPool extractFaultCode; private TransformerPool extractFaultString; private final static String extractNamespaces="xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"";
package eu.theunitry.fabula; import eu.theunitry.fabula.graphics.UNPanel; import eu.theunitry.fabula.graphics.UNWindow; import eu.theunitry.fabula.launcher.UNLauncher; import eu.theunitry.fabula.objects.UNObject; import kuusisto.tinysound.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; public class UNGameScreen extends UNObject { private UNWindow window; private UNLauncher launcher; private UNPanel splash; private JPanel currentPanel; private ArrayList<Music> music; private ArrayList<Sound> sounds; private ArrayList<Image> sprites, backgrounds; private int level, levelMax; public UNGameScreen() { music = new ArrayList<Music>(); sounds = new ArrayList<Sound>(); sprites = new ArrayList<Image>(); backgrounds = new ArrayList<Image>(); this.window = new UNWindow("Fabula", 768, 512); this.launcher = new UNLauncher(this); this.splash = new UNPanel(this, false); try { this.splash.setBackgroundImage(ImageIO.read(new File("res/backgrounds/splash_unitry.png"))); } catch (IOException e) { e.printStackTrace(); } this.window.addPanel(splash); this.window.getFrame().setVisible(true); TinySound.init(); preload(); music.get(0).play(true); music.get(0).setVolume(0.1); this.window.removePanel(splash); this.window.addPanel(launcher); this.currentPanel = launcher; this.window.getFrame().setVisible(true); this.level = 1; this.levelMax = 5; } public void switchPanel(JPanel panel) { this.window.removePanel(currentPanel); this.window.addPanel(panel); this.currentPanel = panel; this.window.getFrame().setVisible(true); } public UNWindow getWindow() { return this.window; } public void switchMusic(int index, boolean loop) { music.get(0).stop(); music.get(index).play(loop); } public ArrayList<Music> getMusic() { return this.music; } public ArrayList<Sound> getSounds() { return this.sounds; } public ArrayList<Image> getSprites() { return this.sprites; } public ArrayList<Image> getBackgrounds() { return this.backgrounds; } public int getLevel() { return level; } public int getLevelMax() { return levelMax; } public void addLevel() { this.level++; } public void resetProgress() { this.level = 1; } public void preload() { /** * Font Preload */ try { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("res/fonts/Minecraftia.ttf"))); } catch (IOException|FontFormatException e) { e.printStackTrace(); } /** * Music Preload */ music.add(0, TinySound.loadMusic("audio/intro.wav")); music.add(1, TinySound.loadMusic("audio/song2.wav")); /** * Sound Effects Preload */ sounds.add(0, TinySound.loadSound("audio/gibberish.wav")); /** * Sprites Preload */ try { //BACKGROUND PRELOAD backgrounds.add(0, ImageIO.read(new File("res/backgrounds/forest.png"))); //SPRITE PRELOAD //TUILTJE IDLE sprites.add(0, ImageIO.read(new File("res/animations/tuiltje/idle/idle0.png"))); sprites.add(1, ImageIO.read(new File("res/animations/tuiltje/idle/idle1.png"))); sprites.add(2, ImageIO.read(new File("res/animations/tuiltje/idle/idle2.png"))); sprites.add(3, ImageIO.read(new File("res/animations/tuiltje/idle/idle3.png"))); sprites.add(4, ImageIO.read(new File("res/animations/tuiltje/idle/idle4.png"))); sprites.add(5, ImageIO.read(new File("res/animations/tuiltje/idle/idle5.png"))); //TUILTJE FLAPPING sprites.add(6, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping0.png"))); sprites.add(7, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping1.png"))); sprites.add(8, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping2.png"))); sprites.add(9, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping3.png"))); sprites.add(10, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping4.png"))); sprites.add(11, ImageIO.read(new File("res/animations/tuiltje/flapping/flapping5.png"))); //TUILTJE SAD sprites.add(12, ImageIO.read(new File("res/animations/tuiltje/sad/sad0.png"))); sprites.add(13, ImageIO.read(new File("res/animations/tuiltje/sad/sad1.png"))); sprites.add(14, ImageIO.read(new File("res/animations/tuiltje/sad/sad2.png"))); sprites.add(15, ImageIO.read(new File("res/animations/tuiltje/sad/sad3.png"))); sprites.add(16, ImageIO.read(new File("res/animations/tuiltje/sad/sad4.png"))); sprites.add(17, ImageIO.read(new File("res/animations/tuiltje/sad/sad5.png"))); //TUILTJE HAPPY sprites.add(18, ImageIO.read(new File("res/animations/tuiltje/happy/happy0.png"))); sprites.add(19, ImageIO.read(new File("res/animations/tuiltje/happy/happy1.png"))); sprites.add(20, ImageIO.read(new File("res/animations/tuiltje/happy/happy2.png"))); sprites.add(21, ImageIO.read(new File("res/animations/tuiltje/happy/happy3.png"))); sprites.add(22, ImageIO.read(new File("res/animations/tuiltje/happy/happy4.png"))); sprites.add(23, ImageIO.read(new File("res/animations/tuiltje/happy/happy5.png"))); sprites.add(24, ImageIO.read(new File("res/animations/tuiltje/happy/happy6.png"))); sprites.add(25, ImageIO.read(new File("res/animations/tuiltje/happy/happy7.png"))); sprites.add(26, ImageIO.read(new File("res/animations/tuiltje/happy/happy8.png"))); sprites.add(27, ImageIO.read(new File("res/animations/tuiltje/happy/happy9.png"))); //TUILTJE QUESTIONING sprites.add(28, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning0.png"))); sprites.add(29, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning1.png"))); sprites.add(30, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning2.png"))); sprites.add(31, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning3.png"))); sprites.add(32, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning4.png"))); sprites.add(33, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning5.png"))); sprites.add(34, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning6.png"))); sprites.add(35, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning7.png"))); sprites.add(36, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning8.png"))); sprites.add(37, ImageIO.read(new File("res/animations/tuiltje/questioning/questioning9.png"))); //LEVEL0 sprites.add(38, ImageIO.read(new File("res/sprites/apple.png"))); sprites.add(39, ImageIO.read(new File("res/sprites/basket.png"))); } catch (IOException e) { e.printStackTrace(); } } }
package alma.acs.nc; import java.util.HashMap; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.text.ParseException; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.IntHolder; import org.omg.CosNaming.Binding; import org.omg.CosNaming.BindingIteratorHolder; import org.omg.CosNaming.BindingListHolder; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContext; import org.omg.CosNaming.NamingContextHelper; import org.omg.CosNotification.Property; import org.omg.CosNotification.PropertyError; import org.omg.CosNotification.UnsupportedAdmin; import org.omg.CosNotification.UnsupportedQoS; import org.omg.CosNotifyChannelAdmin.ChannelNotFound; import com.cosylab.CDB.DAO; import com.cosylab.cdb.client.CDBAccess; import com.cosylab.cdb.client.DAOProxy; import com.cosylab.util.WildcharMatcher; import gov.sandia.NotifyMonitoringExt.EventChannel; import gov.sandia.NotifyMonitoringExt.EventChannelFactory; import gov.sandia.NotifyMonitoringExt.EventChannelFactoryHelper; import gov.sandia.NotifyMonitoringExt.EventChannelHelper; import gov.sandia.NotifyMonitoringExt.NameAlreadyUsed; import gov.sandia.NotifyMonitoringExt.NameMapError; import alma.ACSErrTypeCORBA.wrappers.AcsJNarrowFailedEx; import alma.ACSErrTypeCommon.wrappers.AcsJBadParameterEx; import alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx; import alma.ACSErrTypeCommon.wrappers.AcsJGenericErrorEx; import alma.ACSErrTypeCommon.wrappers.AcsJIllegalArgumentEx; import alma.ACSErrTypeCommon.wrappers.AcsJUnexpectedExceptionEx; import alma.AcsNCTraceLog.LOG_NC_ChannelCreatedRaw_OK; import alma.AcsNCTraceLog.LOG_NC_ChannelCreated_ATTEMPT; import alma.AcsNCTraceLog.LOG_NC_ChannelCreated_OK; import alma.AcsNCTraceLog.LOG_NC_ChannelDestroyed_OK; import alma.AcsNCTraceLog.LOG_NC_TaoExtensionsSubtypeMissing; import alma.acs.container.AdvancedContainerServices; import alma.acs.container.ContainerServicesBase; import alma.acs.exceptions.AcsJException; import alma.acs.logging.AcsLogLevel; import alma.acs.util.StopWatch; import alma.acscommon.ACS_NC_DOMAIN_ARCHIVING; import alma.acscommon.ACS_NC_DOMAIN_LOGGING; import alma.acscommon.ARCHIVE_NOTIFICATION_FACTORY_NAME; import alma.acscommon.LOGGING_NOTIFICATION_FACTORY_NAME; import alma.acscommon.NAMESERVICE_BINDING_NC_DOMAIN_DEFAULT; import alma.acscommon.NAMESERVICE_BINDING_NC_DOMAIN_SEPARATOR; import alma.acscommon.NC_KIND; /** * This class provides methods useful to both supplier and consumer objects, * where it is associated with exactly one Notification Channel. * It can also be used without any notification channel. * Never use a Helper instance for more than once NC! */ public class Helper { /** * In a running system, there can be only one reference to the Naming Service. */ private final NamingContext m_nContext; /** * Java property name for the CORBA Naming Service corbaloc. * This property is set in the acsstartup :: acsStartJava. * <p> * @TODO: Check if we can eliminate this property if we use something similar as in * jmanager's {@link com.cosylab.acs.maci.plug.NamingServiceRemoteDirectory}. */ private static final String m_nameJavaProp = "ORBInitRef.NameService"; /** * Access to the component's name along with the logging service. */ private final ContainerServicesBase m_services; // Our own personal logger protected final Logger m_logger; /** * A Helper instance serves only one NC. */ protected final String channelName; /** * The optional NC domain name, e.g. "ALARMSYSTEM". */ protected final String domainName; /** * Creation time of the channel to be used in order to know the restart of the Notify Service */ protected Date channelTimestamp = new Date(0); /** * channelId is used to reconnect to channel in case that Notify Server crashes */ private int channelId; // Provides access to channel's quality of service properties private final ChannelProperties m_channelProperties; /** * Cached notify factory name where our NC is or should be hosted. * Avoids unnecessary CDB calls. */ private volatile String ncFactoryName; /** * TODO */ private EventChannelFactory notifyFactory; /** * timestamp in ms when config error was found. Initialized to 0L. * <p> * Used similar to a log repeat guard, because the OMC was flooded with NC config problem logs * (as of 2008-03-06). */ private Long channelConfigProblemTimestamp = 0L; /** * Random number generator, used to randomize client names * when used as server-side proxy names. * This class is static and thus shared among the subscribers and suppliers of one client or component, * to reduce the risk that two subscribers or suppliers create * Helper instances at the same time (system time is used as random generator seed) * and thereby produce identical sequences of random numbers, * which would defy the purpose of avoiding name clashes on the server. */ protected static final Random random = new Random(System.currentTimeMillis()); public static String extractChannelName(String channelWithDomainName) throws AcsJIllegalArgumentEx { return splitChannelAndDomainName(channelWithDomainName)[0]; } public static String extractDomainName(String channelWithDomainName) throws AcsJIllegalArgumentEx { return splitChannelAndDomainName(channelWithDomainName)[1]; } private static String[] splitChannelAndDomainName(String channelWithDomainName) throws AcsJIllegalArgumentEx { String[] ret = channelWithDomainName.split(NAMESERVICE_BINDING_NC_DOMAIN_SEPARATOR.value); if (ret.length == 2) { return ret; } else { AcsJIllegalArgumentEx ex = new AcsJIllegalArgumentEx(); ex.setVariable("channelWithDomainName"); ex.setValue(channelWithDomainName); ex.setErrorDesc("No unique NC - domain separation found in NC binding."); throw ex; } } public static String combineChannelAndDomainName(String channelName, String domainName) { String ret = channelName; ret += NAMESERVICE_BINDING_NC_DOMAIN_SEPARATOR.value; if (domainName != null) { ret += domainName; } else { ret += NAMESERVICE_BINDING_NC_DOMAIN_DEFAULT.value; } return ret; } /** * Same as {@link #Helper(String, String, ContainerServicesBase, NamingContext)} but without the NC domain; * the default NC domain ({@link NAMESERVICE_BINDING_NC_DOMAIN_DEFAULT.value}) will be used. * * @param channelName * @param services * @param namingService * @throws AcsJException */ public Helper(String channelName, ContainerServicesBase services, NamingContext namingService) throws AcsJException { this(channelName, null, services, namingService); } /** * Creates a new instance of Helper. * @param channelName The NC that this Helper is made for. * @param domainName The optional NC domain, or <code>null</code>. * @param services A reference to the ContainerServices * @param namingService Reference to the naming service. * @throws AcsJException Generic ACS exception will be thrown if anything in this class is broken. */ public Helper(String channelName, String domainName, ContainerServicesBase services, NamingContext namingService) throws AcsJException { this.channelName = channelName; this.domainName = domainName; if (services == null) { AcsJBadParameterEx ex = new AcsJBadParameterEx(); ex.setReason("Null reference obtained for the ContainerServices!"); throw ex; } // save a local reference to the container services m_services = services; // immediately grab a logger m_logger = m_services.getLogger(); // create a helper object used to retrieve channel properties m_channelProperties = new ChannelProperties(services); m_nContext = namingService; } /** * Returns a reference to the Container Services which are provided by a * container or client. * * @return A valid reference to the ContainerServices instance. */ public ContainerServicesBase getContainerServices() { return m_services; } /** * <b>This method should only be used by specialized framework code, * not by application code that uses NCs.</b> * It retrieves and returns a reference to the Naming Service based on the * Java property <code>ORBInitRef.NameService</code>. * <p> * Even specialized code that has an AcsManagerProxy instance available, * e.g. via an AdvancedComponentClient, * should use the AcsManagerProxy to get the NamingContext reference: * <pre> * nctx = NamingContextHelper.narrow(AdvancedComponentClient.getAcsManagerProxy().get_service("NameService", false); * </pre>. * <p> * * @return Valid reference to the Naming Service. * @throws AcsJException * Thrown when there's a bad corbaloc given for the Naming Service * or the reference cannot be narrowed. * @see #getNamingService() * @deprecated To be removed once we have fixed the leftover usages in modules * jcontnc, laser-core, acssamp, acssampGUI. */ public static NamingContext getNamingServiceInitial(ContainerServicesBase cs) throws AcsJException { // acsStartJava always adds this Java property for us String nameCorbaloc = System.getProperty(m_nameJavaProp); // make sure the end-user is using acsStartJava if (nameCorbaloc == null || nameCorbaloc.trim().isEmpty()) { AcsJBadParameterEx ex = new AcsJBadParameterEx(); ex.setReason("Missing Java property '" + m_nameJavaProp + "' for the Naming Service corbaloc!"); throw ex; } // get the unnarrowed reference to the Naming Service org.omg.CORBA.Object tempCorbaObject = cs.getAdvancedContainerServices().corbaObjectFromString(nameCorbaloc); if (tempCorbaObject == null) { // very bad situation. without the naming service we cannot do anything. Throwable cause = new Throwable("Null reference obtained for the Naming Service, corbaloc=" + nameCorbaloc); //AcsJFailedToResolveServiceEx ex = new AcsJFailedToResolveServiceEx(); // @TODO add parameter "service" and "reason" to definition of AcsJFailedToResolveServiceEx // ex.setReason("Null reference obtained for the Naming Service, corbaloc=" + nameCorbaloc); throw new alma.ACSErrTypeCORBA.wrappers.AcsJFailedToResolveServiceEx(cause); } NamingContext ret = NamingContextHelper.narrow(tempCorbaObject); if (ret == null) { // very bad situation. without the naming service we cannot do anything. Throwable cause = new Throwable("Unable to narrow Naming Service reference to the correct type!"); throw new alma.ACSErrTypeCommon.wrappers.AcsJTypeNotSupportedEx(cause); } return ret; } /** * Returns a reference to the Naming Service. * <p> * @return Valid reference to the Naming Service. */ public NamingContext getNamingService() { return m_nContext; } /** * The TAO extension's reconnect() methods call this (via NCSubscriber etc), * so that we call again {@link org.omg.CosNotifyChannelAdmin.EventChannelFactoryOperations#get_event_channel(int)}. */ public EventChannel getNotificationChannel(EventChannelFactory ecf) { EventChannel ec = null; try { ec = EventChannelHelper.narrow( ecf.get_event_channel(channelId) ); } catch (ChannelNotFound e) { // I cannot recover the channel using the ID } return ec; } /** * This method gets a reference to the event channel. If it is not already * registered with the naming service, it is created. * * @return Reference to the event channel specified by channelName. Never null. * @param channelKind * Kind of the channel as registered with the CORBA naming service ("channels"). * @param notifyFactoryName * Name of the notification service as registered with the CORBA * naming service. * @throws AcsJException * Standard ACS Java exception. */ protected EventChannel getNotificationChannel(String notifyFactoryName) throws AcsJException { String channelKind = NC_KIND.value; // return value EventChannel retValue = null; NameComponent[] t_NameSequence = { new NameComponent(combineChannelAndDomainName(channelName, domainName), channelKind) }; // (retryNumberAttempts * retrySleepSec) = the time before we give up to get a reference or create the channel if // a channel of the given name supposedly gets created already (due to race conditions with other clients). int retryNumberAttempts = 20; int retrySleepSec = 2; do { try { // @TODO move the check for existing channel from naming service to the NC factory, // now that we use the TAO extension with named NCs. // The only advantage of still using the naming service is that the naming service is a real system-wide singleton // and can return also channels that were by mistake created from a different notify service factory than the one configured in the CDB. initializeNotifyFactory(notifyFactoryName); retValue = EventChannelHelper.narrow(getNamingService().resolve(t_NameSequence)); } catch (org.omg.CosNaming.NamingContextPackage.NotFound e) { // No other consumers or suppliers have registered the channel yet... // This can mean that the channel has never been created, or that it is currently being created but has not yet been registered. } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) { // Think there is virtually no chance of this every happening but... throw new AcsJUnexpectedExceptionEx(e); } catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) { // Think there is virtually no chance of this every happening but... throw new AcsJUnexpectedExceptionEx(e); } if (retValue == null) { // Couldn't get the channel object from the naming service. // Let's try to create it, which may fail if some other consumer or supplier is currently doing the same, // but only because we use the TAO extensions that support named NCs. try { retValue = createNotificationChannel(channelKind, notifyFactoryName); } catch (NameAlreadyUsed ex) { m_logger.log(Level.INFO, "NC '" + channelName + "' seems to be getting created. Will wait and try again in " + retrySleepSec + " seconds.", ex); try { Thread.sleep(retrySleepSec*1000); } catch (InterruptedException ex1) { // too bad } } } // The channel could be resolved from the Naming Service else { // Get the channel timestamp located into the Naming Service or set it to the current time initChannelTimestamp(); } } while (retValue == null && --retryNumberAttempts >= 0); if (retValue == null) { AcsJGenericErrorEx ex = new AcsJGenericErrorEx(); ex.setErrorDesc("Giving up to get reference to channel " + channelName); throw ex; } return retValue; } /** * @param notifyFactoryName * @throws AcsJException AcsJCORBAProblemEx if the NotifyService reference cannot be retrieved from the NamingService; * AcsJNarrowFailedEx if the NotifyService is not of the required TAO extension type. */ protected void initializeNotifyFactory(String notifyFactoryName) throws AcsJException { if (notifyFactory == null){ final String standardEventFactoryId = org.omg.CosNotifyChannelAdmin.EventChannelFactoryHelper.id(); final String specialEventFactoryId = gov.sandia.NotifyMonitoringExt.EventChannelFactoryHelper.id(); // get the Notification Factory first. NameComponent[] t_NameFactory = { new NameComponent(notifyFactoryName, "") }; org.omg.CORBA.Object notifyFactoryObj = null; //notifyFactory = null; try { notifyFactoryObj = getNamingService().resolve(t_NameFactory); } catch (org.omg.CosNaming.NamingContextPackage.NotFound ex) { String reason = "The CORBA Notification Service '" + notifyFactoryName + "' is not registered in the Naming Service: " + ex.why.toString(); AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(); ex2.setInfo(reason); throw ex2; } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) { // Think there is virtually no chance of this every happening but... Throwable cause = new Throwable(e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) { // Think there is virtually no chance of this every happening but... Throwable cause = new Throwable(e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } // narrow the notification factory to the TAO extension subtype try { notifyFactory = EventChannelFactoryHelper.narrow(notifyFactoryObj); } catch (BAD_PARAM ex) { if (notifyFactoryObj._is_a(standardEventFactoryId)) { LOG_NC_TaoExtensionsSubtypeMissing.log(m_logger, notifyFactoryName, specialEventFactoryId, standardEventFactoryId); } else { LOG_NC_TaoExtensionsSubtypeMissing.log(m_logger, notifyFactoryName, specialEventFactoryId, "???"); } AcsJNarrowFailedEx ex2 = new AcsJNarrowFailedEx(ex); ex2.setNarrowType(specialEventFactoryId); throw ex2; } } } protected EventChannel createNotificationChannel(String channelKind, String notifyFactoryName) throws AcsJException, NameAlreadyUsed { LOG_NC_ChannelCreated_ATTEMPT.log(m_logger, channelName, notifyFactoryName); // return value EventChannel retValue = null; channelId = -1; // to be assigned by factory StopWatch stopwatch = new StopWatch(); try { initializeNotifyFactory(notifyFactoryName); // create the channel // here we use the channel properties taken directly from our channel properties helper object. // presumably these values come from the ACS configuration database. IntHolder channelIdHolder = new IntHolder(); retValue = createNotifyChannel_internal( m_channelProperties.configQofS(channelName), m_channelProperties.configAdminProps(channelName), channelIdHolder); // The fact that we got here without exception means that the channel name was not used yet. // sanity check if (retValue == null) { // a null reference implies we cannot go any further Throwable cause = new Throwable("Null reference obtained for the '" + channelName + "' channel!"); throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(cause); // TODO: more specific ex type } channelId = channelIdHolder.value; // register our new channel with the naming service try { NameComponent[] t_NameChannel = { new NameComponent( combineChannelAndDomainName(channelName, domainName), channelKind) }; getNamingService().rebind(t_NameChannel, retValue); // Create an entry into the Naming Service to store the timestamp of the channel in order to allow // subscribers to reconnect to the channel (ICT-4730) int maxNumAttempts = 10; int nAttempts = maxNumAttempts; boolean timestampCreated = setChannelTimestamp(retValue); while(false == timestampCreated && nAttempts > 0) { try { Thread.sleep(2000); } catch (InterruptedException ex1) { // too bad } nAttempts timestampCreated = setChannelTimestamp(retValue); } if(false == timestampCreated) { Throwable cause = new Throwable("Failed to register the timestamp of the channel '" + channelName + "' into the Naming Service after " + String.valueOf(maxNumAttempts) + " attempts"); throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(cause); // TODO: more specific ex type } } catch (org.omg.CosNaming.NamingContextPackage.NotFound ex) { // Corba spec: "If already bound, the previous binding must be of type nobject; // otherwise, a NotFound exception with a why reason of not_object is raised." String reason = "Failed to register the new channel '" + channelName + "' with the Naming Service: " + ex.why.toString(); AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(ex); ex2.setInfo(reason); throw ex2; } } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) { // Think there is virtually no chance of this every happening but... Throwable cause = new Throwable(e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) { // Think there is virtually no chance of this every happening but... Throwable cause = new Throwable(e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } catch (org.omg.CosNotification.UnsupportedQoS e) { Throwable cause = new Throwable("The quality of service properties specified for the '" + channelName + "' channel are unsupported: " + e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } LOG_NC_ChannelCreated_OK.log(m_logger, channelName, channelId, notifyFactoryName, stopwatch.getLapTimeMillis()); return retValue; } protected boolean setChannelTimestamp(EventChannel eventChannel) { Date timestamp = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); String id = combineChannelAndDomainName(channelName, domainName) + "-" + dateFormat.format(timestamp); String kind = "NCSupport"; // TODO change it by using acscommon::NC_KIND_NCSUPPORT try { NameComponent[] t_NameChannel = { new NameComponent(id, kind) }; getNamingService().rebind(t_NameChannel, eventChannel); channelTimestamp = timestamp; return true; } catch (org.omg.CosNaming.NamingContextPackage.NotFound e) { m_logger.log(AcsLogLevel.ERROR, "Rebinding channel '" + channelName + "' in order to store the timestamp threw a NotFound exception", e); } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) { m_logger.log(AcsLogLevel.ERROR, "Rebinding channel '" + channelName + "' in order to store the timestamp threw a CannotProceed exception", e); } catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) { m_logger.log(AcsLogLevel.ERROR, "Rebinding channel '" + channelName + "' in order to store the timestamp threw a InvalidName exception", e); } return false; } /** * Returns the current channel's timestamp registered in the Naming Service. */ public Date getChannelTimestamp() { Date timestamp = new Date(0); BindingListHolder bl = new BindingListHolder(); BindingIteratorHolder bi = new BindingIteratorHolder(); String chNameAndDomain = combineChannelAndDomainName(channelName, domainName); try { // Get names of all objects bound in the naming service getNamingService().list(-1, bl, bi); // Extract the useful binding information Id and Kind for (Binding binding : bl.value) { if(binding.binding_name[0].kind.equals("NCSupport")) { // TODO change it by using acscommon::NC_KIND_NCSUPPORT if(binding.binding_name[0].id.startsWith(chNameAndDomain)) { String sts = binding.binding_name[0].id.substring(chNameAndDomain.length() + 1); DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); try { timestamp = df.parse(sts); } catch(ParseException e) { } } } } } catch(Exception e) { } return timestamp; } /** * Initialize the channel timestamp attribute by retrieving its value from the Naming Service. If after * 10 attempts the timestamp cannot be retrieved then it's set to the current time. */ public void initChannelTimestamp() { int nAttempts = 10; channelTimestamp = getChannelTimestamp(); while(channelTimestamp.getTime() == 0 && nAttempts > 0) { channelTimestamp = getChannelTimestamp(); nAttempts try { Thread.sleep(2000); } catch(InterruptedException ex1) {} } if(channelTimestamp.getTime() == 0) { channelTimestamp = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); m_logger.log(AcsLogLevel.WARNING, "Timestamp of NC '" + channelName + "' couldn't be retrieved from the Naming Service. Initialized to: " + dateFormat.format(channelTimestamp)); } } /** * Returns the last timestamp retrieved from the Naming Service */ public Date getLastRegisteredChannelTimestamp() { return channelTimestamp; } /** * Broken out from {@link #createNotificationChannel(String, String, String)} * to give tests better control about the timing when this call to the event factory is made. * @throws NameAlreadyUsed if the call to NotifyFactory#create_named_channel fails with this exception. * @throws AcsJCORBAProblemEx if the TAO extension throws a NameMapError or if the QoS attributes cause a UnsupportedAdmin. */ protected EventChannel createNotifyChannel_internal(Property[] initial_qos, Property[] initial_admin, IntHolder channelIdHolder) throws NameAlreadyUsed, UnsupportedQoS, AcsJNarrowFailedEx, AcsJCORBAProblemEx { EventChannel ret = null; StopWatch stopwatch = new StopWatch(); try { // The TAO extension of the notify factory that we use declares only the plain EventChannel type, // even though it creates the TAO-extension subtype. org.omg.CosNotifyChannelAdmin.EventChannel eventChannelBaseType = notifyFactory.create_named_channel( initial_qos, initial_admin, channelIdHolder, channelName); LOG_NC_ChannelCreatedRaw_OK.log(m_logger, channelName, channelIdHolder.value, stopwatch.getLapTimeMillis()); // re-create the client side corba stub, to get the extension subtype ret = gov.sandia.NotifyMonitoringExt.EventChannelHelper.narrow(eventChannelBaseType); } catch (BAD_PARAM ex) { LOG_NC_TaoExtensionsSubtypeMissing.log(m_logger, channelName, EventChannel.class.getName(), org.omg.CosNotifyChannelAdmin.EventChannelHelper.id()); AcsJNarrowFailedEx ex2 = new AcsJNarrowFailedEx(ex); ex2.setNarrowType(EventChannelHelper.id()); throw ex2; } catch (NameMapError ex) { String msg = "Got a TAO extension-specific NameMapError exception that means the TAO NC extension is not usable. Bailing out since we need the extension."; m_logger.log(AcsLogLevel.ERROR, msg, ex); AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(ex); ex2.setInfo(msg); throw ex2; } catch (UnsupportedAdmin ex) { AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(ex); ex2.setInfo(createUnsupportedAdminLogMessage(ex)); throw ex2; } return ret; } /** * <b>Destroys the channel and unregisters it from the naming service. ONLY * USE THIS METHOD IF YOU KNOW FOR CERTAIN THERE IS ONLY ONE SUPPLIER FOR THE * CHANNEL!!! Use this method with extreme caution as it's likely to become * deprecated in future versions of ACS!</b> * * @param channelName * name of the channel as registered int the CORBA notification * service * @param channelKind * Kind of the channel as registered with the CORBA naming service. * @param channelRef * reference to the channel being destroyed. * Here we use the plain OMG type instead of the TAO extension subtype, because the extensions are * not used for channel destruction. * @throws AcsJException * Thrown when the channel isn't registered with the Naming * Service. * @warning this method assumes */ protected void destroyNotificationChannel(String channelKind, org.omg.CosNotifyChannelAdmin.EventChannel channelRef) throws AcsJException { try { // destroy the remote CORBA object channelRef.destroy(); // unregister our channel with the naming service NameComponent[] t_NameChannel = { new NameComponent( combineChannelAndDomainName(channelName, domainName), channelKind) }; getNamingService().unbind(t_NameChannel); } catch (org.omg.CosNaming.NamingContextPackage.NotFound e) { // Think there is virtually no chance of this every happening but... String msg = "Cannot unbind the '" + channelName + "' channel from the Naming Service!"; m_logger.severe(msg); } catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) { // Think there is virtually no chance of this every happening but... Throwable cause = new Throwable(e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) { // Think there is virtually no chance of this every happening but... Throwable cause = new Throwable(e.getMessage()); throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause); } LOG_NC_ChannelDestroyed_OK.log(m_logger, channelName, ""); // TODO use notif.service name } /** * Provides access to the information about the channel contained within the * ACS CDB * * @return This class's channel properties member. */ public ChannelProperties getChannelProperties() { return m_channelProperties; } /** * Gets the notification channel factory name for the given channel/domain of this Helper class. * <p> * Details: * <ul> * <li>First tries to use the factory name cached from a previous call. * <li>NC domain ARCHIVING (ArchivingChannel) is mapped to ArchiveNotifyEventChannelFactory. * <li>NC domain LOGGING (LoggingChannel) is mapped to LoggingNotifyEventChannelFactory. * <li>If the CDB contains MACI/Channels/NotificationServiceMapping data, we try to find * a matching notify service first based on NC name, then on NC domain, then default. * <li>If no factory has been found, we use NotifyEventChannelFactory. * <li>Otherwise if the factory name found does not end in NotifyEventChannelFactory, * we append NotifyEventChannelFactory. * </ul> * @return notification channel factory name. */ public String getNotificationFactoryNameForChannel() { // try local cache if (ncFactoryName != null) { return ncFactoryName; } // factory name, with or without the "NotifyEventChannelFactory" suffix String ncFactoryNameTmp = ""; // We use hard-coded mappings for logging and archiving system NCs. // As described in ICT-494, these mappings can at the moment not be overridden by CDB mappings. // If we want to allow that, we'd have to also read the CDB mappings from the acsstartup scripts // notify service startup. Then we could move the following code after the CDB access, // to be executed only as a fallback if no CDB mapping was found for the system NCs. if (domainName != null) { if (domainName.equals(ACS_NC_DOMAIN_ARCHIVING.value)) { ncFactoryNameTmp = ARCHIVE_NOTIFICATION_FACTORY_NAME.value; } else if (domainName.equals(ACS_NC_DOMAIN_LOGGING.value)) { ncFactoryNameTmp = LOGGING_NOTIFICATION_FACTORY_NAME.value; } } // lazy initialization of CDB access DAOProxy channelsDAO = null; if (ncFactoryNameTmp.isEmpty()) { try { CDBAccess cdbAccess = new CDBAccess(m_services.getAdvancedContainerServices().getORB(), m_logger); cdbAccess.setDAL(m_services.getCDB()); channelsDAO = cdbAccess.createDAO("MACI/Channels"); } catch (Throwable th) { // keep track of when this occurs Long timeLastError = channelConfigProblemTimestamp; channelConfigProblemTimestamp = System.currentTimeMillis(); // don't log this too often (currently only once) if (timeLastError == 0l) { m_logger.log(AcsLogLevel.CONFIG, "Config issue for channel '" + channelName + "'. " + "Failed to get MACI/Channels DAO from CDB. Will use default notification service."); } } } // query CDB... if (channelsDAO != null) { // if channel mapping exists take it, wildchars are also supported try { // Note that in spite of the NC domain name being appended in the name service mappings, // we still configure simple NC names in the CDB. String[] channelNameList = channelsDAO.get_string_seq("NotificationServiceMapping/Channels_"); for (String pattern : channelNameList) { String regExpStr = WildcharMatcher.simpleWildcardToRegex(pattern); if (Pattern.matches(regExpStr, channelName)) { ncFactoryNameTmp = channelsDAO.get_string("NotificationServiceMapping/Channels_/" + pattern + "/NotificationService"); break; } } } catch (Throwable th) { m_logger.finer("No Channel to NotificationService mapping found for channel: " + channelName); } // try domain mapping, if given if (ncFactoryNameTmp.isEmpty() && domainName != null) { try { ncFactoryNameTmp = channelsDAO.get_string("NotificationServiceMapping/Domains/" + domainName + "/NotificationService"); if (m_logger.isLoggable(Level.FINEST)) { m_logger.finest("NC '" + channelName + "' of domain '" + domainName + "' mapped to NotificationService '" + ncFactoryNameTmp + "'."); } } catch (Throwable th) { if (m_logger.isLoggable(Level.FINER)) { m_logger.finer("No Domain to NotificationService mapping found for domain/channel: " + domainName + "/" + channelName); } } } // use default from CDB if (ncFactoryNameTmp.isEmpty()) { try { ncFactoryNameTmp = channelsDAO.get_string("NotificationServiceMapping/DefaultNotificationService"); } catch (Throwable th) { m_logger.finer("No NotificationServiceMapping/DefaultNotificationService attribute found, returning hardcoded default."); } } } if (!ncFactoryNameTmp.endsWith(alma.acscommon.NOTIFICATION_FACTORY_NAME.value)) { // If we found nothing in the CDB, we default to "NotifyEventChannelFactory". ncFactoryNameTmp += alma.acscommon.NOTIFICATION_FACTORY_NAME.value; } ncFactoryName = ncFactoryNameTmp; return ncFactoryName; } /** * The following returns a map where each key is the name of an event and the * value is the maximum amount of time (in floating point seconds) an event receiver has * to process the event before a warning message is logged. * * @param channelName name of the channel * @return HashMap described above */ public HashMap<String, Double> getEventHandlerTimeoutMap() { // initialize the return value HashMap<String, Double> retVal = new HashMap<String, Double>(); // data access object to traverse the ACS CDB DAO dao = null; // keys into the DAO String[] keys = null; // get the dao for the channel... // ...if this fails, just return. try { dao = m_services.getCDB().get_DAO_Servant( "MACI/Channels/" + channelName); } catch (Exception e) { m_logger.finer("No CDB entry found for '" + channelName + "' channel"); return retVal; } // names of all the events try { keys = dao.get_string_seq("Events"); } catch (Exception e) { m_logger.finer("CDB entry found for '" + channelName + "' but no Events element."); return retVal; } // sanity check on the number of events if (keys.length == 0) { m_logger.finer("No event definitions found for the '" + channelName + "' within the CDB."); return retVal; } // populate the hashmap for (int i = 0; i < keys.length; i++) { // determine the value location String timeoutLocation = "Events/" + keys[i] + "/MaxProcessTime"; // get the value (floating point seconds) try { double value = dao.get_double(timeoutLocation); retVal.put(keys[i], new Double(value)); } catch (Exception e) { e.printStackTrace(); m_logger .severe("Could not convert 'MaxProcessTime' to floating " + "point seconds for the '" + channelName + "' channel and '" + keys[i] + "' event type."); } } return retVal; } public EventChannelFactory getNotifyFactory() { return notifyFactory; } /** * Corba spec: If the implementation of the target object is not capable of supporting * any of the requested administrative property settings, the UnsupportedAdmin exception is raised. * This exception has associated with it a list of name-value pairs of which each name * identifies an administrative property whose requested setting could not be satisfied, * and each associated value the closest setting for that property that could be satisfied. * @param ex * @return a String that contains the information from UnsupportedAdmin */ public String createUnsupportedAdminLogMessage(UnsupportedAdmin ex) { StringBuilder sb = new StringBuilder(); sb.append("Caught " + ex.getMessage() + ": The administrative properties specified for the '" + channelName + "' channel are not supported: "); if (ex.admin_err != null) { for (PropertyError propertyError : ex.admin_err) { sb.append("code=" + propertyError.code).append("; "); sb.append("name=" + propertyError.name); // TODO: Figure out what type (inside the Any) the range values are and add something like the following // sb.append("available_low=" + propertyError.available_range.low_val.extract_long()); // or use alma.acs.nc.AnyAide.#corbaAnyToObject(Any) } } return sb.toString(); } public static synchronized String createRandomizedClientName(String clientName) { StringBuffer clientNameSB = new StringBuffer(); clientNameSB.append(clientName.replace("/", "_")); clientNameSB.append('-'); clientNameSB.append(String.format("%05d", random.nextInt(Integer.MAX_VALUE))); return clientNameSB.toString(); } }
package c5db.log; import c5db.C5ServerConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.READ; /** * LogPersistenceService using Files and FileChannels. */ public class LogFileService implements LogPersistenceService { private static final Logger LOG = LoggerFactory.getLogger(LogFileService.class); private final Path walDir; private final Path archiveDir; public static class FilePersistence implements BytePersistence { private final FileChannel appendChannel; private final File logFile; public FilePersistence(File logFile) throws IOException { appendChannel = FileChannel.open(logFile.toPath(), CREATE, APPEND); this.logFile = logFile; } @Override public long size() throws IOException { return appendChannel.position(); } @Override public void append(ByteBuffer[] buffers) throws IOException { appendChannel.write(buffers); } @Override public PersistenceReader getReader() throws IOException { return new NioReader(FileChannel.open(logFile.toPath(), READ)); } @Override public void truncate(long size) throws IOException { if (size > this.size()) { throw new IllegalArgumentException("Truncation may not grow the file"); } appendChannel.truncate(size); } @Override public void sync() throws IOException { appendChannel.force(true); } @Override public void close() throws IOException { appendChannel.close(); } } private static class NioReader implements PersistenceReader { private final FileChannel fileChannel; public NioReader(FileChannel fileChannel) { this.fileChannel = fileChannel; } @Override public long position() throws IOException { return fileChannel.position(); } public void position(long newPos) throws IOException { fileChannel.position(newPos); } @Override public int read(ByteBuffer dst) throws IOException { return fileChannel.read(dst); } @Override public boolean isOpen() { return fileChannel.isOpen(); } @Override public void close() throws IOException { fileChannel.close(); } } public LogFileService(Path basePath) throws IOException { this.walDir = basePath.resolve(C5ServerConstants.WAL_DIR); this.archiveDir = basePath.resolve(C5ServerConstants.ARCHIVE_DIR); createDirectoryStructure(); } @Override public BytePersistence getPersistence(String quorumId) throws IOException { File logFile = prepareNewLogFileOrFindExisting(quorumId); return new FilePersistence(logFile); } /** * Move everything in the log directory to the archive directory. * * @throws IOException */ public void moveLogsToArchive() throws IOException { for (File file : allFilesInDirectory(walDir)) { boolean success = file.renameTo(archiveDir .resolve(file.getName()) .toFile()); if (!success) { String err = "Unable to move: " + file.getAbsolutePath() + " to " + walDir; throw new IOException(err); } } } /** * Clean out old logs. * * @param timestamp Only clear logs older than timestamp. Or if 0 then remove all logs. * @throws IOException */ public void clearOldArchivedLogs(long timestamp) throws IOException { for (File file : allFilesInDirectory(archiveDir)) { if (timestamp == 0 || file.lastModified() > timestamp) { LOG.debug("Removing old log file" + file); boolean success = file.delete(); if (!success) { throw new IOException("Unable to delete file:" + file); } } } } /** * Finding an existing write-ahead log file to use for the specified quorum, or create * a new one if an old one isn't found. */ private File prepareNewLogFileOrFindExisting(String quorumId) { File logFile = findExistingLogFile(quorumId); if (logFile == null) { logFile = prepareNewLogFile(quorumId); assert logFile != null; } return logFile; } private File findExistingLogFile(String quorumId) { for (File file : allFilesInDirectory(walDir)) { if (file.getName().startsWith(logFilePrefix(quorumId))) { LOG.info("Existing WAL found {} ; using it", file); return file; } } return null; } private File prepareNewLogFile(String quorumId) { long fileNum = System.nanoTime(); return walDir.resolve(logFilePrefix(quorumId) + "-" + fileNum).toFile(); } private static String logFilePrefix(String quorumId) { return C5ServerConstants.LOG_NAME + quorumId; } private void createDirectoryStructure() throws IOException { createDirsIfNecessary(walDir); createDirsIfNecessary(archiveDir); } private static File[] allFilesInDirectory(Path dirPath) { File[] files = dirPath.toFile().listFiles(); if (files == null) { return new File[]{}; } else { return files; } } /** * Create the directory at dirPath if it does not already exist. * * @param dirPath Path to directory to create. * @throws IOException */ private static void createDirsIfNecessary(Path dirPath) throws IOException { if (!dirPath.toFile().exists()) { boolean success = dirPath.toFile().mkdirs(); if (!success) { LOG.error("Creation of path {} failed", dirPath); throw new IOException("createDirsIfNecessary"); } } } }
package org.akvo.flow.util; import java.nio.charset.StandardCharsets; import java.util.Base64; public class OneTimePadCypher { public static String encrypt(final String secretKey, final String text) { return new String(Base64.getUrlEncoder().withoutPadding().encodeToString(xor(secretKey, text.getBytes()))); } public static String decrypt(final String secretKey, final String hash) { return new String(xor(secretKey, Base64.getUrlDecoder().decode(hash.getBytes())), StandardCharsets.UTF_8); } private static byte[] xor(final String secretKey, final byte[] input) { final byte[] output = new byte[input.length]; final byte[] secret = secretKey.getBytes(); int spos = 0; for (int pos = 0; pos < input.length; ++pos) { output[pos] = (byte) (input[pos] ^ secret[spos]); spos += 1; if (spos >= secret.length) { spos = 0; } } return output; } }
package grakn.test.behaviour.connection.database; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static grakn.common.util.Collections.list; import static grakn.common.util.Collections.set; import static grakn.test.behaviour.connection.ConnectionSteps.THREAD_POOL_SIZE; import static grakn.test.behaviour.connection.ConnectionSteps.grakn; import static grakn.test.behaviour.connection.ConnectionSteps.threadPool; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class DatabaseSteps { @When("connection create keyspace: {word}") public void connection_create_database(String name) { connection_create_databases(list(name)); } @When("connection create keyspace(s):") public void connection_create_databases(List<String> names) { for (String name : names) { grakn.databases().create(name); } } @When("connection create keyspaces in parallel:") public void connection_create_databases_in_parallel(List<String> names) { assertTrue(THREAD_POOL_SIZE >= names.size()); CompletableFuture[] creations = new CompletableFuture[names.size()]; int i = 0; for (String name : names) { creations[i++] = CompletableFuture.supplyAsync(() -> grakn.databases().create(name), threadPool); } CompletableFuture.allOf(creations).join(); } @When("connection delete keyspace(s):") public void connection_delete_databases(List<String> names) { for (String databaseName : names) { grakn.databases().get(databaseName).delete(); } } @When("connection delete keyspaces in parallel:") public void connection_delete_databases_in_parallel(List<String> names) { assertTrue(THREAD_POOL_SIZE >= names.size()); CompletableFuture[] deletions = new CompletableFuture[names.size()]; int i = 0; for (String name : names) { deletions[i++] = CompletableFuture.supplyAsync( () -> { grakn.databases().get(name).delete(); return null; }, threadPool ); } CompletableFuture.allOf(deletions).join(); } @Then("connection has keyspace(s):") public void connection_has_databases(List<String> names) { assertEquals(set(names), grakn.databases().getAll().stream() .map(database -> database.name()) .collect(Collectors.toSet())); } @Then("connection does not have keyspace(s):") public void connection_does_not_have_databases(List<String> names) { for (String name : names) { assertNull(grakn.databases().get(name)); } } }
package geoLearnBot; import java.util.ArrayList; import java.util.List; public class MineralsDB { public static List<Minerals> main(String[] args) { // create an empty list to which we'll add the mineral attributes List<Minerals> mineralsList = new ArrayList<>(); // all properties of the minerals arranged as individual arrays String[] titleArray = { "Biotite", "Zeolites", "Fluorite", "Colemanite", "Augite", "Barium", "Gold", "Diamond", "Graphite", "Silver", "Beryllium", "Corundum", "Gypsum", "Chlorite", "Aragonite", "Pyrite", "Calcite", "Autunite", "Aurichalcite", "Feldspar", "Asbestos", "Garnet", "Salt/Halite", "Quartz", "Kaolinite", "Talc" }; String[] descriptionArray = { "Biotite is black magnesium/iron- based mica of low commercial value. It appears in the form of thin sheets which generally range from 0.003 mm to 0.1 mm in thickness.", "Zeolites are a group of silicate minerals with unusual properties with industrial importance.  They usually form beautiful well-formed crystals with pale colors, and are relatively soft and can be crushed and powdered. They are found in geologically young volcanic fields.  Most common zeolite minerals are analcime, chabazite, clinoptilite and mordenite. natrolite, analcime, chabazite, heulandite, phillipsite, and stilbite.  Zeolites appear in many different minerals, such as chabazite, natrolite.", "Fluorite is commercially named fluorspar composed of calcium fluoride (CaF2).  It is the principal source of fluorine. The same is used in production of hydrofluoric acid, which is used in a wide variety of industrial applications including glass etching. Fluorite tends to occur in well-formed isometric crystals, forming cubes and octahedrons. It also occurs in both massive and earthy forms, and as crusts or globular aggregates with radial fibrous texture.", "Colemanite is a hydrated calcium borate, an altered variation of borax. Over 200 minerals contain boron, but colemanite is one of only a few which is commercially important. It contains 50% B2O3. It forms at a lower pH and warmer temperature than other borates including ulexite.", "Augite is a rock-forming mineral of the pyroxene group commonly found within igneous and metamorphic rocks. Because its chemical structure is highly variable, augite might be considered by some to be its own group of minerals rather than an individual mineral. It is also known for its remarkable luster (shine off of a reflective surface).", "Barium (Ba) is obtained chiefly from the mineral barite. Barium is a soft, silvery, reactive metal. Because barium is so dense it is commonly used in some alloys, for example in spark plugs and ball bearings. As of 2013, China, India and Morocco were the world’s largest producers of barium. In the U.S, barite is mined primarily in Nevada and Georgia.", "Gold (element "Diamond is an extraordinary mineral with extreme hardness and inherent beauty that is sought for personal adornment and industrial use. Because the genesis of this unique mineral requires extreme temperature and pressure, natural diamond is so rare that some diamonds are the most valuable commodity on earth, based on weight.", "Pure graphite is a mineral form of the element carbon (element "Silver (Ag) has a bright, metallic luster, and when untarnished, has a white color. It is rarely found in its native form. Silver can be found combined with a number of different elements such as sulfur, arsenic, antimony or chlorine to form a variety of minerals and ores, such as argentite, chlorargyrite, and galena. It is also found in very small amounts in gold, lead, zinc and copper ores. Silver is malleable which means it can be hammered into thin sheets. It is also ductile, meaning it can be drawn into wire.", "Beryllium (Be) is a silver-white and very light metal. It has a very high melting point at 2349 °F (1287 °C). It is found in nature primarily as bertrandite, which is mined in Utah, or as beryl. The combination of its light weight and high melting point makes it valuable for making metal alloys which are used in electronic and electrical components, aerospace, automobiles, computers, oil and gas drilling equipment, and telecommunications.", "Corundum is a crystalline form of aluminum oxide (Al2O3) with traces of iron, titanium and chromium. It is a rock-forming mineral. It is one of the naturally transparent materials, but can have different colors when impurities are present. Transparent specimens are used as gems such as sapphires rubies.", "Gypsum is found in nature in mineral and rock form.  It is a very soft mineral and it can form very pretty, and sometimes extremely large colored crystals.  As a rock, gypsum is a sedimentary rock, typically found in thick beds or layers.  It forms in lagoons where ocean waters high in calcium and sulfate content can slowly evaporate and be regularly replenished with new sources of water.  The result is the accumulation of large beds of sedimentary gypsum.  Gypsum is commonly associated with rock salt and sulfur deposits. It is processed and used as prefabricated wallboard or as industrial or building plaster, used in cement manufacture, agriculture and other uses.", "Chlorite is the name given to a group of minerals with a similar silicate lattice. The chemical formulas of chlorites vary based on the combinations of the elements Zn, Li, Ca, Mg, Fe, Ni and Mn within.", "Aragonite is a carbonate mineral, one of the two common, naturally occurring polymorphs of calcium carbonate, CaCO3. The other polymorph is the mineral calcite. Aragonite’s crystal lattice differs from that of calcite, resulting in a different crystal shape, an orthorhombic system with acicular crystals. Repeated twinning results in pseudo-hexagonal forms.", "Commonly called fool’s gold, pyrite is the earth’s most abundant sulfide mineral. Recognized for its brass-yellow color which resembles that of gold, pyrite is a source of iron and sulfur and is used for the production of sulfuric acid.", "Calcite is the principal mineral of the rock group known as carbonates. Calcite is a major component in limestone and dolomite.", "Autunite is a radioactive orthorhombic mineral which results from the hydrothermal alteration of uranium minerals. Used as a uranium ore, it was first discovered in France in 1852.", "Aurichalcite is soft, monoclinic, copper and zinc bearing mineral. It forms a soft, scaly, greenish-blue crust in oxidized zones of copper-zinc ore deposits. It is considered to be a guide or indicator of zinc ore.", "Feldspar is the name given to a group of minerals distinguished by the presence of alumina and silica (SiO2) in their chemistry.  This group includes aluminum silicates of soda, potassium, or lime. It is the single most abundant mineral group on Earth.  They account for an estimated 60% of exposed rocks, as well as soils, clays, and other unconsolidated sediments, and are principal components in rock classification schemes. The minerals included in this group are the orthoclase, microcline and plagioclase feldspars.", "Asbestos is a commercial term that includes six regulated asbestiform silicate (silicon + oxygen) minerals. Because this group of silicate minerals can be readily separated into thin, strong fibers that are flexible, heat resistant, and chemically inert, asbestos minerals were once used in a wide variety of products. However, due to adverse health effects, the use of asbestos in the U.S. has been significantly decreased. In 2013, for example, the total amount used was only 950 tons, all of which was chrysotile, and was mined in Brazil. Many other countries still mine and use asbestos in insulation products due to less stringent health and safety regulations.", "Garnet is usually thought of as a gemstone but most garnet is mined for industrial uses. A very small number of garnets are pure and flawless enough to be cut as gemstones. The majority of garnet mining is for massive garnet that is crushed and used to make abrasives.  Garnet is a silicate mineral group; in other words, garnet’s complex chemical formula includes the silicate molecule (SiO4).  The different varieties of garnet have different metal ions, such as iron, aluminum, magnesium and chromium.  Some varieties also have calcium.", "Halite, commonly known as table salt or rock salt, is composed of sodium chloride (NaCl).  It is essential for life of humans and animals. Salt is used in food preparation across the globe.", "Quartz is one of the most common minerals in the Earth’s crust. As a mineral name, quartz refers to a specific chemical compound (silicon dioxide, or silica, SiO2), having a specific crystalline form (hexagonal). It is found is all forms of rock: igneous, metamorphic and sedimentary. Quartz is physically and chemically resistant to weathering. When quartz-bearing rocks become weathered and eroded, the grains of resistant quartz are concentrated in the soil, in rivers, and on beaches. The white sands typically found in river beds and on beaches are usually composed mainly of quartz, with some white or pink feldspar as well.", "Kaolinite is a layered silicate clay mineral which forms from the chemical weathering of feldspar or other aluminum silicate minerals. It is usually white, with occasionally a red color impurity due to iron oxide, or blue or brown from other minerals. Kaolinite has a low shrink–swell capacity and a low cation-exchange capacity, making it ideal for many industrial applications.", "The term talc refers both to the pure mineral and a wide variety of soft, talc-containing rocks that are mined and utilized for a variety of applications. Talc forms mica-like flakes. Talc is the softest mineral on the Mohs’ hardness scale at 1 and can be easily cut and crushed. Talc has perfect cleavage in one direction. This means that it breaks into thin sheets. As a result, it feels greasy to the touch (which is why talc is used as a lubricant)" }; String[] typeArray = { "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Element, Mineral", "Mineral", "Mineral", "Element, Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral", "Mineral" }; String[] mineralClassificationArray = { "Mica", "Silicate", "Halide", "Inoborates", "Pyroxene", "Sulfates", "Native", "Native element", "Native", "Native", "Silicate", "Hematite", "Sulfate", "Phyllosilicates", "Carbonate", "Sulfide", "Carbonate", "Autunite", "Carbonate", "Silicate", "Silicate", "Silicate", "Halide", "Silicate", "Phyllosilicates", "Silicate" }; String[] chemicalFormulaArray = { "K(Mg,Fe)3(AlSi3O10)(F,OH)2", "(Ca,K2,Na2)2[Al2Si4O12]2·12H2O", "CaF2", "CaB3O4(OH)3·H2O", "8[(Ca,Na)(Mg,Fe,Al,Ti)(Si,Al)2O6]", "BaSO4", "Au", "C", "C", "Ag", "Be4Si2O7(OH)2 (bertrandite), Be3Al2(SiO3)6 (beryl)", "Al2O3", "CaSO4·2H2O", "Variable", "CaCO3", "FeS2", "CaCO3", "2[Ca(UO2)2(PO4)2·10-12H2O]", "4[(Zn,Cu)5(CO3)2(OH)6]", "KAlSi3O8 – NaAlSi3O8 – CaAl2Si2O8", "Mg3(Si2O5)(OH)4 - Chrysotile; Fe7Si8O22(OH)2 – Amosite; Na2Fe2+3Fe3+2Si8O22(OH)2 – Crocidolite; Ca2Mg5Si8O22(OH)2 – Tremolite asbestos; Ca2(Mg, Fe)5(Si8O22)(OH)2 – Actinolite asbestos; (Mg, Fe)7Si8O22(OH)2 – anthophyllite asbestos", "X3Y2(SiO4)3 (Where X is often Ca or Mg, and Y is often Al or Fe)", "NaCl", "SiO2", "Al2Si2O5(OH)4", "Mg3Si4O10(OH)2" }; String[] streakArray = { "White", "white", "White", "White", "Light green to colorless", "White", "Shining yellow", "Colorless", "Black", "silver white", "White", "White", "White", "Green to gray", "White", "Black or Brown", "White", "Pale Yellow", "very light blue-green", "White", "White", "White", "White", "White", "White", "White, pearl black" }; String[] mohsHardnessArray = { "2.5-3", "4-5", "4", "4.5", "5-6", "3-3.5", "2.5-3", "10", "1–2", "2.5-3", "6 – 7 (bertrandite), 7.5–8 (beryl)", "9.0", "1.5–2", "2-2.5", "3.5-4", "6-6.5", "3", "2-2.5", "2-2.5", "6-6.5", "2.5-3", "6.5-7.5", "2-2.5", "7", "2–2.5", "1" }; String[] crystalSystemArray = { "Monoclinic", "triclinic", "Isometric", "Monoclinic", "Monoclinic", "Orthorhombic", "Isometric", "Isometric", "Hexagonal", "Isometric", "Orthorhombic (bertrandite), Hexagonal (beryl)", "Trigonal", "Monoclinic", "Monoclinic and triclinic", "Orthorhombic", "Isometric", "Hexagonal", "Tetragonal, Orthorhombic", "Monoclinic", "triclinic, monoclinic", "Monoclinic, Orthorhombic", "Isometric (meaning equality in dimension. For example, a cube, octahedron, or dodecahedron)", "Isometric", "trigonal", "Triclinic", "monoclinic, triclinic" }; String[] colorArray = { "Black", "Colourless, white, yellow, pink, red", "Colorless. Samples are often deeply colored owing to impurities", "White, clear, colorless, gray", "Black, brown, greenish, violet-brown; in thin section, colorless to gray", "Colorless, white, light shades of blue, yellow, grey, brown", "Gold", "Typically yellow, brown or gray to colorless. Less often blue, green, black, translucent white, pink, violet, orange, purple and red.", "Iron-black to steel-gray; deep blue in transmitted light", "Silver", "Colorless to pale yellow( bertrandite); green, blue, yellow, colorless, pink and others (beryl)", "Variable; colorless, yellow, red, blue, violet, golden-brown &c.", "Colorless, white", "Green, rarely red, yellow or white", "White, red, yellow, orange, green, purple, grey, blue and brown", "golden brass-yellow", "Colorless or white, but may take on other colors due to impurities", "Yellow, greenish-yellow, pale green; dark green, greenish black", "blue-green and light-blue", "pink, white, gray, brown", "gray, white, blue, green", "Generally brown, virtually all colors, blue very rare", "Colorless or white; also blue, purple, red, pink, yellow, orange, or gray", "Pure quartz is clear. Color variance due to impurities: purple (amethyst), white (milky quartz), black (smoky quartz), pink (rose quartz) and yellow or orange (citrine)", "White, sometimes red, blue or brown tints from impurities", "White, brown, gray, greenish" }; String[] lusterArray = { "Vitreous, may be pearly", "vitreous", "Vitreous", "Vitreous", "Vitreous and dull", "Vitreous, pearly", "Metallic", "Adamantine", "Metallic", "Metallic", "Vitreous, pearly (bertrandite), Vitreous, resinous (beryl)", "Adamantine, Vitreous, and/or Pearly", "Vitreous", "Vitreous, pearly, dull", "Vitreous, resinous on fracture surfaces", "Metallic", "Vitreous and also pearly along cleavage surfaces", "Sub-vitreous, resinous, waxy, pearly", "Pearly, silky", "Vitreous", "Silky", "Vitreous, resinous", "vitreous", "vitreous, waxy, dull", "Pearly to dull earthy", "Pearly" }; String[] fractureArray = { "Micaceous", "irregular/uneven", "Subconchoidal, uneven", "Conchoidal", "Ranges from splintery to uneven", "Uneven", "Jagged", "Conchoidal", "Flaky", "Jagged", "Conchoidal", "Conchoidal", "Conchoidal", "Lamellar", "Subconchoidal", "Very uneven, conchoidal", "Conchoidal", "Micaceous", "Uneven", "conchoidal, uneven", "Fibrous", "Conchoidal, uneven", "conchoidal", "conchoidal", "Irregular/uneven, conchoidal, sub-conchoidal, micaceous", "uneven" }; String[] imageArray = { "https://mineralseducationcoalition.org/wp-content/uploads/Colemanite_16620532-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Barium1_sulfate_138425783-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Autunite_173744783-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Calcite_crystalMineral_312933338-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Aragonite1_Crystals_148090799-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Kaolinite1_141265540-1-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Talc_380238223-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Gold1_90782147-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Quartz1_natural_222926188-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Beryllium_323719931-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/stock-photo-luxury-diamond-in-tweezers-closeup-with-dark-background-307889945-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Gypsum1_323719829-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Aurichalcite_364315322-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Augite_125449619-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Silver1_galena_16620550-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Chlorite_schist_299193245-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Corundum1_Rock_338930951-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Pyrite_147327494-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Salt_halite_307822916-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Graphite_56068858-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Garnet1-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Feldspar1_309985529-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Biotite-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Zeolite_136257968-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Asbestos1_Chrysotile1_297924608-150x150.jpg", "https://mineralseducationcoalition.org/wp-content/uploads/Flourite_364713614-150x150.jpg" }; // create and return a List of all minerals for (int i = 0; i < 25; i++) { String title = titleArray[i]; String description = descriptionArray[i]; String type = typeArray[i]; String mineralClassification = mineralClassificationArray[i]; String chemicalFormula = chemicalFormulaArray[i]; String streak = streakArray[i]; String mohsHardness = mohsHardnessArray[i]; String crystalSystem = crystalSystemArray[i]; String color = colorArray[i]; String luster = lusterArray[i]; String fracture = fractureArray[i]; String image = imageArray[i]; Minerals mineral = new Minerals(title, description, type, mineralClassification, chemicalFormula, streak, mohsHardness, crystalSystem, color, luster, fracture, image); mineralsList.add(mineral); } return mineralsList; } }
package de.loskutov.gitignore; import java.util.*; import java.util.regex.Pattern; public class Strings { static String stripSlashes(String pattern) { while(pattern.length() > 0 && pattern.charAt(pattern.length() - 1) == '/'){ pattern = pattern.substring(0, pattern.length() - 1); } return pattern; } static boolean hasSegments(String s){ int slash = s.indexOf('/', 1); return slash > 0 && slash != s.length() - 1; } static int count(String s, char c, boolean ignoreFirstLast){ int start = 0; int count = 0; while (true) { start = s.indexOf(c, start); if(start == -1) { break; } if(!ignoreFirstLast || (start != 0 && start != s.length())) { count ++; } start ++; } return count; } static List<String> split(String pattern){ int count = count(pattern, '/', true); if(count < 1){ throw new IllegalStateException("Pattern must have at least two segments: " + pattern); } List<String> segments = new ArrayList<String>(count); int right = 0; while (true) { int left = right; right = pattern.indexOf('/', right); if(right == -1) { if(left < pattern.length()){ segments.add(pattern.substring(left)); } break; } if(right - left > 0) { if(left == 1){ // leading slash should remain by the first pattern segments.add(pattern.substring(left - 1, right)); } else if(right == pattern.length() - 1){ // trailing slash should remain too segments.add(pattern.substring(left, right + 1)); } else { segments.add(pattern.substring(left, right)); } } right ++; } return segments; } static boolean isWildCard(String pattern) { return pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1 || pattern.indexOf('[') != -1 || pattern.indexOf(']') != -1; } // static final Pattern BRACKETS_FIX = Pattern.compile(""); static Pattern convert(String subPattern) { String pat = subPattern.replaceAll("\\.", "\\\\."); pat = pat.replaceAll("\\*", ".*"); pat = pat.replaceAll("\\?", "."); pat = pat.replaceAll("\\[!", "[^"); pat = pat.replaceAll("\\[\\[", "[\\\\["); // pat = pat.replaceAll("\\[\\]", "\\\\[]"); // BRACKETS_FIX.matcher(pat).replaceAll(replacement); return Pattern.compile(pat); } }
package dev.kkorolyov.sqlob.persistence; import static org.mockito.Mockito.*; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.sql.DataSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import dev.kkorolyov.sqlob.Stub.BasicStub; import dev.kkorolyov.sqlob.stub.NoOpDataSource; public class SessionTest { private static final int NUM_STUBS = 10; private static final Class<?> stubClass = BasicStub.class; private static final Iterable<Object> stubs = Stream.generate(BasicStub::random) .limit(NUM_STUBS) .collect(Collectors.toList()); private static final Condition condition = new Condition("short", "=", 4); private Connection conn; private DataSource ds; private Session session; @BeforeEach void beforeEach() { conn = mock(Connection.class); ds = new NoOpDataSource() { @Override public Connection getConnection() throws SQLException { return conn; } }; session = new Session(ds); } @TestFactory Iterable<DynamicTest> noCommitOnGetId() throws SQLException { return generateTests(session -> { for (Object stub : stubs) session.getId(stub); verify(conn, never()).commit(); }, new Session(ds, 0), new Session(ds, 1)); } @TestFactory Iterable<DynamicTest> noCommitOnGet() throws SQLException { return generateTests(session -> { for (int i = 0; i < NUM_STUBS; i++) session.get(stubClass, UUID.randomUUID()); verify(conn, never()).commit(); }, new Session(ds, 0), new Session(ds, 1)); } @TestFactory Iterable<DynamicTest> noCommitOnGetByCondition() throws SQLException { return generateTests(session -> { for (int i = 0; i < NUM_STUBS; i++) session.get(stubClass, condition); verify(conn, never()).commit(); }, new Session(ds, 0), new Session(ds, 1)); } @Test void commitEveryWhenBuffer0() throws SQLException { session = new Session(ds, 0); for (Object stub : stubs) session.put(stub); verify(conn, never()).commit(); } @Test void commitEveryWhenBuffer1() { session = new Session(ds, 1); } @Test void commitAfterBufferFills() { } private static Iterable<DynamicTest> generateTests(SessionConsumer test, Session... sessions) { List<DynamicTest> tests = new ArrayList<>(); for (Session session : sessions) { tests.add(DynamicTest.dynamicTest(session.toString(), () -> test.accept(session))); } return tests; } private static interface SessionConsumer { void accept(Session session) throws SQLException; } }
package algorithms.rotationalplanesweep; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.awt.Color; import draw.GridLineSet; import draw.GridPointSet; import algorithms.datatypes.SnapshotItem; import grid.GridGraph; public class RPSScanner { public static ArrayList<List<SnapshotItem>> snapshotList = new ArrayList<>(); private final void saveSnapshot(int sx, int sy, Vertex v) { ArrayList<SnapshotItem> snapshot = new ArrayList<>(); snapshot.add(SnapshotItem.generate(new Integer[]{sx, sy, v.x, v.y}, Color.RED)); // Snapshot current state of heap int heapSize = edgeHeap.size(); Edge[] edges = edgeHeap.getEdgeList(); for (int k=0; k<heapSize; ++k) { Color colour = (k == 0) ? Color.CYAN : Color.GREEN; Edge e = edges[k]; snapshot.add(SnapshotItem.generate(new Integer[]{e.u.x, e.u.y, e.v.x, e.v.y}, colour)); } snapshotList.add(new ArrayList<SnapshotItem>(snapshot)); } public static final void clearSnapshots() { snapshotList.clear(); } public int nSuccessors; public int[] successorsX; public int[] successorsY; private final Vertex[] vertices; private final RPSEdgeHeap edgeHeap; private final GridGraph graph; public static class Vertex { public int x; public int y; public double angle; public Edge edge1; public Edge edge2; public Vertex(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + ", " + y; } } public static class Edge { public Vertex u; public Vertex v; public Vertex originalU; public int heapIndex; public double distance; public Edge(RPSScanner.Vertex u, RPSScanner.Vertex v) { this.u = u; this.v = v; } @Override public String toString() { return u.x + ", " + u.y + ", " + v.x + ", " + v.y; } } public RPSScanner(Vertex[] vertices, Edge[] edges, GridGraph graph) { successorsX = new int[11]; successorsY = new int[11]; nSuccessors = 0; this.vertices = vertices; this.edgeHeap = new RPSEdgeHeap(edges); this.graph = graph; } private final void clearNeighbours() { nSuccessors = 0; } private final void addNeighbour(int x, int y) { if (nSuccessors >= successorsX.length) { successorsX = Arrays.copyOf(successorsX, successorsX.length*2); successorsY = Arrays.copyOf(successorsY, successorsY.length*2); } successorsX[nSuccessors] = x; successorsY[nSuccessors] = y; ++nSuccessors; } private final double getAngle(int sx, int sy, Vertex v) { if (v.x == sx && v.y == sy) return -1; double angle = Math.atan2(v.y-sy, v.x-sx); if (angle < 0) angle += 2*Math.PI; return angle; } private class VertexShortcutter { private Vertex s; private Edge edge1; private Edge edge2; private Vertex end1; private Vertex end2; private boolean end2FirstEdge; public VertexShortcutter(Vertex s) { this.s = s; edge1 = s.edge1; edge2 = s.edge2; if (edge1.u == s) end1 = edge1.v; else end1 = edge1.u; if (edge2.u == s) end2 = edge2.v; else end2 = edge2.u; end2FirstEdge = (end2.edge1 == edge2); } public void shortcut() { // Removal edge1.u = end1; edge1.v = end2; if (end2FirstEdge) end2.edge1 = edge1; else end2.edge2 = edge1; } public void restore() { // Restore edge1.u = s; edge1.v = end1; if (end2FirstEdge) end2.edge1 = edge2; else end2.edge2 = edge2; } } private final void initialiseScan(int sx, int sy, ArrayList<VertexShortcutter> shortcutters) { // Compute angles, apply shortcutting to cut (sx, sy). // The shortcutters arraylist has size at most 2. for (int i=0; i<vertices.length; ++i) { Vertex v = vertices[i]; if (v.x != sx || v.y != sy) { v.angle = Math.atan2(v.y-sy, v.x-sx); if (v.angle < 0) v.angle += 2*Math.PI; } else { v.angle = -1; VertexShortcutter shortcutter = new VertexShortcutter(v); shortcutter.shortcut(); shortcutters.add(shortcutter); } } sortVertices(sx, sy); edgeHeap.clear(); Edge[] edges = edgeHeap.getEdgeList(); reorderEdgeEndpoints(sx, sy, edges); // Note: iterating through the edges like this is a very dangerous operation. // That's because the edges array changes as you insert the edges into the heap. // Reason why it works: When we swap two edges when inserting, both edges have already been checked. // That's because we only swap with edges in the heap, which have a lower index than i. for (int i=0; i<edges.length; ++i) { Edge edge = edges[i]; if (intersectsPositiveXAxis(sx, sy, edge)) { edgeHeap.insert(edge, computeDistance(sx, sy, edge)); } } } private final void restoreShortcuttedVertices(ArrayList<VertexShortcutter> shortcutters) { // Restore shortcutted vertices for (VertexShortcutter shortcutter : shortcutters) { shortcutter.restore(); } } public final void computeAllVisibleSuccessors(int sx, int sy) { clearNeighbours(); if (vertices.length == 0) return; // This arraylist has size at most 2. ArrayList<VertexShortcutter> shortcutters = new ArrayList<>(); initialiseScan(sx, sy, shortcutters); // This queue is used to enforce the order: // INSERT TO EDGEHEAP -> ADD AS NEIGHBOUR -> DELETE FROM EDGEHEAP // for all vertices with the same angle from (sx,sy). Vertex[] vertexQueue = new Vertex[11]; int vertexQueueSize = 0; int i = 0; // Skip vertex if it is (sx,sy). while (vertices[i].x == sx && vertices[i].y == sy) ++i; for (; i<vertices.length; ++i) { if (vertexQueueSize >= vertexQueue.length) { vertexQueue = Arrays.copyOf(vertexQueue, vertexQueue.length*2); } vertexQueue[vertexQueueSize++] = vertices[i]; if (i+1 == vertices.length || !isSameAngle(sx, sy, vertices[i], vertices[i+1])) { // Clear queue // Insert all first for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (isStartOrOriginEdge(sx, sy, v, v.edge1)) { edgeHeap.insert(v.edge1, computeDistance(sx, sy, v.edge1)); } if (isStartOrOriginEdge(sx, sy, v, v.edge2)) { edgeHeap.insert(v.edge2, computeDistance(sx, sy, v.edge2)); } } // Add all for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; //saveSnapshot(sx, sy, v); // UNCOMMENT FOR TRACING Edge edge = edgeHeap.getMin(); if (!linesIntersect(sx, sy, v.x, v.y, edge.u.x, edge.u.y, edge.v.x, edge.v.y)) { addNeighbour(v.x, v.y); } } // Delete all for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (!isStartOrOriginEdge(sx, sy, v, v.edge1)) { edgeHeap.delete(v.edge1); } if (!isStartOrOriginEdge(sx, sy, v, v.edge2)) { edgeHeap.delete(v.edge2); } } // Clear queue vertexQueueSize = 0; } } restoreShortcuttedVertices(shortcutters); } public final void computeAllVisibleTautSuccessors(int sx, int sy) { clearNeighbours(); if (vertices.length == 0) return; // This arraylist has size at most 2. ArrayList<VertexShortcutter> shortcutters = new ArrayList<>(); initialiseScan(sx, sy, shortcutters); // This queue is used to enforce the order: // INSERT TO EDGEHEAP -> ADD AS NEIGHBOUR -> DELETE FROM EDGEHEAP // for all vertices with the same angle from (sx,sy). Vertex[] vertexQueue = new Vertex[11]; int vertexQueueSize = 0; int i = 0; // Skip vertex if it is (sx,sy). while (vertices[i].x == sx && vertices[i].y == sy) ++i; for (; i<vertices.length; ++i) { if (vertexQueueSize >= vertexQueue.length) { vertexQueue = Arrays.copyOf(vertexQueue, vertexQueue.length*2); } vertexQueue[vertexQueueSize++] = vertices[i]; if (i+1 == vertices.length || !isSameAngle(sx, sy, vertices[i], vertices[i+1])) { // Clear queue // Insert all first for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (isStartOrOriginEdge(sx, sy, v, v.edge1)) { edgeHeap.insert(v.edge1, computeDistance(sx, sy, v.edge1)); } if (isStartOrOriginEdge(sx, sy, v, v.edge2)) { edgeHeap.insert(v.edge2, computeDistance(sx, sy, v.edge2)); } } // Add all for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (!isTautSuccessor(sx, sy, v.x, v.y)) continue; //saveSnapshot(sx, sy, v); // UNCOMMENT FOR TRACING Edge edge = edgeHeap.getMin(); if (!linesIntersect(sx, sy, v.x, v.y, edge.u.x, edge.u.y, edge.v.x, edge.v.y)) { addNeighbour(v.x, v.y); } } // Delete all for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (!isStartOrOriginEdge(sx, sy, v, v.edge1)) { edgeHeap.delete(v.edge1); } if (!isStartOrOriginEdge(sx, sy, v, v.edge2)) { edgeHeap.delete(v.edge2); } } // Clear queue vertexQueueSize = 0; } } restoreShortcuttedVertices(shortcutters); } public final void computeAllVisibleTwoWayTautSuccessors(int sx, int sy) { clearNeighbours(); if (vertices.length == 0) return; // This arraylist has size at most 2. ArrayList<VertexShortcutter> shortcutters = new ArrayList<>(); initialiseScan(sx, sy, shortcutters); // We exclude the non-taut region (excludeStart, excludeEnd) double EPSILON = 0.00000001; double excludeStart = 99999; double excludeEnd = 99998; // Setting the interval (excludeStart, excludeEnd) if (graph.bottomLeftOfBlockedTile(sx, sy)) { if (!graph.topRightOfBlockedTile(sx, sy)) { excludeStart = Math.PI + EPSILON; excludeEnd = 3*Math.PI/2 - EPSILON; } } else if (graph.bottomRightOfBlockedTile(sx, sy)) { if (!graph.topLeftOfBlockedTile(sx, sy)) { excludeStart = 3*Math.PI/2 + EPSILON; excludeEnd = 2*Math.PI - EPSILON; } } else if (graph.topRightOfBlockedTile(sx, sy)) { excludeStart = 0 + EPSILON; excludeEnd = Math.PI/2 - EPSILON; } else if (graph.topLeftOfBlockedTile(sx, sy)) { excludeStart = Math.PI/2 + EPSILON; excludeEnd = Math.PI - EPSILON; } // This queue is used to enforce the order: // INSERT TO EDGEHEAP -> ADD AS NEIGHBOUR -> DELETE FROM EDGEHEAP // for all vertices with the same angle from (sx,sy). Vertex[] vertexQueue = new Vertex[11]; int vertexQueueSize = 0; int i = 0; // Skip vertex if it is (sx,sy). while (vertices[i].x == sx && vertices[i].y == sy) ++i; for (; i<vertices.length; ++i) { if (vertexQueueSize >= vertexQueue.length) { vertexQueue = Arrays.copyOf(vertexQueue, vertexQueue.length*2); } vertexQueue[vertexQueueSize++] = vertices[i]; double currentAngle = vertices[i].angle; if (i+1 == vertices.length || !isSameAngle(sx, sy, vertices[i], vertices[i+1])) { // Clear queue // Insert all first for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (isStartOrOriginEdge(sx, sy, v, v.edge1)) { edgeHeap.insert(v.edge1, computeDistance(sx, sy, v.edge1)); } if (isStartOrOriginEdge(sx, sy, v, v.edge2)) { edgeHeap.insert(v.edge2, computeDistance(sx, sy, v.edge2)); } } // Add all (if it doesn't fall within the interval (excludeStart, excludeEnd) ) if (currentAngle <= excludeStart || excludeEnd <= currentAngle) { for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (!isTautSuccessor(sx, sy, v.x, v.y)) continue; //saveSnapshot(sx, sy, v); // UNCOMMENT FOR TRACING Edge edge = edgeHeap.getMin(); if (!linesIntersect(sx, sy, v.x, v.y, edge.u.x, edge.u.y, edge.v.x, edge.v.y)) { addNeighbour(v.x, v.y); } } } // Delete all for (int j=0; j<vertexQueueSize; ++j) { Vertex v = vertexQueue[j]; if (!isStartOrOriginEdge(sx, sy, v, v.edge1)) { edgeHeap.delete(v.edge1); } if (!isStartOrOriginEdge(sx, sy, v, v.edge2)) { edgeHeap.delete(v.edge2); } } // Clear queue vertexQueueSize = 0; } } restoreShortcuttedVertices(shortcutters); } // Assumptions: // 1. (sx, sy) != (nx, ny) // 2. (sx, sy) has line of sight to (nx, ny) // 3. (nx, ny) is an outer corner tile. private final boolean isTautSuccessor(int sx, int sy, int nx, int ny) { int dx = nx - sx; int dy = ny - sy; if (dx == 0 || dy == 0) return graph.isOuterCorner(nx, ny); if (dx > 0) { if (dy > 0) { return !graph.bottomLeftOfBlockedTile(nx, ny); } else { // (dy < 0) return !graph.topLeftOfBlockedTile(nx, ny); } } else { // (dx < 0) if (dy > 0) { return !graph.bottomRightOfBlockedTile(nx, ny); } else { // (dy < 0) return !graph.topRightOfBlockedTile(nx, ny); } } } private final void sortVertices(int sx, int sy) { Arrays.sort(vertices, (a,b) -> Double.compare(a.angle, b.angle)); } private final boolean isSameAngle(int sx, int sy, Vertex u, Vertex v) { int dx1 = u.x - sx; int dy1 = u.y - sy; int dx2 = v.x - sx; int dy2 = v.y - sy; return dx1*dx2 + dy1*dy2 > 0 && dx1*dy2 == dx2*dy1; } private final void reorderEdgeEndpoints(int sx, int sy, Edge[] edges) { // Reorders the endpoints of each edge so that v is anticlockwise from u. for (int i=0; i<edges.length; ++i) { if (isEdgeOrderReversed(sx, sy, edges[i])) { Vertex temp = edges[i].u; edges[i].u = edges[i].v; edges[i].v = temp; } } } private final boolean isEdgeOrderReversed(int sx, int sy, Edge edge) { // Note: No need special case with vertex shortcutting. // Special case: if an endpoint is (sx,sy), then instantly u is (sx,sy) int dx1 = edge.u.x - sx; int dy1 = edge.u.y - sy; int dx2 = edge.v.x - sx; int dy2 = edge.v.y - sy; int crossProd = dx1*dy2 - dx2*dy1; if (dx1*dx2 + dy1*dy2 < 0 && crossProd == 0) { // (sx, sy) is on the edge (but not at the endpoints) // Revert to canonical ordering. return edge.u == edge.originalU; } return crossProd < 0; } private final boolean isStartOrOriginEdge(int sx, int sy, Vertex v, Edge e) { return v == e.u || (e.u.x == sx && e.u.y == sy); } private final double computeDistance(int sx, int sy, Edge edge) { // a = v - u // b = s - u int ax = edge.v.x - edge.u.x; int ay = edge.v.y - edge.u.y; int bx = sx - edge.u.x; int by = sy - edge.u.y; int aDotb = ax*bx + ay*by; int aDota = ax*ax + ay*ay; if (0 <= aDotb && aDotb <= aDota) { // use perpendicular distance. double perpX = bx - (double)(ax * aDotb)/aDota; double perpY = by - (double)(ay * aDotb)/aDota; return perpX*perpX + perpY*perpY; } else { // use distance to closer point. int cx = sx - edge.v.x; int cy = sy - edge.v.y; return Math.min(bx*bx + by*by, cx*cx + cy*cy); } } private final boolean intersectsPositiveXAxis(int sx, int sy, Edge e) { return !(e.u.x == sx && e.u.y == sy) && !(e.v.x == sx && e.v.y == sy) && e.u.angle >= Math.PI && e.v.angle < Math.PI; } private final boolean linesIntersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { int line1dx = x2 - x1; int line1dy = y2 - y1; int cross1 = (x3-x1)*line1dy - (y3-y1)*line1dx; int cross2 = (x4-x1)*line1dy - (y4-y1)*line1dx; int line2dx = x4 - x3; int line2dy = y4 - y3; int cross3 = (x1-x3)*line2dy - (y1-y3)*line2dx; int cross4 = (x2-x3)*line2dy - (y2-y3)*line2dx; if (cross1 != 0 && cross2 != 0 && cross3 != 0 && cross4 != 0) { return ((cross1 > 0) != (cross2 > 0)) && ((cross3 > 0) != (cross4 > 0)); } // There exists a cross product that is 0. One of the degenerate cases. // Not possible: (x1 == x3 && y1 == y3) or (x1 == x4 && y1 == y4) if (x2 == x3 && y2 == y3) { int dx1 = x1-x2; int dy1 = y1-y2; int dx2 = x4-x2; int dy2 = y4-y2; int dx3 = x1-x4; int dy3 = y1-y4; return (dx1*dx2 + dy1*dy2 > 0) && (dx1*dx3 + dy1*dy3 > 0) && (dx1*dy2 == dx2*dy1); } else if (x2 == x4 && y2 == y4) { int dx1 = x1-x2; int dy1 = y1-y2; int dx2 = x3-x2; int dy2 = y3-y2; int dx3 = x1-x3; int dy3 = y1-y3; return (dx1*dx2 + dy1*dy2 > 0) && (dx1*dx3 + dy1*dy3 > 0) && (dx1*dy2 == dx2*dy1); } else { // No equalities whatsoever. // We consider this case an intersection if they intersect. int prod1 = cross1*cross2; int prod2 = cross3*cross4; if (prod1 == 0 && prod2 == 0) { // All four points collinear. int minX1; int minY1; int maxX1; int maxY1; int minX2; int minY2; int maxX2; int maxY2; if (x1 < x2) {minX1 = x1; maxX1 = x2;} else {minX1 = x2; maxX1 = x1;} if (y1 < y2) {minY1 = y1; maxY1 = y2;} else {minY1 = y2; maxY1 = y1;} if (x3 < x4) {minX2 = x3; maxX2 = x4;} else {minX2 = x4; maxX2 = x3;} if (y3 < y4) {minY2 = y3; maxY2 = y4;} else {minY2 = y4; maxY2 = y3;} return !(maxX1 < minX2 || maxY1 < minY2 || maxX2 < minX1 || maxY2 < minY1); } return (prod1 <= 0 && prod2 <= 0); } } public void drawLines(GridLineSet gridLineSet, GridPointSet gridPointSet) { for (int i=0; i<vertices.length; ++i) { Vertex v = vertices[i]; gridPointSet.addPoint(v.x, v.y, Color.YELLOW); } Edge[] edges = edgeHeap.getEdgeList(); for (int i=0; i<edges.length; ++i) { Edge e = edges[i]; gridLineSet.addLine(e.u.x, e.u.y, e.v.x, e.v.y, Color.RED); } } public void snapshotHeap(GridLineSet gridLineSet) { Edge[] edges = edgeHeap.getEdgeList(); for (int i=0; i<edgeHeap.size(); ++i) { Color colour = (i == 0) ? Color.ORANGE : Color.RED; Edge e = edges[i]; gridLineSet.addLine(e.u.x, e.u.y, e.v.x, e.v.y, colour); } } }
package com.dooble.phonertc; import java.util.LinkedList; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.graphics.Point; import android.webkit.WebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.webrtc.DataChannel; import org.webrtc.IceCandidate; import org.webrtc.MediaConstraints; import org.webrtc.MediaStream; import org.webrtc.PeerConnection; import org.webrtc.PeerConnectionFactory; import org.webrtc.SdpObserver; import org.webrtc.SessionDescription; import org.webrtc.PeerConnection.IceConnectionState; import org.webrtc.PeerConnection.IceGatheringState; import org.webrtc.VideoCapturer; import org.webrtc.VideoRenderer; import org.webrtc.VideoRenderer.I420Frame; import org.webrtc.VideoSource; import org.webrtc.VideoTrack; import android.media.AudioManager; import android.util.Log; public class PhoneRTCPlugin extends CordovaPlugin { public static final String ACTION_CALL = "call"; public static final String ACTION_RECEIVE_MESSAGE = "receiveMessage"; public static final String ACTION_DISCONNECT = "disconnect"; public static final String ACTION_UPDATE_VIDEO_POSITION = "updateVideoPosition"; CallbackContext _callbackContext; private final SDPObserver sdpObserver = new SDPObserver(); private final PCObserver pcObserver = new PCObserver(); private boolean isInitiator; private PeerConnectionFactory factory; private PeerConnection pc; private MediaConstraints sdpMediaConstraints; private LinkedList<IceCandidate> queuedRemoteCandidates ; // Synchronize on quit[0] to avoid teardown-related crashes. private final Boolean[] quit = new Boolean[] { false }; private VideoSource videoSource; private VideoStreamsView localVideoView; private VideoStreamsView remoteVideoView; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals(ACTION_CALL)) { isInitiator = args.getBoolean(0); final String turnServerHost = args.getString(1); final String turnUsername = args.getString(2); final String turnPassword = args.getString(3); final JSONObject video = (!args.isNull(4)) ? args.getJSONObject(4) : null; _callbackContext = callbackContext; queuedRemoteCandidates = new LinkedList<IceCandidate>(); quit[0] = false; cordova.getThreadPool().execute(new Runnable() { public void run() { PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); AudioManager audioManager = ((AudioManager) cordova.getActivity().getSystemService(cordova.getActivity().AUDIO_SERVICE)); @SuppressWarnings("deprecation") boolean isWiredHeadsetOn = audioManager.isWiredHeadsetOn(); audioManager.setMode(isWiredHeadsetOn ? AudioManager.MODE_IN_CALL : AudioManager.MODE_IN_COMMUNICATION); audioManager.setSpeakerphoneOn(!isWiredHeadsetOn); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0); abortUnless(PeerConnectionFactory.initializeAndroidGlobals(cordova.getActivity()), "Failed to initializeAndroidGlobals"); final LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<PeerConnection.IceServer>(); iceServers.add(new PeerConnection.IceServer( "stun:stun.l.google.com:19302")); iceServers.add(new PeerConnection.IceServer( turnServerHost, turnUsername, turnPassword)); sdpMediaConstraints = new MediaConstraints(); sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair( "OfferToReceiveAudio", "true")); sdpMediaConstraints.mandatory.add(new MediaConstraints.KeyValuePair( "OfferToReceiveVideo", "true")); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { factory = new PeerConnectionFactory(); MediaConstraints pcMediaConstraints = new MediaConstraints(); pcMediaConstraints.optional.add(new MediaConstraints.KeyValuePair( "DtlsSrtpKeyAgreement", "true")); pc = factory.createPeerConnection(iceServers, pcMediaConstraints, pcObserver); MediaStream lMS = factory.createLocalMediaStream("ARDAMS"); if (video != null) { try { localVideoView = createVideoView(video.getJSONObject("localVideo")); remoteVideoView = createVideoView(video.getJSONObject("remoteVideo")); VideoCapturer capturer = getVideoCapturer(); videoSource = factory.createVideoSource(capturer, new MediaConstraints()); VideoTrack videoTrack = factory.createVideoTrack("ARDAMSv0", videoSource); videoTrack.addRenderer(new VideoRenderer(new VideoCallbacks( localVideoView, VideoStreamsView.Endpoint.REMOTE))); lMS.addTrack(videoTrack); } catch (JSONException e) { Log.e("com.dooble.phonertc", "A JSON exception has occured while trying to add video.", e); } } lMS.addTrack(factory.createAudioTrack("ARDAMSa0")); pc.addStream(lMS, new MediaConstraints()); if (isInitiator) { pc.createOffer(sdpObserver, sdpMediaConstraints); } } }); } }); return true; } else if (action.equals(ACTION_RECEIVE_MESSAGE)) { final String message = args.getString(0); cordova.getThreadPool().execute(new Runnable() { public void run() { try { JSONObject json = new JSONObject(message); String type = (String) json.get("type"); if (type.equals("candidate")) { final IceCandidate candidate = new IceCandidate( (String) json.get("id"), json.getInt("label"), (String) json.get("candidate")); if (queuedRemoteCandidates != null) { queuedRemoteCandidates.add(candidate); } else { cordova.getActivity().runOnUiThread(new Runnable() { public void run() { pc.addIceCandidate(candidate); } }); } } else if (type.equals("answer") || type.equals("offer")) { final SessionDescription sdp = new SessionDescription( SessionDescription.Type.fromCanonicalForm(type), preferISAC((String) json.get("sdp"))); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { pc.setRemoteDescription(sdpObserver, sdp); } }); } else if (type.equals("bye")) { Log.d("com.dooble.phonertc", "Remote end hung up; dropping PeerConnection"); cordova.getActivity().runOnUiThread(new Runnable() { public void run() { disconnect(); } }); } else { //throw new RuntimeException("Unexpected message: " + message); } } catch (JSONException e) { throw new RuntimeException(e); } } }); return true; } else if (action.equals(ACTION_DISCONNECT)) { Log.e("com.dooble.phonertc", "DISCONNECT"); disconnect(); } callbackContext.error("Invalid action"); return false; } VideoStreamsView createVideoView(JSONObject config) throws JSONException { WebView.LayoutParams params = new WebView.LayoutParams(config.getInt("width") * 2, config.getInt("height") * 2, config.getInt("x"), config.getInt("y")); Point displaySize = new Point(config.getInt("width") * 2, config.getInt("height") * 2); VideoStreamsView view = new VideoStreamsView(cordova.getActivity(), displaySize); webView.addView(view, params); return view; } void sendMessage(JSONObject data) { PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); _callbackContext.sendPluginResult(result); } private String preferISAC(String sdpDescription) { String[] lines = sdpDescription.split("\n"); int mLineIndex = -1; String isac16kRtpMap = null; Pattern isac16kPattern = Pattern .compile("^a=rtpmap:(\\d+) ISAC/16000[\r]?$"); for (int i = 0; (i < lines.length) && (mLineIndex == -1 || isac16kRtpMap == null); ++i) { if (lines[i].startsWith("m=audio ")) { mLineIndex = i; continue; } Matcher isac16kMatcher = isac16kPattern.matcher(lines[i]); if (isac16kMatcher.matches()) { isac16kRtpMap = isac16kMatcher.group(1); continue; } } if (mLineIndex == -1) { Log.d("com.dooble.phonertc", "No m=audio line, so can't prefer iSAC"); return sdpDescription; } if (isac16kRtpMap == null) { Log.d("com.dooble.phonertc", "No ISAC/16000 line, so can't prefer iSAC"); return sdpDescription; } String[] origMLineParts = lines[mLineIndex].split(" "); StringBuilder newMLine = new StringBuilder(); int origPartIndex = 0; // Format is: m=<media> <port> <proto> <fmt> ... newMLine.append(origMLineParts[origPartIndex++]).append(" "); newMLine.append(origMLineParts[origPartIndex++]).append(" "); newMLine.append(origMLineParts[origPartIndex++]).append(" "); newMLine.append(isac16kRtpMap).append(" "); for (; origPartIndex < origMLineParts.length; ++origPartIndex) { if (!origMLineParts[origPartIndex].equals(isac16kRtpMap)) { newMLine.append(origMLineParts[origPartIndex]).append(" "); } } lines[mLineIndex] = newMLine.toString(); StringBuilder newSdpDescription = new StringBuilder(); for (String line : lines) { newSdpDescription.append(line).append("\n"); } return newSdpDescription.toString(); } private static void abortUnless(boolean condition, String msg) { if (!condition) { throw new RuntimeException(msg); } } // Cycle through likely device names for the camera and return the first // capturer that works, or crash if none do. private VideoCapturer getVideoCapturer() { String[] cameraFacing = { "front", "back" }; int[] cameraIndex = { 0, 1 }; int[] cameraOrientation = { 0, 90, 180, 270 }; for (String facing : cameraFacing) { for (int index : cameraIndex) { for (int orientation : cameraOrientation) { String name = "Camera " + index + ", Facing " + facing + ", Orientation " + orientation; VideoCapturer capturer = VideoCapturer.create(name); if (capturer != null) { // logAndToast("Using camera: " + name); return capturer; } } } } throw new RuntimeException("Failed to open capturer"); } private class PCObserver implements PeerConnection.Observer { @Override public void onIceCandidate(final IceCandidate iceCandidate) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { try { JSONObject json = new JSONObject(); json.put("type", "candidate"); json.put("label", iceCandidate.sdpMLineIndex); json.put("id", iceCandidate.sdpMid); json.put("candidate", iceCandidate.sdp); sendMessage(json); } catch (JSONException e) { // TODO Auto-generated catch bloc e.printStackTrace(); } } }); } @Override public void onAddStream(final MediaStream stream) { // TODO Auto-generated method stub PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { stream.videoTracks.get(0).addRenderer(new VideoRenderer( new VideoCallbacks(remoteVideoView, VideoStreamsView.Endpoint.REMOTE))); try { JSONObject data = new JSONObject(); data.put("type", "__answered"); sendMessage(data); } catch (JSONException e) { } } }); } @Override public void onDataChannel(DataChannel stream) { // TODO Auto-generated method stub } @Override public void onError() { // TODO Auto-generated method stub } @Override public void onIceConnectionChange(IceConnectionState arg0) { // TODO Auto-generated method stub } @Override public void onIceGatheringChange(IceGatheringState arg0) { // TODO Auto-generated method stub } @Override public void onRemoveStream(MediaStream arg0) { // TODO Auto-generated method stub } @Override public void onRenegotiationNeeded() { // TODO Auto-generated method stub } @Override public void onSignalingChange( PeerConnection.SignalingState signalingState) { } } private class SDPObserver implements SdpObserver { @Override public void onCreateSuccess(final SessionDescription origSdp) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { SessionDescription sdp = new SessionDescription( origSdp.type, preferISAC(origSdp.description)); try { JSONObject json = new JSONObject(); json.put("type", sdp.type.canonicalForm()); json.put("sdp", sdp.description); sendMessage(json); pc.setLocalDescription(sdpObserver, sdp); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } @Override public void onSetSuccess() { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { if (isInitiator) { if (pc.getRemoteDescription() != null) { // We've set our local offer and received & set the // remote // answer, so drain candidates. drainRemoteCandidates(); } } else { if (pc.getLocalDescription() == null) { // We just set the remote offer, time to create our // answer. pc.createAnswer(SDPObserver.this, sdpMediaConstraints); } else { // Sent our answer and set it as local description; // drain // candidates. drainRemoteCandidates(); } } } }); } @Override public void onCreateFailure(final String error) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { throw new RuntimeException("createSDP error: " + error); } }); } @Override public void onSetFailure(final String error) { PhoneRTCPlugin.this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { //throw new RuntimeException("setSDP error: " + error); } }); } private void drainRemoteCandidates() { if (queuedRemoteCandidates == null) return; for (IceCandidate candidate : queuedRemoteCandidates) { pc.addIceCandidate(candidate); } queuedRemoteCandidates = null; } } private void disconnect() { synchronized (quit[0]) { if (quit[0]) { return; } quit[0] = true; if (pc != null) { pc.dispose(); pc = null; } try { JSONObject json = new JSONObject(); json.put("type", "bye"); sendMessage(json); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (factory != null) { factory.dispose(); factory = null; } } try { JSONObject data = new JSONObject(); data.put("type", "__disconnected"); sendMessage(data); } catch (JSONException e) { } } // Implementation detail: bridge the VideoRenderer.Callbacks interface to the // VideoStreamsView implementation. private class VideoCallbacks implements VideoRenderer.Callbacks { private final VideoStreamsView view; private final VideoStreamsView.Endpoint stream; public VideoCallbacks( VideoStreamsView view, VideoStreamsView.Endpoint stream) { this.view = view; this.stream = stream; Log.d("CordovaLog", "VideoCallbacks"); } @Override public void setSize(final int width, final int height) { Log.d("setSize", width + " " + height); view.queueEvent(new Runnable() { public void run() { view.setSize(stream, width, height); } }); } @Override public void renderFrame(I420Frame frame) { view.queueFrame(stream, frame); } } }
package org.opencms.xml.page; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.types.CmsResourceTypeXmlPage; import org.opencms.i18n.CmsEncoder; import org.opencms.main.I_CmsConstants; import org.opencms.report.CmsShellReport; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import org.opencms.util.CmsFileUtil; import org.opencms.workplace.tools.content.CmsElementRename; import org.opencms.xml.CmsXmlEntityResolver; import java.util.ArrayList; import java.util.List; import java.util.Locale; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestSuite; /** * Tests for the XML page that require a running OpenCms system.<p> * * @author Alexander Kandzior (a.kandzior@alkacon.com) * * @version $Revision: 1.13 $ * * @since 5.5.0 */ public class TestCmsXmlPageInSystem extends OpenCmsTestCase { private static final String UTF8 = CmsEncoder.C_UTF8_ENCODING; /** * Test suite for this test class.<p> * * @return the test suite */ public static Test suite() { OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH); TestSuite suite = new TestSuite(); suite.setName(TestCmsXmlPageInSystem.class.getName()); suite.addTest(new TestCmsXmlPageInSystem("testLinkParameterIssue")); suite.addTest(new TestCmsXmlPageInSystem("testSchemaCachePublishIssue")); suite.addTest(new TestCmsXmlPageInSystem("testLinkReplacement")); suite.addTest(new TestCmsXmlPageInSystem("testCommentInSource")); suite.addTest(new TestCmsXmlPageInSystem("testXmlPageRenameElement")); suite.addTest(new TestCmsXmlPageInSystem("testMalformedPage")); TestSetup wrapper = new TestSetup(suite) { protected void setUp() { setupOpenCms("simpletest", "/sites/default/"); } protected void tearDown() { removeOpenCms(); } }; return wrapper; } /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestCmsXmlPageInSystem(String arg0) { super(arg0); } /** * Test malformed page structures.<p> * * @throws Exception in case something goes wrong */ public void testMalformedPage() throws Exception { CmsObject cms = getCmsObject(); echo("Testing malformed page element structures"); // overwrite an existing page with a bad content String resourcename = "/folder1/page2.html"; cms.lockResource(resourcename); CmsFile file = cms.readFile(resourcename); // read malformed XML page String pageStr = CmsFileUtil.readFile("org/opencms/xml/page/xmlpage-5.xml", "ISO-8859-1"); file.setContents(pageStr.getBytes("ISO-8859-1")); cms.writeFile(file); } /** * Test the schema cache publish issue.<p> * * Description of the issue: * After the initial publish, the XML page schema does not work anymore.<p> * * @throws Exception in case something goes wrong */ public void testSchemaCachePublishIssue() throws Exception { CmsObject cms = getCmsObject(); echo("Testing the validation for values in the XML content"); String resourcename = "/folder1/page1.html"; cms.lockResource(resourcename); CmsFile file = cms.readFile(resourcename); CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file); page.validateXmlStructure(new CmsXmlEntityResolver(cms)); page.setStringValue(cms, "body", Locale.ENGLISH, "This is a test"); assertEquals("This is a test", page.getValue("body", Locale.ENGLISH).getStringValue(cms)); file.setContents(page.marshal()); cms.writeFile(file); cms.unlockResource(resourcename); cms.publishResource(resourcename); cms.lockResource(resourcename); file = cms.readFile(resourcename); page = CmsXmlPageFactory.unmarshal(cms, file); page.validateXmlStructure(new CmsXmlEntityResolver(cms)); page.setStringValue(cms, "body", Locale.ENGLISH, "This is a another test"); assertEquals("This is a another test", page.getValue("body", Locale.ENGLISH).getStringValue(cms)); file.setContents(page.marshal()); cms.writeFile(file); } /** * Tests link issue with certain parameters.<p> * * Description of the issue: * links with parameters <code>&lt;a href="form.jsp?a=b&language=xy"&gt;</code> are replaced by * <code>&lt;a href="form.jsp?a=b?uage=xy"&gt;</code>.<p> * * This issue turned out to be a bug in the HtmlParser component, * updating the component from version 1.4 to version 1.5 solved the issue.<p> * * @throws Exception if something goes wrong */ public void testLinkParameterIssue() throws Exception { CmsObject cms = getCmsObject(); echo("Testing XML page link parameter issue"); String filename = "/folder1/subfolder11/test_param_1.html"; String content = CmsXmlPageFactory.createDocument(Locale.ENGLISH, UTF8); List properties = new ArrayList(); properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, UTF8, null)); properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_LOCALE, Locale.ENGLISH.toString(), null)); properties.add(new CmsProperty(CmsXmlPage.C_PROPERTY_ALLOW_RELATIVE, String.valueOf(false), null)); cms.createResource(filename, CmsResourceTypeXmlPage.getStaticTypeId(), content.getBytes(UTF8), properties); CmsFile file = cms.readFile(filename); CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file); String element = "test"; page.addValue(element, Locale.ENGLISH); String text; page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index.html?a=b&someparam=de\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index.html?a=b&someparam=de\">link</a>", text); page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index.html?language=de\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index.html?language=de\">link</a>", text); page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index.html?a=b&language=de\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index.html?a=b&language=de\">link</a>", text); page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index_noexist.html?a=b&language=de\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index_noexist.html?a=b&language=de\">link</a>", text); page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index_noexist.html?a=b&product=somthing\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index_noexist.html?a=b&product=somthing\">link</a>", text); } /** * Tests XML link replacement.<p> * * @throws Exception if something goes wrong */ public void testLinkReplacement() throws Exception { CmsObject cms = getCmsObject(); echo("Testing XML page link replacement"); String filename = "/folder1/subfolder11/test1.html"; String content = CmsXmlPageFactory.createDocument(Locale.ENGLISH, UTF8); List properties = new ArrayList(); properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, UTF8, null)); properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_LOCALE, Locale.ENGLISH.toString(), null)); properties.add(new CmsProperty(CmsXmlPage.C_PROPERTY_ALLOW_RELATIVE, String.valueOf(false), null)); cms.createResource(filename, CmsResourceTypeXmlPage.getStaticTypeId(), content.getBytes(UTF8), properties); CmsFile file = cms.readFile(filename); CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file); String element = "test"; page.addValue(element, Locale.ENGLISH); String text; // test link replacement with existing file page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index.html\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index.html\">link</a>", text); // test link replacement with non-existing file page.setStringValue(cms, element, Locale.ENGLISH, "<a href=\"index_noexist.html\">link</a>"); text = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals("<a href=\"/data/opencms/folder1/subfolder11/index_noexist.html\">link</a>", text); } /** * Tests comments in the page HTML source code.<p> * * @throws Exception if something goes wrong */ public void testCommentInSource() throws Exception { CmsObject cms = getCmsObject(); echo("Testing XML page comment handling"); String filename = "/folder1/subfolder11/test2.html"; List properties = new ArrayList(); properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, UTF8, null)); properties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_LOCALE, Locale.ENGLISH.toString(), null)); String content = CmsXmlPageFactory.createDocument(Locale.ENGLISH, UTF8); cms.createResource(filename, CmsResourceTypeXmlPage.getStaticTypeId(), content.getBytes(UTF8), properties); CmsFile file = cms.readFile(filename); CmsXmlPage page = CmsXmlPageFactory.unmarshal(cms, file); String element = "test"; page.addValue(element, Locale.ENGLISH); String result; // first test using a simple comment content = "<h1>Comment Test 1</h1>\n<!-- This is a comment -->\nSome text here..."; page.setStringValue(cms, element, Locale.ENGLISH, content); result = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals(content, result); // more complex comment test content = "<!-- First comment --><h1>Comment Test 2</h1>\n<!-- This is a comment -->\nSome text here...<!-- Another comment -->"; page.setStringValue(cms, element, Locale.ENGLISH, content); result = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals(content, result); // mix of comment and links content = "<!-- First comment --><img src=\"/data/opencms/image.gif\" alt=\"an image\" />\n<!-- This is a comment -->\n<a href=\"/data/opencms/index.html\">Link</a><!-- Another comment -->"; page.setStringValue(cms, element, Locale.ENGLISH, content); result = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals(content, result); // commented out html tags content = "<!-- <img src=\"/data/opencms/image.gif\" alt=\"an image\" />\n<h1>some text</h1>--><!-- This is a comment -->\n<a href=\"/data/opencms/index.html\">Link</a><!-- Another comment -->"; page.setStringValue(cms, element, Locale.ENGLISH, content); result = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals(content, result); // nested comments content = "<!-- Start of comment <!-- img src=\"/data/opencms/image.gif\" alt=\"an image\" / -->\n<h1>some text</h1><!-- This is a comment -->\n End of comment! --> <a href=\"/data/opencms/index.html\">Link</a><!-- Another comment -->"; page.setStringValue(cms, element, Locale.ENGLISH, content); result = page.getStringValue(cms, element, Locale.ENGLISH); assertEquals(content, result); } /** * Tests accessing element names in the XML page.<p> * * @throws Exception in case something goes wrong */ public void testXmlPageRenameElement() throws Exception { String folder = "/folder1/"; String recursive = "true"; String template = "ALL"; String locale = "ALL"; String oldElement = "body"; String newElement = "NewElement"; String removeEmptyElements = "false"; String validateNewElement = "false"; echo("Testing XML page rename element handling"); CmsElementRename wp = new CmsElementRename(null, getCmsObject(), folder, recursive, template, locale, oldElement, newElement, removeEmptyElements, validateNewElement); echo("Testing initialize CmsElementRename class"); assertEquals(folder, wp.getParamResource()); assertEquals(recursive, wp.getParamRecursive()); assertEquals(template, wp.getParamTemplate()); assertEquals(locale, wp.getParamLocale()); assertEquals(oldElement, wp.getParamOldElement()); assertEquals(newElement, wp.getParamNewElement()); assertEquals(removeEmptyElements, wp.getParamRemoveEmptyElements()); assertEquals(validateNewElement, wp.getParamValidateNewElement()); echo("CmsElementRename class initialized successfully"); echo("Xml Page Element Rename Start"); wp.actionRename(new CmsShellReport()); echo("Xml Page Element Rename End"); } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class H02ProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { H02ProtocolDecoder decoder = new H02ProtocolDecoder(new H02Protocol()); verifyNothing(decoder, buffer( "*HQ,355488020930796,V3,002339,62160,06,024852,035421,148,0,024852,035425,143,,022251,036482,137,,024852,000335,133,,024852,031751,133,,024852,035423,133,,02A1,0,X,010104,EFE7FBFF verifyPosition(decoder, buffer( "*HQ,4106012736,V1,224434,A,1827.3855,N,06705.7577,W,000.00,000,100117,FFFFFBFF,310,260,49101,1753,5 verifyAttributes(decoder, buffer( "*HQ,4208150188,NBR,210249,260,6,0,7,1014,50675,37,1014,50633,27,1014,17933,18,1014,17231,15,1014,50632,12,1014,13211,11,1014,17031,10,281216,FFFFFBFF,2 verifyAttributes(decoder, buffer( "*HQ,1600068812,NBR,141335,262,02,255,6,431,17003,26,431,11101,13,431,6353,13,431,22172,13,431,11093,13,431,60861,10,151216,FFFFFBFF verifyPosition(decoder, buffer( "*HQ,353588020068342,V1,084436,A,3257.01525,N,00655.03865,W,57.78,40,011216,FFFBFFFF,25c,a, 154,b04c verifyNothing(decoder, buffer( "*HQ,356803210091319,BS,,2d4,a,1b63,1969,26,1b63,10b2,31,0,0,25,,ffffffff,60 verifyAttributes(decoder, buffer( "*HQ,1400046168,NBR,160169,460,0,1,4,9338,3692,150,9338,3691,145,9338,3690,140,9338,3692,139,180813,FFFFFBFF verifyAttributes(decoder, buffer( "*HQ,1600068860,NBR,120156,262,03,255,6,802,54702,46,802,5032,37,802,54782,30,802,5052,28,802,54712,12,802,5042,12,081116,FFFFFBFF verifyAttributes(decoder, buffer( "*HQ,1600068860,NBR,110326,262,03,255,6,802,23152,23,812,49449,14,802,35382,13,802,35402,11,812,56622,09,802,23132,04,081116,FFFFFBFF verifyNothing(decoder, buffer( "*HQ,1600068860,LINK,112137,20,8,67,0,0,081116,FFFFFBFF verifyNothing(decoder, buffer( "*HQ,355488020533263,V3,121536,65501,04,000152,014001,156,-64,000161,010642,138,,000152,014003,129,,000152,013973,126,,02E4,0,X,071116,FFFFFBFF verifyPosition(decoder, buffer( "*HQ,4209917484,V19,093043,V,5052.9749,N,00426.4322,E,000.00,000,130916,,0032475874141,8944538530000543700F,FFFFFBFF verifyPosition(decoder, buffer( "*HQ,353505220873067,V1,,V,4605.75732,N,01430.73863,E,0.00,0,,FFFFFFEF,125,194, 64,d3 verifyPosition(decoder, buffer( "*HQ,4210051415,V1,164549,A,0956.3869,N,08406.7068,W,000.00,000,221215,FFFFFBFF,712,01,0,0,6 position("2015-12-22 16:45:49.000", true, 9.93978, -84.11178)); verifyAttributes(decoder, buffer( "*HQ,1451316451,NBR,112315,724,10,2,2,215,2135,123,215,2131,121,011215,FFFFFFFF verifyPosition(decoder, buffer( "*HQ,1451316485,V1,121557,A,-23-3.3408,S,-48-2.8926,W,0.1,158,241115,FFFFFFFF verifyPosition(decoder, buffer( "*HQ,1451316485,V1,121557,A,-23-35.3408,S,-48-2.8926,W,0.1,158,241115,FFFFFFFF verifyPosition(decoder, buffer( "*HQ,355488020119695,V1,050418,,2827.61232,N,07703.84822,E,0.00,0,031015,FFFEFBFF position("2015-10-03 05:04:18.000", false, 28.46021, 77.06414)); verifyPosition(decoder, buffer( "*HQ,1451316409,V1,030149,A,-23-29.0095,S,-46-51.5852,W,2.4,065,070315,FFFFFFFF position("2015-03-07 03:01:49.000", true, -23.48349, -46.85975)); verifyNothing(decoder, buffer( "*HQ,353588020068342,V1,000000,V,0.0000,0,0.0000,0,0.00,0.00,000000,ffffffff,000106,000002,000203,004c87,16 verifyPosition(decoder, buffer( "*HQ,3800008786,V1,062507,V,3048.2437,N,03058.5617,E,000.00,000,250413,FFFFFBFF verifyPosition(decoder, buffer( "*HQ,4300256455,V1,111817,A,1935.5128,N,04656.3243,E,0.00,100,170913,FFE7FBFF verifyPosition(decoder, buffer( "*HQ,123456789012345,V1,155850,A,5214.5346,N,2117.4683,E,0.00,270.90,131012,ffffffff,000000,000000,000000,000000 verifyPosition(decoder, buffer( "*HQ,353588010001689,V1,221116,A,1548.8220,S,4753.1679,W,0.00,0.00,300413,ffffffff,0002d4,000004,0001cd,000047 verifyPosition(decoder, buffer( "*HQ,354188045498669,V1,195200,A,701.8915,S,3450.3399,W,0.00,205.70,050213,ffffffff,000243,000000,000000 verifyPosition(decoder, buffer( "*HQ,2705171109,V1,213324,A,5002.5849,N,01433.7822,E,0.00,000,140613,FFFFFFFF verifyPosition(decoder, buffer( "*TH,2020916012,V1,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S17,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S14,100,10,1,3,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S20,ERROR,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S20,DONE,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,F7FFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,R8,ERROR,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S23,165.165.33.250:8800,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S24,thit.gd,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFF verifyPosition(decoder, buffer( "*TH,2020916012,V4,S1,OK,pass_word,130305,050316,A,2212.8745,N,11346.6574,E,14.28,028,220902,FFFFFBFD verifyPosition(decoder, buffer( "*HQ,353588020068342,V1,062840,A,5241.1249,N,954.9490,E,0.00,0.00,231013,ffffffff,000106,000002,000203,004c87,24 verifyPosition(decoder, buffer( "*HQ,353505220903211,V1,075228,A,5227.5039,N,01032.8443,E,0.00,0,231013,FFFBFFFF,106,14, 201,2173 verifyPosition(decoder, buffer( "*HQ,353505220903211,V1,140817,A,5239.3538,N,01003.5292,E,21.03,312,221013,FFFBFFFF,106,14, 203,1cd verifyPosition(decoder, buffer( "*HQ,356823035368767,V1,083618,A,0955.6392,N,07809.0796,E,0.00,0,070414,FFFBFFFF,194,3b5, 71,c9a9 verifyNothing(decoder, buffer( "*HQ,8401016597,BASE,152609,0,0,0,0,211014,FFFFFFFF verifyPosition(decoder, binary( "2441060116601245431311165035313006004318210e000000fffffbffff0024")); verifyPosition(decoder, binary( "24410600082621532131081504419390060740418306000000fffffbfdff0015060000002c02dc0c000000001f"), position("2015-08-31 21:53:21.000", true, 4.69898, -74.06971)); verifyPosition(decoder, binary( "2427051711092133391406135002584900014337822e000000ffffffffff0000")); verifyPosition(decoder, binary( "2427051711092134091406135002584900014337822e000000ffffffffff0000")); verifyPosition(decoder, binary( "2410307310010503162209022212874500113466574C014028fffffbffff0000")); verifyPosition(decoder, binary( "2441090013450831250401145047888000008554650e000000fffff9ffff001006000000000106020299109c01")); verifyPosition(decoder, binary( "24270517030820321418041423307879000463213792000056fffff9ffff0000")); verifyPosition(decoder, binary( "2441091144271222470112142233983006114026520E000000FFFFFBFFFF0014060000000001CC00262B0F170A")); verifyPosition(decoder, binary( "24971305007205201916101533335008000073206976000000effffbffff000252776566060000000000000000000049")); } }
package org.traccar.protocol; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; public class H02ProtocolDecoderTest { @Test public void testDecode() throws Exception { H02ProtocolDecoder decoder = new H02ProtocolDecoder(null); decoder.setDataManager(new TestDataManager()); assertNotNull(decoder.decode(null, null, "*HQ,123456789012345,V1,155850,A,5214.5346,N,2117.4683,E,0.00,270.90,131012,ffffffff,000000,000000,000000,000000")); assertNotNull(decoder.decode(null, null, "*HQ,353588010001689,V1,221116,A,1548.8220,S,4753.1679,W,0.00,0.00,300413,ffffffff,0002d4,000004,0001cd,000047")); assertNotNull(decoder.decode(null, null, "*HQ,354188045498669,V1,195200,A,701.8915,S,3450.3399,W,0.00,205.70,050213,ffffffff,000243,000000,000000")); } }
/* * $Log: Wsdl.java,v $ * Revision 1.9 2012-09-27 14:28:59 m00f069 * Better error message / adapter name when constructor throws exception. * * Revision 1.8 2012/09/27 13:44:31 Jaco de Groot <jaco.de.groot@ibissource.org> * Updates in generating wsdl namespace, wsdl input message name, wsdl output message name, wsdl port type name and wsdl operation name in case of EsbSoap * * Revision 1.7 2012/09/26 12:41:05 Jaco de Groot <jaco.de.groot@ibissource.org> * Bugfix in WSDL generator: Wrong prefix being used in element attribute of PipeLineInput and PipeLineOutput message part when using EsbSoapValidator. * * Revision 1.6 2012/08/23 11:57:43 Jaco de Groot <jaco.de.groot@ibissource.org> * Updates from Michiel * * Revision 1.5 2012/05/08 15:53:59 Jaco de Groot <jaco.de.groot@ibissource.org> * Fix invalid chars in wsdl:service name. * * Revision 1.4 2012/03/30 17:03:45 Jaco de Groot <jaco.de.groot@ibissource.org> * Michiel added JMS binding/service to WSDL generator, made WSDL validator work for Bis WSDL and made console show syntax problems for schema's used in XmlValidator * * Revision 1.3 2012/03/16 15:35:43 Jaco de Groot <jaco.de.groot@ibissource.org> * Michiel added EsbSoapValidator and WsdlXmlValidator, made WSDL's available for all adapters and did a bugfix on XML Validator where it seems to be dependent on the order of specified XSD's * * Revision 1.2 2011/12/15 10:08:06 Jaco de Groot <jaco.de.groot@ibissource.org> * Added CVS log * */ package nl.nn.adapterframework.soap; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import nl.nn.adapterframework.core.IListener; import nl.nn.adapterframework.core.IPipe; import nl.nn.adapterframework.core.PipeLine; import nl.nn.adapterframework.extensions.esb.EsbSoapWrapperPipe; import nl.nn.adapterframework.http.WebServiceListener; import nl.nn.adapterframework.jms.JmsListener; import nl.nn.adapterframework.pipes.XmlValidator; import nl.nn.adapterframework.util.AppConstants; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.LogUtil; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; class Wsdl { private static final Logger LOG = LogUtil.getLogger(Wsdl.class); private static final String WSDL = "http://schemas.xmlsoap.org/wsdl/"; private static final String SOAP_WSDL = "http://schemas.xmlsoap.org/wsdl/soap/"; private static final String SOAP_HTTP = "http://schemas.xmlsoap.org/soap/http"; private static final String JNDI = "http: private static final String SOAP_JMS = "http: protected static final String XSD = XMLConstants.W3C_XML_SCHEMA_NS_URI; protected static final QName NAME = new QName(null, "name"); protected static final QName TNS = new QName(null, "targetNamespace"); protected static final QName ELFORMDEFAULT = new QName(null, "elementFormDefault"); protected static final QName SCHEMA = new QName(XSD, "schema"); protected static final QName ELEMENT = new QName(XSD, "element"); protected static final QName IMPORT = new QName(XSD, "import"); protected static final QName INCLUDE = new QName(XSD, "include"); protected static final QName SCHEMALOCATION = new QName(null, "schemaLocation"); protected static final QName NAMESPACE = new QName(null, "namespace"); protected static final QName XMLNS = new QName(null, XMLConstants.XMLNS_ATTRIBUTE); private final boolean indentWsdl; private final PipeLine pipeLine; private final String targetNamespace; private final String name; private final XmlValidator inputValidator; private String webServiceListenerNamespace; private boolean recursiveXsds = false; private boolean includeXsds = false; private Set<XSD> xsds = null; private String wsdlInputMessageName = "PipeLineInput"; private String wsdlOutputMessageName = "PipeLineOutput"; private String wsdlPortTypeName = "PipeLine"; private String wsdlOperationName = "Process"; private String esbSoapOperationName; private String esbSoapOperationVersion; private String documentation = "Generated by " + this.getClass().getName() + " on " + new Date(); Wsdl(PipeLine pipeLine, boolean indent) { this.pipeLine = pipeLine; indentWsdl = indent; this.name = this.pipeLine.getAdapter().getName(); if (this.name == null) { throw new IllegalArgumentException("The adapter '" + pipeLine.getAdapter() + "' has no name"); } inputValidator = (XmlValidator)pipeLine.getInputValidator(); if (inputValidator == null) { throw new IllegalStateException("The adapter '" + getName() + "' has no input validator"); } AppConstants appConstants = AppConstants.getInstance(); String tns = appConstants.getResolvedProperty("wsdl." + getName() + ".targetNamespace"); if (tns == null) { tns = appConstants.getResolvedProperty("wsdl.targetNamespace"); } if (tns == null) { EsbSoapWrapperPipe inputWrapper = getEsbSoapInputWrapper(); EsbSoapWrapperPipe outputWrapper = getEsbSoapOutputWrapper(); if (outputWrapper != null) { tns = outputWrapper.getOutputNamespaceBaseUri() + "/" + outputWrapper.getBusinessDomain() + "/" + outputWrapper.getServiceName() + "/" + outputWrapper.getServiceContext() + "/" + outputWrapper.getServiceContextVersion(); esbSoapOperationName = outputWrapper.getOperationName(); esbSoapOperationVersion = outputWrapper.getOperationVersion(); initEsbSoap(outputWrapper.getParadigm()); } else if (inputWrapper != null && EsbSoapWrapperPipe.isValidNamespace(getFirstNamespaceFromSchemaLocation(inputValidator))) { // One-way tns = getFirstNamespaceFromSchemaLocation(inputValidator); int i = tns.lastIndexOf('/'); esbSoapOperationName = tns.substring(i + 1); tns = tns.substring(0, i); i = tns.substring(0, i).lastIndexOf('/'); esbSoapOperationVersion = tns.substring(i + 1); tns = tns.substring(0, i); initEsbSoap(null); } else { for(IListener l : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (l instanceof WebServiceListener) { webServiceListenerNamespace = ((WebServiceListener)l).getServiceNamespaceURI(); tns = webServiceListenerNamespace; } } if (tns == null) { tns = getFirstNamespaceFromSchemaLocation(inputValidator); } if (tns != null) { if (tns.endsWith("/")) { tns = tns + "wsdl/"; } else { tns = tns + "/wsdl/"; } } else { tns = "${wsdl." + getName() + ".targetNamespace}"; } } } this.targetNamespace = WsdlUtils.validUri(tns); } protected void initEsbSoap(String paradigm) { if (inputValidator instanceof SoapValidator) { String soapBody = ((SoapValidator)inputValidator).getSoapBody(); if (soapBody != null) { int i = soapBody.lastIndexOf('_'); if (i != -1) { wsdlInputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + soapBody.substring(i + 1); } } } if (paradigm != null) { wsdlOutputMessageName = esbSoapOperationName + "_" + esbSoapOperationVersion + "_" + paradigm; } wsdlPortTypeName = esbSoapOperationName + "_Interface_" + esbSoapOperationVersion; wsdlOperationName = esbSoapOperationName + "_" + esbSoapOperationVersion; } /** * Writes the WSDL to an output stream * @param out * @param servlet The servlet what is used as the web service (because this needs to be present in the WSDL) * @throws XMLStreamException * @throws IOException */ public void wsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, URISyntaxException, NamingException { XMLStreamWriter w = WsdlUtils.createWriter(out, indentWsdl); w.writeStartDocument(WsdlUtils.ENCODING, "1.0"); w.setPrefix("wsdl", WSDL); w.setPrefix("xsd", XSD); w.setPrefix("soap", SOAP_WSDL); w.setPrefix("jms", SOAP_JMS); if (needsJndiNamespace()) { w.setPrefix("jndi", JNDI); } w.setPrefix("ibis", getTargetNamespace()); for (XSD xsd : getXSDs()) { w.setPrefix(xsd.pref, xsd.nameSpace); } w.writeStartElement(WSDL, "definitions"); { w.writeNamespace("wsdl", WSDL); w.writeNamespace("xsd", XSD); w.writeNamespace("soap", SOAP_WSDL); if (needsJndiNamespace()) { w.writeNamespace("jndi", JNDI); } w.writeNamespace("ibis", getTargetNamespace()); for (XSD xsd : getXSDs()) { w.writeNamespace(xsd.pref, xsd.nameSpace); } w.writeAttribute("targetNamespace", getTargetNamespace()); documentation(w); types(w); messages(w); portType(w); binding(w); service(w, servlet); } w.writeEndDocument(); w.close(); } /** * Generates a zip file (and writes it to the given outputstream), containing the WSDL and all referenced XSD's. * @see {@link #wsdl(java.io.OutputStream, String)} */ public void zip(OutputStream stream, String servletName) throws IOException, XMLStreamException, URISyntaxException, NamingException { ZipOutputStream out = new ZipOutputStream(stream); // First an entry for the WSDL itself: ZipEntry wsdlEntry = new ZipEntry(getName() + ".wsdl"); out.putNextEntry(wsdlEntry); wsdl(out, servletName); out.closeEntry(); //And then all XSD's setRecursiveXsds(true); Set<String> entries = new HashSet<String>(); Map<String, String> correctingNamespaces = new HashMap<String, String>(); for (XSD xsd : getXSDs()) { String zipName = xsd.getBaseUrl() + xsd.getName(); if (entries.add(zipName)) { ZipEntry xsdEntry = new ZipEntry(zipName); out.putNextEntry(xsdEntry); XMLStreamWriter writer = WsdlUtils.createWriter(out, false); WsdlUtils.includeXSD(xsd, writer, correctingNamespaces, true); out.closeEntry(); } else { LOG.warn("Duplicate xsds in " + this + " " + xsd + " " + getXSDs()); } } out.close(); } public String getName() { return name; } protected String getTargetNamespace() { return targetNamespace; } private List<XSD> parseSchema(String schemaLocation) throws MalformedURLException, URISyntaxException { List<XSD> result = new ArrayList<XSD>(); if (schemaLocation != null) { String[] split = schemaLocation.split("\\s+"); if (split.length % 2 != 0) throw new IllegalStateException("The schema must exist from an even number of strings, but it is " + schemaLocation); for (int i = 0; i < split.length; i += 2) { result.add(getXSD(split[i], split[i + 1])); } } return result; } /** * Returns a map: namespace -> Collection of all relevant XSD's * @return * @throws XMLStreamException * @throws IOException */ Map<String, Collection<XSD>> getMappedXSDs() throws XMLStreamException, IOException, URISyntaxException { Map<String, Collection<XSD>> result = new HashMap<String, Collection<XSD>>(); for (XSD xsd : getXSDs()) { Collection<XSD> col = result.get(xsd.nameSpace); if (col == null) { col = new ArrayList<XSD>(); result.put(xsd.nameSpace, col); } col.add(xsd); } return result; } Set<XSD> getXSDs() throws IOException, XMLStreamException, URISyntaxException { if (xsds == null) { xsds = new TreeSet<XSD>(); String inputSchema = inputValidator.getSchema(); if (inputSchema != null) { // In case of a WebServiceListener using soap=true it might be // valid to use the schema attribute (in which case the schema // doesn't have a namespace) as the WebServiceListener will // remove the soap envelop and body element before it is // validated. In this case we use the serviceNamespaceURI from // the WebServiceListener as the namespace for the schema. if (webServiceListenerNamespace != null) { XSD x = getXSD(webServiceListenerNamespace, inputSchema); if (recursiveXsds) { x.getImportXSDs(xsds); } } else { throw new IllegalStateException("The adapter " + pipeLine + " has an input validator using the schema attribute but a namespace is required"); } } for (XSD x : parseSchema(inputValidator.getSchemaLocation())) { if (recursiveXsds) { x.getImportXSDs(xsds); } } XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator != null) { String outputSchema = outputValidator.getSchema(); if (outputSchema != null) { getXSD(null, outputSchema); } parseSchema(outputValidator.getSchemaLocation()); } } return xsds; } protected XSD getXSD(String nameSpace) throws IOException, XMLStreamException, URISyntaxException { if (nameSpace == null) throw new IllegalArgumentException("Cannot get an XSD for null namespace"); for (XSD xsd : getXSDs()) { if (xsd.nameSpace.equals(nameSpace)) { return xsd; } } throw new IllegalArgumentException("No xsd for namespace '" + nameSpace + "' found (known are " + getXSDs() + ")"); } /** * Outputs a 'documentation' section of the WSDL */ protected void documentation(XMLStreamWriter w) throws XMLStreamException { w.writeStartElement(WSDL, "documentation"); w.writeCData(documentation); w.writeEndElement(); } /** * Output the 'types' section of the WSDL * @param w * @throws XMLStreamException * @throws IOException */ protected void types(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "types"); Map<String, String> correctingNamesSpaces = new HashMap<String, String>(); if (includeXsds) { for (XSD xsd : getXSDs()) { WsdlUtils.includeXSD(xsd, w, correctingNamesSpaces, false); } } else { for (Map.Entry<String, Collection<XSD>> xsd: getMappedXSDs().entrySet()) { WsdlUtils.xsincludeXSDs(xsd.getKey(), xsd.getValue(), w, correctingNamesSpaces); } } w.writeEndElement(); } /** * Outputs the 'messages' section. * @param w * @throws XMLStreamException * @throws IOException */ protected void messages(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { message(w, "Header", getHeaderTags()); message(w, wsdlInputMessageName, getInputTags()); XmlValidator outputValidator = (XmlValidator) pipeLine.getOutputValidator(); if (outputValidator == null) { LOG.debug("The PipeLine " + pipeLine + " has no output validator, this is a oneway wsdl"); } else { Collection<QName> out = getOutputTags(); message(w, wsdlOutputMessageName, out); } //message(w, "PipeLineFault", "error", "bla:bloe"); } protected void message(XMLStreamWriter w, String name, Collection<QName> tags) throws XMLStreamException, IOException { if (tags == null) throw new IllegalArgumentException("Tag cannot be null for " + name); if (!tags.isEmpty()) { w.writeStartElement(WSDL, "message"); w.writeAttribute("name", name); { for (QName tag : tags) { w.writeEmptyElement(WSDL, "part"); w.writeAttribute("name", getIbisName(tag)); String typ = tag.getPrefix() + ":" + tag.getLocalPart(); w.writeAttribute("element", typ); } } w.writeEndElement(); } } protected void portType(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "portType"); w.writeAttribute("name", wsdlPortTypeName); { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(WSDL, "input"); w.writeAttribute("message", "ibis:" + wsdlInputMessageName); if (getOutputTags() != null) { w.writeEmptyElement(WSDL, "output"); w.writeAttribute("message", "ibis:" + wsdlOutputMessageName); } /* w.writeEmptyElement(WSDL, "fault"); w.writeAttribute("message", "ibis:PipeLineFault"); */ } w.writeEndElement(); } w.writeEndElement(); } protected String getSoapAction() { AppConstants appConstants = AppConstants.getInstance(); String sa = appConstants.getResolvedProperty("wsdl." + getName() + ".soapAction"); if (sa != null) return sa; sa = appConstants.getResolvedProperty("wsdl.soapAction"); if (sa != null) return sa; if (esbSoapOperationName != null && esbSoapOperationVersion != null) { return esbSoapOperationName + "_" + esbSoapOperationVersion; } return "${wsdl." + getName() + ".soapAction}"; } private EsbSoapWrapperPipe getEsbSoapInputWrapper() { IPipe inputWrapper = pipeLine.getInputWrapper(); if (inputWrapper instanceof EsbSoapWrapperPipe) { return (EsbSoapWrapperPipe) inputWrapper; } return null; } private EsbSoapWrapperPipe getEsbSoapOutputWrapper() { IPipe outputWrapper = pipeLine.getOutputWrapper(); if (outputWrapper instanceof EsbSoapWrapperPipe) { return (EsbSoapWrapperPipe) outputWrapper; } return null; } protected void binding(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpBinding(w); } else if (listener instanceof JmsListener) { jmsBinding(w, (JmsListener) listener); } else { w.writeComment("Binding: Unrecognized listener " + listener.getClass() + ": " + listener.getName()); } } } protected void httpBinding(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("transport", SOAP_HTTP); w.writeAttribute("style", "document"); writeSoapOperation(w); } w.writeEndElement(); } protected void writeSoapOperation(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "operation"); w.writeAttribute("name", wsdlOperationName); { w.writeEmptyElement(SOAP_WSDL, "operation"); w.writeAttribute("style", "document"); w.writeAttribute("soapAction", getSoapAction()); w.writeStartElement(WSDL, "input"); { writeSoapHeader(w); Collection<QName> inputTags = getInputTags(); //w.writeEmptyElement(input.xsd.nameSpace, input.getRootTag()); w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, inputTags); w.writeAttribute("use", "literal"); } w.writeEndElement(); Collection<QName> outputTags = getOutputTags(); if (outputTags != null) { w.writeStartElement(WSDL, "output"); { writeSoapHeader(w); ///w.writeEmptyElement(outputTag.xsd.nameSpace, outputTag.getRootTag()); w.writeEmptyElement(SOAP_WSDL, "body"); writeParts(w, outputTags); w.writeAttribute("use", "literal"); } w.writeEndElement(); } /* w.writeStartElement(WSDL, "fault"); { w.writeEmptyElement(SOAP_WSDL, "error"); w.writeAttribute("use", "literal"); } w.writeEndElement(); */ } w.writeEndElement(); } protected void writeSoapHeader(XMLStreamWriter w) throws XMLStreamException, IOException, URISyntaxException { Collection<QName> headers = getHeaderTags(); if (! headers.isEmpty()) { if (headers.size() > 1) { LOG.warn("Can only deal with one soap header. Taking only the first of " + headers); } w.writeEmptyElement(SOAP_WSDL, "header"); w.writeAttribute("part", getIbisName(headers.iterator().next())); w.writeAttribute("use", "literal"); w.writeAttribute("message", "ibis:Header"); } } protected void writeParts(XMLStreamWriter w, Collection<QName> tags) throws XMLStreamException { StringBuilder builder = new StringBuilder(); for (QName outputTag : tags) { if (builder.length() > 0) builder.append(" "); builder.append(getIbisName(outputTag)); } w.writeAttribute("parts", builder.toString()); } protected String getIbisName(QName qname) { return qname.getLocalPart(); } protected void jmsBinding(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, IOException, URISyntaxException { w.writeStartElement(WSDL, "binding"); w.writeAttribute("name", "SoapBinding"); w.writeAttribute("type", "ibis:" + wsdlPortTypeName); { w.writeEmptyElement(SOAP_WSDL, "binding"); w.writeAttribute("style", "document"); w.writeAttribute("transport", SOAP_JMS); w.writeEmptyElement(SOAP_JMS, "binding"); w.writeAttribute("messageFormat", "Text"); writeSoapOperation(w); } w.writeEndElement(); } protected void service(XMLStreamWriter w, String servlet) throws XMLStreamException, NamingException { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof WebServiceListener) { httpService(w, servlet); } else if (listener instanceof JmsListener) { jmsService(w, (JmsListener) listener); } else { w.writeComment("Service: Unrecognized listener " + listener.getClass() + " " + listener); } } } protected boolean needsJndiNamespace() { for (IListener listener : WsdlUtils.getListeners(pipeLine.getAdapter())) { if (listener instanceof JmsListener) { return true; } } return false; } protected void httpService(XMLStreamWriter w, String servlet) throws XMLStreamException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapHttp"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); w.writeAttribute("location", servlet); } w.writeEndElement(); } w.writeEndElement(); } protected void jmsService(XMLStreamWriter w, JmsListener listener) throws XMLStreamException, NamingException { w.writeStartElement(WSDL, "service"); w.writeAttribute("name", WsdlUtils.getNCName(getName())); { w.writeStartElement(WSDL, "port"); w.writeAttribute("name", "SoapJMS"); w.writeAttribute("binding", "ibis:SoapBinding"); { w.writeEmptyElement(SOAP_WSDL, "address"); String destinationName = listener.getDestinationName(); if (destinationName != null) { w.writeAttribute("location", destinationName); } writeJndiContext(w); w.writeStartElement(SOAP_JMS, "connectionFactory"); { w.writeCharacters("QueueConnectionFactory"); } w.writeEndElement(); w.writeStartElement(SOAP_JMS, "targetAddress"); String destinationType = listener.getDestinationType(); if (destinationType != null) { w.writeAttribute("destination", destinationType); } w.writeCharacters(listener.getPhysicalDestinationShortName()); w.writeEndElement(); } w.writeEndElement(); } w.writeEndElement(); } protected void writeJndiContext(XMLStreamWriter w) throws XMLStreamException, NamingException { // TODO Context ctx = new InitialContext(); w.writeStartElement(JNDI, "context"); { // TODO untested Map<?, ?> environment = ctx.getEnvironment(); // I have no idea for (Map.Entry<?, ?> entry : environment.entrySet()) { w.writeStartElement(JNDI, "property"); { w.writeAttribute("name", entry.getKey().toString()); w.writeAttribute("type", entry.getValue().getClass().toString()); } w.writeCharacters(entry.getValue().toString()); w.writeEndElement(); } } w.writeEndElement(); } protected PipeLine getPipeLine() { return pipeLine; } protected Collection<QName> getHeaderTags(XmlValidator xmlValidator) throws XMLStreamException, IOException, URISyntaxException { if (xmlValidator instanceof SoapValidator) { String root = ((SoapValidator)xmlValidator).getSoapHeader(); QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } } return Collections.emptyList(); } protected Collection<QName> getRootTags(XmlValidator xmlValidator) throws IOException, XMLStreamException, URISyntaxException { String root; if (xmlValidator instanceof SoapValidator) { root = ((SoapValidator)xmlValidator).getSoapBody(); } else { root = xmlValidator.getRoot(); } QName q = getRootTag(root); if (q != null) { return Collections.singleton(q); } return Collections.emptyList(); } protected QName getRootTag(String tag) throws XMLStreamException, IOException, URISyntaxException { if (StringUtils.isNotEmpty(tag)) { for (XSD xsd : xsds) { for (String rootTag : xsd.rootTags) { if (tag.equals(rootTag)) { return xsd.getTag(tag); } } } LOG.warn("Root element '" + tag + "' not found in XSD's"); } return null; } protected Collection<QName> getHeaderTags() throws IOException, XMLStreamException, URISyntaxException { return getHeaderTags(inputValidator); } protected Collection<QName> getInputTags() throws IOException, XMLStreamException, URISyntaxException { return getRootTags(inputValidator); } protected Collection<QName> getOutputTags() throws IOException, XMLStreamException, URISyntaxException { XmlValidator outputValidator = (XmlValidator) getPipeLine().getOutputValidator(); if (outputValidator != null) { return getRootTags((XmlValidator) getPipeLine().getOutputValidator()); } else { LOG.debug("Oneway"); return null; } } protected String getFirstNamespaceFromSchemaLocation(XmlValidator inputValidator) { String schemaLocation = inputValidator.getSchemaLocation(); if (schemaLocation != null) { String[] split = schemaLocation.split("\\s+"); if (split.length > 0) { return split[0]; } } return null; } private XSD getXSD(String ns, String resource) throws URISyntaxException { URI url = ClassUtils.getResourceURL(resource).toURI(); if (url == null) { throw new IllegalArgumentException("No such resource " + resource); } for (XSD xsd : xsds) { if (xsd.nameSpace == null) { if (xsd.url.equals(url)) { return xsd; } } else { if (xsd.nameSpace.equals(ns) && xsd.url.equals(url)){ return xsd; } } } XSD xsd = new XSD("", ns, url, xsds.size() + 1); xsds.add(xsd); return xsd; } public boolean isRecursiveXsds() { return recursiveXsds; } /** * Make an effort to collect all XSD's also the included ones in {@link #getXSDs()} * @param recursiveXsds */ public void setRecursiveXsds(boolean recursiveXsds) { this.recursiveXsds = recursiveXsds; xsds = null; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public boolean isIncludeXsds() { return includeXsds; } public void setIncludeXsds(boolean includeXsds) { this.includeXsds = includeXsds; } /* public void easywsdl(OutputStream out, String servlet) throws XMLStreamException, IOException, SchemaException, URISyntaxException { Description description = WSDLFactory.newInstance().newDescription(AbsItfDescription.WSDLVersionConstants.WSDL11); SchemaFactory fact = SchemaFactory.newInstance(); Types t = description.getTypes(); for (XSD xsd : getXsds()) { description.addNamespace(xsd.pref, xsd.nameSpace); SchemaReader sr = fact.newSchemaReader(); Schema s = sr.read(xsd.url); t.addSchema(s); } InterfaceType it = description.createInterface(); Operation o = it.createOperation(); Input i = o.createInput(); i.setName("IbisInput"); //i. // s t.addOperation(it.createOperation()); description.addInterface(); Binding binding = description.createBinding(); BindingOperation op = binding.createBindingOperation(); //description.addBinding(binding); } */ }
package io.car.server.rest.coding; import java.net.URI; import java.util.Iterator; import java.util.Map.Entry; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.inject.Inject; import com.vividsolutions.jts.geom.Geometry; import io.car.server.core.dao.PhenomenonDao; import io.car.server.core.dao.SensorDao; import io.car.server.core.entities.Measurement; import io.car.server.core.entities.MeasurementValue; import io.car.server.core.entities.Phenomenon; import io.car.server.core.entities.Sensor; import io.car.server.core.entities.User; import io.car.server.core.util.GeoJSONConstants; import io.car.server.rest.MediaTypes; import io.car.server.rest.resources.MeasurementsResource; import io.car.server.rest.resources.TrackResource; /** * @author Arne de Wall <a.dewall@52north.org> * @author Christian Autermann <autermann@uni-muenster.de> */ public class MeasurementCoder extends AbstractEntityCoder<Measurement> { private final EntityEncoder<Geometry> geometryEncoder; private final EntityDecoder<Geometry> geometryDecoder; private final EntityEncoder<User> userProvider; private final EntityEncoder<Sensor> sensorProvider; private final EntityEncoder<Phenomenon> phenomenonProvider; private final PhenomenonDao phenomenonDao; private final SensorDao sensorDao; @Inject public MeasurementCoder(EntityEncoder<Geometry> geometryEncoder, EntityDecoder<Geometry> geometryDecoder, EntityEncoder<User> userProvider, EntityEncoder<Sensor> sensorProvider, EntityEncoder<Phenomenon> phenomenonProvider, PhenomenonDao phenomenonDao, SensorDao sensorDao) { this.geometryDecoder = geometryDecoder; this.geometryEncoder = geometryEncoder; this.userProvider = userProvider; this.sensorProvider = sensorProvider; this.phenomenonProvider = phenomenonProvider; this.phenomenonDao = phenomenonDao; this.sensorDao = sensorDao; } @Override public Measurement decode(JsonNode j, MediaType mediaType) { Measurement measurement = getEntityFactory().createMeasurement(); if (j.has(JSONConstants.GEOMETRY_KEY)) { measurement.setGeometry(geometryDecoder.decode(j.path(JSONConstants.GEOMETRY_KEY), mediaType)); } if (j.has(GeoJSONConstants.PROPERTIES_KEY)) { JsonNode p = j.path(GeoJSONConstants.PROPERTIES_KEY); if (p.has(JSONConstants.SENSOR_KEY)) { measurement.setSensor(sensorDao.getByName(p.path(JSONConstants.SENSOR_KEY) .path(JSONConstants.NAME_KEY).textValue())); } if (p.has(JSONConstants.TIME_KEY)) { measurement.setTime(getDateTimeFormat().parseDateTime(p.path(JSONConstants.TIME_KEY).textValue())); } if (p.has(JSONConstants.PHENOMENONS_KEY)) { JsonNode phens = p.path(JSONConstants.PHENOMENONS_KEY); Iterator<Entry<String, JsonNode>> fields = phens.fields(); while (fields.hasNext()) { Entry<String, JsonNode> field = fields.next(); Phenomenon phenomenon = phenomenonDao.getByName(field.getKey()); JsonNode valueNode = field.getValue().get(JSONConstants.VALUE_KEY); if (valueNode.isValueNode()) { Object value = null; if (valueNode.isNumber()) { value = valueNode.asDouble(); } else if (valueNode.isBoolean()) { value = valueNode.booleanValue(); } else if (valueNode.isTextual()) { value = valueNode.textValue(); } measurement.addValue(getEntityFactory().createMeasurementValue() .setValue(value).setPhenomenon(phenomenon)); } } } } return measurement; } @Override public ObjectNode encode(Measurement t, MediaType mediaType) { ObjectNode measurement = getJsonFactory().objectNode(); measurement.put(GeoJSONConstants.TYPE_KEY, GeoJSONConstants.FEATURE_TYPE); measurement.put(JSONConstants.GEOMETRY_KEY, geometryEncoder.encode(t.getGeometry(), mediaType)); ObjectNode properties = measurement.putObject(GeoJSONConstants.PROPERTIES_KEY); properties.put(JSONConstants.IDENTIFIER_KEY, t.getIdentifier()); properties.put(JSONConstants.TIME_KEY, getDateTimeFormat().print(t.getTime())); if (!mediaType.equals(MediaTypes.TRACK_TYPE)) { properties.put(JSONConstants.SENSOR_KEY, sensorProvider.encode(t.getSensor(), mediaType)); properties.put(JSONConstants.USER_KEY, userProvider.encode(t.getUser(), mediaType)); properties.put(JSONConstants.MODIFIED_KEY, getDateTimeFormat().print(t.getLastModificationDate())); properties.put(JSONConstants.CREATED_KEY, getDateTimeFormat().print(t.getCreationDate())); } else { URI href = getUriInfo().getRequestUriBuilder() .path(TrackResource.MEASUREMENTS) .path(MeasurementsResource.MEASUREMENT) .build(t.getIdentifier()); properties.put(JSONConstants.HREF_KEY, href.toString()); } ObjectNode values = properties.putObject(JSONConstants.PHENOMENONS_KEY); for (MeasurementValue mv : t.getValues()) { ObjectNode phenomenon = phenomenonProvider.encode(mv.getPhenomenon(), mediaType); Object value = mv.getValue(); if (value instanceof Number) { phenomenon.put(JSONConstants.VALUE_KEY, ((Number) value).doubleValue()); } else if (value instanceof Boolean) { phenomenon.put(JSONConstants.VALUE_KEY, (Boolean) value); } else if (value != null) { phenomenon.put(JSONConstants.VALUE_KEY, value.toString()); } values.put(mv.getPhenomenon().getName(), phenomenon); } return measurement; } }